branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>wesfree163/IG.Assistantz<file_sep>/README.md # IG.Assistantz Allows users to upload straight from their laptop by navigating a hidden web browser. Requires compatible Python version and web driver. <file_sep>/instagram.py #!/usr/bin/env Python3 # from pywinauto import Application from time import sleep # import json # import os # import autoit from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait # from pywinauto import Application # Variables driver = "" def launch_inst(): global driver print("Opening instagram") # Chrome browser options mobile_emulation = {"deviceMetrics": {"width": 360, "height": 640, "pixelRatio": 3.0}, "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"} opts = webdriver.ChromeOptions() opts.add_argument("window-size=1,765") opts.add_experimental_option("mobileEmulation", mobile_emulation) driver = webdriver.Chrome(executable_path=r"chromedriver.exe", options=opts) # Opens Instagram main_url = "https://www.instagram.com" driver.get(main_url) sleep(10) def login(): # Logs into instagram print("Logging into Instagram") driver.find_element_by_class_name("sqdOP").click() username = driver.find_element_by_name("username") username.send_keys("") sleep(3) password = driver.find_element_by_name("password") password.send_keys("", Keys.ENTER) # password.send_keys(Keys.RETURN) for Mac users sleep(3) # driver.find_element_by_xpath("//a[contains(text(),'Not now')]").click() def remove_popups(): print("Removing any popups") try: driver.find_element_by_xpath("//a[contains(text(),'Not Now')]").click() except: try: driver.find_element_by_xpath("//button[contains(text(),'Not Now')]").click() except: try: driver.find_element_by_xpath("//button[contains(text(),'Cancel')]").click() except: pass def post(): print("Posting your trials") sleep(2) driver.find_element_by_class_name("_8-yf5").click() sleep(7) remove_popups() sleep(3) launch_inst() login() remove_popups() sleep(15) remove_popups() sleep(15) remove_popups() sleep(15) remove_popups() sleep(15) remove_popups() post()
c2f954eeb5f32b25fec40c9ae76d45fbf73e631d
[ "Markdown", "Python" ]
2
Markdown
wesfree163/IG.Assistantz
b76b728f07e3ccf0b2d3b4c4aa5fa48afc778e5f
653f6fc576b2e296ef1d5c4ea54c04ee91b863a3
refs/heads/main
<file_sep># iimi project <file_sep>// var canvas = new fabric.Canvas('c'); // alert('hi') // console.log(canvas) // canvas.setBackgroundImage('http://lorempixel.com/400/400/fashion', canvas.renderAll.bind(canvas)); // $("#text").on("click", function(e) { // text = new fabric.Text($("#text").val(), { left: 100, top: 100 }); // canvas.add(text); // }); // $("#rect").on("click", function(e) { // e.preventDefault(); // rect = new fabric.Rect({ // left: 40, // top: 40, // width: 50, // height: 50, // fill: 'transparent', // stroke: 'green', // strokeWidth: 5, // }); // canvas.add(rect); // }); // $("#circ").on("click", function(e) { // e.preventDefault(); // rect = new fabric.Circle({ // left: 40, // top: 40, // radius: 50, // fill: 'transparent', // stroke: 'green', // strokeWidth: 5, // }); // canvas.add(rect); // }); // $("#save").on("click", function(e) { // $(".save").html(canvas.toSVG()); // }); $("#rect").on("click", function(e) { var canvas = document.getElementById('c'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); } }); $("#circ").on("click", function(e) {//from w w w . j a va 2s . c o m var canvas = new fabric.Canvas("c"); var circle, isDown, origX, origY; canvas.on('mouse:down', function(o){ isDown = true; var pointer = canvas.getPointer(o.e); origX = pointer.x; origY = pointer.y; circle = new fabric.Circle({ left: origX, top: origY, originX: 'left', originY: 'top', radius: pointer.x-origX, angle: 0, fill: '', stroke:'red', strokeWidth:3, }); canvas.add(circle); }); canvas.on('mouse:move', function(o){ if (!isDown) return; var pointer = canvas.getPointer(o.e); var radius = Math.max(Math.abs(origY - pointer.y),Math.abs(origX - pointer.x))/2; if (radius > circle.strokeWidth) { radius -= circle.strokeWidth/2; } circle.set({ radius: radius}); if(origX>pointer.x){ circle.set({originX: 'right' }); } else { circle.set({originX: 'left' }); } if(origY>pointer.y){ circle.set({originY: 'bottom' }); } else { circle.set({originY: 'top' }); } canvas.renderAll(); }); canvas.on('mouse:up', function(o){ isDown = false; }); });
f2543d57ff437dd3765f84d604cc7d5d39df2004
[ "Markdown", "JavaScript" ]
2
Markdown
JasimSG/iimi
d0f4267bc45e9d207b41a5e95fa620f677cfdf25
e7e3b60db871376e19056f38b9bf1e3e0c3746fc
refs/heads/master
<repo_name>lequangquochung/Angular-Material<file_sep>/src/app/customer-edit/customer-edit.component.ts import { JobService } from './../shared/job.service'; import { Validators, FormGroup, FormBuilder } from '@angular/forms'; import { Customer } from './../Models/customer.model'; import { CustomerAccountService } from './../shared/customer-account.service'; import { Component, OnInit, Input, AfterViewInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { RouterModule, Routes, Router } from '@angular/router'; import { FormComponentBase } from '../infrastructure/form-component-base'; import { CrossFieldErrorMatcher } from '../infrastructure/cross-field-error-matcher'; import Swal from 'sweetalert2'; @Component({ selector: 'app-customer-edit', templateUrl: './customer-edit.component.html', styleUrls: ['./customer-edit.component.css'] }) export class CustomerEditComponent extends FormComponentBase implements OnInit, AfterViewInit { jobList = []; customerList: Customer[] = []; // customerForm: FormArray = this.fb.array([]); customerForm: FormGroup; urlImage: any; base64textString: string; customer: Customer; errorMatcher = new CrossFieldErrorMatcher(); constructor( private fb: FormBuilder, private route: ActivatedRoute, private location: Location, private customerAccountService: CustomerAccountService, private jobService: JobService, private router: Router) { super(); this.validationMessages = { first_name: { required: 'First Name is required.', minlength: 'First Name minimum length is 2.', pattern: 'First Name minimum length 2, no special character.' }, last_name: { required: 'Last Name is required.', minlength: 'Last Name minimum length is 2.', pattern: 'Last Name minimum length 2, no special character.' }, address: { minlength: 'Last Name minimum length is 2.', required: 'Address is required.' }, city: { minlength: 'Last Name minimum length is 2.', required: 'City is required.' }, email: { required: 'Email is required.', pattern: 'Email is not properly formatted.', }, phone_number: { required: 'Phone number is required.', minlength: 'Phone number minimum length is 9.', maxlength: 'Phone number maximum length is 12', pattern: 'Phone number minimum length 9, numbers only. No spaces.' }, description: { minlength: 'Description minimum length is 2.', required: 'Description is required.' } }; this.formErrors = { first_name: '', last_name: '', address: '', city: '', email: '', phone_number: '', description: '', }; this.customerForm = this.fb.group({ customer_id: ['', Validators.required], first_name: ['', [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z0-9]*$') ] ], last_name: ['', [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z0-9]*$') ] ], gender: ['', [ Validators.required ] ], address: ['', [ Validators.required ] ], city: ['', [ Validators.required ] ], email: ['', [ Validators.required, Validators.email ] ], phone_number: ['', [ Validators.required, Validators.minLength(10), Validators.maxLength(11), Validators.pattern("^[0-9\-\+]{10,12}$") ] ], description: ['', [ Validators.required, Validators.minLength(2) ] ], job_id: [1], imgUrl: [] }); } ngOnInit() { const customer_id = +this.route.snapshot.paramMap.get('customer_id'); console.log(`this.route.snapshot.paramMap = ${JSON.stringify(this.route.snapshot.paramMap)}`); this.customerAccountService.getCustomerById(customer_id).subscribe((customer) => { this.customerForm = this.fb.group({ customer_id: [ customer.customer_id, Validators.required ], first_name: [ customer.first_name, [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z]*$') ] ], last_name: [ customer.last_name, [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z]*$') ] ], gender: ['Male'], address: [ customer.address, [ Validators.required, Validators.minLength(2) ] ], city: [ customer.city, [ Validators.required, Validators.minLength(2) ] ], email: [ customer.email, [ Validators.required, Validators.email, Validators.pattern("^[a-z][a-z0-9_\.]{5,32}@[a-z0-9]{2,}(\.[a-z0-9]{2,4}){1,2}$") ] ], phone_number: [ customer.phone_number, [ Validators.required, Validators.minLength(10), Validators.pattern("^[0-9\-\+]{10,12}$") ] ], description: [ customer.description, [ Validators.required, Validators.minLength(2) ] ], job_id: [1], imgUrl: [customer.imgUrl] }); if (customer.imgUrl !== null) { this.urlImage = customer.imgUrl; } }); //job Service this.jobService.getJobList().subscribe( res => this.jobList = res as [] ); } onFormSubmit() { let customer = this.customerForm.value; if (this.urlImage) { customer.imgUrl = this.urlImage; } console.log(this.customerForm.value); this.customerAccountService.editCustomer(customer).subscribe(); this.successfully(); // this.customerForm.reset(); } successfully(): void { Swal.fire({ icon: 'success', title: 'Successfully !', text: 'Updated Successfully !', }) } deleteCustomer(customer_id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted!', 'success' ), this.customerAccountService.deleteCustomter(customer_id).subscribe(); this.ngOnInit(); } }) } ngAfterViewInit(): void { setTimeout(() => { // this.firstItem.nativeElement.focus(); }, 250); this.startControlMonitoring(this.customerForm); } onSelectFile(event) { if (event.target.files && event.target.files[0]) { var reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); reader.onload = (event) => { this.urlImage = (event.target as any).result; } } } cancel(): void { Swal.fire({ title: 'Are you sure?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes' }).then((result) => { if (result.value) { this.router.navigate(['/listcustomer']); } }) } goBack(): void { this.location.back(); } } <file_sep>/src/app/shared/customer-account.service.ts import { Customer } from './../Models/customer.model'; import { Injectable } from '@angular/core'; import { HttpClient, HttpHandler, HttpHeaders } from '@angular/common/http'; import { environment } from './../../environments/environment'; import { Observable, of } from 'rxjs'; import { NgForm } from '@angular/forms'; import { catchError, tap, } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class CustomerAccountService { constructor(private http: HttpClient) { } //GET API: Customer Account List getCustomerList(): Observable<Customer[]> { return this.http.get<Customer[]>(environment.apiBaseURL + '/customer/AllCustomer'); } getCustomerById(customer_id: number): Observable<Customer> { const url = `${environment.apiBaseURL}/customer/customerbyid/${customer_id}`; return this.http.get<Customer>(url).pipe( // tap(selected => console.log(`selected = ${JSON.stringify(selected)}`)), // catchError(error => of(new Customer)) ); } getCustomerByJobId(job_id: number): Observable<Customer> { const url = `${environment.apiBaseURL}/customer/customerlist/${job_id}`; return this.http.get<Customer>(url).pipe( // tap(selected => console.log(`selected = ${JSON.stringify(selected)}`)), // catchError(error => of(new Customer)) ); } createCustomer(customer: Customer) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.post(environment.apiBaseURL + '/customer/createnewcustomer', customer); } editCustomer(customer: Customer) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.put(environment.apiBaseURL + '/customer/editcustomer', customer); } deleteCustomter(customer_id: number) { return this.http.delete(environment.apiBaseURL + '/customer/deletecustomer/' + customer_id); } } <file_sep>/src/app/shared/report.service.ts import { environment } from './../../environments/environment'; import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Job } from './../Models/job.model'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; const reportURL = 'http://192.168.145.99:5001/api'; @Injectable({ providedIn: 'root' }) export class ReportService { constructor( private http: HttpClient) { } getReportCusTomer(): Observable<string> { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.get<string>(reportURL + '/export/listCustomer'); } getReportJobList(): Observable<string> { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.get<string>(reportURL + '/export/joblist'); } getReportCusTomerByJob(job_id: number): Observable<string> { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; // const url = `${environment.apiBaseURL}/export/${job_id}`; return this.http.get<string>(reportURL + '/export/'+ job_id); } } <file_sep>/src/app/shared/job.service.ts import { environment } from './../../environments/environment'; import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Job } from './../Models/job.model'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class JobService { constructor(private http: HttpClient) { } getJobList() { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.get(environment.apiBaseURL + '/Jobs/JobList'); } getJobById (job_id: number): Observable<Job>{ const url = `${environment.apiBaseURL}/Jobs/GetJobById/${job_id}`; return this.http.get<Job>(url).pipe( // tap(selected => console.log(`selected = ${JSON.stringify(selected)}`)), // catchError(error => of(new Customer)) ); } createJob(job: Job) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.post(environment.apiBaseURL + '/Jobs/CreateNewJob',job); } editJob(job: Job){ const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.put(environment.apiBaseURL + '/Jobs/EditJob/', job); } deleteJob(job_id: number) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.delete(environment.apiBaseURL+ '/Jobs/DeleteJob/'+ job_id); } } <file_sep>/src/app/customer-account/customer-account.component.ts import { Location } from '@angular/common'; import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core'; import { FormBuilder, FormArray, Validators, FormGroup } from '@angular/forms'; import Swal from 'sweetalert2'; import { CrossFieldErrorMatcher } from '../infrastructure/cross-field-error-matcher'; import { FormComponentBase } from '../infrastructure/form-component-base'; import { RouterModule, Routes, Router } from '@angular/router'; //model import { Customer } from '../Models/customer.model'; //service import { JobService } from '../shared/job.service'; import { CustomerAccountService } from '../shared/customer-account.service'; @Component({ selector: 'app-customer-account', templateUrl: './customer-account.component.html', styleUrls: ['./customer-account.component.css'] }) export class CustomerAccountComponent extends FormComponentBase implements OnInit, AfterViewInit { jobList = []; customerForm: FormGroup; urlImage: any; base64textString: string; // @ViewChild('email') firstItem: ElementRef; errorMatcher = new CrossFieldErrorMatcher(); constructor(private jobService: JobService, private customerAccountService: CustomerAccountService, private fb: FormBuilder, private location: Location, private router: Router) { super(); this.validationMessages = { first_name: { required: 'First Name is required.', minlength: 'First Name minimum length is 2.', pattern: 'First Name minimum length 2, no special character.' }, last_name: { required: 'Last Name is required.', minlength: 'Last Name minimum length is 2.', pattern: 'Last Name minimum length 2, no special character.' }, address: { minlength: 'Last Name minimum length is 2.', required: 'Address is required.' }, city: { minlength: 'Last Name minimum length is 2.', required: 'City is required.' }, email: { required: 'Email is required.', pattern: 'Email is not properly formatted.', }, phone_number: { required: 'Phone number is required.', minlength: 'Phone number minimum length is 9.', maxlength: 'Phone number maximum length is 12.', pattern: 'Phone number minimum length 9, numbers only. No spaces.' }, description: { required: 'Description is required.' } }; this.formErrors = { first_name: '', last_name: '', address: '', city: '', email: '', phone_number: '', description: '', }; } ngOnInit() { this.customerForm = this.fb.group({ first_name: ['', [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z]*$') ] ], last_name: ['', [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z]*$') ] ], gender: ['Male'], address: ['', [ Validators.required, Validators.minLength(2) ] ], city: ['', [ Validators.required, Validators.minLength(2), ] ], email: ['', [ Validators.required, Validators.email, Validators.pattern("^[a-z][a-z0-9_\.]{5,32}@[a-z0-9]{2,}(\.[a-z0-9]{2,4}){1,2}$")] ], phone_number: ['', [ Validators.required, Validators.minLength(10), Validators.pattern("^[0-9\-\+]{10,12}$") ] ], description: ['', [ Validators.required, ] ], job_id: [1], imgUrl: [] }); this.jobService.getJobList().subscribe( res => this.jobList = res as [] ); } onFormSubmit() { let customer = this.customerForm.value; this.createCustomer(customer); } createCustomer(customer: Customer) { if (this.urlImage) { customer.imgUrl = this.urlImage; } console.log(customer); this.customerAccountService.createCustomer(customer).subscribe(); this.confirmRedirect(); // this.customerForm.reset(); } onSelectFile(event) { // called each time file input changes if (event.target.files && event.target.files[0]) { var reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); // read file as data url reader.onload = (event) => { // called once readAsDataURL is completed this.urlImage = (event.target as any).result; } } } ngAfterViewInit(): void { setTimeout(() => { // this.firstItem.nativeElement.focus(); }, 250); this.startControlMonitoring(this.customerForm); } ///Alert successfully(): void { Swal.fire({ icon: 'success', title: 'Successfully !', text: 'Created Successfully !', }) } confirmRedirect(): void { Swal.fire({ title: 'Success', icon: 'success', showCancelButton: true, confirmButtonColor: '#FF7F50', cancelButtonColor: '#3085d6', confirmButtonText: 'Back To List', cancelButtonText: 'Continue' }).then((result) => { if (result.value) { this.router.navigate(['/listcustomer']); } else { this.customerForm.reset(); return; } }) } cancel(): void { Swal.fire({ title: 'Are you sure?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes' }).then((result) => { if (result.value) { this.location.back(); } }) } // goBack(): void { this.location.back(); } } <file_sep>/src/app/Models/job.model.ts export class Job { job_id: number; job_code: number; job_name: string; job_description: string; totalCustomer: number; } <file_sep>/src/app/job-create/job-create.component.ts import { FormComponentBase } from './../infrastructure/form-component-base'; import { CrossFieldErrorMatcher } from './../infrastructure/cross-field-error-matcher'; import { Location } from '@angular/common'; import { Component, OnInit, AfterViewInit } from '@angular/core'; import { FormBuilder, FormArray, Validators, FormGroup } from '@angular/forms'; import Swal from 'sweetalert2'; //model import { Customer } from '../Models/customer.model'; import { Job } from './../Models/job.model'; import { RouterModule, Routes, Router } from '@angular/router'; //service import { JobService } from '../shared/job.service'; import { CustomerAccountService } from '../shared/customer-account.service'; @Component({ selector: 'app-job-create', templateUrl: './job-create.component.html', styleUrls: ['./job-create.component.css'] }) export class JobCreateComponent extends FormComponentBase implements OnInit, AfterViewInit { customerList = []; jobForm: FormGroup; errorMatcher = new CrossFieldErrorMatcher(); constructor(private jobService: JobService, private customerAccountService: CustomerAccountService, private location: Location, private fb: FormBuilder, private router: Router) { super(); this.validationMessages = { job_code: { required: 'Code is required.', minlength: 'Code minimum length is 2.', pattern: 'Code minimum length 2, no special character.' }, job_name: { required: 'Name is required.', minlength: 'Name minimum length is 2.', }, job_description: { required: 'Description is required.', minlength: 'Description minimum length is 2.', }, }; this.formErrors = { job_code: '', job_name: '', job_description: '' } } ngOnInit() { this.jobForm = this.fb.group({ job_code: [ '', [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z0-9]*$') ] ], job_name: [ '', [ Validators.required, Validators.minLength(2) ] ], job_description: [ '', [ Validators.required, Validators.minLength(2) ] ] }); this.customerAccountService.getCustomerList().subscribe( res => this.customerList = res as [] ) } onFormSubmit() { let job = this.jobForm.value; this.createJob(job); } createJob(job: Job) { this.jobService.createJob(job).subscribe( (data) => { console.log(data) } ); console.log(job); this.confirmRedirect(); } ngAfterViewInit(): void { setTimeout(() => { // this.firstItem.nativeElement.focus(); }, 250); this.startControlMonitoring(this.jobForm); } goBack(): void { this.location.back(); } ///Alert successfully(): void { Swal.fire({ icon: 'success', title: 'Successfully !', text: 'Created Successfully !', }) } confirmRedirect(): void { Swal.fire({ title: 'Success', icon: 'success', showCancelButton: true, confirmButtonColor: '#FF7F50', cancelButtonColor: '#3085d6', confirmButtonText: 'Back To List', cancelButtonText: 'Continue' }).then((result) => { if (result.value) { this.router.navigate(['/joblist']); } else { this.jobForm.reset(); return; } }) } cancel(): void { Swal.fire({ title: 'Are you sure?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes' }).then((result) => { if (result.value) { this.location.back(); } }) } // } <file_sep>/src/app/job-edit/job-edit.component.ts import { FormComponentBase } from './../infrastructure/form-component-base'; import { Component, OnInit, AfterViewInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { Validators, FormGroup, FormBuilder } from '@angular/forms'; //library import Swal from 'sweetalert2'; //model import { Job } from '../Models/job.model'; //service import { CustomerAccountService } from './../shared/customer-account.service'; import { JobService } from './../shared/job.service'; import { ReportService } from '../shared/report.service'; @Component({ selector: 'app-job-edit', templateUrl: './job-edit.component.html', styleUrls: ['./job-edit.component.css'] }) export class JobEditComponent extends FormComponentBase implements OnInit, AfterViewInit { jobList: Job[] = []; job: Job; jobForm: FormGroup; constructor( private fb: FormBuilder, private route: ActivatedRoute, private location: Location, private customerAccountService: CustomerAccountService, private jobService: JobService, private reportService: ReportService, ) { super(); this.validationMessages = { job_code: { required: 'Code is required.', minlength: 'Code minimum length is 2.', pattern: 'Code minimum length 2, no special character.' }, job_name: { required: 'Name is required.', minlength: 'Name minimum length is 2.', pattern: 'Name minimum length 2, no special character.' }, job_description: { required: 'Description is required.', minlength: 'Description minimum length is 2.', pattern: 'Description minimum length 2, no special character.' }, }; this.formErrors = { job_code: '', job_name: '', job_description: '' } } ngAfterViewInit(): void { setTimeout(() => { // this.firstItem.nativeElement.focus(); }, 250); this.startControlMonitoring(this.jobForm); } ngOnInit() { const job_id = +this.route.snapshot.paramMap.get('job_id'); console.log(`this.route.snapshot.paramMap = ${JSON.stringify(this.route.snapshot.paramMap)}`); this.jobService.getJobById(job_id).subscribe((job) => { this.jobForm = this.fb.group({ job_id: [job_id, Validators.required], job_code: [job.job_code, [ Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z0-9]*$') ] ], job_name: [job.job_name, [ Validators.required, Validators.minLength(2) ] ], job_description: [job.job_description, [ Validators.required, Validators.minLength(2) ] ] }) }); } onFormSubmit() { let job = this.jobForm.value; console.log(this.jobForm.value); this.jobService.editJob(job).subscribe(); this.successfully(); // this.customerForm.reset(); } // deleteJob(job_id) { // Swal.fire({ // title: 'Are you sure?', // text: "You won't be able to revert this!", // icon: 'warning', // showCancelButton: true, // confirmButtonColor: '#3085d6', // cancelButtonColor: '#d33', // confirmButtonText: 'Yes, delete it!' // }).then((result) => { // if (result.value) { // Swal.fire( // 'Deleted!', // 'Your file has been deleted!', // 'success' // ), // this.jobService.deleteJob(job_id).subscribe( // (data) => { console.log(data) } // ); // this.ngOnInit(); // } // }) // } ///Alert successfully(): void { Swal.fire({ icon: 'success', title: 'Successfully !', text: 'Created Successfully !', }) } cancel(): void { Swal.fire({ title: 'Are you sure?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes' }).then((result) => { if (result.value) { this.location.back(); } }) } // goBack(): void { this.location.back(); } } <file_sep>/src/app/customer-detail/customer-detail.component.ts import { Customer } from './../Models/customer.model'; import { CustomerAccountService } from './../shared/customer-account.service'; import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core'; import {ActivatedRoute, NavigationExtras} from '@angular/router'; import { RouterModule, Routes, Router } from '@angular/router'; import { Location } from '@angular/common'; import Swal from 'sweetalert2'; //model import { Job } from './../Models/job.model'; //services import { JobService } from './../shared/job.service'; @Component({ selector: 'app-customer-detail', templateUrl: './customer-detail.component.html', styleUrls: ['./customer-detail.component.css'] }) export class CustomerDetailComponent implements OnInit { @Input() customer: Customer @Output() DeletedId = new EventEmitter<number>(); // customer: Customer; constructor( private route: ActivatedRoute, private router: Router, private location: Location, private customerAccountService: CustomerAccountService, private jobService: JobService) { } ngOnInit() { this.getCustomerById(); } getCustomerById(): void { // const customer_id = +this.route.snapshot.params.get('customer_id'); const customer_id = +this.route.snapshot.paramMap.get('customer_id'); console.log(`this.route.snapshot.paramMap = ${JSON.stringify(this.route.snapshot.paramMap)}`); this.customerAccountService.getCustomerById(customer_id).subscribe(customer => this.customer = customer); } deleteCustomer(customer_id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted!', 'success' ), this.customerAccountService.deleteCustomter(customer_id).subscribe(); let navigationExtra: NavigationExtras = { queryParams : { "deletedId":customer_id } } // this.router.navigate(['/listcustomer'],navigationExtra); this.goBack(); this.ngOnInit(); } }) } cancel(): void { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted!', 'success' ), this.ngOnInit(); } }) } goBack(): void { this.location.back(); } } <file_sep>/src/app/customer-account-list/customer-account-list.component.ts import { MatSort, MatPaginator, MatTableDataSource } from '@angular/material/'; import { Job } from './../Models/job.model'; import { Component, OnInit, Output, EventEmitter, ViewChild } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { Location } from '@angular/common'; import Swal from 'sweetalert2'; import { ReportService } from '../shared/report.service'; // import { Customer } from '../Models/customer.model'; //service import { CustomerAccountService } from '../shared/customer-account.service'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-customer-account-list', templateUrl: './customer-account-list.component.html', styleUrls: ['./customer-account-list.component.css'] }) export class CustomerAccountListComponent implements OnInit { customer: Customer[] = []; ELEMENT_DATA: Customer[]; displayedColumns: string[] = [ 'first_name', 'last_name', 'gender', 'address', 'city', 'email', 'phone_number', 'description', 'job_name', 'imgUrl', 'customer_id']; @ViewChild(MatSort, { static: true }) sort: MatSort; @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator; dataSource = new MatTableDataSource<Customer>(this.ELEMENT_DATA); constructor(private customerAccountService: CustomerAccountService, private location: Location, private reportService: ReportService, private route: ActivatedRoute, ) { this.route.queryParams.subscribe(params => { this.ngOnInit(); }) } ngOnInit() { this.customerAccountService.getCustomerList().subscribe( customer => { this.dataSource.data = customer as Customer[] // console.log(customer) } ); this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; } deleteCustomer(customer_id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted!', 'success' ), this.customerAccountService.deleteCustomter(customer_id).subscribe( data => { this.ngOnInit() }); } }); } getReportJobList() { this.reportService.getReportCusTomer().subscribe( data => { window.open(data) } ); } apllyFilter(filterValue: string) { this.dataSource.filter = filterValue.trim().toLowerCase(); } goBack(): void { this.location.back(); } } <file_sep>/src/app/Models/customer.model.ts export class Customer { customer_id: number; first_name: string; last_name: number; gender: string; address: string; city: string; email: string; phone_number: string; description: string; job_name: string; imgUrl: string; }<file_sep>/src/app/app-routing.module.ts import { JobDetailComponent } from './job-detail/job-detail.component'; import { JobEditComponent } from './job-edit/job-edit.component'; import { JobListComponent } from './job-list/job-list.component'; import { CustomerEditComponent } from './customer-edit/customer-edit.component'; import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; //models import {Customer} from './Models/customer.model'; import{CustomerAccountComponent} from './customer-account/customer-account.component'; import {CustomerAccountListComponent} from './customer-account-list/customer-account-list.component'; import { CustomerDetailComponent } from './customer-detail/customer-detail.component'; import { JobCreateComponent } from './job-create/job-create.component'; const routes: Routes = [ {path: '',redirectTo:'/listcustomer',pathMatch: 'full'}, {path: 'createcustomer', component: CustomerAccountComponent}, {path: 'listcustomer', component: CustomerAccountListComponent}, {path: 'customerdetail/:customer_id', component: CustomerDetailComponent}, {path: 'customerdetail/:customer_id/edit', component: CustomerEditComponent}, {path: 'createjob', component: JobCreateComponent}, {path: 'joblist', component: JobListComponent}, {path: 'jobdetail/:job_id', component: JobDetailComponent}, {path: 'jobdetail/:job_id/edit', component: JobEditComponent}, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/job-list/job-list.component.ts import { Component, OnInit, Output, EventEmitter, ViewChild } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { Location } from '@angular/common'; import { Observable } from 'rxjs'; import Swal from 'sweetalert2'; //model import { Job } from './../Models/job.model'; //services import { JobService } from './../shared/job.service'; import {ReportService} from '../shared/report.service'; import { MatTableDataSource, MatSort, MatPaginator } from '@angular/material/'; @Component({ selector: 'app-job-list', templateUrl: './job-list.component.html', styleUrls: ['./job-list.component.css'] }) export class JobListComponent implements OnInit { job: Job[] = []; ELEMENT_DATA: Job[]; displayedColumns: string[] = [ 'job_code', 'job_name', 'job_description', 'totalCustomer', 'job_id']; @ViewChild(MatSort, { static: true }) sort: MatSort; @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator; // dataSource = new MatTableDataSource<Job>(this.ELEMENT_DATA); dataSource = new MatTableDataSource<Job>(this.ELEMENT_DATA); constructor(private jobService: JobService, private reportService: ReportService, private location: Location) { } ngOnInit() { this.jobService.getJobList().subscribe( Subdata => { this.dataSource.data = Subdata as Job[] // console.log(Subdata) } ); this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; } deleteJob(job_id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted!', 'success' ),this.jobService.deleteJob(job_id).subscribe(data => {this.ngOnInit();}); } }) } // get Report getReportJobList(){ this.reportService.getReportJobList().subscribe( data => {window.open(data)} ); } apllyFilter(filterValue: string) { this.dataSource.filter = filterValue.trim().toLowerCase(); } cancel(): void { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted!', 'success' ), this.ngOnInit(); } }) } goBack(): void { this.location.back(); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import {HttpClientModule} from '@angular/common/http'; //service import {CustomerAccountService} from './shared/customer-account.service'; import {JobService} from './shared/job.service'; // import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; //material import { MatTableModule } from '@angular/material/table'; import {MatSortModule} from '@angular/material/sort'; import {MatPaginatorModule} from '@angular/material/paginator'; import {MatButtonModule} from '@angular/material/button'; import {MatIconModule} from '@angular/material/icon'; import {MatInputModule} from '@angular/material/input'; import {MatDialogModule} from '@angular/material/dialog'; import {MatRadioModule} from '@angular/material/radio'; import {MatGridListModule} from '@angular/material/grid-list'; //Component import { CustomerAccountComponent } from './customer-account/customer-account.component'; import { CustomerAccountListComponent } from './customer-account-list/customer-account-list.component'; import { CustomerDetailComponent } from './customer-detail/customer-detail.component'; import { CustomerEditComponent } from './customer-edit/customer-edit.component'; import { JobCreateComponent } from './job-create/job-create.component'; import { JobDetailComponent } from './job-detail/job-detail.component'; import { JobListComponent } from './job-list/job-list.component'; import { JobEditComponent } from './job-edit/job-edit.component'; @NgModule({ declarations: [ AppComponent, CustomerAccountComponent, CustomerAccountListComponent, CustomerDetailComponent, CustomerEditComponent, JobCreateComponent, JobDetailComponent, JobListComponent, JobEditComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, ReactiveFormsModule, BrowserAnimationsModule, MatTableModule, MatSortModule, MatPaginatorModule, MatButtonModule, MatIconModule, MatInputModule, MatDialogModule, MatRadioModule, MatGridListModule ], providers: [ JobService, CustomerAccountService ], bootstrap: [ AppComponent ], entryComponents: [ CustomerAccountComponent ] }) export class AppModule { }
28f9d7c5f519abd98bf8ddc32a75fa5e011c6f56
[ "TypeScript" ]
14
TypeScript
lequangquochung/Angular-Material
f5d6d17cb44079e80ecf468cc840e3aac9bfe1ce
2f0c52798b40e25f4de7b7e43908911d62eda592
refs/heads/main
<repo_name>sarandeepmannam/ASSIGNMENT4<file_sep>/Assignment4.py import matplotlib.pyplot as plt import numpy as np import math def F(x): return math.sqrt(1/math.sqrt(2*math.pi))*math.exp(-pow(x-1,2)/2) X=np.linspace(-3,5,100000) Y=[F(x) for x in X] plt.plot(X,Y) plt.xlabel('$x$') plt.ylabel('$f_X(x)$') plt.title('PDF') plt.show
e9ae8d78bde68c18fe62e813910bc4de5aeab7aa
[ "Python" ]
1
Python
sarandeepmannam/ASSIGNMENT4
242970d3a9e81809d9615ac082de617bddb2b374
f37fa050782dac2b68c32ba080d2b5b939bd659c
refs/heads/master
<file_sep>pub mod batch; pub mod helper; pub mod prover; pub mod rndoracle; pub mod zkproof; <file_sep>/*********************************************************************** This source file implements dense representation of sparse matrix. ***********************************************************************/ pub use super::vector::{DenseVector, SparseVector}; use pairing::Field; use sprs::{CsMat, CsVecView}; use std::ops::Index; #[derive(Clone)] pub struct DenseMatrix<F> { pub value: CsMat<F>, zero: F, } impl<F> Index<(usize, usize)> for DenseMatrix<F> where F: Field, { type Output = F; fn index(&self, index: (usize, usize)) -> &F { match self.value.get(index.0, index.1) { None => &self.zero, Some(x) => x, } } } pub trait SparseMatrix<F: Field> { fn new(depth: usize, width: usize) -> Self; fn shape(&self) -> (usize, usize); fn append(&mut self, index: &[usize], value: &[F]); fn insert(&mut self, row: usize, col: usize, value: F); } impl<F: Field> SparseMatrix<F> for DenseMatrix<F> { fn new(depth: usize, width: usize) -> Self { Self { value: CsMat::<F>::zero((depth, width)), zero: F::zero(), } } fn shape(&self) -> (usize, usize) { (self.value.rows(), self.value.cols()) } fn append(&mut self, index: &[usize], value: &[F]) { let len = self.value.shape().1; let f = std::mem::replace(&mut self.value, CsMat::<F>::zero((0, 0))); self.value = f.append_outer_csvec(CsVecView::<F>::new_view(len, index, value).unwrap()); } fn insert(&mut self, row: usize, col: usize, value: F) { self.value.insert(row, col, value); } } <file_sep>/*************************************************************************************************** This source file implements Sonic's performance test. The following tests are implemented: 1. This tests the performance of Sonic prover/helper/verifier functionality against a collection of computation statements that are EC group element checks similar to group_element_check_test The collection consists of 1K statements initialised as vector of witnesses to be proved and verified in zero-knowledge ***************************************************************************************************/ use circuits::constraint_system::{CircuitGate, ConstraintSystem, Witness}; use colored::Colorize; use commitment::urs::URS; use pairing::{bls12_381::Bls12, Engine, Field, PrimeField}; use polynomials::univariate::Univariate; use protocol::batch::{BatchProof, ProverProof}; use rand::OsRng; use sprs::CsVec; use std::io; use std::io::Write; use std::time::Instant; #[test] fn sonic_performance_test() { test::<Bls12>(); } fn test<E: Engine>() { let mut rng = OsRng::new().unwrap(); // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); // Jubjub Edwards form coefficient d: y^2-x^2=1+d*y^2*x^2 let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let mut negd = d; negd.negate(); // our circuit cinstraint system let mut cs = ConstraintSystem::<E::Fr>::create(3); cs.append('a', &[0], &[one]); cs.append('a', &[1], &[one]); cs.append('a', &[], &[]); cs.append('a', &[2], &[one]); cs.append('a', &[2], &[negd]); cs.append('b', &[0], &[neg1]); cs.append('b', &[1], &[neg1]); cs.append('b', &[2], &[one]); cs.append('b', &[], &[]); cs.append('b', &[2], &[one]); cs.append('c', &[], &[]); cs.append('c', &[], &[]); cs.append('c', &[1], &[negd]); cs.append('c', &[0], &[neg1]); cs.append('c', &[2], &[d]); cs.k = CsVec::<E::Fr>::new(5, vec![4], vec![negd]); // generate sample URS let depth = cs.k.dim() + 4 * cs.a.shape().1 + 8; let urs = URS::<E>::create( depth, vec![ depth, cs.a.shape().1 + 1, cs.a.shape().1 * 2 + 1, cs.a.shape().1 + cs.a.shape().0 + 1, ], Univariate::<E::Fr>::rand(&mut rng), Univariate::<E::Fr>::rand(&mut rng), ); // We have the constraint system. Let's choose examples of satisfying witness for Jubjub // y^2-x^2=1+d*y^2*x^2 let mut points = Vec::<(E::Fr, E::Fr)>::new(); let mut witness_batch = Vec::<Witness<E::Fr>>::new(); for _ in 0..1 { points.push(( E::Fr::from_str( "47847771272602875687997868466650874407263908316223685522183521003714784842376", ) .unwrap(), E::Fr::from_str( "14866155869058627094034298869399931786023896160785945564212907054495032619276", ) .unwrap(), )); points.push(( E::Fr::from_str( "23161233924022868901612849355320019731199638537911088707556787060776867075186", ) .unwrap(), E::Fr::from_str( "46827933816106251659874509206068992514697956295153175925290603211849263285943", ) .unwrap(), )); points.push(( E::Fr::from_str( "21363808388261502515395491234587106714641012878496416205209487567367794065894", ) .unwrap(), E::Fr::from_str( "35142660575087949075353383974189325596183489114769964645075603269317744401507", ) .unwrap(), )); points.push(( E::Fr::from_str( "48251804265475671293065183223958159558134840367204970209791288593670022317146", ) .unwrap(), E::Fr::from_str( "39492112716472193454928048607659273702179031506049462277700522043303788873919", ) .unwrap(), )); points.push(( E::Fr::from_str( "26076779737997428048634366966120809315559597005242388987585832521797042997837", ) .unwrap(), E::Fr::from_str( "2916200718278883184735760742052487175592570929008292238193865643072375227389", ) .unwrap(), )); points.push(( E::Fr::from_str( "6391827799982489600548224857168349263868938761394485351819740320403055736778", ) .unwrap(), E::Fr::from_str( "26714606321943866209898052587479168369119695309696311252068260485776094410355", ) .unwrap(), )); points.push(( E::Fr::from_str( "34225834605492133647358975329540922898558190785910349822925459742326697718965", ) .unwrap(), E::Fr::from_str( "42503065208497349411091392685178794164009360876034587048702740318812028372175", ) .unwrap(), )); points.push(( E::Fr::from_str( "39706901109420478047209734657640449984347408718517226120651505259450485889935", ) .unwrap(), E::Fr::from_str( "44842351859583855521445972897388346257004580582454107427806918461747670509399", ) .unwrap(), )); points.push(( E::Fr::from_str( "28360026567573852013315702401149784452531421169317971653481741133982080381509", ) .unwrap(), E::Fr::from_str( "34586051224595854378884048103686100857425100914523816028360306191122507857625", ) .unwrap(), )); points.push(( E::Fr::from_str( "45719850001957217643735562111452029570487585222534789798311082643976688162166", ) .unwrap(), E::Fr::from_str( "51398963553553644922019770691279615862813421731845531818251689044792926267778", ) .unwrap(), )); } // check whether the points are on the curve println!( "{}", "Preparing the computation statements for the prover".green() ); let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let one = E::Fr::one(); let mut start = Instant::now(); for i in 0..points.len() { let (x, y) = points[i]; let mut xx = x; let mut yy = y; xx.square(); yy.square(); let mut yy_xx_1 = yy; yy_xx_1.sub_assign(&xx); yy_xx_1.sub_assign(&one); let mut dxx = d; dxx.mul_assign(&xx); let mut dxxyy = dxx; dxxyy.mul_assign(&yy); assert_eq!(yy_xx_1, dxxyy); /* The point is on the curve, let's compute the witness and verify the circuit satisfiability for each point. Wire labels a=[y, x, yy] b=[y, x, dxx] c=[yy, xx, yy-xx-1] */ let mut witness = Witness::<E::Fr>::create(3, &mut rng); witness.gates[0] = CircuitGate::<E::Fr> { a: y, b: y, c: yy }; witness.gates[1] = CircuitGate::<E::Fr> { a: x, b: x, c: xx }; witness.gates[2] = CircuitGate::<E::Fr> { a: yy, b: dxx, c: yy_xx_1, }; // verify the circuit satisfiability by the computed witness assert_eq!(cs.verify(None, &witness), true); // add the witness to the batch witness_batch.push(witness); print!("{:?}\r", i); io::stdout().flush().unwrap(); } println!("{}{:?}", "Execution time: ".yellow(), start.elapsed()); // Create zk-proof batch of the statements let s = String::from( "In the blockchain setting this has to come from the block context" ); let batch_context: Vec<u8> = s.into_bytes(); let mut prover_proofs = Vec::<(ProverProof<E>, Option<CsVec<E::Fr>>)>::new(); // create the vector of prover's proofs for the given witness vector println!("{}", "Prover zk-proofs computation".green()); start = Instant::now(); for i in 0..points.len() { match ProverProof::<E>::create(&witness_batch[i], &cs, None, &urs) { Err(error) => { panic!("Failure creating the prover's proof: {}", error); } Ok(proof) => prover_proofs.push((proof, None)), } if i % 10 == 0 { print!("{:?}\r", i); io::stdout().flush().unwrap(); } } println!("{}{:?}", "Execution time: ".yellow(), start.elapsed()); // Verify the batch of prover's zk-proofs for the given witness vector and create the helper's // batch. println!("{}", "Helper zk-proofs computation".green()); start = Instant::now(); match BatchProof::<E>::create(&batch_context, &prover_proofs, &cs, &urs, &mut rng) { Err(error) => { panic!(error); } Ok(mut batch) => { for i in 0..batch.batch.len() { match &batch.batch[i].helper { Err(error) => { panic!("Failure verifying the prover's proof: {}", error); } Ok(_) => continue, } } println!("{}{:?}", "Execution time: ".yellow(), start.elapsed()); println!("{}", "Verifier zk-proofs verification".green()); start = Instant::now(); match batch.verify( &batch_context, &cs, &vec![None; batch.batch.len()], &urs, &mut rng ) { Err(error) => { panic!("Failure verifying the zk-proof: {}", error); } Ok(_) => {} } println!("{}{:?}", "Execution time: ".yellow(), start.elapsed()); } } } <file_sep>[workspace] members = [ "protocol", "commitment", "polynomials", "circuits", ] [profile.release] lto = true panic = 'abort' codegen-units = 1 <file_sep>/******************************************************************************************** This source file implements batch zk-proof primitives. This primitive is the top-level aggregate of Sonic zk-proof format that provides means of optimized batch verification of the individual constituent zk-proofs with a single evaluation of a bivariate polynomial for all the proofs in the batch. It consists, besides the batch proof group element values, the vector of individual zk-proofs that aggregate ProverProof and HelperProof at the lower aggregation level. *********************************************************************************************/ pub use super::helper::HelperProof; pub use super::prover::ProverProof; pub use super::rndoracle::{ProofError, RandomOracleArgument}; pub use super::zkproof::ZkProof; use circuits::constraint_system::{ConstraintSystem}; use commitment::urs::URS; use merlin::Transcript; use pairing::{Engine, Field}; use rayon::prelude::*; use rand::OsRng; use sprs::CsVec; pub struct BatchProof<E: Engine> { // Commitment to univariate polynomial s(u, X) pub sux_comm: E::G1Affine, // Commitment sux_comm to s(u, X) opening at v proof pub sux_v_prf: E::G1Affine, // batch of proof tuples with verification status pub batch: Vec<ZkProof<E>>, } impl<E: Engine> BatchProof<E> { // This function constructs helper's batch zk-proof from the // constraint system and prover's proofs against URS instance // context: batch context for the random oracle argument // prover: batch of prover's proofs with optional public parameter updates // cs: constraint system // urs: universal reference string // RETURN: helper's batch zk-proof pub fn create( context: &Vec<u8>, provers: &Vec<(ProverProof<E>, Option<CsVec<E::Fr>>)>, cs: &ConstraintSystem<E::Fr>, urs: &URS<E>, rng: &mut OsRng, ) -> Result<Self, ProofError> { // the helper's transcript of the random oracle argument let mut argument = Transcript::new(&[]); // batch context for the random oracle argument argument.append_message(b"bytes", context); // query random scalar challenge from verifier let u: E::Fr = argument.challenge(); // compute s(u, X) polynomial let rslt = cs.evaluate_s(u, true); if rslt.is_none() { return Err(ProofError::SuXvEvalComputation); } let sux = rslt.unwrap(); // commit to univariate polynomial s(u, X) let sux_comm = urs.commit(&sux, cs.a.shape().1 + cs.a.shape().0 + 1); argument.commit_point(&sux_comm); // query random scalar challenge from verifier let v: E::Fr = argument.challenge(); // helper opens the polynomial s(u, X) commitment at v let rslt = urs.open(&sux, v); if rslt.is_none() { return Err(ProofError::SuXvPrfComputation); } let sux_v_prf = rslt.unwrap(); // retrieve random oracle values let mut oracles: Vec<(E::Fr, E::Fr, E::Fr, E::Fr)> = Vec::new(); for proof in provers.iter() { oracles.push(proof.0.oracles(cs, &proof.1)) } // assemble the prover's proofs into a proof vector over for verification over the batched EC pairings let mut vecver: bool = false; let mut prfrx1: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); let mut prfbatch: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); for (proof, oracle) in provers.iter().zip(oracles.iter()) { let rslt = cs.evaluate_s(oracle.0, true); if rslt.is_none() { return Err(ProofError::SXyxPrfComputation); } let sxy = rslt.unwrap(); // evaluate k(Y) at oracle.1 let ky = cs.evaluate_k(proof.1.clone(), oracle.1); match proof.0.txy((Some(ky), sxy.evaluate(oracle.1))) { Err(_) => { vecver = true; break; } // vector verification failed, will verify individual proofs Ok(txy) => { prfrx1.push(( oracle.2, E::Fr::one(), vec![(proof.0.rx1_comm, proof.0.rx1_xy_evl, cs.a.shape().1 + 1)], proof.0.rx1_xy_prf, )); prfbatch.push(( oracle.0, oracle.3, vec![ (proof.0.txy_comm, txy, urs.gnax.len()), (proof.0.rx1_comm, proof.0.rx1_x_evl, cs.a.shape().1 + 1), ], proof.0.batch_x_prf, )); } } } // verify the assembled vector proof rx1_xy_prf against the commitment rx1_comm and evaluations rx1_xy_evl // verify the assembled vector proof batch_x_prf against the commitments rx1_comm & txy_comm // and evaluations rx1_x_evl and the computed evaluations t(x, y) of the bivariate polynomial // t(X, Y) at the points (x, y) if urs.verify(&vec![prfrx1, prfbatch], rng) == false { vecver = true; } // assemble the individual proofs in parallel Ok ( BatchProof { sux_comm, sux_v_prf, batch: provers.par_iter().map ( |prover| { let mut prover= prover.clone(); let helper = HelperProof::create(&mut prover.0, cs, prover.1, &sux, urs, vecver, u); ZkProof { prover: prover.0, helper: helper} } ).collect(), } ) } // This function verifies the batch zk-proof // context: batch context for the random oracle argument // cs: constraint system // urs: universal reference string // RETURN: verification status pub fn verify( &mut self, context: &Vec<u8>, cs: &ConstraintSystem<E::Fr>, k: &Vec<Option<CsVec<E::Fr>>>, urs: &URS<E>, rng: &mut OsRng, ) -> Result<bool, ProofError> { // the helper's transcript of the random oracle argument let mut argument = Transcript::new(&[]); // batch context for the random oracle argument argument.append_message(b"bytes", context); // query random scalar challenge from verifier let u: E::Fr = argument.challenge(); // add s(u, X) commitment to the context argument.commit_point(&self.sux_comm); // query random scalar challenge from verifier let v: E::Fr = argument.challenge(); // evaluate s(X, Y) at (u, v) let suv: E::Fr; match cs.evaluate_s(u, true) { None => return Err(ProofError::SuXvEvalComputation), Some(evl) => match evl.evaluate(v) { None => return Err(ProofError::SuXvEvalComputation), Some(evl) => suv = evl, }, } // retrieve random oracle values for multipoint evaluation over the vector let mut oracles: Vec<(E::Fr, E::Fr, E::Fr, E::Fr)> = Vec::new(); for (proof, k) in self.batch.iter().zip(k.iter()) { oracles.push(proof.prover.oracles(cs, &k)) } // verify individual proofs vectored over EC pairings let mut prfsxy: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); let mut prfrx1: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); let mut prfbatch: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); let mut prfsux: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); // verify the proof sux_v_prf against the commitment sux_comm and the computed above evaluation s(u, v) prfsux.push(( v, E::Fr::one(), vec![(self.sux_comm, suv, cs.a.shape().1 + cs.a.shape().0 + 1)], self.sux_v_prf, )); for ((proof, oracle), k) in self.batch.iter().zip(oracles.iter()).zip(k.iter()) { match (&proof.helper, proof.txy(Some(cs.evaluate_k(k.clone(), oracle.1)))) { (Err(_), _) => return Err(ProofError::ProverVerification), (_, Err(err)) => return Err(err), (Ok(helper), Ok(txy)) => { prfsux.push(( oracle.1, E::Fr::one(), vec![( self.sux_comm, helper.sxy_u_evl, cs.a.shape().1 + cs.a.shape().0 + 1, )], helper.sux_y_prf, )); prfsxy.push(( u, E::Fr::one(), vec![(helper.sxy_comm, helper.sxy_u_evl, cs.a.shape().1 * 2 + 1)], helper.sxy_u_prf, )); prfrx1.push(( oracle.2, E::Fr::one(), vec![( proof.prover.rx1_comm, proof.prover.rx1_xy_evl, cs.a.shape().1 + 1, )], proof.prover.rx1_xy_prf, )); prfbatch.push(( oracle.0, oracle.3, vec![ (proof.prover.txy_comm, txy, urs.gnax.len()), ( proof.prover.rx1_comm, proof.prover.rx1_x_evl, cs.a.shape().1 + 1, ), (helper.sxy_comm, helper.sxy_x_evl, cs.a.shape().1 * 2 + 1), ], proof.prover.batch_x_prf, )); } } //if self.batch[i].verify(u, self.sux_comm, cs, urs) == false {return Err(ProofError::ProverVerification);} //This would be if verified individually } // Verify the assembled vector proofs. First, verify the helper's proofs // verify the proof sux_y_prf against the commitment sux_comm and the evaluation sxy_u_evl=s(u, y) // verify the proof sxy_u_prf against the commitment sxy_comm and the evaluation sxy_u_evl=s(u, y) // verify the proof rx1_xy_prf against the commitment rx1_comm and evaluation rx1_xy_evl // verify the proof batch_x_prf against the commitments sxy_comm, rx1_comm & txy_comm and evaluations // sxy_x_evl, rx1_x_evl and the computed evaluation t(x, y) of the bivariate polynomial t(X, Y) // at the point (x, y) if urs.verify(&vec![prfsux, prfsxy, prfrx1, prfbatch], rng) == false { return Err(ProofError::ProverVerification); } Ok(true) } } <file_sep>/***************************************************************************************************************** This source file implements Sonic computation circuit gate primitive. Sonic factors out the linear relations for the computation into the system of linear constraints. The computation circuit, modulo the linear relations, consists of multiplicative gates that have two inputs and one output: Left input A Right input B Output C *****************************************************************************************************************/ use pairing::Field; #[derive(Clone)] pub struct CircuitGate<F: Field> { pub a: F, // left input wire pub b: F, // right input wire pub c: F, // output wire } impl<F: Field> CircuitGate<F> { // This function creates zero-instance circuit gate pub fn create() -> Self { Self { a: F::zero(), b: F::zero(), c: F::zero(), } } } <file_sep>[package] name = "polynomials" version = "0.1.0" authors = ["IOHK"] edition = "2018" [dependencies.pairing] version = "0.14.2" features = ["u128-support"] [dependencies] merlin = "1.1.0" rand = "0.4" colored = "1.8" rand_core = { version = "0.5" } <file_sep>/***************************************************************************************************************** This source file implements Sonic Constraint System primitive. Sonic constraint system is defined by: Labeling of the circuit wires that provide input and carry output values to/from the multiplicative gates of the circuit. The labeling is defined as three vectors of wire labels: Left input A Right input B Output C Set of linear constraint equations on the set of wire labels with coefficients Set of left input coefficient vectors U Set of right input coefficient vectors V Set of output coefficient vectors W Set of scalar values k Given the above, Sonic constrains the proved statement computation with: Multiplicative constraint system of equations AxB=C Linear constraint system of equations A*U+B*V+C*W=k for any assignment of values to the variables A, B & C of the constrained computation that satisfy the computation circuit. Here x means Hadamard (component-wise) Vector Multiplication and * means Cartesian Vector Multiplication. Sonic constraint system is defined as the wire label vectors and sets of linear constraint vectors and scalar values: a = […] b = […] c = […] u = [[…], …, […]] v = [[…], …, […]] w = [[…], …, […]] k = […] *****************************************************************************************************************/ extern crate bincode; pub use super::gate::CircuitGate; pub use super::witness::Witness; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use pairing::{Field, PrimeField}; use polynomials::univariate::Univariate; use sprs::{CsMat, CsVec, CsVecView}; use std::fmt; use std::io::{self, Read, Write}; #[derive(Clone)] pub struct ConstraintSystem<F: Field> { pub a: CsMat<F>, // left input wire coefficients pub b: CsMat<F>, // right input wire coefficients pub c: CsMat<F>, // output wire coefficients pub k: CsVec<F>, // public parameters } impl<F: PrimeField> ConstraintSystem<F> { // This function creates CS instance for given depth n // n: depth of the circuit pub fn create(n: usize) -> Self { Self { a: CsMat::<F>::zero((0, n)), b: CsMat::<F>::zero((0, n)), c: CsMat::<F>::zero((0, n)), k: CsVec::<F>::empty(0), } } // this function appends sparse row to the matrix pub fn append(&mut self, matrix: char, index: &[usize], value: &[F]) { match matrix { 'a' => { let len = self.a.shape().1; let f = std::mem::replace(&mut self.a, CsMat::<F>::zero((0, 0))); self.a = f.append_outer_csvec(CsVecView::<F>::new_view(len, index, value).unwrap()); } 'b' => { let len = self.b.shape().1; let f = std::mem::replace(&mut self.b, CsMat::<F>::zero((0, 0))); self.b = f.append_outer_csvec(CsVecView::<F>::new_view(len, index, value).unwrap()); } 'c' => { let len = self.c.shape().1; let f = std::mem::replace(&mut self.c, CsMat::<F>::zero((0, 0))); self.c = f.append_outer_csvec(CsVecView::<F>::new_view(len, index, value).unwrap()); } _ => {} } } pub fn append_to_k( &mut self, dimension: usize, vector_of_indices: &[usize], vector_of_values: &[F], ) { self.k = CsVec::<F>::new( self.k.dim() + dimension, [self.k.indices(), vector_of_indices].concat(), [self.k.data(), vector_of_values].concat(), ); } // This function evaluates sparse k polynomial pub fn evaluate_k(&self, k: Option<CsVec<F>>, elm: F) -> F { let mut rslt = F::zero(); let kv: CsVec<F> = match k { Some(kv) => kv, None => self.k.clone() }; for x in kv.iter() { let mut monom = *x.1; monom.mul_assign(&elm.pow(&[(x.0 + self.a.shape().1 + 1) as u64])); rslt.add_assign(&monom); } rslt } // This function evaluates sparse s polynomial at (x, Y) // TODO: benchmark the evaluation performance for large circuits with the two different implementations below pub fn evaluate_sxy(&self, x: F, y: F) -> Option<F> { match (x.inverse(), y.inverse()) { (Some(xi), Some(yi)) => { let shape = self.a.shape(); // precompute powers of parameters and inverses let mut yp = vec![F::zero(); shape.0]; yp[0] = y.pow([(shape.1 + 1) as u64]); for i in 1..shape.0 { yp[i] = yp[i - 1]; yp[i].mul_assign(&y); } let mut xp = vec![F::zero(); shape.0 + shape.1]; xp[0] = x; for i in 1..shape.0 + shape.1 { xp[i] = xp[i - 1]; xp[i].mul_assign(&x); } let mut xpi = vec![F::zero(); shape.1]; xpi[0] = xi; for i in 1..shape.1 { xpi[i] = xpi[i - 1]; xpi[i].mul_assign(&xi); } let mut rslt = F::zero(); for entry in self.a.iter() { let mut monom = *entry.0; monom.mul_assign(&xpi[(entry.1).1]); monom.mul_assign(&yp[(entry.1).0]); rslt.add_assign(&monom); } for entry in self.b.iter() { let mut monom = *entry.0; monom.mul_assign(&xp[(entry.1).1]); monom.mul_assign(&yp[(entry.1).0]); rslt.add_assign(&monom); } for entry in self.c.iter() { let mut monom = *entry.0; monom.mul_assign(&xp[(entry.1).1 + shape.0]); monom.mul_assign(&yp[(entry.1).0]); rslt.add_assign(&monom); } let mut xy = x; xy.mul_assign(&y); let mut xyi = x; xyi.mul_assign(&yi); let mut xpy = x.pow([(shape.1) as u64]); let mut xny = xpy; for _ in 0..shape.1 { xpy.mul_assign(&xy); rslt.sub_assign(&xpy); xny.mul_assign(&xyi); rslt.sub_assign(&xny); } return Some(rslt); } (_, _) => return None, } } /* pub fn evaluate_sxy(&self, x: F, y: F) -> Option<F> { match (x.inverse(), y.inverse()) { (Some(xi), Some(yi)) => { let mut rslt = F::zero(); let shape = self.a.shape(); for entry in self.a.iter() { let xp = xi.pow([((entry.1).1 + 1) as u64]); let yp = y.pow([((entry.1).0 + shape.1 + 1) as u64]); let mut monom = *entry.0; monom.mul_assign(&xp); monom.mul_assign(&yp); rslt.add_assign(&monom); } for entry in self.b.iter() { let xp = x.pow([((entry.1).1 + 1) as u64]); let yp = y.pow([((entry.1).0 + shape.1 + 1) as u64]); let mut monom = *entry.0; monom.mul_assign(&xp); monom.mul_assign(&yp); rslt.add_assign(&monom); } for entry in self.c.iter() { let xp = x.pow([((entry.1).1 + shape.0 + 1) as u64]); let yp = y.pow([((entry.1).0 + shape.1 + 1) as u64]); let mut monom = *entry.0; monom.mul_assign(&xp); monom.mul_assign(&yp); rslt.add_assign(&monom); } let mut xy = x; xy.mul_assign(&y); let mut xyi = x; xyi.mul_assign(&yi); let mut xpy = x.pow([(shape.1) as u64]); let mut xny = xpy; for _ in 0..shape.1 { xpy.mul_assign(&xy); rslt.sub_assign(&xpy); xny.mul_assign(&xyi); rslt.sub_assign(&xny); } return Some(rslt); } (_, _) => return None, } } */ // This function evaluates sparse s polynomial against one variable value pub fn evaluate_s(&self, elm: F, var: bool) -> Option<Univariate<F>> { match elm.inverse() { None => return None, Some(inv) => { let shape = self.a.shape(); if var == false { let mut rslt = Univariate::<F>::create(shape.1 + 1, 2 * shape.1 + 1); let mut y = F::one(); let mut yp = vec![F::zero(); shape.0 + shape.1]; for x in yp.iter_mut() { y.mul_assign(&elm); *x = y } y = F::one(); let mut yn = vec![F::zero(); shape.1]; for x in yn.iter_mut() { y.mul_assign(&inv); *x = y } for entry in self.a.iter() { let mut monom = *entry.0; monom.mul_assign(&yp[(entry.1).0 + shape.1]); rslt.neg[(entry.1).1 + 1].add_assign(&monom); } for entry in self.b.iter() { let mut monom = *entry.0; monom.mul_assign(&yp[(entry.1).0 + shape.1]); rslt.pos[(entry.1).1 + 1].add_assign(&monom); } for entry in self.c.iter() { let mut monom = *entry.0; monom.mul_assign(&yp[(entry.1).0 + shape.1]); rslt.pos[(entry.1).1 + shape.1 + 1].add_assign(&monom); } for i in 0..shape.1 { rslt.pos[i + shape.1 + 1].sub_assign(&yp[i]); rslt.pos[i + shape.1 + 1].sub_assign(&yn[i]); } return Some(rslt); } else { let mut rslt = Univariate::<F>::create(shape.1 + 1, shape.0 + shape.1 + 1); let mut x = F::one(); let mut xp = vec![F::zero(); 2 * shape.1]; for y in xp.iter_mut() { x.mul_assign(&elm); *y = x } x = F::one(); let mut xn = vec![F::zero(); shape.1]; for y in xn.iter_mut() { x.mul_assign(&inv); *y = x } for entry in self.a.iter() { let mut monom = *entry.0; monom.mul_assign(&xn[(entry.1).1]); rslt.pos[(entry.1).0 + shape.1 + 1].add_assign(&monom); } for entry in self.b.iter() { let mut monom = *entry.0; monom.mul_assign(&xp[(entry.1).1]); rslt.pos[(entry.1).0 + shape.1 + 1].add_assign(&monom); } for entry in self.c.iter() { let mut monom = *entry.0; monom.mul_assign(&xp[shape.1 + (entry.1).1]); rslt.pos[(entry.1).0 + shape.1 + 1].add_assign(&monom); } for i in 0..shape.1 { rslt.pos[i + 1].sub_assign(&xp[i + shape.1]); rslt.neg[i + 1].sub_assign(&xp[i + shape.1]); } return Some(rslt); } } } } // This function verifies the consistency of the wire assignements (witness) against the constraints // witness: wire assignement witness // k: optional public params as vector K update // RFTURN: verification status pub fn verify(&self, k: Option<CsVec<F>>, witness: &Witness<F>) -> bool { let kv: CsVec<F> = match k { Some(kv) => kv, None => self.k.clone() }; // verify the witness against the multiplicative constraints for wt in witness.gates.iter() { let mut ab = wt.a; ab.mul_assign(&wt.b); if ab != wt.c { return false; } } if self.a.shape().1 != witness.gates.len() || self.b.shape().1 != witness.gates.len() || self.c.shape().1 != witness.gates.len() || self.a.shape().0 != self.b.shape().0 || self.b.shape().0 != self.c.shape().0 { return false; } // verify the witness against the linear constraints for ((row, a), (b, c)) in self .a .outer_iterator() .enumerate() .zip(self.b.outer_iterator().zip(self.c.outer_iterator())) { let mut acc = F::zero(); for (col, constraint) in a.iter() { let mut vc = witness.gates[col].a; if !vc.is_zero() { vc.mul_assign(&constraint); acc.add_assign(&vc) } } for (col, constraint) in b.iter() { let mut vc = witness.gates[col].b; if !vc.is_zero() { vc.mul_assign(&constraint); acc.add_assign(&vc) } } for (col, constraint) in c.iter() { let mut vc = witness.gates[col].c; if !vc.is_zero() { vc.mul_assign(&constraint); acc.add_assign(&vc) } } if acc != match kv.get(row) { None => F::zero(), Some(x) => *x, } { return false; } } true } pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> { // write a writer.write_u32::<BigEndian>(self.a.rows() as u32)?; writer.write_u32::<BigEndian>(self.a.cols() as u32)?; writer.write_u32::<BigEndian>(self.a.indptr().len() as u32)?; for index in self.a.indptr().iter().cloned() { writer.write_u32::<BigEndian>(index as u32)?; } writer.write_u32::<BigEndian>(self.a.indices().len() as u32)?; for index in self.a.indices().iter().cloned() { writer.write_u32::<BigEndian>(index as u32)?; } writer.write_u32::<BigEndian>(self.a.data().len() as u32)?; for item in &self.a.data()[..] { for digit in item.into_repr().as_ref().iter().rev() { writer.write_u64::<BigEndian>(*digit)?; } } // write b writer.write_u32::<BigEndian>(self.b.rows() as u32)?; writer.write_u32::<BigEndian>(self.b.cols() as u32)?; writer.write_u32::<BigEndian>(self.b.indptr().len() as u32)?; for index in self.b.indptr().iter().cloned() { writer.write_u32::<BigEndian>(index as u32)?; } writer.write_u32::<BigEndian>(self.b.indices().len() as u32)?; for index in self.b.indices().iter().cloned() { writer.write_u32::<BigEndian>(index as u32)?; } writer.write_u32::<BigEndian>(self.b.data().len() as u32)?; for item in &self.b.data()[..] { for digit in item.into_repr().as_ref().iter().rev() { writer.write_u64::<BigEndian>(*digit)?; } } // write c writer.write_u32::<BigEndian>(self.c.rows() as u32)?; writer.write_u32::<BigEndian>(self.c.cols() as u32)?; writer.write_u32::<BigEndian>(self.c.indptr().len() as u32)?; for index in self.c.indptr().iter().cloned() { writer.write_u32::<BigEndian>(index as u32)?; } writer.write_u32::<BigEndian>(self.c.indices().len() as u32)?; for index in self.c.indices().iter().cloned() { writer.write_u32::<BigEndian>(index as u32)?; } writer.write_u32::<BigEndian>(self.c.data().len() as u32)?; for item in &self.c.data()[..] { for digit in item.into_repr().as_ref().iter().rev() { writer.write_u64::<BigEndian>(*digit)?; } } // write k writer.write_u32::<BigEndian>(self.k.dim() as u32)?; writer.write_u32::<BigEndian>(self.k.indices().len() as u32)?; for index in self.k.indices().iter().cloned() { writer.write_u32::<BigEndian>(index as u32)?; } writer.write_u32::<BigEndian>(self.k.data().len() as u32)?; for item in &self.k.data()[..] { for digit in item.into_repr().as_ref().iter().rev() { writer.write_u64::<BigEndian>(*digit)?; } } Ok(()) } pub fn read<R: Read>(mut reader: R) -> io::Result<Self> { let read_field_element = |reader: &mut R| -> io::Result<F> { let mut repr = <F as PrimeField>::Repr::default(); for digit in repr.as_mut().iter_mut().rev() { *digit = reader.read_u64::<BigEndian>()?; } repr.as_mut()[3] &= 0x7fffffffffffffff; Ok(F::from_repr(repr).unwrap()) }; let a: CsMat<F>; let b: CsMat<F>; let c: CsMat<F>; let k: CsVec<F>; // read a { let rows = reader.read_u32::<BigEndian>()? as usize; let cols = reader.read_u32::<BigEndian>()? as usize; let mut indptr = vec![]; let mut indices = vec![]; let mut data = vec![]; let indptr_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..indptr_len { indptr.push(reader.read_u32::<BigEndian>()? as usize) } let indices_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..indices_len { indices.push(reader.read_u32::<BigEndian>()? as usize) } let data_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..data_len { data.push(read_field_element(&mut reader)?) } a = CsMat::new((rows, cols), indptr, indices, data) } // read b { let rows = reader.read_u32::<BigEndian>()? as usize; let cols = reader.read_u32::<BigEndian>()? as usize; let mut indptr = vec![]; let mut indices = vec![]; let mut data = vec![]; let indptr_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..indptr_len { indptr.push(reader.read_u32::<BigEndian>()? as usize) } let indices_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..indices_len { indices.push(reader.read_u32::<BigEndian>()? as usize) } let data_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..data_len { data.push(read_field_element(&mut reader)?) } b = CsMat::new((rows, cols), indptr, indices, data) } // read c { let rows = reader.read_u32::<BigEndian>()? as usize; let cols = reader.read_u32::<BigEndian>()? as usize; let mut indptr = vec![]; let mut indices = vec![]; let mut data = vec![]; let indptr_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..indptr_len { indptr.push(reader.read_u32::<BigEndian>()? as usize) } let indices_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..indices_len { indices.push(reader.read_u32::<BigEndian>()? as usize) } let data_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..data_len { data.push(read_field_element(&mut reader)?) } c = CsMat::new((rows, cols), indptr, indices, data) } // read k { let dim = reader.read_u32::<BigEndian>()? as usize; let mut indices = vec![]; let mut data = vec![]; let indices_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..indices_len { indices.push(reader.read_u32::<BigEndian>()? as usize) } let data_len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..data_len { data.push(read_field_element(&mut reader)?) } k = CsVec::<F>::new(dim, indices, data); } Ok(ConstraintSystem::<F> { a, b, c, k }) } } impl<F: Field> PartialEq for ConstraintSystem<F> { fn eq(&self, other: &Self) -> bool { if self.a != other.a || self.b != other.b || self.c != other.c || self.k != other.k { return false; } return true; } } impl<F: Field> fmt::Debug for ConstraintSystem<F> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Constraint system: {:?}, {:?}, {:?}, {:?}", self.a, self.b, self.c, self.k ) } } <file_sep>pub use super::constraint_system::ConstraintSystem; pub use super::witness::Witness; use pairing::{Engine, Field}; pub fn compute_sparseness<E: Engine>( cs: &mut ConstraintSystem<E::Fr>, witness: &mut Witness<E::Fr>, ) { let mut count = 0; let mut total = 0; for wt in witness.gates.iter() { if wt.a.is_zero() { count = count + 1; } if wt.b.is_zero() { count = count + 1; } if wt.c.is_zero() { count = count + 1; } total = total + 3 } println!( "total: {}, zeros:: {}, ratio: {}", total, count, (count as f64) / (total as f64) ); let mut count = 0; let mut total = 0; for i in 0..cs.a.rows() { for j in 0..cs.a.cols() { match cs.a.get(i, j) { None => count = count + 1, Some(_) => {} } } } for i in 0..cs.b.rows() { for j in 0..cs.b.cols() { match cs.b.get(i, j) { None => count = count + 1, Some(_) => {} } } } for i in 0..cs.c.rows() { for j in 0..cs.c.cols() { match cs.c.get(i, j) { None => count = count + 1, Some(_) => {} } } } total = total + 3; println!( "total: {}, zeros:: {}, ratio: {}", total, count, (count as f64) / (total as f64) ); } <file_sep>[package] name = "commitment" version = "0.1.0" authors = ["IOHK"] edition = "2018" [dependencies.pairing] version = "0.14.2" features = ["u128-support"] [dependencies] polynomials = { path = "../polynomials" } circuits = { path = "../circuits" } merlin = "1.1.0" rand = "0.4" colored = "1.8" byteorder = "1" rayon = "1.3.0" <file_sep>/******************************************************************************************** This source file implements prover's zk-proof primitives. This proof is constructed by prover. It is verified by both the helper and the verifier as part of the computation of the helper's proof as well as the verification of the NP-statement Sonic zk-proof. This is one of the two constituent parts of the NP-statement Sonic zk-proof, the other being the HelperProof. *********************************************************************************************/ pub use super::rndoracle::{ProofError, RandomOracleArgument}; use circuits::constraint_system::{ConstraintSystem, Witness}; use commitment::urs::URS; use merlin::Transcript; use pairing::{Engine, Field}; use polynomials::univariate::Univariate; use rayon::prelude::*; use rand::OsRng; use sprs::CsVec; #[derive(Clone, Copy)] pub struct ProverProof<E: Engine> { // Commitment to univariate polynomial r(X, 1) pub rx1_comm: E::G1Affine, // Commitment to univariate polynomial t(X, y) pub txy_comm: E::G1Affine, // Commitment to rx1, txy & sxy to r(X, 1) opening at x batched proof pub batch_x_prf: E::G1Affine, // rx1 evaluation at x pub rx1_x_evl: E::Fr, // Commitment rx1_comm to r(X, 1) opening at xy pub rx1_xy_prf: E::G1Affine, pub rx1_xy_evl: E::Fr, } impl<E: Engine> ProverProof<E> { // This function constructs prover's zk-proof from the witness & the constraint system against URS instance // witness: computation witness // cs: constraint system // k: optional public params as vector K update // urs: universal reference string // RETURN: prover's zk-proof pub fn create( witness: &Witness<E::Fr>, cs: &ConstraintSystem<E::Fr>, k: Option<CsVec<E::Fr>>, urs: &URS<E>, ) -> Result<Self, ProofError> { // the transcript of the random oracle non-interactive argument let mut argument = Self::fiatshamir(cs, &k); // compute r(X, 1) polynomial let rx1 = witness.compute(E::Fr::one()); // commit to univariate polynomial r(X, 1) let rx1_comm = urs.commit(&rx1, cs.a.shape().1 + 1); // add r(X, 1) commitment to the random oracle context argument.commit_point(&rx1_comm); // query random scalar challenge from verifier let y: E::Fr = argument.challenge(); // compute t(X, y) polynomial let rslt = Self::t(witness, cs, k, rx1.clone(), y); if rslt.is_none() { return Err(ProofError::TXyxEvalComputation); } let txy = rslt.unwrap(); // commit to univariate polynomial t(X, y) let txy_comm = urs.commit(&txy, urs.gnax.len()); // add t(X, y) commitment to the random oracle context argument.commit_point(&txy_comm); // query random scalar challenge from verifier let x: E::Fr = argument.challenge(); let mut xy = x; xy.mul_assign(&y); // prover opens the polynomial r(X, 1) commitment at xy let rslt = rx1.evaluate(xy); if rslt.is_none() { return Err(ProofError::RX1xyEvalComputation); } let rx1_xy_evl = rslt.unwrap(); let rslt = urs.open(&rx1, xy); if rslt.is_none() { return Err(ProofError::RX1xyPrfComputation); } let rx1_xy_prf = rslt.unwrap(); // add r(X, 1) opening proof to the random oracle context argument.commit_point(&rx1_xy_prf); // query random scalar mask challenge from verifier let mask: E::Fr = argument.challenge(); // prover supplies the polynomial r(X, 1) evaluation at x let rslt = rx1.evaluate(x); if rslt.is_none() { return Err(ProofError::RX1xEvalComputation); } let rx1_x_evl = rslt.unwrap(); // prover opens the polynomial t(X, y) & r(X, 1) commitments at x let rslt = urs.open_batch(&vec![txy, rx1], mask, x); if rslt.is_none() { return Err(ProofError::RX1xPrfComputation); } let batch_x_prf = rslt.unwrap(); Ok(ProverProof { rx1_comm: rx1_comm, txy_comm: txy_comm, batch_x_prf: batch_x_prf, rx1_x_evl: rx1_x_evl, rx1_xy_prf: rx1_xy_prf, rx1_xy_evl: rx1_xy_evl, }) } // This function constructs prover's zk-proofs in parallel from the // witness vector & the constraint system against URS instance // witness: computation witness array with // optional public params as vector K update // cs: constraint system // urs: universal reference string // RETURN: prover's zk-proof array pub fn create_parallel ( witness: &Vec<(Witness<E::Fr>, Option<CsVec<E::Fr>>)>, cs: &ConstraintSystem<E::Fr>, urs: &URS<E>, ) -> Result<Vec<Self>, ProofError> { witness.par_iter().map ( |witness| ProverProof::<E>::create ( &witness.0, cs, witness.1.clone(), urs, ) ).collect::<Result<Vec<_>, _>>() } // This function verifies the prover's zk-proof // sxy: evaluation of s(X, Y) polynomial at (x, y). Helper, upon verification, // computes the value himself. Verifier, upon verification, provides this evaluation as // computed by the helper // cs: constraint system // k: optional public params as vector K update // urs: universal reference string // RETURN: verification status pub fn verify( &self, sxy: &E::Fr, cs: &ConstraintSystem<E::Fr>, k: Option<CsVec<E::Fr>>, urs: &URS<E>, rng: &mut OsRng, ) -> bool { // query random oracle values from verifier let (x, y, xy, mask) = self.oracles(cs, &k); // evaluate k(Y) at y let ky = match k { Some(k) => { let mut rslt = E::Fr::zero(); for x in k.iter() { let mut monom = *x.1; monom.mul_assign(&y.pow(&[(x.0 + cs.a.shape().1 + 1) as u64])); rslt.add_assign(&monom); } rslt } None => {cs.evaluate_k(k, y)} }; // compute the evaluation of polynomial t(X, Y) at the point (x, y) let mut txy = self.rx1_xy_evl; txy.add_assign(&sxy); txy.mul_assign(&self.rx1_x_evl); txy.sub_assign(&ky); // verify the proof rx1_xy_prf against the commitment rx1_comm and evaluation rx1_xy_evl if urs.verify( &vec![ vec![( xy, E::Fr::one(), vec![(self.rx1_comm, self.rx1_xy_evl, cs.a.shape().1 + 1)], self.rx1_xy_prf, )], vec![( x, mask, vec![ (self.txy_comm, txy, urs.gnax.len()), (self.rx1_comm, self.rx1_x_evl, cs.a.shape().1 + 1), ], self.batch_x_prf, )], ], rng, ) == false { return false; } true } // This function evaluation of t(X, Y) polynomial at (x, y) // evaluations: // ky: k(Y) polynomial evaluatoiion at y // sxy: s(X, Y) polynomial evaluatoiion at (x, y) // RETURN: prepared verification context: // txy: t(X, Y) evaluation at (x, y) pub fn txy(&self, evaluations: (Option<E::Fr>, Option<E::Fr>)) -> Result<E::Fr, ProofError> { let (ky, sxy) = evaluations; match (ky, sxy) { (Some(ky), Some(sxy)) => { // compute the evaluation of polynomial t(X, Y) at the point (x, y) let mut txy = self.rx1_xy_evl; txy.add_assign(&sxy); txy.mul_assign(&self.rx1_x_evl); txy.sub_assign(&ky); Ok(txy) } (_, _) => return Err(ProofError::TXyxEvalComputation), } } // This function queries random oracle values from verifier pub fn fiatshamir(cs: &ConstraintSystem<E::Fr>, k: &Option<CsVec<E::Fr>>) -> Transcript { // the transcript of the random oracle non-interactive argument let mut argument = Transcript::new(&[]); // add public assignments into the argument match k { Some(k) => {for value in k.data().iter() {argument.commit_scalar(value)}} None => {for value in cs.k.data().iter() {argument.commit_scalar(value)}} } argument } // This function queries random oracle values from verifier pub fn oracles(&self, cs: &ConstraintSystem<E::Fr>, k: &Option<CsVec<E::Fr>>) -> (E::Fr, E::Fr, E::Fr, E::Fr) { // the transcript of the random oracle non-interactive argument let mut argument = Self::fiatshamir(cs, &k); // add r(X, 1) commitment to the random oracle context argument.commit_point(&self.rx1_comm); // query random scalar challenge from verifier let y: E::Fr = argument.challenge(); // add t(X, y) commitment to the random oracle context argument.commit_point(&self.txy_comm); // query random scalar challenge from verifier let x: E::Fr = argument.challenge(); // add r(X, 1) opening proof to the random oracle context argument.commit_point(&self.rx1_xy_prf); // query random scalar mask challenge from verifier let mask: E::Fr = argument.challenge(); let mut xy = x; xy.mul_assign(&y); (x, y, xy, mask) } // This function constructs t polynomial from the witness & the constraint system // witness: computation witness // cs: constraint system // k: optional public params as vector K update // RETURN: s polynomial pub fn t( witness: &Witness<E::Fr>, cs: &ConstraintSystem<E::Fr>, k: Option<CsVec<E::Fr>>, rx1: Univariate<E::Fr>, y: E::Fr, ) -> Option<Univariate<E::Fr>> { let _shape = cs.a.shape(); // compute r(X, y) polynomial let mut rxy = witness.compute(y); // compute s(X, y) polynomial match cs.evaluate_s(y, false) { None => return None, Some(sxy) => rxy.add_assign(&sxy), } // multiply r1 & rx1 polynomials let mut t = rxy.mul(&rx1); // subtract k(Y) polynomial t.pos[0].sub_assign(&cs.evaluate_k(k, y)); Some(t) } } <file_sep>/******************************************************************************************** This source file implements zk-proof primitives. This primitive is the aggregate of types ProverProof and HelperProof. It represents the complete individual proof that consists of the prover's and the helper's parts *********************************************************************************************/ pub use super::batch::{BatchProof, HelperProof, ProofError, ProverProof, RandomOracleArgument}; use circuits::constraint_system::ConstraintSystem; use commitment::urs::URS; use pairing::{Engine, Field}; use rand::OsRng; use sprs::CsVec; pub struct ZkProof<E: Engine> { pub prover: ProverProof<E>, pub helper: Result<HelperProof<E>, ProofError>, } impl<E: Engine> ZkProof<E> { // This function verifies the helper's zk-proof // u: random oracle argument value // sux_comm: commitment to s(u, X) polynomial // cs: constraint system // k: optional public params as vector K update // urs: universal reference string // RETURN: verification status pub fn verify( &mut self, u: E::Fr, sux_comm: E::G1Affine, cs: &ConstraintSystem<E::Fr>, k: Option<CsVec<E::Fr>>, urs: &URS<E>, rng: &mut OsRng, ) -> bool { // query random oracle values from verifier let (x, y, xy, mask) = self.prover.oracles(cs, &k); // evaluate k(Y) at y match (&self.helper, self.txy(Some(cs.evaluate_k(k, y)))) { (Ok(helper), Ok(txy)) => { // First, verify the helper's proof // verify the proof sux_y_prf against the commitment sux_comm and the evaluation sxy_u_evl=s(u, y) if urs.verify( &vec![ vec![( y, E::Fr::one(), vec![( sux_comm, helper.sxy_u_evl, cs.a.shape().1 + cs.a.shape().0 + 1, )], helper.sux_y_prf, )], // verify the proof sxy_u_prf against the commitment sxy_comm and the evaluation sxy_u_evl=s(u, y) vec![( u, E::Fr::one(), vec![(helper.sxy_comm, helper.sxy_u_evl, cs.a.shape().1 * 2 + 1)], helper.sxy_u_prf, )], // Second, verify the prover's proof // verify the proof rx1_xy_prf against the commitment rx1_comm and evaluation rx1_xy_evl vec![( xy, E::Fr::one(), vec![( self.prover.rx1_comm, self.prover.rx1_xy_evl, cs.a.shape().1 + 1, )], self.prover.rx1_xy_prf, )], // verify the proof batch_x_prf against the commitments sxy_comm, rx1_comm & txy_comm and evaluations // sxy_x_evl, rx1_x_evl and the computed evaluation t(x, y) of the bivariate polynomial t(X, Y) // at the point (x, y) vec![( x, mask, vec![ (self.prover.txy_comm, txy, urs.gnax.len()), ( self.prover.rx1_comm, self.prover.rx1_x_evl, cs.a.shape().1 + 1, ), (helper.sxy_comm, helper.sxy_x_evl, cs.a.shape().1 * 2 + 1), ], self.prover.batch_x_prf, )], ], rng, ) == false { self.helper = Err(ProofError::ProverVerification); return false; } } (_, _) => return false, } true } // This function evaluation of t(X, Y) polynomial at (x, y) // ky: k(Y) polynomial eavluation // RETURN: prepared verification context: // x: random oracle value // y: random oracle value // xy: random oracle value product // mask: random oracle masking value // txy: t(X, Y) evaluation at (x, y) pub fn txy(&self, ky: Option<E::Fr>) -> Result<E::Fr, ProofError> { match &self.helper { Err(_) => return Err(ProofError::HelperVerification), Ok(helper) => { match ky { Some(ky) => { // compute the evaluation of polynomial t(X, Y) at the point (x, y) let mut txy = self.prover.rx1_xy_evl; txy.add_assign(&helper.sxy_x_evl); txy.mul_assign(&self.prover.rx1_x_evl); txy.sub_assign(&ky); Ok(txy) } None => return Err(ProofError::TXyxEvalComputation), } } } } } <file_sep>/***************************************************************************************************************** This source file, for now, implements URS unit test suite driver. The following tests are implemented: 1. urs_test This unit test generates a Universal Reference String for circuit depth of up to 20, computes its update and proceeds to the verification of URS update consistency against its zk-proof with the bilinear pairing map checks. *****************************************************************************************************************/ use circuits::constraint_system::ConstraintSystem; use colored::Colorize; use commitment::urs::URS; use pairing::bls12_381::Bls12; use pairing::{Engine, Field, PrimeField}; use rand::OsRng; use std::io; use std::io::Write; use std::time::Instant; // The following test verifies the consistency of the // URS generation with the pairings of the URS exponents #[test] fn urs_test() { test::<Bls12>(); test_binary_compressed::<Bls12>(); test_binary_uncompressed::<Bls12>(); } #[allow(dead_code)] fn progress(depth: usize) { print!("{:?}\r", depth); io::stdout().flush().unwrap(); } fn test<E: Engine>() { let mut rng = OsRng::new().unwrap(); let depth = 30; let iterations = 1; // generate sample URS string for circuit depth of up to 'depth' println!("{}", "Generating the initial URS".green()); let mut start = Instant::now(); let mut urs = URS::<E>::create( depth, vec![3, 7], E::Fr::from_str("11111").unwrap(), E::Fr::from_str("3333333").unwrap(), ); println!("{}{:?}", "Execution time: ".yellow(), start.elapsed()); for i in 0..iterations { println!("{}{:?}", "Iteration: ", i); println!("{}", "Computing the update of the URS".green()); // save necessary URS elements to verify next update let hp1x1 = urs.hp1x1; let hpax0 = urs.hpax0; start = Instant::now(); // update sample URS string for circuit depth of up to 'depth' urs.update( E::Fr::from_str("55555").unwrap(), E::Fr::from_str("7777777").unwrap(), ); println!("{}{:?}", "Execution time: ".yellow(), start.elapsed()); println!("{}", "Verifying the update against its zk-proof".green()); start = Instant::now(); assert_eq!(urs.check(hp1x1, hpax0, progress, &mut rng), true); println!("{}{:?}", "Execution time: ".yellow(), start.elapsed()); } } fn test_binary_uncompressed<E: Engine>() { // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); // Jubjub Edwards form coefficient d: y^2-x^2=1+d*y^2*x^2 let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let mut negd = d; negd.negate(); // our test circuit let mut cs = ConstraintSystem::<E::Fr>::create(3); cs.append('a', &[0], &[one]); cs.append('a', &[1], &[one]); cs.append('a', &[], &[]); cs.append('a', &[2], &[one]); cs.append('a', &[2], &[negd]); cs.append('b', &[0], &[neg1]); cs.append('b', &[1], &[neg1]); cs.append('b', &[2], &[one]); cs.append('b', &[], &[]); cs.append('b', &[2], &[one]); cs.append('c', &[], &[]); cs.append('c', &[], &[]); cs.append('c', &[1], &[negd]); cs.append('c', &[0], &[neg1]); cs.append('c', &[2], &[d]); cs.append_to_k(5, &[4], &[negd]); let field_element1 = E::Fr::from_str( "54799959613707685803997198407519087143449000911774710148164155636221645225006191", ) .unwrap(); let field_element2 = E::Fr::from_str( "36138681238004545275106256624762827227968497741908195957194228995387484282295954", ) .unwrap(); let mut start = Instant::now(); let urs = URS::<E>::create_cs_based(&cs, field_element1, field_element2); println!("{}{:?}", "Generating URS time: ", start.elapsed()); let g1_elements_count = urs.gp1x.len() + urs.gn1x.len() + urs.gpax.len() + urs.gnax.len(); // hp1x1, hpax0, hpax1 are single G2 elements let g2_elements_count = urs.hn1x.len() + 3; let coordinates = g1_elements_count * 2 + g2_elements_count * 4; println!( "total G1 elements: {} G2: elements: {}, coordinates: {}", g1_elements_count, g2_elements_count, coordinates ); let mut v = vec![]; start = Instant::now(); urs.write_uncompressed(&mut v).unwrap(); println!( "{}{:?}", "Binary serializing time (uncompressed): ", start.elapsed() ); std::fs::write("raw.urs", v.clone()).expect("unable to write into file"); let attr = std::fs::metadata("raw.urs").unwrap(); println!("Size: {} Mb", attr.len() / 1048576); let v = std::fs::read("raw.urs").unwrap(); let start = Instant::now(); let de_urs = URS::<E>::read_uncompressed(&v[..], false).unwrap(); assert!(urs == de_urs); println!( "{}{:?}", "Binary deserializing time (uncompressed): ", start.elapsed() ); } fn test_binary_compressed<E: Engine>() { // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); // Jubjub Edwards form coefficient d: y^2-x^2=1+d*y^2*x^2 let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let mut negd = d; negd.negate(); // our test circuit let mut cs = ConstraintSystem::<E::Fr>::create(3); cs.append('a', &[0], &[one]); cs.append('a', &[1], &[one]); cs.append('a', &[], &[]); cs.append('a', &[2], &[one]); cs.append('a', &[2], &[negd]); cs.append('b', &[0], &[neg1]); cs.append('b', &[1], &[neg1]); cs.append('b', &[2], &[one]); cs.append('b', &[], &[]); cs.append('b', &[2], &[one]); cs.append('c', &[], &[]); cs.append('c', &[], &[]); cs.append('c', &[1], &[negd]); cs.append('c', &[0], &[neg1]); cs.append('c', &[2], &[d]); cs.append_to_k(5, &[4], &[negd]); let field_element1 = E::Fr::from_str( "54799959613707685803997198407519087143449000911774710148164155636221645225006191", ) .unwrap(); let field_element2 = E::Fr::from_str( "36138681238004545275106256624762827227968497741908195957194228995387484282295954", ) .unwrap(); let mut start = Instant::now(); let urs = URS::<E>::create_cs_based(&cs, field_element1, field_element2); println!("{}{:?}", "Generating URS time: ", start.elapsed()); let g1_elements_count = urs.gp1x.len() + urs.gn1x.len() + urs.gpax.len() + urs.gnax.len(); // hp1x1, hpax0, hpax1 are single G2 elements let g2_elements_count = urs.hn1x.len() + 3; let coordinates = g1_elements_count * 2 + g2_elements_count * 4; println!( "total G1 elements: {} G2: elements: {}, coordinates: {}", g1_elements_count, g2_elements_count, coordinates ); let mut v = vec![]; start = Instant::now(); urs.write_compressed(&mut v).unwrap(); println!( "{}{:?}", "Binary serializing time (compressed): ", start.elapsed() ); std::fs::write("raw.urs", v.clone()).expect("unable to write into file"); let attr = std::fs::metadata("raw.urs").unwrap(); println!("Size: {} Mb", attr.len() / 1048576); start = Instant::now(); let de_urs = URS::<E>::read_compressed(&v[..], false).unwrap(); assert!(urs == de_urs); println!( "{}{:?}", "Binary deserializing time (compressed): ", start.elapsed() ); } <file_sep>pub mod commitment; pub mod urs; <file_sep># Sonic Sonic presents a new SNARKs protocol with the benefit of the updateability of its Universal SRS (structured reference string) with the size linear in the size of the arithmetic circuit that describes the computational statement being proven. URS is circuit independent and can be used for the proofing system of many circuits whose size (depth) is limited by the URS size. The source code of this repository implements the Sonic proofing system with Helper support. <file_sep>/***************************************************************************************************************** This source file implements the univariate polynomial test suite driver. The following tests are implemented: 1. Univariate polynomial multiplication test 1. Generate two random univariate polynomials A & B 2. For a random field element x a. evaliate A at x and B at x b. multiply evaluations to obtain z1 c. muliply polynomials A & B a. evaliate A*B at x b. record result of the above as z2 3. Compare results z1 & z2 *****************************************************************************************************************/ use pairing::{bls12_381::Bls12, Engine, Field}; use polynomials::univariate::Univariate; use rand::OsRng; use rand::Rng; #[test] fn univariate_mul_test() { test::<Bls12>(); } fn test<E: Engine>() { let mut rng = OsRng::new().unwrap(); let depth = 1000; for _ in 0..10 { // generate sample random polynomials over the scalar field let a = Univariate::<E::Fr>::random( rng.gen_range::<usize>(1, depth), rng.gen_range::<usize>(0, depth), &mut rng, ); let b = Univariate::<E::Fr>::random( rng.gen_range::<usize>(1, depth), rng.gen_range::<usize>(0, depth), &mut rng, ); // we have the polynomials, evaluate them at a random scalar field element for _ in 0..10 { let x = Univariate::rand(&mut rng); let ax = a.evaluate(x).unwrap(); let bx = b.evaluate(x).unwrap(); let mut axbx = ax; axbx.mul_assign(&bx); let ab = a.mul(&b); let abx = ab.evaluate(x).unwrap(); assert_eq!(abx, axbx); } } } <file_sep>/***************************************************************************************************************** This source file implements miscellaneous utilities. *****************************************************************************************************************/ pub use super::univariate::Univariate; use pairing::PrimeField; use rand::{OsRng, Rand}; impl<F: PrimeField> Univariate<F> { pub fn rand(rng: &mut OsRng) -> F { loop { if let Ok(y) = F::from_repr(F::Repr::rand(rng)) { return y; } } } // This function creates a zero instance of a polynomial of given dimensions pub fn random(n: usize, p: usize, rng: &mut OsRng) -> Self { let mut plnm = Self::create(n, p); for x in plnm.neg.iter_mut() { *x = Self::rand(rng); } for x in plnm.pos.iter_mut() { *x = Self::rand(rng); } plnm } } <file_sep>/***************************************************************************************************************** This source file implements the polynomial commitment unit test suite driver. The following tests are implemented: 1. Polynomial commiment test 1. Generate URS instance of sufficient depth 2. Generate a random polynomials vector over the base field that fits into the URS depth. The polynomial coefficients are random base field elements. 3. Commit to the polynomials against the URS instance 4. Evaluate the polynomials at a given randomly generated base field elements 5. Open the polynomials commitment at the given random base field element producing the opening proof 6. Verify the commitment opening proofs against the: a. the URS instance b. Polynomial evaluations at the given base field element c. The given base field elements d. Commitment opening proofs *****************************************************************************************************************/ use commitment::urs::URS; use pairing::{bls12_381::Bls12, Engine, Field}; use polynomials::univariate::Univariate; use rand::OsRng; #[test] fn single_commitment_test() { test::<Bls12>(); } fn test<E: Engine>() { let mut rng = OsRng::new().unwrap(); let depth = 50; // generate sample URS let urs = URS::<E>::create( depth, vec![depth / 3 - 3], Univariate::<E::Fr>::rand(&mut rng), Univariate::<E::Fr>::rand(&mut rng), ); // generate sample random vector of polynomials over the base field, commit and evaluate them let mut plnms: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); for _ in 0..10 { let plnm = Univariate::<E::Fr> { pos: (0..depth / 3 - 3) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), neg: (0..depth / 3 - 7) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), }; let y = Univariate::<E::Fr>::rand(&mut rng); let comm = urs.commit(&plnm, plnm.pos.len()); // Open and verify the polynomial commitments match plnm.evaluate(y) { None => { panic!("This error should not happen"); } Some(eval) => match urs.open(&plnm, y) { None => { panic!("This error should not happen"); } Some(prf) => { plnms.push((y, E::Fr::one(), vec![(comm, eval, depth / 3 - 3)], prf)); } }, } } assert_eq!(true, urs.verify(&vec![plnms; 1], &mut rng)); } <file_sep>[package] name = "protocol" version = "0.1.0" authors = ["IOHK"] edition = "2018" [dependencies.pairing] version = "0.14.2" features = ["u128-support"] [dependencies] circuits = { path = "../circuits" } polynomials = { path = "../polynomials" } commitment = { path = "../commitment" } merlin = "1.1.0" rand = "0.4" colored = "1.8" sprs = "0.6.5" rand_core = "0.5" rayon = "1.3.0" <file_sep>/*********************************************************************** This source file implements dense representation of sparse vectors. ***********************************************************************/ use pairing::Field; use sprs::CsVec; use std::ops::Index; #[derive(Clone)] pub struct DenseVector<F> { pub value: CsVec<F>, zero: F, } pub enum Operation { Set, Add, Sub, } impl<F> Index<usize> for DenseVector<F> where F: Field, { type Output = F; fn index(&self, index: usize) -> &F { match self.value.get(index) { None => &self.zero, Some(x) => x, } } } pub trait SparseVector<F: Field> { fn new(len: usize) -> Self; fn create(size: usize, index: Vec<usize>, value: Vec<F>) -> Self; fn append(&mut self, index: &[usize], value: &[F]); fn len(&self) -> usize; } impl<F: Field> SparseVector<F> for DenseVector<F> { fn new(len: usize) -> Self { DenseVector { value: CsVec::<F>::empty(len), zero: F::zero(), } } fn create(size: usize, index: Vec<usize>, value: Vec<F>) -> Self { DenseVector { value: CsVec::<F>::new(size, index, value), zero: F::zero(), } } fn append(&mut self, index: &[usize], value: &[F]) { for (i, v) in index.iter().zip(value) { self.value.append(*i, *v); } } fn len(&self) -> usize { self.value.dim() } } <file_sep>/***************************************************************************************************************** This source file implements the random oracle argument API for Sonic. The idea and the implementation of the use of Merlin create for Fiat-Shamir heuristic is borrowed from https://github.com/zknuckles/sonic *****************************************************************************************************************/ use merlin::Transcript; use pairing::{CurveAffine, PrimeField, PrimeFieldRepr}; use std::fmt; use std::io; #[derive(Debug)] pub enum ProofError { RX1Computation, TXyComputation, TXyxEvalComputation, TXyxPrfComputation, RX1xEvalComputation, RX1xPrfComputation, RX1xyEvalComputation, RX1xyPrfComputation, SXyComputation, SXyxEvalComputation, SXyxPrfComputation, SXyuEvalComputation, SXyuPrfComputation, SuXComputation, SuXyPrfComputation, SuXvEvalComputation, SuXvPrfComputation, ProverVerification, HelperVerification, BatchVerification, KyEvalComputation, } // Implement `Display` for ProofError impl fmt::Display for ProofError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({})", self) } } pub trait RandomOracleArgument { fn commit_point<G: CurveAffine>(&mut self, point: &G); fn commit_scalar<F: PrimeField>(&mut self, scalar: &F); fn challenge<F: PrimeField>(&mut self) -> F; } impl RandomOracleArgument for Transcript { fn commit_point<G: CurveAffine>(&mut self, point: &G) { self.append_message(b"point", point.into_compressed().as_ref()); } fn commit_scalar<F: PrimeField>(&mut self, scalar: &F) { let mut v = vec![]; scalar.into_repr().write_le(&mut v).unwrap(); self.append_message(b"scalar", &v); } fn challenge<F: PrimeField>(&mut self) -> F { loop { let mut repr: F::Repr = Default::default(); repr.read_be(TranscriptReader(self)).unwrap(); if let Ok(result) = F::from_repr(repr) { if let Some(_) = result.inverse() { return result; } self.commit_scalar(&result); } } } } struct TranscriptReader<'a>(&'a mut Transcript); impl<'a> io::Read for TranscriptReader<'a> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.challenge_bytes(b"read", buf); Ok(buf.len()) } } <file_sep>/*************************************************************************************************** This source file implements Sonic's zk-proof primitive unit test suite driver. The following tests are implemented: 1. This tests batch of Sonic statement proofs as per section 4.2.5 of circuits.pdf document. The Jubjub constrained computation verifies if an array of EC points (given by Edwards coordinates) belongs to the Elliptic Curve group. First, the test verifies that the witness array satisfies the constraint equations. Second, it computes and verifies the Sonic KZ-proofs of all the statements (against the constraint system). The proof batch consists of Sonic zk-proofs, each of them proving, in zero-knowledge, that a point in the array of EC points belongs to the Jubjub EC group. For the wire labels a = [x, y] b = [v, u+1] c = [sqrt(-40964)*u, u-1] the linear constraint system is: u= [[0,0],[0,0]] v= [[0,1],[0,-sqrt(-40964)]] w= [[0,-1],[1,0]] k= [2,-sqrt(-40964)] The test verifies both positive and negative outcomes for satisfying and not satisfying witnesses. ***************************************************************************************************/ use circuits::constraint_system::{CircuitGate, ConstraintSystem, Witness}; use commitment::urs::URS; use pairing::{bls12_381::Bls12, Engine, Field, PrimeField}; use polynomials::univariate::Univariate; use protocol::batch::{BatchProof, ProverProof}; use rand::OsRng; use sprs::CsVec; #[test] fn group_conversion_test() { test::<Bls12>(); } #[allow(non_snake_case)] fn test<E: Engine>() { let mut rng = OsRng::new().unwrap(); // field zero element let zero = E::Fr::zero(); // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); let two = E::Fr::from_str("2").unwrap(); let negsqrtmjjA = E::Fr::from_str( "34620988240753777635981679240161257563063072671290560217967936669160105133864", ) .unwrap(); // our circuit cinstraint system let mut cs = ConstraintSystem::<E::Fr>::create(2); cs.b.insert(0, 1, one); cs.c.insert(0, 1, neg1); cs.c.insert(1, 0, one); cs.b.insert(1, 1, negsqrtmjjA); cs.a.insert(0, 0, zero); cs.a.insert(1, 0, zero); let inds = vec![0, 1]; let vals = vec![two, negsqrtmjjA]; cs.k = CsVec::<E::Fr>::new(2, inds, vals); let depth = cs.k.dim() + 4 * cs.a.shape().1 + 8; // generate sample URS let urs = URS::<E>::create( depth, vec![ depth, cs.a.shape().1 + 1, cs.a.shape().1 * 2 + 1, cs.a.shape().1 + cs.a.shape().0 + 1, ], Univariate::<E::Fr>::rand(&mut rng), Univariate::<E::Fr>::rand(&mut rng), ); positive::<E>(&urs, &cs, &mut rng); negative::<E>(&urs, &cs, &mut rng); } #[allow(non_snake_case)] fn positive<E: Engine>(urs: &URS<E>, cs: &ConstraintSystem<E::Fr>, rng: &mut OsRng) { // We have the constraint system. Let's choose examples of satisfying witness for Jubjub y^2-x^2=1+d*y^2*x^2 let mut points = Vec::<(E::Fr, E::Fr, E::Fr, E::Fr)>::new(); let mut witness_batch = Vec::<Witness<E::Fr>>::new(); let one = E::Fr::one(); let sqrtmjjA = E::Fr::from_str( "17814886934372412843466061268024708274627479829237077604635722030778476050649", ) .unwrap(); points.push(( E::Fr::from_str( "853554559207543847252664416966410582098606963183071025729253243887385698701", ) .unwrap(), E::Fr::from_str( "14764243698000945526787211915034316971081786721517742096668223329470205650604", ) .unwrap(), E::Fr::from_str( "49792417373762009466546315427310015213131913431044267875338124358756912689577", ) .unwrap(), E::Fr::from_str( "18704088696874163653775932556954898929880637695754080357664668755728034697568", ) .unwrap(), )); // check whether the points are on the curve for i in 0..points.len() { let (x, y, u, v) = points[i]; let mut up1 = u; up1.add_assign(&one); let mut um1 = u; um1.sub_assign(&one); let mut xv = x; xv.mul_assign(&v); let mut yup1 = y; yup1.mul_assign(&up1); let mut sqrtmjjAu = sqrtmjjA; sqrtmjjAu.mul_assign(&u); assert_eq!(xv, sqrtmjjAu); assert_eq!(yup1, um1); let mut witness = Witness::<E::Fr>::create(2, rng); witness.gates[0] = CircuitGate::<E::Fr> { a: x, b: v, c: sqrtmjjAu, }; witness.gates[1] = CircuitGate::<E::Fr> { a: y, b: up1, c: um1, }; // verify the circuit satisfiability by the computed witness assert_eq!(cs.verify(None, &witness), true); // add the witness to the batch witness_batch.push(witness); } // The computation circuit is satisfied by the witness array // Now let's create zk-proof batch of the statements let s = String::from("In the blockchain setting this has to come from the block context"); let batch_context: Vec<u8> = s.into_bytes(); let mut prover_proofs = Vec::<(ProverProof<E>, Option<CsVec<E::Fr>>)>::new(); // create the vector of prover's proofs for the given witness vector for i in 0..points.len() { match ProverProof::<E>::create(&witness_batch[i], &cs, None, &urs) { Err(error) => { panic!("Failure creating the prover's proof: {}", error); } Ok(proof) => prover_proofs.push((proof, None)), } } // create and verify the batch of zk-proofs for the given witness vector match BatchProof::<E>::create(&batch_context, &prover_proofs, &cs, &urs, rng) { Err(error) => { panic!(error); } Ok(mut batch) => { for i in 0..batch.batch.len() { match &batch.batch[i].helper { Err(error) => { panic!("Failure verifying the prover's proof: {}", error); } Ok(_) => continue, } } match batch.verify(&batch_context, &cs, &vec![None; batch.batch.len()], &urs, rng) { Err(_) => { panic!("Failure verifying the zk-proof"); } Ok(_) => { // we expect exit here on successful proof verification, since test is positive } } } } } #[allow(non_snake_case)] fn negative<E: Engine>(urs: &URS<E>, cs: &ConstraintSystem<E::Fr>, rng: &mut OsRng) { // We have the constraint system. Let's choose examples of satisfying witness for Jubjub y^2-x^2=1+d*y^2*x^2 let mut points = Vec::<(E::Fr, E::Fr, E::Fr, E::Fr)>::new(); let mut witness_batch = Vec::<Witness<E::Fr>>::new(); let one = E::Fr::one(); let sqrtmjjA = E::Fr::from_str( "17814886934372412843466061268024708274627479829237077604635722030778476050649", ) .unwrap(); // witness that does not satisfy the statement points.push(( E::Fr::from_str( "853554559207543847252664416966410582098606963183071025729253243887385698701", ) .unwrap(), E::Fr::from_str( "14764243698000945526787211915034316971081786721517742096668223329470205650604", ) .unwrap(), E::Fr::from_str( "49792417373762009466546315427310015213131913431044267875338124358756912689577", ) .unwrap(), E::Fr::from_str( "1", // wrong value ) .unwrap(), )); // check whether the points are on the curve for i in 0..points.len() { let (x, y, u, v) = points[i]; let mut up1 = u; up1.add_assign(&one); let mut um1 = u; um1.sub_assign(&one); let mut xv = x; xv.mul_assign(&v); let mut yup1 = y; yup1.mul_assign(&up1); let mut sqrtmjjAu = sqrtmjjA; sqrtmjjAu.mul_assign(&u); let mut witness = Witness::<E::Fr>::create(2, rng); witness.gates[0] = CircuitGate::<E::Fr> { a: x, b: v, c: sqrtmjjAu, }; witness.gates[1] = CircuitGate::<E::Fr> { a: y, b: up1, c: um1, }; // add the witness to the batch witness_batch.push(witness); } // The computation circuit is satisfied by the witness array // Now let's create zk-proof batch of the statements let s = String::from("In the blockchain setting this has to come from the block context"); let batch_context: Vec<u8> = s.into_bytes(); let mut prover_proofs = Vec::<(ProverProof<E>, Option<CsVec<E::Fr>>)>::new(); // create the vector of prover's proofs for the given witness vector for i in 0..points.len() { match ProverProof::<E>::create(&witness_batch[i], &cs, None, &urs) { Err(error) => { panic!("Failure creating the prover's proof: {}", error); } Ok(proof) => prover_proofs.push((proof, None)), } } // create and verify the batch of zk-proofs for the given witness vector match BatchProof::<E>::create(&batch_context, &prover_proofs, &cs, &urs, rng) { Err(error) => { panic!(error); } Ok(mut batch) => { for i in 0..batch.batch.len() { match &batch.batch[i].helper { Err(_) => {} Ok(_) => { panic!("Failure invalidating the prover's proof"); } } } match batch.verify(&batch_context, &cs, &vec![None; batch.batch.len()], &urs, rng) { Err(_) => { // we expect exit here on proof verification error, since test is negative } Ok(_) => { panic!("Failure invalidating the zk-proof"); } } } } } <file_sep>/***************************************************************************************************************** This source file implements the Sonic universal reference string primitive Sonic universal SRS={{g^(x^i)}, {g^(αx^i)}\g^α, {h^(β^i)}, {h^(αx^i)}} updateability enables user updating URS in such a way that, once the user discards his update trapdoor secrets, no other party is in possession of the updated trapdoor secrets. This is possible due to the facts that, unlike other SNARKs protocols utilizing polynomial evaluations in exponents of URS, Sonic only uses evaluations of monomials in its universal URS which has size linear in the size of the circuit. In Midnight setting, the use case of this functionality would have to have a special “configuration” transaction type implemented that would allow a user to generate an update to the trusted setup in such a way that, from the point on as the transaction gets committed to the ledger, the user can be confident that no other party possesses the knowledge of the trapdoors of the public setup to generate the false proofs. With this system, the adversarial attack can only exploit the case when all of the updaters of the public setup collude collectively and with the original setup generation. As soon as one non-colluding user updates the setup, the setup becomes secure from the viewpoint of this type of attack. This special transaction contains, together with the computed setup update, a NIZK proof of the correctness of the update. This proof is verified by all the peer nodes upon the transaction/block commitment and by miners upon block generation. Once the transaction gets committed to the ledger, all the subsequent private transactions with zk-SNARKs proofs are computed and verified against the updated public setup. *****************************************************************************************************************/ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use circuits::constraint_system::ConstraintSystem; use pairing::EncodedPoint; use pairing::{CurveAffine, CurveProjective, Engine, Field, PrimeField, PrimeFieldRepr}; use polynomials::univariate::Univariate; use std::collections::HashMap; use std::fmt; use std::io::{self, Read, Write}; use rand::OsRng; use rayon::prelude::*; // check pairing of a&b vs pairing of c&d macro_rules! pairing_check1 { ($a:expr, $b:expr, $c:expr, $d:expr) => { if <E>::pairing($a, $b) != <E>::pairing($c, $d) { return false; } }; } // check pairing of a&b vs c macro_rules! pairing_check2 { ($a:expr, $b:expr, $c:expr) => { if <E>::pairing($a, $b) != $c { return false; } }; } // URS update proof pub struct UpdateProof<E: Engine> { pub gx: E::G1Affine, pub ga: E::G1Affine, } pub struct URS<E: Engine> { pub gp1x: Vec<E::G1Affine>, // g^(x^i) for 0 <= i < d pub gn1x: Vec<E::G1Affine>, // g^(x^i) for -d < i <= 0 pub gpax: Vec<E::G1Affine>, // g^(αx^i) for 0 <= i < d, gpax[0]=E::G1::one() pub gnax: Vec<E::G1Affine>, // g^(αx^i) for -d < i <= 0, gnax[0]=E::G1::one() pub hn1x: HashMap<usize, E::G2Affine>, // h^(x^i) for -d < i <= 0 pub hp1x1: E::G2Affine, // h^(x) pub hpax0: E::G2Affine, // h^(α) pub hpax1: E::G2Affine, // h^(αx) // TODO: have to do the complete proof chain pub prf: UpdateProof<E>, } impl<E: Engine> URS<E> { // empty default calback, use as <obj::URS<E>>::callback pub fn callback(_i: usize) {} // This function creates URS instance for circuits up to depth d // depth: maximal depth of the circuits // xp: trapdoor secret // a: trapdoor secret pub fn create(depth: usize, degrees: Vec<usize>, xp: E::Fr, a: E::Fr) -> Self { let window_size = if depth < 32 {3} else {(2.0 / 3.0 * (f64::from(depth as u32)).log2() + 2.0).ceil() as usize}; let g = Self::get_window_table ( E::Fr::NUM_BITS as usize, window_size, E::G1::one() ); fn table<E: Engine> ( scalar: &Vec<E::Fr>, table: &mut Vec<Vec<E::G1>>, size: usize ) -> Vec<E::G1Affine> { let mut elm = URS::<E>::multi_scalar_mul ( E::Fr::NUM_BITS as usize, size, table, scalar, ); E::G1::batch_normalization(&mut elm); elm.into_iter().map(|e| e.into_affine()).collect() } let xn = xp.inverse().unwrap(); let mut gx = E::G1::one(); gx.mul_assign(xp); let mut hp1x1 = E::G2::one(); hp1x1.mul_assign(xp); let mut hpax0 = E::G2::one(); hpax0.mul_assign(a); let mut hpax1 = hpax0; hpax1.mul_assign(xp); let mut hn1x: HashMap<usize, E::G2Affine> = HashMap::new(); for degree in degrees.iter() { hn1x.insert(depth - *degree, { let mut x = E::G2::one(); x.mul_assign(xn.pow([(depth - *degree) as u64])); x.into_affine() }); } let mut x = [ (E::Fr::one(), xn), (E::Fr::one(), xp), (a, xn), (a, xp) ]; let powers = x.par_iter_mut().map ( |(s, y)| (0..depth).map(|_| {let ret = *s; s.mul_assign(&y); ret}).collect::<Vec<_>>() ).collect::<Vec<_>>(); let mut urs = URS { gn1x: table::<E>(&powers[0], &mut g.clone(), window_size), gp1x: table::<E>(&powers[1], &mut g.clone(), window_size), gnax: table::<E>(&powers[2], &mut g.clone(), window_size), gpax: table::<E>(&powers[3], &mut g.clone(), window_size), hn1x, hp1x1: hp1x1.into_affine(), hpax0: hpax0.into_affine(), hpax1: hpax1.into_affine(), prf: UpdateProof { gx: E::G1Affine::from(gx), ga: E::G1Affine::one(), // intentionally erasing this according to the spec }, }; // Erase the first element from gnax & gpax according to spec urs.gnax[0] = E::G1Affine::one(); urs.gpax[0] = E::G1Affine::one(); urs } pub fn create_cs_based(cs: &ConstraintSystem<E::Fr>, xp: E::Fr, a: E::Fr) -> Self { Self::create ( cs.k.dim() + 4 * cs.a.shape().1 + 8, vec! [ cs.k.dim() + 4 * cs.a.shape().1 + 8, cs.a.shape().1 + 1, cs.a.shape().1 * 2 + 1, cs.a.shape().1 + cs.a.shape().0 + 1, ], xp, a ) } // This function updates URS instance and computes the update proof // xp: trapdoor secret // a: trapdoor secret // RETURN: computed zk-proof pub fn update(&mut self, xp: E::Fr, a: E::Fr) { fn exponentiate<C: CurveAffine>(scalar: &Vec<C::Scalar>, urs: &mut Vec<C>) { urs.par_iter_mut().zip(scalar).for_each ( |(p, s)| {*p = p.mul(s.into_repr()).into_affine()} ) } let xn = xp.inverse().unwrap(); // Compute the URS update let mut x = [ (E::Fr::one(), self.gn1x.len(), xn), (E::Fr::one(), self.gp1x.len(), xp), (a, self.gnax.len(), xn), (a, self.gpax.len(), xp) ]; let powers = x.par_iter_mut().map ( |(s, size, y)| (0..*size).map(|_| {let ret = *s; s.mul_assign(&y); ret}).collect::<Vec<_>>() ).collect::<Vec<_>>(); exponentiate(&powers[0], &mut self.gn1x); exponentiate(&powers[1], &mut self.gp1x); exponentiate(&powers[2], &mut self.gnax); exponentiate(&powers[3], &mut self.gpax); let mut hp1x1 = self.hp1x1.into_projective(); hp1x1.mul_assign(xp); self.hp1x1 = hp1x1.into_affine(); let mut hpax0 = self.hpax0.into_projective(); hpax0.mul_assign(a); self.hpax0 = hpax0.into_affine(); let mut hpax1 = self.hpax1.into_projective(); hpax1.mul_assign(a); hpax1.mul_assign(xp); self.hpax1 = hpax1.into_affine(); for x in self.hn1x.iter_mut() { let mut y = x.1.into_projective(); y.mul_assign(xn.pow([*x.0 as u64])); *x.1 = y.into_affine(); } // Erase the first element from gnax & gpax according to spec self.gnax[0] = E::G1Affine::one(); self.gpax[0] = E::G1Affine::one(); let mut gx = E::G1::one(); gx.mul_assign(xp); let mut ga = E::G1::one(); ga.mul_assign(a); self.prf = UpdateProof { gx: E::G1Affine::from(gx), ga: E::G1Affine::from(ga), } } // This function verifies the updated URS against the zk-proof and the previous URS instance // exp2[0]: previous URS hp1x[1] // exp2[5]: previous URS hpax[0] // RETURN: zk-proof verification status pub fn check<F>(&mut self, hp1x1: E::G2Affine, hpax0: E::G2Affine, callback: F, rng: &mut OsRng) -> bool where F: Fn(usize), { // TODO: have to do the complete zk-proof chain verification, not just URS let xy = <E>::pairing(E::G1::from(self.prf.gx), E::G2::from(hp1x1)); let ab = <E>::pairing(<E>::G1::one(), E::G2::from(self.hpax0)); // verify gp1x[1] consistency with zk-proof pairing_check2!(E::G1::from(self.gp1x[1]), E::G2::one(), xy); // verify hp1x[1] consistency with zk-proof pairing_check2!(E::G1::one(), E::G2::from(self.hp1x1), xy); // verify gpax[1] consistency against hpax[1] which is verified inductively from hpax[0] pairing_check1!( E::G1::from(self.gpax[1]), E::G2::one(), E::G1::one(), E::G2::from(self.hpax1) ); // verify hpax[0] consistency with zk-proof pairing_check2!(E::G1::from(self.prf.ga), E::G2::from(hpax0), ab); let fk = <E>::pairing(E::G1Affine::one(), E::G2Affine::one()); for x in self.hn1x.iter() { if <E>::pairing(self.gp1x[*x.0], *x.1) != fk { return false; } } let mut g0: Vec<(E::G1Affine, E::Fr)> = vec![]; let mut g1: Vec<(E::G1Affine, E::Fr)> = vec![]; for i in 1..self.gp1x.len() { let randomiser: Vec<E::Fr> = (0..4).map(|_| Univariate::<E::Fr>::rand(rng)).collect(); // inductively verify gp1x & gn1x from gp1x[1] g0.push((self.gp1x[i], randomiser[0])); g0.push((self.gn1x[i - 1], randomiser[1])); g1.push((self.gp1x[i - 1], randomiser[0])); g1.push((self.gn1x[i], randomiser[1])); if i != 1 // this is accounting for the "hole" in the URS { // inductively verify gpax & gnax from gpax[1] g0.push((self.gpax[i], randomiser[2])); g0.push((self.gnax[i - 1], randomiser[3])); g1.push((self.gpax[i - 1], randomiser[2])); g1.push((self.gnax[i], randomiser[3])); } callback(i); } let mut table = vec![]; table.push((Self::multiexp(&g0).prepare(), E::G2Affine::one().prepare())); table.push(( Self::multiexp(&g1).prepare(), ({ let mut neg = self.hp1x1; neg.negate(); neg }) .prepare(), )); let x: Vec<( &<E::G1Affine as CurveAffine>::Prepared, &<E::G2Affine as CurveAffine>::Prepared, )> = table.iter().map(|x| (&x.0, &x.1)).collect(); E::final_exponentiation(&E::miller_loop(&x)).unwrap() == E::Fqk::one() } pub fn get_window_table<T: CurveProjective>( scalar_size: usize, window: usize, g: T, ) -> Vec<Vec<T>> { let in_window = 1 << window; let outerc = (scalar_size + window - 1) / window; let last_in_window = 1 << (scalar_size - (outerc - 1) * window); let mut multiples_of_g = vec![vec![T::zero(); in_window]; outerc]; let mut g_outer = g; for outer in 0..outerc { let mut g_inner = T::zero(); let cur_in_window = if outer == outerc - 1 { last_in_window } else { in_window }; for inner in 0..cur_in_window { multiples_of_g[outer][inner] = g_inner; g_inner.add_assign(&g_outer); } for _ in 0..window { g_outer.double(); } } multiples_of_g } pub fn windowed_mul<T: CurveProjective>( outerc: usize, window: usize, multiples_of_g: &[Vec<T>], scalar: &T::Scalar, ) -> T { let mut scalar_repr = scalar.into_repr(); let scalar_val = (0..<T::Scalar as PrimeField>::NUM_BITS as usize).map ( |_| { let x = if scalar_repr.as_ref()[0] & 1u64 == 1 {true} else {false}; scalar_repr.div2(); x } ).collect::<Vec<_>>(); //scalar_val.reverse(); let mut res = multiples_of_g[0][0]; for outer in 0..outerc { let mut inner = 0usize; for i in 0..window { if outer * window + i < (<T::Scalar as PrimeField>::NUM_BITS as usize) && scalar_val[outer * window + i] { inner |= 1 << i; } } res.add_assign(&multiples_of_g[outer][inner]); } res } pub fn multi_scalar_mul<T: CurveProjective>( scalar_size: usize, window: usize, table: &[Vec<T>], v: &[T::Scalar], ) -> Vec<T> { let outerc = (scalar_size + window - 1) / window; assert!(outerc <= table.len()); v.par_iter().map(|e| Self::windowed_mul::<T>(outerc, window, table, e)).collect::<Vec<_>>() } pub fn write_uncompressed<W: Write>(&self, mut writer: W) -> io::Result<()> { writer.write_u32::<BigEndian>(self.gp1x.len() as u32)?; for g in &self.gp1x[..] { writer.write_all(g.into_uncompressed().as_ref())?; } writer.write_u32::<BigEndian>(self.gn1x.len() as u32)?; for g in &self.gn1x[..] { writer.write_all(g.into_uncompressed().as_ref())?; } writer.write_u32::<BigEndian>(self.gpax.len() as u32)?; for g in &self.gpax[..] { writer.write_all(g.into_uncompressed().as_ref())?; } writer.write_u32::<BigEndian>(self.gnax.len() as u32)?; for g in &self.gnax[..] { writer.write_all(g.into_uncompressed().as_ref())?; } writer.write_u32::<BigEndian>(self.hn1x.len() as u32)?; for (key, val) in self.hn1x.iter() { writer.write_u32::<BigEndian>(*key as u32)?; writer.write_all((*val).into_uncompressed().as_ref())?; } writer.write_all(self.hp1x1.into_uncompressed().as_ref())?; writer.write_all(self.hpax0.into_uncompressed().as_ref())?; writer.write_all(self.hpax1.into_uncompressed().as_ref())?; writer.write_all(&self.prf.ga.into_uncompressed().as_ref())?; writer.write_all(&self.prf.gx.into_uncompressed().as_ref())?; Ok(()) } pub fn read_uncompressed<R: Read>(mut reader: R, checked: bool) -> io::Result<Self> { let read_g1_uncompressed = |reader: &mut R| -> io::Result<E::G1Affine> { let mut repr = <E::G1Affine as CurveAffine>::Uncompressed::empty(); reader.read_exact(repr.as_mut())?; if checked { repr.into_affine() } else { repr.into_affine_unchecked() } .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) .and_then(|e| { if e.is_zero() { Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )) } else { Ok(e) } }) }; let read_g2_uncompressed = |reader: &mut R| -> io::Result<E::G2Affine> { let mut repr = <E::G2Affine as CurveAffine>::Uncompressed::empty(); reader.read_exact(repr.as_mut())?; if checked { repr.into_affine() } else { repr.into_affine_unchecked() } .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) .and_then(|e| { if e.is_zero() { Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )) } else { Ok(e) } }) }; let mut gp1x = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gp1x.push(read_g1_uncompressed(&mut reader)?); } } let mut gn1x = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gn1x.push(read_g1_uncompressed(&mut reader)?); } } let mut gpax = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gpax.push(read_g1_uncompressed(&mut reader)?); } } let mut gnax = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gnax.push(read_g1_uncompressed(&mut reader)?); } } let hn1x_len = reader.read_u32::<BigEndian>()? as usize; let mut hn1x: HashMap<usize, E::G2Affine> = HashMap::with_capacity(hn1x_len); { let mut key: usize; let mut value: E::G2Affine; for _ in 0..hn1x_len { key = reader.read_u32::<BigEndian>()? as usize; value = read_g2_uncompressed(&mut reader)?; hn1x.insert(key, value); } } let hp1x1 = read_g2_uncompressed(&mut reader)?; let hpax0 = read_g2_uncompressed(&mut reader)?; let hpax1 = read_g2_uncompressed(&mut reader)?; let ga = read_g1_uncompressed(&mut reader)?; let gx = read_g1_uncompressed(&mut reader)?; let prf = UpdateProof::<E> { ga, gx }; Ok(URS::<E> { gp1x, gn1x, gpax, gnax, hn1x, hp1x1, hpax0, hpax1, prf, }) } pub fn write_compressed<W: Write>(&self, mut writer: W) -> io::Result<()> { writer.write_u32::<BigEndian>(self.gp1x.len() as u32)?; for g in &self.gp1x[..] { writer.write_all(g.into_compressed().as_ref())?; } writer.write_u32::<BigEndian>(self.gn1x.len() as u32)?; for g in &self.gn1x[..] { writer.write_all(g.into_compressed().as_ref())?; } writer.write_u32::<BigEndian>(self.gpax.len() as u32)?; for g in &self.gpax[..] { writer.write_all(g.into_compressed().as_ref())?; } writer.write_u32::<BigEndian>(self.gnax.len() as u32)?; for g in &self.gnax[..] { writer.write_all(g.into_compressed().as_ref())?; } writer.write_u32::<BigEndian>(self.hn1x.len() as u32)?; for (key, val) in self.hn1x.iter() { writer.write_u32::<BigEndian>(*key as u32)?; writer.write_all((*val).into_compressed().as_ref())?; } writer.write_all(self.hp1x1.into_compressed().as_ref())?; writer.write_all(self.hpax0.into_compressed().as_ref())?; writer.write_all(self.hpax1.into_compressed().as_ref())?; writer.write_all(&self.prf.ga.into_compressed().as_ref())?; writer.write_all(&self.prf.gx.into_compressed().as_ref())?; Ok(()) } pub fn read_compressed<R: Read>(mut reader: R, checked: bool) -> io::Result<Self> { let read_g1_compressed = |reader: &mut R| -> io::Result<E::G1Affine> { let mut repr = <E::G1Affine as CurveAffine>::Compressed::empty(); reader.read_exact(repr.as_mut())?; if checked { repr.into_affine() } else { repr.into_affine_unchecked() } .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) .and_then(|e| { if e.is_zero() { Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )) } else { Ok(e) } }) }; let read_g2_compressed = |reader: &mut R| -> io::Result<E::G2Affine> { let mut repr = <E::G2Affine as CurveAffine>::Compressed::empty(); reader.read_exact(repr.as_mut())?; if checked { repr.into_affine() } else { repr.into_affine_unchecked() } .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) .and_then(|e| { if e.is_zero() { Err(io::Error::new( io::ErrorKind::InvalidData, "point at infinity", )) } else { Ok(e) } }) }; let mut gp1x = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gp1x.push(read_g1_compressed(&mut reader)?); } } let mut gn1x = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gn1x.push(read_g1_compressed(&mut reader)?); } } let mut gpax = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gpax.push(read_g1_compressed(&mut reader)?); } } let mut gnax = vec![]; { let len = reader.read_u32::<BigEndian>()? as usize; for _ in 0..len { gnax.push(read_g1_compressed(&mut reader)?); } } let hn1x_len = reader.read_u32::<BigEndian>()? as usize; let mut hn1x: HashMap<usize, E::G2Affine> = HashMap::with_capacity(hn1x_len); { let mut key: usize; let mut value: E::G2Affine; for _ in 0..hn1x_len { key = reader.read_u32::<BigEndian>()? as usize; value = read_g2_compressed(&mut reader)?; hn1x.insert(key, value); } } let hp1x1 = read_g2_compressed(&mut reader)?; let hpax0 = read_g2_compressed(&mut reader)?; let hpax1 = read_g2_compressed(&mut reader)?; let ga = read_g1_compressed(&mut reader)?; let gx = read_g1_compressed(&mut reader)?; let prf = UpdateProof::<E> { ga, gx }; Ok(URS::<E> { gp1x, gn1x, gpax, gnax, hn1x, hp1x1, hpax0, hpax1, prf, }) } } impl<E: Engine> PartialEq for UpdateProof<E> { fn eq(&self, other: &Self) -> bool { if self.ga != other.ga || self.gx != other.gx { return false; } return true; } } impl<E: Engine> PartialEq for URS<E> { fn eq(&self, other: &Self) -> bool { if self.gp1x != other.gp1x || self.gn1x != other.gn1x || self.gpax != other.gpax || self.gnax != other.gnax //|| self.hp1x != other.hp1x || self.hn1x != other.hn1x //|| self.hnax != other.hnax //|| self.hpax != other.hpax || self.prf != other.prf { return false; } return true; } } impl<E: Engine> fmt::Debug for UpdateProof<E> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UpdateProof < ga: {:?}, gx {:?} >", self.ga, self.gx) } } impl<E: Engine> fmt::Debug for URS<E> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "URS < gp1x: {:?}, gn1x: {:?}, gpax: {:?}, gnax: {:?}, hn1x: {:?}, prf: {:?} >", self.gp1x, self.gn1x, self.gpax, self.gnax, self.hn1x, self.prf ) } } <file_sep>/***************************************************************************************************************** This source file implements the univariate polynomial primitive. *****************************************************************************************************************/ use pairing::{Field, PrimeField}; use std::iter::FromIterator; use std::ops::Neg; #[derive(Clone)] pub struct Univariate<F: Field> { pub neg: Vec<F>, pub pos: Vec<F>, // TODO: Simplify with more consise definition of Laurent // polynomial as a single vector with the integer shift factor } impl<F: PrimeField> Univariate<F> { // This function evaluates the polynomial at a field element value with Horner's method // elm: field element to evaluate at // RETURN: evaluation field element result // NOTE: Sparse polynomial evaluation can be more efficient with exponentiation // optimized with square-and-add method which is log(N). pub fn evaluate(&self, elm: F) -> Option<F> { let mut result = F::zero(); if self.pos.len() > 0 { let n = self.pos.len() - 1; result = self.pos[n]; for i in 0..n { result.mul_assign(&elm); result.add_assign(&self.pos[n - i - 1]); } } if self.neg.len() < 2 { return Some(result); } let n = self.neg.len() - 1; match elm.inverse() { Some(inv) => { let mut neg = self.neg[n]; for i in 0..n - 1 { neg.mul_assign(&inv); neg.add_assign(&self.neg[n - i - 1]); } neg.mul_assign(&inv); result.add_assign(&neg); Some(result) } None => None, } } // This function multiplies this polynomial by the other // other: the other polynomial // result: result reference // RETURN: multiplication status pub fn mul(&self, other: &Self) -> Self { // contract the polynomials let (self1, sn) = self.contract(); let (other1, on) = other.contract(); let n = sn + on; let sp = self.pos.len(); let op = other.pos.len(); let p = if sp + op == 0 { 0 } else { sp + op - 1 }; // transform the vectors let mut trnsfm1 = Self::dft(self1.pos, Some(n + p), false); let trnsfm2 = Self::dft(other1.pos, Some(n + p), false); for (trns1, trns2) in trnsfm1.iter_mut().zip(trnsfm2.iter()) { trns1.mul_assign(trns2); } // interpolate the result let mut product = Self::dft(trnsfm1, None, true); product.resize(n + p, F::zero()); let result = Self { neg: vec![F::zero(); 1], pos: product, }; // expand the polynomial result.expand(n as isize) } // This function divides the polynomial difference: (F(x)-F(elm))/(x-elm) in linear time // The algorithm adea is borrowed from https://github.com/zknuckles/sonic // elm: base field element // RETURN: resulting polynomial product pub fn divide(&self, mut elm: F) -> Option<Self> { elm.negate(); let mut pos = vec![F::zero(); self.pos.len() - 1]; let mut rcff = F::zero(); for (x, y) in self.pos.iter().rev().zip(pos.iter_mut().rev()) { *y = *x; y.sub_assign(&rcff); rcff = *y; rcff.mul_assign(&elm); } elm.negate(); match elm.inverse() { Some(inv) => { rcff = F::zero(); let mut neg = vec![F::zero(); self.neg.len()]; for (x, y) in self.neg.iter().rev().zip(neg.iter_mut().rev()) { *y = *x; y.add_assign(&rcff); y.mul_assign(&inv); rcff = *y; y.negate(); } Some(Self { neg: neg, pos: pos }) } None => None, } } // This function computes Discrete Fourier Transform of the vector // rou: root of unity for the transform // sz: optional evaluation size // RETURN: Fourier Transform of the vector pub fn dft(mut vec: Vec<F>, sz: Option<usize>, reverse: bool) -> Vec<F> { let n = vec.len(); // compute the nearest 2^ above and the root of unity for the transform let (mut prou, size, log) = Self::rou(if sz.is_none() { n } else { sz.unwrap() }); // pad the vector to the nearest power of 2 size vec.resize(size, F::zero()); if reverse == true { prou = prou.inverse().unwrap(); } // primitive roots of unity have to be such that rou^len=1 let mut prsou: Vec<F> = vec![F::zero(); log]; for i in 0..log { prou.square(); prsou[log - i - 1] = prou; } // divide and conquer recursively to compute the transform's coefficients fn dft<F: Field>(input: &Vec<F>, rou: &Vec<F>, log: usize) -> Vec<F> { let n = input.len(); if n == 1 { vec![input[0]] } else { let mut w = F::one(); // NOTE: this could be optimized without new vector allocation // with index calculation [passing on to each recursion step let mut input0: Vec<F> = vec![F::zero(); n / 2]; let mut input1: Vec<F> = vec![F::zero(); n / 2]; for i in 0..n / 2 { input0[i] = input[i * 2]; input1[i] = input[i * 2 + 1]; } let output0 = dft::<F>(&input0, rou, log - 1); let output1 = dft::<F>(&input1, rou, log - 1); let mut output: Vec<F> = vec![F::zero(); n]; for i in 0..n / 2 { let mut out = output1[i]; out.mul_assign(&w); output[i] = output0[i]; output[i].add_assign(&out); output[i + n / 2] = output0[i]; output[i + n / 2].sub_assign(&out); w.mul_assign(&rou[log - 1]); } output } }; let mut result = dft::<F>(&vec, &prsou, log); if reverse == false { return result; } // for reverse transform, scale the result by the vector size let size = F::from_str(&format!("{}", result.len())) .unwrap() .inverse() .unwrap(); for i in 0..result.len() { result[i].mul_assign(&size); } result } // This function computes n-th primitive root of unity as the generator of n-muiltiplicative subgroup of rous // len: interpolation size // RETURN: root of unity, size and log for the transform pub fn rou(len: usize) -> (F, usize, usize) { // compute the nearest 2^ above and the primitive root of unity for the transform let mut size = 1; let mut log: usize = 0; let mut prou = F::root_of_unity(); while size < len { size <<= 1; log += 1; } for _ in log..F::S as usize - 1 { prou.square() } (prou, size, log) } // This function contracts the given polynomial pub fn contract(&self) -> (Self, usize) { let mut n = self.neg.len(); let mut vec = vec![F::zero(); 0]; if n > 1 { vec = Vec::from_iter(self.neg[1..n].iter().cloned()); vec.reverse(); } else { n = 1 } vec.append(&mut self.pos.clone()); ( Self { neg: vec![F::zero(); 1], pos: vec, }, n - 1, ) } // This function expands the given polynomial pub fn expand(&self, i: isize) -> Self { let (n, p) = (self.neg.len(), self.pos.len()); let s: usize = if i > 0 { i as usize } else { i.neg() as usize }; let (mut neg, mut pos): (Vec<F>, Vec<F>); if i > 0 { neg = Vec::from_iter(self.pos[0..if s > p { p } else { s }].iter().cloned()); if s > p { neg.resize(s, F::zero()) } neg.resize(neg.len() + 1, F::zero()); neg.reverse(); neg.append(&mut Vec::from_iter(self.neg[1..n].iter().cloned())); if s < p { pos = Vec::from_iter(self.pos[s..p].iter().cloned()) } else { pos = vec![F::zero()] } } else if i < 0 { pos = Vec::from_iter(self.neg[1..if s > n { n } else { s }].iter().cloned()); if s > n - 1 { pos.resize(s, F::zero()) } pos.reverse(); pos.append(&mut Vec::from_iter(self.pos[0..p].iter().cloned())); neg = vec![F::zero()]; if s < n { neg.append(&mut Vec::from_iter(self.pos[s + 1..n].iter().cloned())) } } else { neg = self.neg.clone(); pos = self.pos.clone(); } let result = Self { neg: neg, pos: pos }; //result.truncate(); result } // This function creates a positive polynomial from a vector pub fn polynom(vec: Vec<F>) -> Self { Self { neg: vec![F::zero(); 1], pos: vec, } } // This function multiplies this polynomial by a scalar // elm: multiplication scalar pub fn mul_assign(&self, elm: F) -> Self { let mut ret = self.clone(); for x in ret.neg.iter_mut() { x.mul_assign(&elm); } for x in ret.pos.iter_mut() { x.mul_assign(&elm); } ret } // This function adds this polynomial to the other // other: the other polynomial // RETURN: resulting polynomial sum pub fn add_alloc(&self, other: &Self) -> Self { let n = if self.neg.len() > other.neg.len() { self.neg.len() } else { other.neg.len() }; let p = if self.pos.len() > other.pos.len() { self.pos.len() } else { other.pos.len() }; let zero = F::zero(); let mut m = Self { neg: vec![F::zero(); n], pos: vec![F::zero(); p], }; for i in 0..n { m.neg[i].add_assign(if i >= self.neg.len() { &zero } else { &self.neg[i] }); m.neg[i].add_assign(if i >= other.neg.len() { &zero } else { &other.neg[i] }); } for i in 0..p { m.pos[i].add_assign(if i >= self.pos.len() { &zero } else { &self.pos[i] }); m.pos[i].add_assign(if i >= other.pos.len() { &zero } else { &other.pos[i] }); } m } // This function adds this polynomial to the other // other: the other polynomial pub fn add_assign(&mut self, other: &Self) { if self.pos.len() < other.pos.len() { self.pos.resize(other.pos.len(), F::zero()); } if self.neg.len() < other.neg.len() { self.neg.resize(other.neg.len(), F::zero()); } for (x, y) in self.pos.iter_mut().zip(other.pos.iter()) { x.add_assign(&y); } for (x, y) in self.neg.iter_mut().zip(other.neg.iter()) { x.add_assign(&y); } } // This function subtracts from this polynomial the other // other: the other polynomial pub fn sub_assign(&mut self, other: &Self) { if self.pos.len() < other.pos.len() { self.pos.resize(other.pos.len(), F::zero()); } if self.neg.len() < other.neg.len() { self.neg.resize(other.neg.len(), F::zero()); } for (x, y) in self.pos.iter_mut().zip(other.pos.iter()) { x.sub_assign(&y); } for (x, y) in self.neg.iter_mut().zip(other.neg.iter()) { x.sub_assign(&y); } } // This function creates a zero instance of a polynomial of given dimensions // n: max degere of negative x // p: max degere of positive x pub fn create(n: usize, p: usize) -> Self { Self { neg: vec![F::zero(); n], pos: vec![F::zero(); p], } } // Helper function pub fn truncate(&mut self) { let mut vec: Vec<F> = self .pos .clone() .into_iter() .rev() .skip_while(|&x| x.is_zero()) .collect(); vec.reverse(); if vec.len() == 0 { vec = vec![F::zero()] } self.pos = vec; vec = self .neg .clone() .into_iter() .rev() .skip_while(|&x| x.is_zero()) .collect(); vec.reverse(); if vec.len() == 0 { vec = vec![F::zero()] } self.neg = vec; } } <file_sep>/*************************************************************************************************** This source file implements Sonic's zk-proof primitive unit test suite driver. The following tests are implemented: 1. This tests batch of Sonic statement proofs as per section 4.2.1 of circuits.pdf document. The Jubjub constrained computation verifies if an array of EC points (given by Edwards coordinates) belongs to the Elliptic Curve group. First, the test verifies that the witness array satisfies the constraint equations. Second, it computes and verifies the Sonic ZK-proofs of all the statements (against the constraint system). The proof batch consists of Sonic zk-proofs, each of them proving, in zero-knowledge, that a point in the array of EC points belongs to the Jubjub EC group. For the wire labels a=[y, x, yy] b=[y, x, dxx] c= [yy, xx, yy-xx-1] the linear constraint system is: u= [[1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 1], [0, 0, -d]] v= [[-1, 0, 0], [0, -1, 0], [0, 0, 1], [0, 0, 0], [0, 0, 1]] w= [[0, 0, 0], [0, 0, 0], [0, -d, 0], [-1, 0, 0], [0, 0, d]] k= [0, 0, 0, 0, -d] The test verifies both positive and negative outcomes for satisfying and not satisfying witnesses. ***************************************************************************************************/ use circuits::constraint_system::{CircuitGate, ConstraintSystem, Witness}; use commitment::urs::URS; use pairing::{bls12_381::Bls12, Engine, Field, PrimeField}; use polynomials::univariate::Univariate; use protocol::batch::{BatchProof, ProverProof}; use rand::OsRng; use sprs::CsVec; #[test] fn group_element_check_test() { test::<Bls12>(); } fn test<E: Engine>() { let mut rng = OsRng::new().unwrap(); // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); // <NAME> form coefficient d: y^2-x^2=1+d*y^2*x^2 let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let mut negd = d; negd.negate(); // our circuit cinstraint system let mut cs = ConstraintSystem::<E::Fr>::create(3); cs.append('a', &[0], &[one]); cs.append('a', &[1], &[one]); cs.append('a', &[], &[]); cs.append('a', &[2], &[one]); cs.append('a', &[2], &[negd]); cs.append('b', &[0], &[neg1]); cs.append('b', &[1], &[neg1]); cs.append('b', &[2], &[one]); cs.append('b', &[], &[]); cs.append('b', &[2], &[one]); cs.append('c', &[], &[]); cs.append('c', &[], &[]); cs.append('c', &[1], &[negd]); cs.append('c', &[0], &[neg1]); cs.append('c', &[2], &[d]); cs.k = CsVec::<E::Fr>::new(5, vec![4], vec![negd]); // generate sample URS let depth = cs.k.dim() + 4 * cs.a.shape().1 + 8; let urs = URS::<E>::create( depth, vec![ depth, cs.a.shape().1 + 1, cs.a.shape().1 * 2 + 1, cs.a.shape().1 + cs.a.shape().0 + 1, ], Univariate::<E::Fr>::rand(&mut rng), Univariate::<E::Fr>::rand(&mut rng), ); positive::<E>(&urs, &cs, &mut rng); negative::<E>(&urs, &cs, &mut rng); } fn positive<E: Engine>(urs: &URS<E>, cs: &ConstraintSystem<E::Fr>, rng: &mut OsRng) { let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); // We have the constraint system. Let's choose examples of satisfying witness for Jubjub y^2-x^2=1+d*y^2*x^2 let mut points = Vec::<(E::Fr, E::Fr)>::new(); let mut witness_batch = Vec::<Witness<E::Fr>>::new(); let one = E::Fr::one(); points.push(( E::Fr::from_str( "47847771272602875687997868466650874407263908316223685522183521003714784842376", ) .unwrap(), E::Fr::from_str( "14866155869058627094034298869399931786023896160785945564212907054495032619276", ) .unwrap(), )); points.push(( E::Fr::from_str( "23161233924022868901612849355320019731199638537911088707556787060776867075186", ) .unwrap(), E::Fr::from_str( "46827933816106251659874509206068992514697956295153175925290603211849263285943", ) .unwrap(), )); points.push(( E::Fr::from_str( "21363808388261502515395491234587106714641012878496416205209487567367794065894", ) .unwrap(), E::Fr::from_str( "35142660575087949075353383974189325596183489114769964645075603269317744401507", ) .unwrap(), )); points.push(( E::Fr::from_str( "48251804265475671293065183223958159558134840367204970209791288593670022317146", ) .unwrap(), E::Fr::from_str( "39492112716472193454928048607659273702179031506049462277700522043303788873919", ) .unwrap(), )); points.push(( E::Fr::from_str( "26076779737997428048634366966120809315559597005242388987585832521797042997837", ) .unwrap(), E::Fr::from_str( "2916200718278883184735760742052487175592570929008292238193865643072375227389", ) .unwrap(), )); points.push(( E::Fr::from_str( "6391827799982489600548224857168349263868938761394485351819740320403055736778", ) .unwrap(), E::Fr::from_str( "26714606321943866209898052587479168369119695309696311252068260485776094410355", ) .unwrap(), )); points.push(( E::Fr::from_str( "34225834605492133647358975329540922898558190785910349822925459742326697718965", ) .unwrap(), E::Fr::from_str( "42503065208497349411091392685178794164009360876034587048702740318812028372175", ) .unwrap(), )); points.push(( E::Fr::from_str( "39706901109420478047209734657640449984347408718517226120651505259450485889935", ) .unwrap(), E::Fr::from_str( "44842351859583855521445972897388346257004580582454107427806918461747670509399", ) .unwrap(), )); points.push(( E::Fr::from_str( "28360026567573852013315702401149784452531421169317971653481741133982080381509", ) .unwrap(), E::Fr::from_str( "34586051224595854378884048103686100857425100914523816028360306191122507857625", ) .unwrap(), )); points.push(( E::Fr::from_str( "45719850001957217643735562111452029570487585222534789798311082643976688162166", ) .unwrap(), E::Fr::from_str( "51398963553553644922019770691279615862813421731845531818251689044792926267778", ) .unwrap(), )); // check whether the points are on the curve for i in 0..points.len() { let (x, y) = points[i]; let mut xx = x; let mut yy = y; xx.square(); yy.square(); let mut yy_xx_1 = yy; yy_xx_1.sub_assign(&xx); yy_xx_1.sub_assign(&one); let mut dxx = d; dxx.mul_assign(&xx); let mut dxxyy = dxx; dxxyy.mul_assign(&yy); assert_eq!(yy_xx_1, dxxyy); /* The point is on the curve, compute the witness and verify the circuit satisfiability for each point. Wire labels a=[y, x, yy] b=[y, x, dxx] c= [yy, xx, yy-xx-1] */ let mut witness = Witness::<E::Fr>::create(3, rng); witness.gates[0] = CircuitGate::<E::Fr> { a: y, b: y, c: yy }; witness.gates[1] = CircuitGate::<E::Fr> { a: x, b: x, c: xx }; witness.gates[2] = CircuitGate::<E::Fr> { a: yy, b: dxx, c: yy_xx_1, }; // verify the circuit satisfiability by the computed witness assert_eq!(cs.verify(None, &witness), true); // add the witness to the batch witness_batch.push(witness); } // The computation circuit is satisfied by the witness array // Now let's create zk-proof batch of the statements let s = String::from( "In the blockchain setting this has to come from the block context" ); let batch_context: Vec<u8> = s.into_bytes(); let mut prover_proofs = Vec::<(ProverProof<E>, Option<CsVec<E::Fr>>)>::new(); // create the vector of prover's proofs for the given witness vector for i in 0..points.len() { match ProverProof::<E>::create(&witness_batch[i], &cs, None, &urs) { Err(error) => { panic!("Failure creating the prover's proof: {}", error); } Ok(proof) => prover_proofs.push((proof, None)), } } // create and verify the batch of zk-proofs for the given witness vector match BatchProof::<E>::create(&batch_context, &prover_proofs, &cs, &urs, rng) { Err(error) => { panic!(error); } Ok(mut batch) => { for i in 0..batch.batch.len() { match &batch.batch[i].helper { Err(error) => { panic!("Failure verifying the prover's proof: {}", error); } Ok(_) => continue, } } match batch.verify(&batch_context, &cs, &vec![None; batch.batch.len()], &urs, rng) { Err(_) => { panic!("Failure verifying the zk-proof"); } Ok(_) => {} } } } } fn negative<E: Engine>(urs: &URS<E>, cs: &ConstraintSystem<E::Fr>, rng: &mut OsRng) { let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); // We have the constraint system. Let's choose examples of satisfying witness for Jubjub // y^2-x^2=1+d*y^2*x^2 let mut points = Vec::<(E::Fr, E::Fr)>::new(); let mut witness_batch = Vec::<Witness<E::Fr>>::new(); let one = E::Fr::one(); // witness that does not satisfy the statement points.push(( E::Fr::from_str( "45719850001957217643735562111452029570487585222534789798311082643976688162166", ) .unwrap(), E::Fr::from_str( "51398963553553644922019770691279615862813421731845531818251689044792926267779", ) .unwrap(), )); // check whether the points are on the curve for i in 0..points.len() { let (x, y) = points[i]; let mut xx = x; let mut yy = y; xx.square(); yy.square(); let mut yy_xx_1 = yy; yy_xx_1.sub_assign(&xx); yy_xx_1.sub_assign(&one); let mut dxx = d; dxx.mul_assign(&xx); let mut dxxyy = dxx; dxxyy.mul_assign(&yy); assert_ne!(yy_xx_1, dxxyy); /* the point is on the curve, compute the witness and verify the circuit satisfiability for each point Wire labels a=[y, x, yy] b=[y, x, dxx] c= [yy, xx, yy-xx-1] */ let mut witness = Witness::<E::Fr>::create(3, rng); witness.gates[0] = CircuitGate::<E::Fr> { a: y, b: y, c: yy }; witness.gates[1] = CircuitGate::<E::Fr> { a: x, b: x, c: xx }; witness.gates[2] = CircuitGate::<E::Fr> { a: yy, b: dxx, c: yy_xx_1, }; // verify the circuit satisfiability by the computed witness assert_ne!(cs.verify(None, &witness), true); // add the witness to the batch witness_batch.push(witness); } // The computation circuit is satisfied by the witness array // Now let's create zk-proof batch of the statements let s = String::from( "In the blockchain setting this has to come from the block context" ); let batch_context: Vec<u8> = s.into_bytes(); let mut prover_proofs = Vec::<(ProverProof<E>, Option<CsVec<E::Fr>>)>::new(); // create the vector of prover's proofs for the given witness vector for i in 0..points.len() { match ProverProof::<E>::create(&witness_batch[i], &cs, None, &urs) { Err(error) => { panic!("Failure creating the prover's proof: {}", error); } Ok(proof) => prover_proofs.push((proof, None)), } } // create and verify the batch of zk-proofs for the given witness vector match BatchProof::<E>::create(&batch_context, &prover_proofs, &cs, &urs, rng) { Err(error) => { panic!(error); } Ok(mut batch) => { for i in 0..batch.batch.len() { match &batch.batch[i].helper { Err(_) => {} Ok(_) => { panic!("Failure invalidating the prover's proof"); } } } match batch.verify(&batch_context, &cs, &vec![None; batch.batch.len()], &urs, rng) { Err(_) => {} Ok(_) => { panic!("Failure invalidating the zk-proof"); } } } } } <file_sep>pub mod constraint_system; pub mod gate; pub mod util; pub mod witness; <file_sep>/***************************************************************************************************************** This source file implements the polynomial commitment batch primitive. The primitive provides the following zero- knowledge protocol: 1. Commit to the batch of vectors of polynomials against the URS instance 2. Evaluate the vector of polynomials at the given base field element 3. Open the polynomial commitment batch at the given random base field element producing the opening proof with the masking base field element 4. Verify the commitment opening proof against the following; a. the URS instance b. Polynomial evaluations at the given base field element c. The given base field element d. The given masking base field element e. Commitment opening proof *****************************************************************************************************************/ pub use super::urs::URS; use pairing::{CurveAffine, CurveProjective, Engine, Field, PrimeField, PrimeFieldRepr}; use polynomials::univariate::Univariate; use rand::OsRng; use rayon::prelude::*; impl<E: Engine> URS<E> { // This function commits the polynomial against URS instance // plnm: polynomial to commit // max: maximal degree of the polynomial // RETURN: commitment group element pub fn commit(&self, plnm: &Univariate<E::Fr>, max: usize) -> E::G1Affine { let d = self.gnax.len(); let mut exp: Vec<(E::G1Affine, E::Fr)> = vec![]; for i in 0..plnm.pos.len() { if plnm.pos[i].is_zero() { continue; } if i + d >= max { exp.push((self.gpax[i + d - max], plnm.pos[i])) } else { exp.push((self.gnax[max - i - d], plnm.pos[i])) } } for i in 1..plnm.neg.len() { if plnm.neg[i].is_zero() { continue; } if i + max >= d { exp.push((self.gnax[i + max - d], plnm.neg[i])) } else { exp.push((self.gpax[d - i - max], plnm.neg[i])) } } Self::multiexp(&exp) } // This function exponentiates the polynomial against URS instance // plnm: polynomial to exponentiate // RETURN: commitment group element pub fn exponentiate(&self, plnm: &Univariate<E::Fr>) -> Option<E::G1Affine> { if plnm.pos.len() > self.gp1x.len() || plnm.neg.len() > self.gn1x.len() { return None; } let mut exp: Vec<(E::G1Affine, E::Fr)> = vec![]; for (x, y) in plnm.pos.iter().zip(self.gp1x.iter()) { if x.is_zero() { continue; } exp.push((*y, *x)); } for (x, y) in plnm.neg.iter().skip(1).zip(self.gn1x.iter().skip(1)) { if x.is_zero() { continue; } exp.push((*y, *x)); } Some(Self::multiexp(&exp)) } // This function opens the polynomial commitment // elm: base field element to open the commitment at // plnm: commited polynomial // RETURN: commitment opening proof pub fn open(&self, plnm: &Univariate<E::Fr>, elm: E::Fr) -> Option<E::G1Affine> { // do polynomial division (F(x)-F(elm))/(x-elm) match plnm.divide(elm) { None => None, Some(div) => self.exponentiate(&div), } } // This function computes the polynomial commitment batch // plnms: batch of polynomials to commit // urs: universal reference string // RETURN: evaluation field element result pub fn commit_batch(&self, plnms: &Vec<(Univariate<E::Fr>, usize)>) -> Vec<E::G1Affine> { let mut commitment = vec![E::G1Affine::zero(); plnms.len()]; for (x, y) in commitment.iter_mut().zip(plnms.iter()) { *x = self.commit(&y.0, y.1); } commitment } // This function opens the polynomial commitment batch // plnms: batch of commited polynomials // mask: base field element masking value // elm: base field element to open the commitment at // RETURN: commitment opening proof pub fn open_batch( &self, plnms: &Vec<Univariate<E::Fr>>, mask: E::Fr, elm: E::Fr, ) -> Option<E::G1Affine> { let mut acc = Univariate::<E::Fr>::create(0, 0); let mut scale = mask; for x in plnms.iter() { acc = acc.add_alloc(&x.mul_assign(scale)); scale.mul_assign(&mask); } match acc.divide(elm) { None => None, Some(div) => self.exponentiate(&div), } } // This function updates the polynomial commitment opening batch with another opening proof // batch: polynomial commitment opening batch to update // proof: polynomial commitment opening proof to update with // mask: base field element masking value // index: update index // RETURN: updated commitment opening batch proof pub fn update_batch( batch: E::G1Affine, proof: E::G1Affine, mut mask: E::Fr, index: usize, ) -> E::G1Affine { mask = mask.pow(&[index as u64]); let mut projt = batch.into_projective(); projt.add_assign(&proof.mul(mask)); projt.into_affine() } // This function verifies the batch polynomial commitment proofs of vectors of polynomials // base field element to open the commitment at // base field element masking value // polynomial commitment batch of // commitment value // polynomial evaluation // max positive powers size of the polynomial // polynomial commitment opening proof // RETURN: verification status pub fn verify( &self, batch: &Vec<Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)>>, rng: &mut OsRng, ) -> bool { let d = self.gnax.len(); let mut open: Vec<(E::G1Affine, E::Fr)> = vec![]; let mut openy: Vec<(E::G1Affine, E::Fr)> = vec![]; let mut table = vec![]; for prf in batch.iter() { let mut pcomm: Vec<Vec<(E::G1Affine, E::Fr)>> = vec![vec![]; prf[0].2.len()]; let mut eval = E::Fr::zero(); for x in prf.iter() { let rnd = Univariate::<E::Fr>::rand(rng); open.push((x.3, rnd)); let mut ry = rnd; ry.mul_assign(&x.0); ry.negate(); openy.push((x.3, ry)); let mut scale = x.1; let mut v = E::Fr::zero(); for (z, y) in x.2.iter().zip(pcomm.iter_mut()) { let mut vi = z.1; vi.mul_assign(&scale); v.add_assign(&vi); let mut vj = rnd; vj.mul_assign(&scale); y.push((z.0, vj)); scale.mul_assign(&x.1); } v.mul_assign(&rnd); eval.add_assign(&v); } openy.push((self.gp1x[0], eval)); for (z, y) in prf[0].2.iter().zip(pcomm.iter_mut()) { if !self.hn1x.contains_key(&(d - z.2)) { return false; } table.push(( Self::multiexp(&y).prepare(), ({ let mut g = self.hn1x[&(d - z.2)]; g.negate(); g }) .prepare(), )); } } table.push((Self::multiexp(&open).prepare(), self.hpax1.prepare())); table.push((Self::multiexp(&openy).prepare(), self.hpax0.prepare())); let x: Vec<( &<E::G1Affine as CurveAffine>::Prepared, &<E::G2Affine as CurveAffine>::Prepared, )> = table.iter().map(|x| (&x.0, &x.1)).collect(); E::final_exponentiation(&E::miller_loop(&x)).unwrap() == E::Fqk::one() } // This function multipoint exponentiates the array of group and scalar element tuples // this implementation of the multiexponentiation's Pippenger algorithm // is adapted from that of zexe algebra crate // RETURN: multipoint exponentiaton result pub fn multiexp<G: CurveAffine>(elm: &Vec<(G, G::Scalar)>) -> G { let bases = elm.iter().map(|p| p.0).collect::<Vec<_>>(); let scalars = elm.iter().map(|p| p.1.into_repr()).collect::<Vec<_>>(); let c = if scalars.len() < 32 { 3 } else { (2.0 / 3.0 * (f64::from(scalars.len() as u32)).log2() + 2.0).ceil() as usize }; let num_bits = <G::Engine as Engine>::Fr::NUM_BITS as usize; let fr_one = G::Scalar::one().into_repr(); let zero = G::zero().into_projective(); let window_starts: Vec<_> = (0..num_bits).step_by(c).collect(); let window_sums: Vec<_> = window_starts .into_par_iter() .map(|w_start| { let mut res = zero; let mut buckets = vec![zero; (1 << c) - 1]; scalars .iter() .zip(bases.iter()) .filter(|(s, _)| !s.is_zero()) .for_each(|(&scalar, base)| { if scalar == fr_one { if w_start == 0 { res.add_assign_mixed(&base); } } else { let mut scalar = scalar; scalar.shr(w_start as u32); let scalar = scalar.as_ref()[0] % (1 << c); if scalar != 0 { buckets[(scalar - 1) as usize].add_assign_mixed(&base); } } }); G::Projective::batch_normalization(&mut buckets); let mut running_sum = G::Projective::zero(); for b in buckets.into_iter().map(|g| g.into_affine()).rev() { running_sum.add_assign_mixed(&b); res.add_assign(&running_sum); } res }) .collect(); let lowest = window_sums.first().unwrap(); let mut sums = window_sums[1..] .iter() .rev() .fold(zero, |mut total, sum_i| { total.add_assign(&sum_i); for _ in 0..c { total.double() } total }); sums.add_assign(&lowest); sums.into_affine() } } <file_sep>/***************************************************************************************************************** This source file implements Sonic Constraint System unit test suite driver. The following tests are implemented: 1. Checking Point to be a Group Element This test implements the constraint system as per section 4.2.1 of circuits.pdf document. The Curve constrained computation verifies if an element (given by its Edwards coordinates) belongs to the Elliptic Curve group. The test runs the verification that check that a witness (given by its Edwards coordinates) satisfies the constraint equations. For the wire labels a=[y, x, yy] b=[y, x, dxx] c= [yy, xx, yy-xx-1] the linear constraint system is: u= [[ 1, 0, 0], [0, 1, 0], [0, 0, 0], [ 0, 0, 1], [0, 0, -d]] v= [[-1, 0, 0], [0, -1, 0], [0, 0, 1], [ 0, 0, 0], [0, 0, 1]] w= [[ 0, 0, 0], [0, 0, 0], [0, -d, 0], [-1, 0, 0], [0, 0, d]] k= [0, 0, 0, 0, -d] The test verifies both positive and negative outcomes for satisfying and not satisfying witnesses *****************************************************************************************************************/ use circuits::constraint_system::{ConstraintSystem, Witness}; use circuits::gate::CircuitGate; use pairing::{bls12_381::Bls12, Engine, Field, PrimeField}; use rand::OsRng; use sprs::CsVec; // The following test verifies the polynomial commitment scheme #[test] fn constraints_test() { group_element_test::<Bls12>(); } fn group_element_test<E: Engine>() { let mut rng = OsRng::new().unwrap(); // initialise constants // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); // <NAME> form coefficient d: y^2-x^2=1+d*y^2*x^2 let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let mut negd = d; negd.negate(); /* u= [[ 1, 0, 0], [0, 1, 0], [0, 0, 0], [ 0, 0, 1], [0, 0, -d]] v= [[-1, 0, 0], [0, -1, 0], [0, 0, 1], [ 0, 0, 0], [0, 0, 1]] w= [[ 0, 0, 0], [0, 0, 0], [0, -d, 0], [-1, 0, 0], [0, 0, d]] k= [0, 0, 0, 0, -d] */ // our circuit cinstraint system let mut cs = ConstraintSystem::<E::Fr>::create(3); cs.append('a', &[0], &[one]); cs.append('a', &[1], &[one]); cs.append('a', &[], &[]); cs.append('a', &[2], &[one]); cs.append('a', &[2], &[negd]); cs.append('b', &[0], &[neg1]); cs.append('b', &[1], &[neg1]); cs.append('b', &[2], &[one]); cs.append('b', &[], &[]); cs.append('b', &[2], &[one]); cs.append('c', &[], &[]); cs.append('c', &[], &[]); cs.append('c', &[1], &[negd]); cs.append('c', &[0], &[neg1]); cs.append('c', &[2], &[d]); cs.k = CsVec::<E::Fr>::new(5, vec![4], vec![negd]); // We have the constraint system. Let's choose an example satisfying witness for Jubjub y^2-x^2=1+d*y^2*x^2 let x = E::Fr::from_str( "47847771272602875687997868466650874407263908316223685522183521003714784842376", ) .unwrap(); let y = E::Fr::from_str( "14866155869058627094034298869399931786023896160785945564212907054495032619276", ) .unwrap(); // check whether the point is on the curve let mut xx = x; let mut yy = y; xx.square(); yy.square(); let mut yy_xx_1 = yy; yy_xx_1.sub_assign(&xx); yy_xx_1.sub_assign(&one); let mut dxx = d; dxx.mul_assign(&xx); let mut dxxyy = dxx; dxxyy.mul_assign(&yy); assert_eq!(yy_xx_1, dxxyy); /* the point is on the curve, let's compute the witness and verify the circuit satisfiability Wire labels a=[y, x, yy] b=[y, x, dxx] c= [yy, xx, yy-xx-1] */ let mut witness = Witness::<E::Fr>::create(3, &mut rng); witness.gates[0] = CircuitGate::<E::Fr> { a: y, b: y, c: yy }; witness.gates[1] = CircuitGate::<E::Fr> { a: x, b: x, c: xx }; witness.gates[2] = CircuitGate::<E::Fr> { a: yy, b: dxx, c: yy_xx_1, }; // verify the circuit satisfiability by the computed witness assert_eq!(cs.verify(None, &witness), true); // The computation circuit is satisfied by the witness // Now let's chose invalid witness by changing just one digit let x = E::Fr::from_str( "57847771272602875687997868466650874407263908316223685522183521003714784842376", ) .unwrap(); let y = E::Fr::from_str( "14866155869058627094034298869399931786023896160785945564212907054495032619276", ) .unwrap(); // check whether the point is on the curve let mut xx = x; let mut yy = y; xx.square(); yy.square(); let mut yy_xx_1 = yy; yy_xx_1.sub_assign(&xx); yy_xx_1.sub_assign(&one); let mut dxx = d; dxx.mul_assign(&xx); let mut dxxyy = dxx; dxxyy.mul_assign(&yy); assert_ne!(yy_xx_1, dxxyy); /* the point is not on the curve, let's compute the witness and verify the circuit satisfiability Wire labels a=[y, x, yy] b=[y, x, dxx] c= [yy, xx, yy-xx-1] */ let mut witness = Witness::<E::Fr>::create(3, &mut rng); witness.gates[0] = CircuitGate::<E::Fr> { a: y, b: y, c: yy }; witness.gates[1] = CircuitGate::<E::Fr> { a: x, b: x, c: xx }; witness.gates[2] = CircuitGate::<E::Fr> { a: yy, b: dxx, c: yy_xx_1, }; // verify the circuit satisfiability by the computed witness assert_eq!(cs.verify(None, &witness), false); // The computation circuit is not satisfied by the witness } <file_sep>/******************************************************************************************** This source file implements helper's zk-proof primitives. This proof is constructed by helper after the successfull verification of the ProverProof. It is verified by the verifier as part of the verification of the NP-statement Sonic zk-proof. This is one of the two constituent parts of the NP-statement Sonic zk-proof, the other being the ProverProof. *********************************************************************************************/ pub use super::batch::{ProofError, ProverProof, RandomOracleArgument}; use circuits::constraint_system::ConstraintSystem; use commitment::urs::URS; use pairing::Engine; use polynomials::univariate::Univariate; use rand::OsRng; use sprs::CsVec; #[derive(Clone, Copy)] pub struct HelperProof<E: Engine> { // Commitment to univariate polynomial s(X, y) pub sxy_comm: E::G1Affine, // s(X, y) evaluation at x pub sxy_x_evl: E::Fr, // Commitment sxy_comm to s(X, y) opening at u pub sxy_u_prf: E::G1Affine, pub sxy_u_evl: E::Fr, // Proof of commitment sux_comm to s(u, X) opening at y pub sux_y_prf: E::G1Affine, } impl<E: Engine> HelperProof<E> { // This function constructs helper's zk-proof from the constraint system and prover's proof against URS instance // prover: prover's proof // cs: constraint system // k: optional public params as vector K update // sux: batch proof polynomial reference // urs: universal reference string // u: random oracle from the batch proof // verify: flag indicating whether to verify the prover's proof (if verified in batch) // RETURN: helper's zk-proof pub fn create( prover: &mut ProverProof<E>, cs: &ConstraintSystem<E::Fr>, k: Option<CsVec<E::Fr>>, sux: &Univariate<E::Fr>, urs: &URS<E>, verify: bool, u: E::Fr, ) -> Result<Self, ProofError> { let mut rng = OsRng::new().unwrap(); // the prover's transcript of the random oracle non-interactive argument let (x, y, _, mask) = prover.oracles(cs, &k); // compute s(X, y) polynomial let rslt = cs.evaluate_s(y, false); if rslt.is_none() { return Err(ProofError::SXyxEvalComputation); } let sxy = rslt.unwrap(); // eveluate s(X, Y) at (x, y) let rslt = sxy.evaluate(x); if rslt.is_none() { return Err(ProofError::SXyxEvalComputation); } let sxy_x_evl = rslt.unwrap(); // vrify the prover's proof if batch verification was not successfull if verify && !prover.verify(&sxy_x_evl, cs, k, urs, &mut rng) { return Err(ProofError::ProverVerification); } // commit to univariate polynomial s(X, y) let sxy_comm = urs.commit(&sxy, cs.a.shape().1 * 2 + 1); // helper opens the polynomial s(X, y) commitment at x by updating prover's batch_x_prf let rslt = urs.open(&sxy, x); if rslt.is_none() { return Err(ProofError::SXyxPrfComputation); } prover.batch_x_prf = URS::<E>::update_batch(prover.batch_x_prf, rslt.unwrap(), mask, 3); // helper opens the polynomial s(X, y) commitment at u let rslt = sxy.evaluate(u); if rslt.is_none() { return Err(ProofError::SXyuEvalComputation); } let sxy_u_evl = rslt.unwrap(); let rslt = urs.open(&sxy, u); if rslt.is_none() { return Err(ProofError::SXyuPrfComputation); } let sxy_u_prf = rslt.unwrap(); // helper opens the polynomial s(u, X) commitment at y let rslt = urs.open(&sux, y); if rslt.is_none() { return Err(ProofError::SuXyPrfComputation); } let sux_y_prf = rslt.unwrap(); Ok(HelperProof { sxy_comm: sxy_comm, sxy_x_evl: sxy_x_evl, sxy_u_prf: sxy_u_prf, sxy_u_evl: sxy_u_evl, sux_y_prf: sux_y_prf, }) } } <file_sep>/***************************************************************************************************************** This source file implements the Fast Fourier Transform test. The tests proceeds as follows: 1. generate random vector 2. compute its Discrete Fourier Transform 3. compute the reverse Discrete Fourier Transform of the transform 4. compare the computed RDFT with the original vector *****************************************************************************************************************/ use pairing::{bls12_381::Bls12, Engine, Field, PrimeField}; use polynomials::univariate::Univariate; use rand::Rng; #[test] fn dft_test() { test::<Bls12>(); } fn test<E: Engine>() { let mut rng = rand::thread_rng(); let mut rand = || -> E::Fr { loop { let rnd: u64 = rng.gen(); let x: String = rnd.to_string(); if let Some(y) = E::Fr::from_str(&x) { return y; } } }; let vec1: Vec<E::Fr> = (0..579).map(|_| -> E::Fr { rand() }).collect(); let vec2 = Univariate::<E::Fr>::dft(vec1.clone(), None, false); let vec3 = Univariate::<E::Fr>::dft(vec2.clone(), None, true); let vec4 = Univariate::<E::Fr>::dft(vec3.clone(), None, false); let vec5 = Univariate::<E::Fr>::dft(vec4.clone(), None, true); fn eq<E: Engine>(mut a: E::Fr, b: E::Fr) -> bool { a.sub_assign(&b); a.is_zero() } assert_eq!(vec3.len(), vec5.len()); assert_eq!( vec3.iter().zip(vec5.iter()).all(|(&a, &b)| eq::<E>(a, b)), true ); } <file_sep>/***************************************************************************************************************** This source file implements the batched polynomial commitment unit test suite driver. The following tests are implemented: 1. Batched polynomial commiment test 1. Generate URS instance of sufficient depth 2. Generate vector of vectors of random polynomials over the base field that fits into the URS depth. The polynomial coefficients are random base filed elements 3. Commit to the polynomial vectors against the URS instance with masking/scaling value 4. Evaluate the polynomials at a given randomly generated base field element 5. Open the polynomial commitment vectors at the given random base field element producing the opening proof 6. Verify the commitment vector opening proof against the: a. the URS instance b. Polynomial evaluations at the given base field element c. The given base field element d. Commitment opening proof *****************************************************************************************************************/ use commitment::urs::URS; use pairing::{bls12_381::Bls12, Engine}; use polynomials::univariate::Univariate; use rand::OsRng; #[test] fn batch_commitment_test() { test::<Bls12>(); } fn test<E: Engine>() { let mut rng = OsRng::new().unwrap(); let depth = 50; // generate sample URS let urs = URS::<E>::create( depth, vec![depth / 3 - 3, depth / 3 - 4, depth / 3 - 5], Univariate::<E::Fr>::rand(&mut rng), Univariate::<E::Fr>::rand(&mut rng), ); // generate random polynomials over the base field let mut block: Vec<(E::Fr, E::Fr, Vec<(E::G1Affine, E::Fr, usize)>, E::G1Affine)> = Vec::new(); for _ in 0..7 { let elm = Univariate::<E::Fr>::rand(&mut rng); let mask = Univariate::<E::Fr>::rand(&mut rng); let mut plnms: Vec<Univariate<E::Fr>> = Vec::new(); let mut max: Vec<usize> = Vec::new(); let mut eval: Vec<E::Fr> = Vec::new(); let mut plnm = Univariate::<E::Fr> { pos: (0..depth / 3 - 3) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), neg: (0..depth / 3 - 7) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), }; max.push(plnm.pos.len()); eval.push(plnm.evaluate(elm).unwrap()); plnms.push(plnm); plnm = Univariate::<E::Fr> { pos: (0..depth / 3 - 4) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), neg: (0..depth / 3 - 9) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), }; max.push(plnm.pos.len()); eval.push(plnm.evaluate(elm).unwrap()); plnms.push(plnm); plnm = Univariate::<E::Fr> { pos: (0..depth / 3 - 5) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), neg: (0..depth / 3 - 3) .map(|_| -> E::Fr { Univariate::<E::Fr>::rand(&mut rng) }) .collect(), }; max.push(plnm.pos.len()); eval.push(plnm.evaluate(elm).unwrap()); plnms.push(plnm); // Commit, open and verify the polynomial commitments let comm = urs.commit_batch( &plnms .clone() .into_iter() .zip(max.clone().into_iter()) .collect(), ); match urs.open_batch(&plnms, mask, elm) { None => { panic!("This error should not happen"); } Some(prf) => { block.push(( elm, mask, comm.into_iter() .zip(eval.into_iter()) .zip(max.into_iter()) .map(|((x, y), z)| (x, y, z)) .collect(), prf, )); } } } assert_eq!(true, urs.verify(&vec![block; 1], &mut rng)); } <file_sep>/***************************************************************************************************************** This source file implements Sonic computation witness primitive. Sonic witness consists of value assignements to the circuit wires that provide input and carry output values to/from the multiplicative gates of the circuit. Thus assigned value witness is defined as three vectors of wire label value assignements: Left input A Right input B Output C *****************************************************************************************************************/ pub use super::gate::CircuitGate; use pairing::{Field, PrimeField}; use polynomials::univariate::Univariate; use rand::OsRng; #[derive(Clone)] pub struct Witness<F: Field> { pub gates: Vec<CircuitGate<F>>, // circuit gate array blinders: (F, F, F, F), } impl<F: PrimeField> Witness<F> { // This function creates zero-instance witness of given depth pub fn create(n: usize, rng: &mut OsRng) -> Self { Self { gates: vec![CircuitGate::<F>::create(); n], blinders: ( Univariate::<F>::rand(rng), Univariate::<F>::rand(rng), Univariate::<F>::rand(rng), Univariate::<F>::rand(rng), ), } } // This function constructs r polynomial from the witness pub fn compute(&self, y: F) -> Univariate<F> { let depth = self.gates.len(); let mut rx = Univariate::<F>::create(2 * depth + 5, depth + 1); // adjust rx with blinders rx.neg[2 * depth + 1] = self.blinders.0; rx.neg[2 * depth + 2] = self.blinders.0; rx.neg[2 * depth + 3] = self.blinders.0; rx.neg[2 * depth + 4] = self.blinders.0; if y == F::one() { for i in 0..depth { rx.pos[i + 1] = self.gates[i].a; rx.neg[i + 1] = self.gates[i].b; rx.neg[i + depth + 1] = self.gates[i].c; } } else { let yinv = y.inverse().unwrap(); let mut yaccinv = F::one(); let mut yacc = F::one(); for i in 0..depth { yacc.mul_assign(&y); rx.pos[i + 1] = self.gates[i].a; rx.pos[i + 1].mul_assign(&yacc); yaccinv.mul_assign(&yinv); rx.neg[i + 1] = self.gates[i].b; rx.neg[i + 1].mul_assign(&yaccinv); } for i in 0..depth { yaccinv.mul_assign(&yinv); rx.neg[i + depth + 1] = self.gates[i].c; rx.neg[i + depth + 1].mul_assign(&yaccinv); } for i in 0..4 { yaccinv.mul_assign(&yinv); rx.neg[2 * depth + 1 + i].mul_assign(&yaccinv); } } rx } } <file_sep>use circuits::constraint_system::ConstraintSystem; use pairing::{bls12_381::Bls12, Engine, Field, PrimeField}; use sprs::CsVec; #[test] fn constraints_system_serialization_test() { simple_test::<Bls12>(); } fn simple_test<E: Engine>() { // initialise constants // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); // Jubjub Edwards form coefficient d: y^2-x^2=1+d*y^2*x^2 let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let mut negd = d; negd.negate(); /* u= [[ 1, 0, 0], [0, 1, 0], [0, 0, 0], [ 0, 0, 1], [0, 0, -d]] v= [[-1, 0, 0], [0, -1, 0], [0, 0, 1], [ 0, 0, 0], [0, 0, 1]] w= [[ 0, 0, 0], [0, 0, 0], [0, -d, 0], [-1, 0, 0], [0, 0, d]] k= [0, 0, 0, 0, -d] */ let mut cs = ConstraintSystem::<E::Fr>::create(3); cs.append('a', &[0], &[one]); cs.append('a', &[1], &[one]); cs.append('a', &[], &[]); cs.append('a', &[2], &[one]); cs.append('a', &[2], &[negd]); cs.append('b', &[0], &[neg1]); cs.append('b', &[1], &[neg1]); cs.append('b', &[2], &[one]); cs.append('b', &[], &[]); cs.append('b', &[2], &[one]); cs.append('c', &[], &[]); cs.append('c', &[], &[]); cs.append('c', &[1], &[negd]); cs.append('c', &[0], &[neg1]); cs.append('c', &[2], &[d]); cs.k = CsVec::<E::Fr>::new(5, vec![4], vec![negd]); let mut v = vec![]; cs.write(&mut v).unwrap(); let de_cs = ConstraintSystem::<E::Fr>::read(&v[..]).unwrap(); assert_eq!(cs, de_cs); } <file_sep>/***************************************************************************************************************** This source file implements Sonic Constraint System unit test suite driver. The following tests are implemented: 1. Checking Point conversion formula between Edwards and Montgomery coordinates. This test implements the constraint system as per section 4.2.5 of circuits.pdf document. For the wire labels a = [x, y] b = [v, u+1] c = [sqrt(-40964)*u, u-1] the linear constraint system is: u= [[0,0],[0,0]] v= [[0,1],[0,-sqrt(-40964)]] w= [[0,-1],[1,0]] k= [2,-sqrt(-40964)] The test verifies both positive and negative outcomes for satisfying and not satisfying witnesses *****************************************************************************************************************/ use circuits::constraint_system::{CircuitGate, ConstraintSystem, Witness}; use pairing::{bls12_381::Bls12, Engine, Field, PrimeField}; use rand::OsRng; use sprs::CsVec; // The following test verifies the addition of jubjub points #[test] fn constraints_test() { group_convert_test::<Bls12>(); } #[allow(non_snake_case)] fn group_convert_test<E: Engine>() { let mut rng = OsRng::new().unwrap(); // initialise constants // field zero element let zero = E::Fr::zero(); // field unity element let one = E::Fr::one(); let mut neg1 = one; // field negative unit element neg1.negate(); let two = E::Fr::from_str("2").unwrap(); let negsqrtmjjA = E::Fr::from_str( "34620988240753777635981679240161257563063072671290560217967936669160105133864", ) .unwrap(); let sqrtmjjA = E::Fr::from_str( "17814886934372412843466061268024708274627479829237077604635722030778476050649", ) .unwrap(); // <NAME> form coefficient d: y^2-x^2=1+d*y^2*x^2 let d = E::Fr::from_str( "19257038036680949359750312669786877991949435402254120286184196891950884077233", ) .unwrap(); let mut negd = d; negd.negate(); // our circuit cinstraint system let mut cs = ConstraintSystem::<E::Fr>::create(2); cs.b.insert(0, 1, one); cs.c.insert(0, 1, neg1); cs.c.insert(1, 0, one); cs.b.insert(1, 1, negsqrtmjjA); cs.a.insert(0, 0, zero); cs.a.insert(1, 0, zero); let inds = vec![0, 1]; let vals = vec![two, negsqrtmjjA]; cs.k = CsVec::<E::Fr>::new(2, inds, vals); // We have the constraint system. Let's choose points (x,y) and (u,v) // correspond to their addition let x = E::Fr::from_str( "853554559207543847252664416966410582098606963183071025729253243887385698701", ) .unwrap(); let y = E::Fr::from_str( "14764243698000945526787211915034316971081786721517742096668223329470205650604", ) .unwrap(); let u = E::Fr::from_str( "49792417373762009466546315427310015213131913431044267875338124358756912689577", ) .unwrap(); let v = E::Fr::from_str( "18704088696874163653775932556954898929880637695754080357664668755728034697568", ) .unwrap(); // check whether the point is on the curve /* a = [x, y] b = [v, u+1] c = [sqrt(-40964)*u, u-1] */ let mut up1 = u; up1.add_assign(&one); let mut um1 = u; um1.sub_assign(&one); let mut xv = x; xv.mul_assign(&v); let mut yup1 = y; yup1.mul_assign(&up1); let mut sqrtmjjAu = sqrtmjjA; sqrtmjjAu.mul_assign(&u); assert_eq!(xv, sqrtmjjAu); assert_eq!(yup1, um1); /* the point (x,y) in Edwards coordinates corresponds to point (u,v) in Montgomery coordinates. Wire labels a = [x, y] b = [v, u+1] c = [sqrt(-40964)*u, u-1] */ let mut witness = Witness::<E::Fr>::create(2, &mut rng); witness.gates[0] = CircuitGate::<E::Fr> { a: x, b: v, c: sqrtmjjAu, }; witness.gates[1] = CircuitGate::<E::Fr> { a: y, b: up1, c: um1, }; // verify the circuit satisfiability by the computed witness assert_eq!(cs.verify(None, &witness), true); } <file_sep>pub mod univariate; pub mod utils;
681339be324d348863b7f840f2eb653a3e5c0e5d
[ "TOML", "Rust", "Markdown" ]
35
Rust
input-output-hk/sonic
c3fc1da9c8eece10a4db1814b985eed8b7735210
b93643550e3344c1fcf0992f3384fdd7eda1c2ae
refs/heads/master
<repo_name>ofnlut/PyDrive<file_sep>/robot.py #!/usr/bin/env python3 ''' This sample program shows how to control a motor using a joystick. In the operator control part of the program, the joystick is read and the value is written to the motor. Joystick analog values range from -1 to 1 and speed controller inputs also range from -1 to 1 making it easy to work together. The program also delays a short time in the loop to allow other threads to run. This is generally a good idea, especially since the joystick values are only transmitted from the Driver Station once every 20ms. ''' import wpilib class MyRobot(wpilib.SampleRobot): #: update every 0.005 seconds/5 milliseconds (200Hz) kUpdatePeriod = 0.005 def robotInit(self): '''Robot initialization function''' self.motor1 = wpilib.CANTalon(2) # initialize the motor as a Talon on channel 1 self.motor2 = wpilib.CANTalon(3) self.motor3 = wpilib.CANTalon(4).reverseOutput(True) #reverses the motor set so that it goes into the right direction self.motor4 = wpilib.CANTalon(1).reverseOutput(True) self.stick = wpilib.Joystick(0) # initialize the joystick on port 0 self.stick2 = wpilib.Joystick(1) # initialize the joystick on port 1 self.switch = wpilib.DigitalInput(9) self.piston1 = wpilib.DoubleSolenoid(0,1) self.encoder1 = wpilib.Encoder(0,1) if self.isReal(): self.compressor = wpilib.Compressor() self.compressor.start() def autonomous(self): '''Called when autonomous mode is enabled.''' while self.isAutonomous() and self.isEnabled(): wpilib.Timer.delay(0.01) def operatorControl(self): '''Runs the motor from a joystick.''' while self.isOperatorControl() and self.isEnabled(): # Set the motor's output. # This takes a number from -1 (100% speed in reverse) to # +1 (100% speed going forward) self.motor2.setFeedbackDevice() #Enables the dashboard to show the boolean of the object wpilib.SmartDashboard.putBoolean('Limit Switch', self.switch.get()) wpilib.SmartDashboard.putBoolean('Compressor', self.compressor.enabled()) wpilib.SmartDashboard.putBoolean('TRIGGER', self.stick.getTrigger()) #Still have no idea how this worked wpilib.SmartDashboard.putNumber('Encoder Distance', self.motor2.getEncPosition()) #reacts to joystick0 self.motor1.set(self.stick1.getY()) self.motor2.set(self.stick1.getY()) #reacts to joystick1 self.motor3.set(self.stick2.getY()) self.motor4.set(self.stick2.getY()) if self.stick.getTrigger(): self.piston1.set(1) else: self.piston1.set(2) wpilib.Timer.delay(self.kUpdatePeriod) # wait 5ms to the next update if __name__ == "__main__": wpilib.run(MyRobot)<file_sep>/README.md # PyDrive Stolen from Team 1915 to test out different drive types for FRC robots...to use for the programming team....for 1915.
b92362f77d6d7294ae6b2b89444cb424e278924f
[ "Markdown", "Python" ]
2
Python
ofnlut/PyDrive
4309c95192e8d2552e63880fde8e4aaca8bfe1a7
9a608f423d90147af2e23f0d384dba89362e5d9f
refs/heads/master
<file_sep>import React from 'react' const Messages = () => ( <div className="section"> <div className="container"> <h1>Messages</h1> </div> </div> ) export default Messages<file_sep>import React, { Component } from 'react'; import Base from './app/Base' import Coffee from './app/coffee/Layout' import Cookie from './app/cookie/Layout' class App extends Component { render() { return ( <Cookie /> ); } } export default App; <file_sep>import React from 'react'; import Star from '../../img/star.png'; // PROPS: // username - used for URL purposes // user - actual Name of user // date - date posted // desc - status update // hashtags - hashtags class PostStatus extends React.Component { constructor(props){ super(props); } render(){ var url = "/users/" + this.props.username; var fav = "none"; if (this.props.favorite) fav = "auto"; return( <div> <h2><date>{this.props.date} </date> <img src={Star} style={{width: '15px', marginRight: '5px', display: fav}} /> <a href={url}>{this.props.user}</a> updated their status.</h2> <hr /> <p>{this.props.user} says: "{this.props.desc}"</p> <p style={{color: 'blue'}}>{this.props.hashtags}</p> <br /><br /><br /> </div> ); } } export default PostStatus;<file_sep>import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import Cookie from './cookie/Layout' import Coffee from './coffee/Layout' class Base extends Component { constructor(props){ super(props); this.state = { cookie: false, coffee: false } this.cookieClick = this.cookieClick.bind(this); this.coffeeClick = this.cookieClick.bind(this); } cookieClick(){ this.setState({ cookie: true, coffee: false }); } coffeeClick(){ this.setState({ cookie: false, coffee: true }) } pick(){ if(this.state.coffee) return <Coffee/>; } render() { return ( <div> "Hello" <button onClick={this.coffeeClick}>coffee</button> {this.pick()} </div> ); } } export default Base; <file_sep>import React from 'react' import Star from '../img/star.png'; function User({ match }) { var username = match.params.id; var nameArr = []; nameArr = username.split("-"); var fullName = ""; for(var i = 0; i < nameArr.length; i++){ fullName = fullName + nameArr[i].charAt(0).toUpperCase() + nameArr[i].slice(1) + " "; } return(<div className="section"> <div className="container"> <h1>{fullName}</h1> <hr /> Here is the user's information </div> </div>); } export default User<file_sep>import React from 'react' import Star from '../img/star.png'; const Home = () => ( <div className="section"> <div className="container"> BOOP <h1>Hi there, welcome to <strong>sweetsmart: version cookie</strong>!</h1> <p>We're excited to have you here. We are currently in Beta, and we're super excited that you're one of the first humans to review our user interface platform. <strong>sweetsmart</strong> is a social media website whose aim is to keep accessibility design in mind. Our goal is to create more satisfying user experiences through ethical web design and increasing awareness of accessibility in technology. This is the first of 7 interfaces that you are going to review throughout this session. Any questions, please let us know! Below are some notes to discuss before we get started... </p> <br /> <p> <center> <table className="table"> <thead> <tr> <th>Symbol</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td> <img src={Star} style={{width: '15px'}}/> </td> <td> Indicates a favorite person, i.e. someone you are close to. </td> </tr> </tbody> </table> </center> </p> <br /> <p>Once you are finished reviewing this interface, click the two buttons below to review this interface, and then move on to the next one. You can spend as much or as little time on each interface as you wish.</p> <br /> <center> <p><a className="button is-primary"><strong>Step 1: review</strong></a></p> <br /> <p><a className="button is-primary" href="/coffee"><strong>Step 2: version coffee</strong></a></p> </center> </div> </div> ) export default Home<file_sep>import React from 'react'; import Star from '../../img/star.png'; // PROPS: // username - used for URL purposes // user - actual Name of user // date - date posted // photo - photo name saved in /img // desc - photo description // hashtags - hashtags class PostPic extends React.Component { constructor(props){ super(props); } render(){ var url = "/users/" + this.props.username; var photo = this.props.photo; var fav = "none"; if (this.props.favorite) fav = "auto"; return( <div> <h2><date>{this.props.date} </date> <img src={Star} style={{width: '15px', marginRight: '5px', display: fav}} /> <a href={url}>{this.props.user}</a> posted a new picture.</h2> <hr /> <img src={require(`../../img/${photo}.png`)} style={{width: '100px', height: '100px', margin: '10px', float: 'left'}}/><p>{this.props.user} says: "{this.props.desc}"</p> <p style={{color: 'blue'}}>{this.props.hashtags}</p> <br /><br /><br /> </div> ); } } export default PostPic;<file_sep>import React from 'react' import Star from '../img/star.png'; const Friends = () => ( <div className="section"> <div className="container"> <h1>Friends List</h1> <hr /> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2><img src={Star} style={{width: '15px'}} />&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2><img src={Star} style={{width: '15px'}} />&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2 style={{marginLeft: '15px'}}>&nbsp;<NAME></h2> <h2><img src={Star} style={{width: '15px'}} /> Tammy Pickles</h2> <h2><img src={Star} style={{width: '15px'}} /> Tana Lee</h2> <h2 style={{marginLeft: '15px'}}>&nbsp;Vera Bradley</h2> <h2 style={{marginLeft: '15px'}}>&nbsp;Wanda Grapes</h2> <h2 style={{marginLeft: '15px'}}>&nbsp;Yusef Romaine Lettuce</h2> </div> </div> ) export default Friends<file_sep>import React from 'react' import { Switch, Route } from 'react-router-dom' import Base from './Base' // cookie import HomeCookie from './cookie/Home' import MessagesCookie from './cookie/Messages' import TimelineCookie from './cookie/Timeline' import FriendsCookie from './cookie/Friends' import UserCookie from './cookie/User' // coffee import HomeCoffee from './coffee/Home' import MessagesCoffee from './coffee/Messages' import TimelineCoffee from './coffee/Timeline' import FriendsCoffee from './coffee/Friends' const Router = () => ( <Switch> <Route exact path='/' component={Base}/> <Route exact path='/cookie' component={HomeCookie}/> <Route path='/cookie/timeline' component={TimelineCookie}/> <Route path='/cookie/friends' component={FriendsCookie}/> <Route path='/cookie/messages' component={MessagesCookie}/> <Route path='/cookie/users/:id' component={UserCookie}/> <Route exact path='/coffee' component={HomeCoffee}/> <Route path='/coffee/timeline' component={TimelineCoffee}/> <Route path='/coffee/friends' component={FriendsCoffee}/> <Route path='/coffee/messages' component={MessagesCoffee}/> </Switch> ) export default Router
cf109044ec2b346d71b3004499d0a6457c804ab6
[ "JavaScript" ]
9
JavaScript
egoroza/sweetsmart
fdcfc5b65d85413b5ff99e5aff493d971bcd491d
a5e807dfb69e8abc8209c028ace875374e6db513
refs/heads/master
<file_sep>package Ejercicio1; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; class NodoA { Agencia agencia; NodoA izquierdo; NodoA derecho; NodoA() { agencia = null; izquierdo = null; derecho = null; } public boolean NodoHoja() { if(this.derecho == null && this.izquierdo == null) { return true; } else return false; } } public class ArbolAgencias { NodoA raiz; NodoA actual; String[] provincias = { "Guanacaste", "Limon", "Alajuela", "<NAME>", "Cartago", "Heredia", "Puntarenas" }; ArrayList<String> recorrido = new ArrayList<String>(); ArrayList<Agencia> agencias = new ArrayList<Agencia>(); ArrayList<Integer> agenciasDisponibles = new ArrayList<Integer>(); ArrayList<Integer> agenciasIngresadas = new ArrayList<Integer>(); int size; boolean encontrado = false; boolean eliminado = false; File fichero = null; public ArbolAgencias() { raiz = null; size = 0; } /** * get size * @return - size */ public int size() { return size; } /** * Verifica el numero de agencia para luego asiganrle una provincia a la agencia * @param codigo - Int odigo agencia * @param canton - String canton * @return */ public String verificarInsercion(int codigo, String canton) { String provincia = ""; String re = ""; if (codigo > 0 && codigo < 101) { provincia = "Guanacaste"; } else if (codigo > 101 && codigo < 201) { provincia = "Limon"; } else if (codigo > 201 && codigo < 301) { provincia = "Alajuela"; } else if (codigo > 301 && codigo < 401) { provincia = "San Jose"; } else if (codigo > 401 && codigo < 501) { provincia = "Cartago"; } else if (codigo > 501 && codigo < 601) { provincia = "Heredia"; } else if (codigo > 601 && codigo < 701) { provincia = "Puntarenas"; } int cp = 25; do { cp = Integer.parseInt(JOptionPane .showInputDialog("Ingrese la cantidad de la planilla:")); if (cp >24 && cp < 201) break; JOptionPane.showMessageDialog(null, "EL numero minimo de Planilla debe ser de 25 y maximo 200"); } while (true); NodoA nuevoNodo = new NodoA(); Agencia nuevaAgencia = new Agencia(codigo, provincia, canton, cp); nuevoNodo.derecho = null; nuevoNodo.izquierdo = null; nuevoNodo.agencia = nuevaAgencia; re = insertar(nuevoNodo, this.raiz); return re; } /** * Inserta un nodo. Es un metodo recursivo. * Se busca un nodo a la izquierda o derecha dependiendo de la condicio * @param nodo - Nodo a insertar * @param padre - Nodo padre * @return */ public String insertar(NodoA nodo, NodoA padre) { String r = ""; if (padre == null) { this.raiz = nodo; r = "Agencia agregada con exito!"; size++; } else { if (nodo.agencia.codigo < padre.agencia.codigo) { if (padre.izquierdo == null) { padre.izquierdo = nodo; r = "Agencia agregada con exito"; size++; } else { insertar(nodo, padre.izquierdo); } } else { if (padre.derecho == null) { padre.derecho = nodo; r = "Agencia agregada con exito"; size++; } else { insertar(nodo, padre.derecho); } } } return r; } // ******************************** /** * Se muestran los nodos del arbol dependiendo del orden seleccionado * @param orden - String orden * @return - String */ public String listarPorRecorrido(String orden) { String re = ""; recorrido.clear(); if (orden.equals("EnOrden")) { re += "\nEnOrden:" + "\nC.d.P : Cantidad de planilla" + "\nC.d.E: Cantidad de empleados ingresados" + "\nCodigo:\tProvincia:\tCanton:\tC.d.P\tC.d.E"; listarEnOrden(); } else if (orden.equals("PreOrden")) { re += "\nPreOrden:" + "\nC.d.P : Cantidad de planilla" + "\nC.d.E: Cantidad de empleados ingresados" + "\nCodigo:\tProvincia:\tCanton:\tC.d.P\tC.d.E"; listarPreOrden(); } else if (orden.equals("PostOrden")) { re += "\nPostOrden:" + "\nC.d.P : Cantidad de planilla" + "\nC.d.E: Cantidad de empleados ingresados" + "\nCodigo:\tProvincia:\tCanton:\tC.d.P\tC.d.E"; listarPostOrden(); } for (int x = 0; x < recorrido.size(); x++) { re += recorrido.get(x); } return re; } // ******************************** public void listarPreOrden() { listarPreOrden(raiz); } /** * Se lista en preorden, guardando lo encontrado en un array de string * @param reco */ private void listarPreOrden(NodoA reco) { if (reco != null) { recorrido.add("\n" + reco.agencia.codigo + "\t" + reco.agencia.provincia + "\t" + reco.agencia.canton + "\t" + reco.agencia.cantidadPlanilla + "\t" + reco.agencia.cantidadEmpleadosIngresados); listarPreOrden(reco.izquierdo); listarPreOrden(reco.derecho); } } // ******************************** public void listarEnOrden() { listarEnOrden(raiz); } /** * Se lista en En orden, guardando lo encontrado en un array de string * * @param reco * - Nodo raiz */ private void listarEnOrden(NodoA reco) { if (reco != null) { listarEnOrden(reco.izquierdo); recorrido.add("\n" + reco.agencia.codigo + "\t" + reco.agencia.provincia + "\t" + reco.agencia.canton + "\t" + reco.agencia.cantidadPlanilla + "\t" + reco.agencia.cantidadEmpleadosIngresados); listarEnOrden(reco.derecho); } } // ******************************** public void listarPostOrden() { listarPostOrden(raiz); } /** * Se lista en postorden, guardando lo encontrado en un array de string * * @param reco * - Nodo raiz */ private void listarPostOrden(NodoA reco) { if (reco != null) { listarPostOrden(reco.izquierdo); listarPostOrden(reco.derecho); recorrido.add("\n" + reco.agencia.codigo + "\t" + reco.agencia.provincia + "\t" + reco.agencia.canton + "\t" + reco.agencia.cantidadPlanilla + "\t" + reco.agencia.cantidadEmpleadosIngresados); } } // ******************************** /** * Busca un nodo- Es un metodo recursivo que se llama si no se encuentra el * nodo Se utiliza un nodo llamada actual para hacer la referencia al nodo * encontrado * * @param codigo * - Int codgo de la agencia * @param padre * - Nodo raiz */ private void buscar(int codigo, NodoA padre) { if (padre == null) { encontrado = false; } else if (codigo == padre.agencia.codigo) { actual = padre; encontrado = true; } else if (codigo < padre.agencia.codigo) { buscar(codigo, padre.izquierdo); } else { buscar(codigo, padre.derecho); } } /** * Muestra una agencia a partir de la busqueda por medio de su codigo * * @param codigo * - Int codigo de la agencia * @return String */ public String mostrarAgencia(int codigo) { String r = ""; buscar(codigo, raiz); if (size() > 0) { if (encontrado) { r = "Se ha encontrado!"; r += "\n\nC.d.P : Cantidad de planilla" + "\nC.d.E: Cantidad de empleados ingresados" + "\nCodigo:\tProvincia:\tCanton:\tC.d.P\tC.d.E"; r += "\n" + actual.agencia.codigo + "\t" + actual.agencia.provincia + "\t" + actual.agencia.canton + "\t" + actual.agencia.cantidadPlanilla + "\t" + actual.agencia.cantidadEmpleadosIngresados; } else { r = "No se ha encontrado!"; } } else { r = "Sin agencias agregadas!"; } return r; } /** * Insertamos un Empleado en una agencia que se busca por su codigo * * @param codigo * - Int codigo de la agencia a buscar * @param e * - Empleado que se agregara * @return String - Resultado que se seteara en el JTextArea */ public String insertarEmpleado(int codigo, Empleados e) { String r = ""; boolean flag = false; encontrado = false; buscar(codigo, raiz); if (encontrado) { if (actual.agencia.cantidadEmpleadosIngresados <= actual.agencia.cantidadPlanilla) flag = actual.agencia.arbolEmpleados.insertar(e); else r = "La planila esta al maximo! No se pueden agregar mas empleados."; } else { r = "Agencia no encontrada!"; } if (flag) { r = "Empleado agregado con exito!"; actual.agencia.cantidadEmpleadosIngresados++; } else r = "Empleado ya ingresado!"; return r; } /** * Se busca una agencia determinada y luego en empleado * * @param codigo * - Int codigo de la agencia * @param identi * - Int identificacion del empleado * @return - String texto que se setea en el JTextArea */ public String buscarEmpleado(int codigo, int identi) { String r = ""; encontrado = false; buscar(codigo, raiz); if (encontrado) { r += actual.agencia.arbolEmpleados.mostrarEmpleado(identi); } return r; } // ******************************** public void elimina( int borrar){ NodoA padre = raiz; NodoA actual = raiz; boolean detiene = false; if(raiz.agencia.codigo == borrar && raiz.derecho==null && raiz.izquierdo==null){ raiz=null; JOptionPane.showMessageDialog(null,"Registro Eliminado "); detiene=true; } else if(raiz.agencia.codigo == borrar && raiz.izquierdo!=null && raiz.derecho!=null){ raiz=raiz.derecho; } else if(raiz.agencia.codigo == borrar && raiz.izquierdo!=null && raiz.derecho!=null){ raiz=raiz.izquierdo; } else if( raiz.agencia.codigo == borrar && raiz.derecho!=null && raiz.derecho!=null){//xx if( raiz.derecho.NodoHoja() && raiz.izquierdo.NodoHoja() ){ raiz.derecho.izquierdo = raiz.izquierdo; raiz=raiz.derecho; listarPostOrden(); } else {//jj JOptionPane.showMessageDialog(null," Antes de ciclo"); NodoA temporal=raiz.izquierdo; NodoA BuscaExtremo=raiz.derecho; NodoA FuturaRaiz = raiz.derecho; // padre.derecha=actual.izquierda; while(BuscaExtremo.izquierdo!=null){ //whileb BuscaExtremo=BuscaExtremo.izquierdo; JOptionPane.showMessageDialog(null,"Buscando Extremo izquierdo de Raiz Derecho"); } //whileb BuscaExtremo.izquierdo=temporal; raiz=null; raiz=FuturaRaiz; detiene = true; }//jj }//xx while (detiene != true){///Whilerr JOptionPane.showMessageDialog(null,"ciclo"); if( actual.derecho!=null&& actual.izquierdo!=null){ JOptionPane.showMessageDialog(null, "Lo sentimos , El registro que Desea borrar No existe" ) ; } if(borrar > actual.agencia.codigo && actual.derecho!=null){ padre=actual; actual=actual.derecho; } if( borrar < actual.agencia.codigo && actual.izquierdo!=null) { padre=actual; actual=actual.izquierdo; } if(borrar == actual.agencia.codigo) { Borra(actual,padre); JOptionPane.showMessageDialog(null,"Entro"); detiene=true; } }///Whilerr }//// borrar public boolean Borra(NodoA actual, NodoA padre){ if (actual == padre.izquierdo){ // CUANDO VA BORRAR EL LADO IZQUIERDO if(actual.derecho==null && actual.izquierdo==null ){//gg if(padre.izquierdo == actual){ padre.izquierdo=null; actual=null; return true; } if (padre.derecho == actual){ padre.derecho =null; actual=null; return true; } }//gg if(actual.derecho==null && actual.izquierdo==null ){//hh padre.izquierdo=actual.izquierdo; actual = null; return true; }//hh if(actual.izquierdo==null && actual.derecho==null){//kk padre.izquierdo =actual.derecho; actual=null; return true; }//kk if(actual.derecho!=null && actual.izquierdo!=null){//nn NodoA temporal=actual.izquierdo; NodoA BuscaExtremo=actual.derecho; padre.izquierdo=actual.derecho; while(BuscaExtremo.izquierdo!=null){ //wwhile BuscaExtremo=BuscaExtremo.izquierdo; JOptionPane.showMessageDialog(null,"Buscando Extremo Izquierdo del actual derecha"); } //wwhile BuscaExtremo.izquierdo=temporal; actual=null; return true; }//nn }// CUANDO VA BORRAR EL LADO IZQUIERDO if(actual == padre.derecho){ // CUANDO VA BORRAR EN EL LADO DERECHO if(actual.derecho==null && actual.izquierdo==null){//oo if(padre.derecho == actual){ padre.derecho=null; actual=null; return true; } if (padre.izquierdo == actual){ padre.izquierdo =null; actual=null; return true; } }//oo if(actual.derecho!=null && actual.izquierdo==null) { padre.derecho=actual.derecho; actual = null; return true; } if(actual.derecho==null && actual.izquierdo!=null){ padre.derecho=actual.izquierdo; actual=actual.izquierdo; } if(actual.derecho!=null && actual.izquierdo!=null){//dd NodoA temporal=actual.derecho; NodoA BuscaExtremo=actual.izquierdo; padre.derecho=actual.izquierdo; while(BuscaExtremo.derecho!=null){ BuscaExtremo=BuscaExtremo.derecho; JOptionPane.showMessageDialog(null,"Buscando Extremo derecho del actual izquierda"); } BuscaExtremo.derecho=temporal; actual=null; return true; }//dd }// CUANDO VA BORRAR EN EL LADO DERECHO return true; }// borra /** * Guarda las agencia en un archivo plano .dat. Utilizando el orden * PreoOrden */ public void guardar() { JFileChooser chooser = new JFileChooser(); fichero = new File("Arboles.dat"); chooser.setSelectedFile(fichero); int seleccion = chooser.showSaveDialog(null); if (seleccion == JFileChooser.APPROVE_OPTION) { fichero = chooser.getSelectedFile(); try { agencias.clear(); ObjectOutputStream output = new ObjectOutputStream( new FileOutputStream(fichero)); recorrerPreOrden(raiz); System.out.println(agencias.size()); for (int x = 0; x < agencias.size(); x++) { Agencia age = agencias.get(x); output.writeObject(age); } output.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Recupera y crea el arbol de las agencias a partir del archivo .dat */ public void recuperar() { JFileChooser chooser = new JFileChooser(); fichero = chooser.getSelectedFile(); int seleccion = chooser.showOpenDialog(null); if (seleccion == JFileChooser.APPROVE_OPTION) { fichero = chooser.getSelectedFile(); try { ObjectInputStream input = new ObjectInputStream( new FileInputStream(fichero)); Agencia aux = (Agencia) input.readObject(); while (aux != null) { if (aux instanceof Agencia) { agencias.add(aux); agenciasIngresadas.add(aux.codigo); for (int x = 0; x < agenciasDisponibles.size(); x++) { if (agenciasDisponibles.get(x) == aux.codigo) { agenciasDisponibles.remove(x); } } } try { aux = (Agencia) input.readUnshared(); } catch (Exception ex) { break; } } input.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } for (int x = 0; x < agencias.size(); x++) { NodoA nuevo = new NodoA(); nuevo.agencia = agencias.get(x); this.insertar(nuevo, raiz); } } /** * Recorre en orden PreOrden para llenar el arraylist con las agencias para * ser guardadas en ese orden en el archivo .dat * * @param reco * - Nodo raiz */ private void recorrerPreOrden(NodoA reco) { if (reco != null) { agencias.add(reco.agencia); recorrerPreOrden(reco.izquierdo); recorrerPreOrden(reco.derecho); } } // ******************************** /** * Listadas los empleados en orden: EnOrnden */ public String buscarAgenciaYListarEmpleados(int codigo) { String r = ""; buscar(codigo, raiz); if (encontrado) { r += "C.d.P: Cantidad de planilla"; r += "\nC.d.E: Cantidad de empleados agregados"; r += "\n\nAgencia codigo:\t" + actual.agencia.codigo; r += "\nProvincia:\t" + actual.agencia.provincia; r += "\nCanton:\t" + actual.agencia.canton; r += "\nC.d.P:\t" + actual.agencia.cantidadPlanilla; r += "\nC.d.E:\t" + actual.agencia.cantidadEmpleadosIngresados; r += actual.agencia.arbolEmpleados.listarEmpleados(); } else r = "No encontrado"; return r; } }<file_sep>package Ejercicio3; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import javax.swing.JFileChooser; public class RecuperarGuardar { public static void guardar(ArrayList<?> lista) { try { JFileChooser chooser = new JFileChooser(); File fichero = new File("--.dat"); chooser.setSelectedFile(fichero); int seleccion = chooser.showSaveDialog(null); if (seleccion == JFileChooser.APPROVE_OPTION) { fichero = chooser.getSelectedFile(); ObjectOutputStream output = new ObjectOutputStream( new FileOutputStream(fichero)); for (int x = 0; x < lista.size(); x++) { output.writeObject(lista.get(x)); } output.close(); } } catch (IOException ioex) { ioex.printStackTrace(); } } /** * Recupera los productos de un archivo plano * * @return */ public static ArrayList<Producto> recuperarProductos() { ArrayList<Producto> productos = new ArrayList<Producto>(); try { JFileChooser chooser = new JFileChooser(); int seleccion = chooser.showOpenDialog(null); if (seleccion == JFileChooser.APPROVE_OPTION) { File fichero = chooser.getSelectedFile(); ObjectInputStream input = new ObjectInputStream( new FileInputStream(fichero)); Producto p = (Producto) input.readObject(); while (p != null) { productos.add(p); try { p = (Producto) input.readUnshared(); } catch (Exception ex) { break; } } input.close(); } } catch (IOException ioex) { ioex.printStackTrace(); } catch (ClassNotFoundException cnfex) { cnfex.printStackTrace(); } return productos; } /** * Recupera las ventas de un archivo plano * * @return */ public static ArrayList<Ventas> recuperarVentas() { ArrayList<Ventas> ventas = new ArrayList<Ventas>(); try { JFileChooser chooser = new JFileChooser(); int seleccion = chooser.showOpenDialog(null); if (seleccion == JFileChooser.APPROVE_OPTION) { File fichero = chooser.getSelectedFile(); ObjectInputStream input = new ObjectInputStream( new FileInputStream(fichero)); Ventas v = (Ventas) input.readObject(); while (v != null) { ventas.add(v); try { v = (Ventas) input.readUnshared(); } catch (Exception ex) { break; } } input.close(); } } catch (IOException ioex) { ioex.printStackTrace(); } catch (ClassNotFoundException cnfex) { cnfex.printStackTrace(); } return ventas; } public static ArrayList<Compras> recuperarCompras() { ArrayList<Compras> compras = new ArrayList<Compras>(); try { JFileChooser chooser = new JFileChooser(); int seleccion = chooser.showOpenDialog(null); if (seleccion == JFileChooser.APPROVE_OPTION) { File fichero = chooser.getSelectedFile(); ObjectInputStream input = new ObjectInputStream( new FileInputStream(fichero)); Compras c = (Compras) input.readObject(); while (c != null) { compras.add(c); c = (Compras) input.readUnshared(); try { c = (Compras) input.readUnshared(); } catch (Exception ex) { break; } } input.close(); } } catch (IOException ioex) { ioex.printStackTrace(); } catch (ClassNotFoundException cnfex) { cnfex.printStackTrace(); } return compras; } } <file_sep>package Ejercicio3; import java.util.ArrayList; import javax.swing.JOptionPane; public class Mezcla { private static int[] facturas; private static int[] aux; private static int intercambios = 0; private static int comparaciones = 0; public static ArrayList<Object> ordenar(ArrayList<Compras> compras, ArrayList<Ventas> ventas) { intercambios = 0; comparaciones = 0; ArrayList<Object> comprasVentas = new ArrayList<Object>(); comprasVentas.addAll(compras); comprasVentas.addAll(ventas); facturas = getFacturas(comprasVentas); aux = new int[facturas.length]; mezclar(0, facturas.length - 1); comprasVentas = ordenarProductos(comprasVentas, facturas); JOptionPane.showMessageDialog(null, "Intercambios: " + intercambios + "\nComparaciones: " + comparaciones, "MEZCLA", JOptionPane.INFORMATION_MESSAGE); return comprasVentas; } public static int[] getFacturas(ArrayList<Object> compras) { int[] facturas = new int[compras.size()]; Compras c = null; Ventas v = null; for (int x = 0; x < compras.size(); x++) if (compras.get(x) instanceof Compras) { c = (Compras) compras.get(x); facturas[x] = (int) c.precioTotalSinDescuento; } else if (compras.get(x) instanceof Ventas) { v = (Ventas) compras.get(x); facturas[x] = v.numeroFactura; } return facturas; } private static ArrayList<Object> ordenarProductos(ArrayList<Object> lista, int[] facturas) { int pos = 0; ArrayList<Object> ordenadas = new ArrayList<Object>(); Compras c = null; Ventas v = null; for (int x = 0; x < lista.size(); x++) { for (int y = 0; y < lista.size(); y++) { if (lista.get(y) instanceof Compras) { c = (Compras) lista.get(y); if (c.precioTotalSinDescuento == facturas[pos]) { ordenadas.add(lista.get(y)); break; } } else if (lista.get(y) instanceof Ventas) { v = (Ventas) lista.get(y); if (v.numeroFactura == facturas[pos]) { ordenadas.add(lista.get(y)); break; } } } pos++; } return ordenadas; } private static void mezclar(int menor, int mayor) { if (menor < mayor) { int medio = menor + (mayor - menor) / 2; mezclar(menor, medio); mezclar(medio + 1, mayor); mezclar(menor, medio, mayor); } } private static void mezclar(int menor, int medio, int mayor) { for (int x = menor; x <= mayor; x++) aux[x] = facturas[x]; int i = menor; int j = medio + 1; int k = menor; while (i <= medio && j <= mayor) { comparaciones++; if (aux[i] <= aux[j]) { intercambios++; facturas[k] = aux[i]; i++; } else { intercambios++; facturas[k] = aux[j]; j++; } k++; } while (i <= medio) { intercambios++; facturas[k] = aux[i]; k++; i++; } } } <file_sep>package Ejercicio1; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.TitledBorder; public class Florida_Bebidas_SA extends JFrame { /** * Generado por el IDE */ private static final long serialVersionUID = 4286148739855335695L; private JTextArea jtxa_resultados; private JScrollPane jscrl_scroll; private JPanel jpnl_gestionEmpleados; private JPanel jpnl_gestionarAgencias; private JComboBox<Integer> jcbx_agenciasDisponibles; private JComboBox<String> jcbx_orden; private JComboBox<Integer> jcbx_agenciasAgregadasE; private JComboBox<Integer> jcbx_agenciasAgregadasA; private JPanel jpnl_agencias; ArrayList<Integer> agenciasDisponibles = new ArrayList<Integer>(); ArrayList<Integer> agenciasIngresadas = new ArrayList<Integer>(); ArbolAgencias arbolAgencias = new ArbolAgencias(); private JTextField jtxt_canton; private JTextField jtxt_identificarEmpleado; private JButton jbtn_eliminarEmpleado; private JButton jbtn_agregarEmpleado; private JButton jbtn_bucarEmpleado; private JTextField jtxt_salarioEmpleado; private JComboBox<String> jcbx_puestos; private JTextField jtxt_nombreEmpleado; /** * Constructor */ public Florida_Bebidas_SA(){ setTitle("Florida Bebidas S.A."); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(null); setSize(1017, 412); JTabbedPane jtpn_tabs = new JTabbedPane(JTabbedPane.TOP); jtpn_tabs.setBounds(10, 11, 491, 352); getContentPane().add(jtpn_tabs); jtxa_resultados = new JTextArea(); jtxa_resultados.setEditable(false); jtxa_resultados.setForeground(Color.RED); jtxa_resultados.setBackground(Color.BLACK); jscrl_scroll = new JScrollPane(jtxa_resultados); jscrl_scroll .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jscrl_scroll .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); jscrl_scroll.setBounds(551, 11, 440, 352); getContentPane().add(jscrl_scroll); jpnl_agencias = new JPanel(); jtpn_tabs.addTab("Agencias", null, jpnl_agencias, null); jpnl_agencias.setLayout(null); JLabel jlbl_nombreAgencia = new JLabel("Agregar Agencia"); jlbl_nombreAgencia.setBounds(10, 14, 120, 14); jpnl_agencias.add(jlbl_nombreAgencia); jpnl_gestionarAgencias = new JPanel(); jpnl_gestionarAgencias.setBorder(new TitledBorder(null, "Gestionar Agencias", TitledBorder.LEADING, TitledBorder.TOP, null, null)); jpnl_gestionarAgencias.setBounds(10, 69, 447, 244); jpnl_agencias.add(jpnl_gestionarAgencias); jpnl_gestionarAgencias.setLayout(null); JLabel jlbl_codigoAgencia = new JLabel("Codigo de agencia:"); jlbl_codigoAgencia.setEnabled(false); jlbl_codigoAgencia.setBounds(10, 33, 118, 14); jpnl_gestionarAgencias.add(jlbl_codigoAgencia); JButton jbtn_eliminarAgencia = new JButton("Eliminar"); jbtn_eliminarAgencia.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { eliminar(); } }); jbtn_eliminarAgencia.setEnabled(false); jbtn_eliminarAgencia.setBounds(10, 58, 89, 23); jpnl_gestionarAgencias.add(jbtn_eliminarAgencia); JButton jbtn_mostrarAgencia = new JButton("Mostrar"); jbtn_mostrarAgencia.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { mostrarAgencia(); } }); jbtn_mostrarAgencia.setEnabled(false); jbtn_mostrarAgencia.setBounds(109, 58, 89, 23); jpnl_gestionarAgencias.add(jbtn_mostrarAgencia); JSeparator jseparador1 = new JSeparator(); jseparador1.setBounds(10, 92, 301, 2); jpnl_gestionarAgencias.add(jseparador1); JButton jbtn_buscarAgencia = new JButton("Buscar Agencia"); jbtn_buscarAgencia.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { buscarAgencia(); } }); jbtn_buscarAgencia.setEnabled(false); jbtn_buscarAgencia.setBounds(10, 103, 135, 23); jpnl_gestionarAgencias.add(jbtn_buscarAgencia); JSeparator jseparador2 = new JSeparator(); jseparador2.setBounds(10, 171, 301, 2); jpnl_gestionarAgencias.add(jseparador2); JLabel jlbl_listarAgencias = new JLabel("Listar Agencias:"); jlbl_listarAgencias.setEnabled(false); jlbl_listarAgencias.setBounds(10, 184, 101, 14); jpnl_gestionarAgencias.add(jlbl_listarAgencias); jcbx_orden = new JComboBox<String>(); jcbx_orden.addItem("EnOrden"); jcbx_orden.addItem("PreOrden"); jcbx_orden.addItem("PostOrden"); jcbx_orden.setEnabled(false); jcbx_orden.setBounds(126, 181, 135, 20); jpnl_gestionarAgencias.add(jcbx_orden); JButton jbtn_listar = new JButton("Listar"); jbtn_listar.setEnabled(false); jbtn_listar.setBounds(10, 209, 89, 23); jbtn_listar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { listarPorOrden(); } }); jpnl_gestionarAgencias.add(jbtn_listar); JSeparator separator = new JSeparator(); separator.setOrientation(SwingConstants.VERTICAL); separator.setBounds(321, 11, 6, 221); jpnl_gestionarAgencias.add(separator); JButton jbtn_guardar = new JButton("Guardar"); jbtn_guardar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { guardarArbol(); } }); jbtn_guardar.setEnabled(false); jbtn_guardar.setBounds(337, 71, 100, 23); jpnl_gestionarAgencias.add(jbtn_guardar); JButton jbtn_recuperar = new JButton("Recuperar"); jbtn_recuperar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recuperarArbol(); } }); jbtn_recuperar.setBounds(337, 117, 100, 23); jpnl_gestionarAgencias.add(jbtn_recuperar); JButton btnBuscarAgenciaY = new JButton( "Buscar Agencia y listar empleados"); btnBuscarAgenciaY.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buscarAgenciaYListarEmpleados(); } }); btnBuscarAgenciaY.setEnabled(false); btnBuscarAgenciaY.setBounds(10, 137, 251, 23); jpnl_gestionarAgencias.add(btnBuscarAgenciaY); jcbx_agenciasAgregadasA = new JComboBox<Integer>(); jcbx_agenciasAgregadasA.setEnabled(false); jcbx_agenciasAgregadasA.setBounds(138, 30, 73, 20); jpnl_gestionarAgencias.add(jcbx_agenciasAgregadasA); JButton btnAgregar = new JButton("Agregar"); btnAgregar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { agregarAgencia(); } }); btnAgregar.setBounds(10, 39, 89, 23); jpnl_agencias.add(btnAgregar); jcbx_agenciasDisponibles = new JComboBox<Integer>(); jcbx_agenciasDisponibles.setBounds(140, 11, 120, 20); jpnl_agencias.add(jcbx_agenciasDisponibles); jtxt_canton = new JTextField(); jtxt_canton.setBounds(270, 11, 106, 20); jpnl_agencias.add(jtxt_canton); jtxt_canton.setColumns(10); JLabel label = new JLabel("<< Canton"); label.setBounds(386, 14, 90, 14); jpnl_agencias.add(label); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setToolTipText("El numero de empleados debe ser minimo de 25 personas y maximo 200."); lblNewLabel.setIcon(new ImageIcon(Florida_Bebidas_SA.class.getResource("/recursos/icono_informacion.jpg"))); lblNewLabel.setBounds(107, 39, 26, 14); jpnl_agencias.add(lblNewLabel); JPanel jpnl_empleados = new JPanel(); jtpn_tabs.addTab("Empleados", null, jpnl_empleados, null); jpnl_empleados.setLayout(null); jpnl_gestionEmpleados = new JPanel(); jpnl_gestionEmpleados.setBorder(new TitledBorder(UIManager .getBorder("TitledBorder.border"), "Gestion de Empleados", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); jpnl_gestionEmpleados.setBounds(10, 11, 220, 234); jpnl_empleados.add(jpnl_gestionEmpleados); jpnl_gestionEmpleados.setLayout(null); JLabel jlbl_nombreEmpleado = new JLabel("Nombre:"); jlbl_nombreEmpleado.setEnabled(false); jlbl_nombreEmpleado.setBounds(10, 84, 67, 14); jpnl_gestionEmpleados.add(jlbl_nombreEmpleado); jtxt_nombreEmpleado = new JTextField(); jtxt_nombreEmpleado.setEnabled(false); jtxt_nombreEmpleado.setBounds(102, 81, 100, 20); jpnl_gestionEmpleados.add(jtxt_nombreEmpleado); jtxt_nombreEmpleado.setColumns(10); JLabel jlbl_identificador = new JLabel("Identificador:"); jlbl_identificador.setEnabled(false); jlbl_identificador.setBounds(10, 59, 82, 14); jpnl_gestionEmpleados.add(jlbl_identificador); jtxt_identificarEmpleado = new JTextField(); jtxt_identificarEmpleado.setEnabled(false); jtxt_identificarEmpleado.setBounds(102, 56, 100, 20); jpnl_gestionEmpleados.add(jtxt_identificarEmpleado); jtxt_identificarEmpleado.setColumns(10); JLabel jlbl_puestoEmpleado = new JLabel("Puesto:"); jlbl_puestoEmpleado.setEnabled(false); jlbl_puestoEmpleado.setBounds(10, 109, 67, 14); jpnl_gestionEmpleados.add(jlbl_puestoEmpleado); jcbx_puestos = new JComboBox<String>(); jcbx_puestos.addItem("Distribuidor"); jcbx_puestos.addItem("Vendedor"); jcbx_puestos.addItem("Bodegero"); jcbx_puestos.setEnabled(false); jcbx_puestos.setBounds(102, 106, 100, 20); jpnl_gestionEmpleados.add(jcbx_puestos); JLabel jlbl_salario = new JLabel("Salario:"); jlbl_salario.setEnabled(false); jlbl_salario.setBounds(10, 134, 67, 14); jpnl_gestionEmpleados.add(jlbl_salario); jtxt_salarioEmpleado = new JTextField(); jtxt_salarioEmpleado.setEnabled(false); jtxt_salarioEmpleado.setBounds(102, 131, 100, 20); jpnl_gestionEmpleados.add(jtxt_salarioEmpleado); jtxt_salarioEmpleado.setColumns(10); JLabel jlbl_agencia = new JLabel("Agencia:"); jlbl_agencia.setEnabled(false); jlbl_agencia.setBounds(10, 29, 67, 14); jpnl_gestionEmpleados.add(jlbl_agencia); jbtn_agregarEmpleado = new JButton("Agregar"); jbtn_agregarEmpleado.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { agregarEmpleado(); } }); jbtn_agregarEmpleado.setEnabled(false); jbtn_agregarEmpleado.setBounds(10, 159, 89, 23); jpnl_gestionEmpleados.add(jbtn_agregarEmpleado); jbtn_bucarEmpleado = new JButton("Buscar"); jbtn_bucarEmpleado.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buscarEmpleado(); } }); jbtn_bucarEmpleado.setEnabled(false); jbtn_bucarEmpleado.setBounds(112, 159, 89, 23); jpnl_gestionEmpleados.add(jbtn_bucarEmpleado); jbtn_eliminarEmpleado = new JButton("Eliminar"); jbtn_eliminarEmpleado.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { eliminar(); } }); jbtn_eliminarEmpleado.setEnabled(false); jbtn_eliminarEmpleado.setBounds(10, 193, 89, 23); jpnl_gestionEmpleados.add(jbtn_eliminarEmpleado); jcbx_agenciasAgregadasE = new JComboBox<Integer>(); jcbx_agenciasAgregadasE.setEnabled(false); jcbx_agenciasAgregadasE.setBounds(102, 26, 100, 20); jpnl_gestionEmpleados.add(jcbx_agenciasAgregadasE); JButton jbtn_faq = new JButton(); jbtn_faq.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { faq(); } }); jbtn_faq.setIcon(new ImageIcon(getClass().getResource( "/recursos/faq.png"))); jbtn_faq.setBounds(240, 11, 45, 39); jpnl_empleados.add(jbtn_faq); initCombos(); setVisible(true); setLocationRelativeTo(null); } // ******************************** /** * Agrega una agencia al arbol de agencias */ public void agregarAgencia() { if (!(jcbx_agenciasDisponibles.getSelectedItem().toString().isEmpty()) && !(jtxt_canton.getText().isEmpty())) { int codigo = (int) jcbx_agenciasDisponibles.getSelectedItem(); String canton = jtxt_canton.getText(); String re = arbolAgencias.verificarInsercion(codigo, canton); jtxa_resultados.setText(re); for (int x = 0; x < agenciasDisponibles.size(); x++) { if (agenciasDisponibles.get(x) == codigo) { agenciasIngresadas.add(codigo); agenciasDisponibles.remove(x); break; } } activarPaneles(); actualizarCombos(); }else { JOptionPane.showMessageDialog(null, "estrictamente debe de indicar el canton donde se encuentra la agencia."); } } /** * Lista las agencias del arbol por el orden seleccionado */ public void listarPorOrden() { String re = ""; re = arbolAgencias.listarPorRecorrido(jcbx_orden.getSelectedItem() .toString()); jtxa_resultados.setText(re); } /** * Muestra una agencia */ public void mostrarAgencia() { String re = ""; re = arbolAgencias.mostrarAgencia((int) jcbx_agenciasAgregadasA .getSelectedItem()); jtxa_resultados.setText(re); } /** * Busca una agencia */ public void buscarAgencia() { String d = JOptionPane.showInputDialog("Ingrese el codigo de agencia"); String re = arbolAgencias.mostrarAgencia(Integer.parseInt(d)); jtxa_resultados.setText(re); } /** * Elimina una agencia */ public void eliminar() { int codigo =(int) jcbx_agenciasAgregadasA.getSelectedItem(); arbolAgencias.elimina(codigo); JOptionPane.showMessageDialog(null, "Eliminado con exito!!!"); } /** * Agreg un empleado */ public void agregarEmpleado() { String n = jtxt_nombreEmpleado.getText(); int i = Integer.parseInt(jtxt_identificarEmpleado.getText()); int a = (int) jcbx_agenciasAgregadasE.getSelectedItem(); String p = (String) jcbx_puestos.getSelectedItem(); String s = jtxt_salarioEmpleado.getText(); System.out.println(s); Empleados e = new Empleados(i, n, p, s); n = arbolAgencias.insertarEmpleado(a, e); jtxa_resultados.setText(n); } /** * Busca un empleado */ public void buscarEmpleado() { if (!(jtxt_identificarEmpleado.getText().isEmpty())) { int a = (int) jcbx_agenciasAgregadasA.getSelectedItem(); int i = Integer.parseInt(jtxt_identificarEmpleado.getText()); String r = arbolAgencias.buscarEmpleado(a, i); jtxa_resultados.setText(r); } else { String d = JOptionPane .showInputDialog("Ingrese el identificador del empleado"); int a = (int) jcbx_agenciasAgregadasA.getSelectedItem(); String r = arbolAgencias.buscarEmpleado(a, Integer.parseInt(d)); jtxa_resultados.setText(r); } } /** * Guarda el arbol */ public void guardarArbol() { arbolAgencias.guardar(); } /** * Recupera el arbol */ public void recuperarArbol() { if (arbolAgencias != null) { arbolAgencias = null; arbolAgencias = new ArbolAgencias(); agenciasIngresadas.clear(); arbolAgencias.agenciasDisponibles = agenciasDisponibles; arbolAgencias.agenciasIngresadas = agenciasIngresadas; arbolAgencias.recuperar(); agenciasDisponibles = arbolAgencias.agenciasDisponibles; agenciasIngresadas = arbolAgencias.agenciasIngresadas; actualizarCombos(); activarPaneles(); } } /** * Busca una agencia y lista en EnOrden todos sus empleados */ public void buscarAgenciaYListarEmpleados() { String d = JOptionPane .showInputDialog("Ingrese el codigo de la agencia"); String g = arbolAgencias.buscarAgenciaYListarEmpleados(Integer.parseInt(d)); jtxa_resultados.setText(g); } // ******************************** /** * Muestra una pequeña ayuda */ public void faq() { String re = "\t~ F.A.Q ~" + "\nPrimero se debe de crear una agencia." + "\npara crearla debe ir a la tabs Agencias." + "\nLas agencias se agregan simplemente escogiendo" + "\nsu codigo e ingresando su canton." + "\nLuego de agregar la agencia el codigo desaparece del" + "\ncombo y se puede seleccionar para realizar las gestiones." + "\n\nLuego se pueden gestionar las agencias." + "\n* Se pueden elegir por medio de su codigo, no" + "\nse pueden eliminar del arbol. Tambien se pueden" + "\nmostrar, nada mas desplega su codigo y cantidad de " + "\nempleados." + "\n* La opcion de buscar agencia hace lo mismo que" + "\n'Mostrar', solo que en este caso nos da la opcion de" + "\nbuscar ingresando el codigo en una cuadro de texto." + "\n* La opcion 'Buscar Agencia y Listar Clientes' muestra" + "\nlos datos de la agencia y lista todos los clientes que " + "\ntiene en orde 'EnOrden'." + "\nLa opcion de 'Listar Agencias' nos permite elegir en" + "\nque orden se dese listar la lista." + "\n* Para gestionar los empleados se debe ir a la tab" + "\n'Empleados'." + "\n* Para agregar un empleado se deben de llenar todos los" + "\ncampos." + "\n* Para 'Buscar' un empleado basta tan solo elegir la" + "\nagencia e ingresar su identificar." + "\n* La opcion de 'Eliminar' tampoco funciona para este arbol." + "\nSe deben tambien elegir la agencia e ingresar su identificador personal." + "\n\nAlgoritmos - Tarea programada 1 - Ejercicio 2." + "\n<NAME> B26375" + "\n<NAME> B11428"; jtxa_resultados.setText(re); } // ******************************** /** * Activa o desactiva los paneles */ public void activarPaneles() { if (arbolAgencias.size() > 0) { Component[] c = jpnl_gestionEmpleados.getComponents(); for (Component com : c) com.setEnabled(true); Component[] co = jpnl_gestionarAgencias.getComponents(); for (Component com : co) com.setEnabled(true); } else { Component[] c = jpnl_gestionEmpleados.getComponents(); for (Component com : c) com.setEnabled(false); Component[] co = jpnl_gestionarAgencias.getComponents(); for (Component com : co) com.setEnabled(false); } } /** * Actualiza los JComboBox de las agencias disponibles y las agregadas */ public void actualizarCombos() { jcbx_agenciasDisponibles.removeAllItems(); for (int x = 0; x < agenciasDisponibles.size(); x++) { jcbx_agenciasDisponibles.addItem(agenciasDisponibles.get(x)); } jcbx_agenciasAgregadasE.removeAllItems(); jcbx_agenciasAgregadasA.removeAllItems(); for (int x = 0; x < agenciasIngresadas.size(); x++) { jcbx_agenciasAgregadasE.addItem(agenciasIngresadas.get(x)); jcbx_agenciasAgregadasA.addItem(agenciasIngresadas.get(x)); } } void initCombos() { for (int x = 10; x <= 700; x += 10) { agenciasDisponibles.add(x); } actualizarCombos(); } // ******************************** public static void main(String[] agh) { new Florida_Bebidas_SA(); } } <file_sep>package Ejercicio3; import java.util.ArrayList; import javax.swing.JOptionPane; public class InsercionDirecta { private static int comparaciones; private static int intercambios; public static ArrayList<Compras> insercionDirecta(ArrayList<Compras> c) { comparaciones = 0; intercambios = 0; int n = c.size(); for (int x = 1; x < n; x++) { Compras co = c.get(x); int j = x - 1; while (j >= 0 && c.get(j).precioTotalSinDescuento > co.precioTotalSinDescuento) { c.set(j + 1, c.get(j)); j--; intercambios++; comparaciones++; } c.set(j + 1, co); intercambios++; } JOptionPane.showMessageDialog(null, "Comparaciones: " + comparaciones + "\nIntercambios: " + intercambios, "INSERCION DIRECTA", JOptionPane.INFORMATION_MESSAGE); return c; } } <file_sep>package Ejercicio3; import java.util.ArrayList; public class Shell { public static ArrayList<Ventas> shell(ArrayList<Ventas> c){ int salto, i; boolean cambios; for(salto=c.size()/2; salto!=0; salto/=2){ cambios=true; while(cambios){ // Mientras se intercambie algún elemento cambios=false; for(i=salto; i< c.size(); i++) // se da una pasada if(c.get(i-salto).totalConIVA>c.get(i).totalConIVA){ // y si están desordenados Ventas aux=c.get(i); // se reordenan c.set(i, c.get(i-salto)); c.set(i-salto, aux); cambios=true; // y se marca como cambio. } } } return c; } } <file_sep>package Ejercicio2; import java.util.ArrayList; import javax.swing.JOptionPane; public class hashSorteo { private Sorteo[] posiciones; private int primo = 101; int posicion=0; public hashSorteo() { posiciones = new Sorteo[100]; } public String insertar(Sorteo sor) { int pos = funcionModulo(sor.numero+sor.serie); String re = ""; if (posiciones[pos] == null) { posiciones[pos] = sor; sor.posicion=pos; re = "Sorteo agregado con exito"; } else { JOptionPane.showMessageDialog(null, "El el numero y serie ya existe"); re = "El Sorteo ya existe"; } return re; } private int funcionModulo(int codi) { return (codi % primo); } public Sorteo buscar(int codigo) { Sorteo sor = null; int pos = funcionModulo(codigo); if (posiciones[pos] != null){ sor = posiciones[pos]; sor.posicion=pos; }else JOptionPane.showMessageDialog(null, "El numero y serie no existen"); return sor; } public String listarSorteo() { String re = "Numero" + "\t" + "Serie " + "\t" + "Aņo" + "\t" + "Provincia" + "\t" + "Posicion" + "\n"; for (Sorteo sor : posiciones) if (sor != null) re += sor.numero + "\t" + sor.serie + "\t" + sor.anio + "\t" + sor.provincia+ "\t" + sor.posicion + "\n"; return re; } public ArrayList<Sorteo> getLlaves() { ArrayList<Sorteo> sor = new ArrayList<Sorteo>(); for (Sorteo e : posiciones) if (e != null) sor.add(e); return sor; } } <file_sep>package Ejercicio3; import java.io.Serializable; import java.net.ServerSocket; import java.util.ArrayList; import java.util.stream.Stream; public class Compras implements Serializable { /** * Gnerado por el IDE */ private static final long serialVersionUID = -4916343553235328518L; String numeroFactura; String nombreProveedor; String cedulaJuridica; String nombre; int cantidadProductos; double precioUnitario; double montoDescuento; double descuento; double precioTotal; double precioTotalSinDescuento; double precioTotalConConDescuento; ArrayList<Producto> productos = new ArrayList<Producto>(); public Compras(String factura, String proveedor, String cedula, String nombre, double descuento, ArrayList<Producto> productos) { numeroFactura = factura; nombreProveedor = proveedor; cedulaJuridica = cedula; this.nombre = nombre; this.descuento = descuento; this.productos.addAll(productos); cantidadProductos = productos.size(); calcular(); } private void calcular() { double aux = 0; for (Producto p : productos) aux += p.cantidadTotal * p.precioUnitario; precioTotal = aux; montoDescuento = precioTotal * descuento / 100.0; precioTotalSinDescuento = precioTotal; precioTotalConConDescuento = precioTotal - montoDescuento; } }
1b9da86716f54161222f23e53a623a10335f3eff
[ "Java" ]
8
Java
xxPEKESxx/proyecto1algoritmos
13047f682af0745c560be146bb86e5d08c6e649c
8c0a0302f069c19629a0f5d8f155d6712c17d227
refs/heads/master
<file_sep># DRUMS - Place in its own buffer - RUN FIRST use_bpm 175 sync :drums define :drum do |repeat, samp, rests, end_sleep| repeat.times do rests.each do |r| sample samp sleep r end end sleep end_sleep end # KICK in_thread do sleep 64 with_fx :ixi_techno, amp: 0.75, mix: 1, phase: 112, res: 0 do |phaser| drum(4, :bd_ada, [1, 1, 1, 1, 1, 1, 1, 0.75, 0.25], 0) drum(15, :bd_ada, [1], 0) drum(1, :bd_ada, [0.75, 0.25, 1, 1, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5], 0) control phaser, mix: 0.1, phase: 32 drum(208, :bd_ada, [2], 0) drum(1, :bd_ada, [0.5, 2.5, 1], 0) drum(31, :bd_ada, [2], 0) drum(1, :bd_ada, [1, 0.25, 0.25, 0.25, 0.25], 0) drum(32, :bd_ada, [2], 0) end end # SNARE snare_loops = [{:sn_dolf => "....X.......X..."}, {:sn_dolf => "....X.......X.X."}, {:sn_dolf => "X.XXX.X.....X.X."}, {:sn_dolf => "....X...X...X.X."}, {:sn_dolf => "....X.X.....X..."}, {:sn_dolf => "..X.X.....XXX.X."}, {:sn_dolf => "..X.X...X.XXX.X."}, {:sn_dolf => "....X.......X.XX"}, {:sn_dolf => "..........XX..XX"}, {:sn_dolf => "..X.X.....X.X.X."}, {:sn_dolf => "....X..........."}] snare_order = [[[0, 1], 19], [[0, 2, 0, 3, 0, 3, 4, 1, 5, 6], 1], [[0, 1], 7], [[0, 2], 1], [[0, 1], 3],[[0, 2, 0, 3, 0, 3, 4, 1, 5, 6], 1], [[0, 1], 11], [[0, 7, 8], 1], [[0, 1], 3], [[0, 2, 0, 3, 0, 3, 4, 1, 5, 9], 1], [[0, 1], 8], [[0, 10], 8]] in_thread do sleep 65 with_fx :ixi_techno, amp: 0.75, mix: 1, phase: 112, res: 0 do |phaser| drum(26, :sn_dolf, [2], 0) drum(1, :sn_dolf, [0.5, 1, 1, 0.5], 0) control phaser, mix: 0.1 snare_order.each do |loops, repeat| repeat.times do loops.each do |i| 16.times do |j| snare_loops[i].each do |samp, patt| sample samp, sustain: 0.12, amp: 0.6 if patt[j] == "X" sample :elec_filt_snare, sustain: 0.1 if patt[j] == "X" end sleep 0.25 end end end end end end # CLAPS in_thread do sleep 117.5 drum(3, :elec_mid_snare, [1], 0.5) drum(66, :elec_mid_snare, [2], 0) 2.times do drum(3, :elec_mid_snare, [1], 1) drum(62, :elec_mid_snare, [2], 0) end drum(14, :elec_mid_snare, [2], 4) drum(2, :elec_mid_snare, [2, 2, 1, 1, 1], 1) drum(26, :elec_mid_snare, [2], 0) drum(1, :elec_mid_snare, [2.25, 0.5, 1.25], 0) 2.times do drum(2, :elec_mid_snare, [2, 2, 1, 1, 1], 1) drum(12, :elec_mid_snare, [2], 0) end drum(8, :elec_mid_snare, [2, 2, 1, 1, 1], 1) end # HI-HAT in_thread do sleep 64.5 with_fx :ixi_techno, amp: 0.75, mix: 1, phase: 112, res: 0 do |phaser| drum(50, :drum_cymbal_pedal, [1], 0.5) drum(1, :drum_cymbal_pedal, [0.5, 1.5, 0.5], 0) control phaser, mix: 0.1, phase: 32 drum(323, :drum_cymbal_pedal, [1], 0) drum(96, :drum_cymbal_closed, [1], 4) drum(160, :drum_cymbal_pedal, [1], 0) end end # SHORT SPLASH CYMBAL in_thread do sleep 102.5 with_fx :compressor, amp: 0.8, clamp_time: 0.01, slope_below: 3 do drum(1, :drum_cymbal_open, [12, 2, 18, 32, 32, 32, 24, 8, 8, 4, 2, 10, 8, 8, 4, 20, 32, 14, 10, 8, 8, 4, 2, 10, 8, 8, 4, 28, 24, 24, 24, 12, 8, 8, 4, 2, 10, 8, 8, 4, 12, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8], 0) end end # BIG CRASH CYMBAL in_thread do sleep 120 drum(1, :drum_splash_hard, [128, 32, 32, 32, 32, 32, 32, 24, 24, 24, 25, 3, 32, 32, 32, 32], 0) end <file_sep># INSTRUMENTS - Place in its own buffer - RUN SECOND use_bpm 175 cue :drums # VOCALS (KIND OF) define :bassvox do |notes, repeat| with_fx :lpf, reps: repeat do notes.each do |n, t, r| # |notes, time in between notes, repetitions| r.times do play_pattern_timed n, t end end end end in_thread do use_synth :piano with_fx :reverb, amp: 1.75, mix: 0.4, room: 0.6, damp: 0.99 do |verb| sleep 120 bassvox([[[:F4, :C4], [3.5, 0.5], 1], [[:F4], [1], 3], [[:G4, :E4, :C4, :C4, :E4, :E4, :E4, :F4, :D4, :C4, :Bb3, :Bb3, :Bb3], [0.5, 3.5, 0.5, 0.5, 0.5, 1, 1, 1, 1.5, 1, 1, 1, 0.5], 1], [[:Bb3, :Bb3, :Bb3, :Bb3], [1, 1, 1.5, 0.5], 2], [[:A3, :G3], [1.5, 1], 1]], 1) bassvox([[[:F3, :F3, :F4], [1, 0, 4], 1], [[:F4], [1], 3], [[:G4, :E4, :C4, :C4, :E4, :E4, :E4, :F4, :D4, :C4, :Bb3, :Bb3, :Bb3], [0.5, 3.5, 0.5, 0.5, 0.5, 1, 1, 1, 1.5, 1, 1, 1, 0.5], 1], [[:Bb3, :Bb3, :Bb3, :Bb3], [1, 1, 1.5, 0.5], 2], [[:A3, :G3, :F3, :F3], [1.5, 1, 1, 0], 1]], 1) 2.times do bassvox([[[:F4], [4], 1], [[:F4], [1], 3], [[:G4, :E4, :C4, :C4, :E4, :E4, :E4, :F4, :D4, :C4, :Bb3, :Bb3, :Bb3], [0.5, 3.5, 0.5, 0.5, 0.5, 1, 1, 1, 1.5, 1, 1, 1, 0.5], 1], [[:Bb3, :Bb3, :Bb3, :Bb3], [1, 1, 1.5, 0.5], 2], [[:A3, :G3], [1.5, 1], 1]], 1) bassvox([[[:F3, :C4, :F4, :C4], [0, 1, 3.5, 0.5], 1], [[:F4], [1], 3], [[:G4, :E4, :C4, :C4, :E4, :E4, :E4, :F4, :D4, :C4, :Bb3, :Bb3, :Bb3], [0.5, 3.5, 0.5, 0.5, 0.5, 1, 1, 1, 1.5, 1, 1, 1, 0.5], 1], [[:Bb3, :Bb3, :Bb3, :Bb3], [1, 1, 1.5, 0.5], 2], [[:A3, :G3, :F3], [1.5, 1, 1], 1]], 1) with_synth :fm do bassvox([[[:C5], [1], 5], [[:A4, :C5], [1], 1], [[:D5, :C5, :C5, :D5, :F5], [2], 1], [[:Bb4, :Bb4, :A4, :F4], [5, 2, 7, 1], 1]], 1) bassvox([[[:C5], [1], 5], [[:A4, :C5], [1], 1], [[:D5, :C5, :C5, :D5, :F5], [2], 1], [[:Bb4, :Bb4, :D5, :A4, :G4, :F4], [4, 2, 2, 2, 1, 4], 1]], 1) end end sleep 100 with_synth :fm do 2.times do bassvox([[[:C5], [1], 5], [[:A4, :C5], [1], 1], [[:D5, :C5, :C5, :D5, :F5], [2], 1], [[:Bb4, :Bb4, :A4, :F4], [5, 2, 7, 1], 1]], 1) bassvox([[[:C5], [1], 5], [[:A4, :C5], [1], 1], [[:D5, :C5, :C5, :D5, :F5], [2], 1], [[:Bb4, :Bb4, :D5, :A4, :G4, :F4, :F4], [4, 2, 2, 2, 1, 3, 1], 1]], 1) end bassvox([[[:C5], [1], 5], [[:A4, :C5], [1], 1], [[:D5, :C5, :C5, :D5, :F5], [2], 1], [[:Bb4], [15], 1]], 1) control verb, amp: 1.5, mix: 0.7, room: 0.75, damp: 0.9 bassvox([[[:C5, :C5, :C5], [2, 1], 1], [[:A4, :C5, :C5, :C5, :F5, :Bb4], [1, 3, 2, 4, 2, 3], 1]], 1) end end end # EIGHTH NOTES define :eighths do |notes, repeat, sleep_after| repeat.times do notes.each do |updown, n| play_pattern_timed [n, :C5, n, n, :C5, n, n, :C5], [0.5] if updown == 1 # If updown == 1, play low-high ending play_pattern_timed [n, :C5, n, n, :C5, n, n, :C5], [0.5] else # If updown != 1, play high-low ending play_pattern_timed [n, :C5, n, n, :C5, n, :C5, n], [0.5] end end end sleep sleep_after end in_thread do with_fx :panslicer, phase: 1 do eighths([[0, :F4], [1, :E4]], 7, 0) eighths([[0, :F4]], 1, 128) eighths([[0, :F4], [1, :E4], [0, :D4], [1, :A4]], 2, 64) eighths([[0, :F4], [1, :E4], [0, :D4], [1, :A4]], 2, 0) eighths([[0, :F4], [1, :E4]], 6, 4) eighths([[0, :F4], [1, :E4], [0, :D4], [1, :A4]], 2, 0) eighths([[0, :F4], [1, :E4]], 10, 0) end end # OPENING SYNTH in_thread do 5.times do play_pattern_timed [:C5, :C5, :C5, :C5, :E5, :C5, :E5, :C5, :E5, :C5, :E5, :C5], [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], amp: 0.4 play_pattern_timed [:C5, :C5, :C5, :C5, :E5, :C5, :E5, :C5, :E5, :C5, :E5, :C5], [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], amp: 0.4 play_pattern_timed [:D5, :D5, :D5, :D5, :D5, :D5, :D5, :E5, :G5], [1, 1, 1, 1, 1, 1, 1, 0.5, 0.5], amp: 0.4 end sleep 484 6.times do play_pattern_timed [:C5, :C5, :C5, :C5, :E5, :C5, :E5, :C5, :E5, :C5, :E5, :C5], [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], amp: 0.4 play_pattern_timed [:C5, :C5, :C5, :C5, :E5, :C5, :E5, :C5, :E5, :C5, :E5, :C5], [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], amp: 0.4 play_pattern_timed [:D5, :D5, :D5, :D5, :D5, :D5, :D5, :E5, :G5], [1, 1, 1, 1, 1, 1, 1, 0.5, 0.5], amp: 0.4 end play_pattern_timed [:C5, :C5, :C5, :C5, :E5, :C5, :E5, :C5, :E5, :C5, :E5, :C5], [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], amp: 0.4 play_pattern_timed [:C5, :C5, :C5, :C5, :E5, :C5, :E5, :C5, :E5, :C5, :E5, :C5], [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], amp: 0.4 end # BACKGROUND SYNTH in_thread do sleep 312 with_fx :mono, reps: 16 do play_pattern [:F5, :G5, :F5, :E5], attack: 1.2, release: 0.1 end end # BACKGROUND CHORDS define :chords do |sleep_before, notes, repeat| sleep sleep_before repeat.times do notes.each do |n| play_pattern_timed n, [0, 0, 0, 8], sustain: 8, amp: 0.175 end end end in_thread do use_synth :saw chords(248, [[:C4, :A3, :F3, :C3], [:C4, :G3, :E3, :C3], [:D4, :Bb3, :F3, :D3], [:A3, :F3, :C3, :A3]], 2) chords(64, [[:C4, :A3, :F3, :C3], [:C4, :G3, :E3, :C3], [:D4, :Bb3, :F3, :D3], [:A3, :F3, :C3, :A3]], 2) chords(100, [[:C4, :A3, :F3, :C3], [:C4, :G3, :E3, :C3], [:D4, :Bb3, :F3, :D3], [:A3, :F3, :C3, :A3]], 5) chords(0, [[:C4, :A3, :F3, :C3], [:C4, :G3, :E3, :C3]], 1) end # BASS LINE in_thread do use_synth :tb303 use_synth_defaults amp: 0.9, env_curve: 7, res: 0, sustain: 0.98, release: 0.02, cutoff: 80 sleep 64 bassvox([[[:F1], [1], 8], [[:A1], [1], 8], [[:G1], [1], 8], [[:F1], [1], 8], [[:A1], [1], 8], [[:G1], [1], 16]], 1) bassvox([[[:F1], [1], 8], [[:A1], [1], 8], [[:G1], [1], 8], [[:Bb1], [1], 4], [[:C2], [1], 4]], 2) 2.times do bassvox([[[:F1], [1], 8], [[:A1], [1], 8], [[:G1], [1], 8], [[:Bb1], [1], 4], [[:C2], [1], 4], [[:F1], [1], 8], [[:A1], [1], 8], [[:G1], [1], 8], [[:C2], [1], 4], [[:Bb1], [1], 4]], 1) bassvox([[[:F1], [1], 6], [[:A1], [1], 1], [[:B1], [1], 1], [[:C2], [1], 8], [[:Bb1], [1], 8], [[:A1], [1], 8]], 2) end bassvox([[[:F1], [1], 8], [[:A1], [1], 8], [[:G1], [1], 8]], 4) bassvox([[[:Bb1], [1], 4]], 1) bassvox([[[:F1], [1], 6], [[:A1], [1], 1], [[:B1], [1], 1], [[:C2], [1], 8], [[:Bb1], [1], 8], [[:A1], [1], 8]], 4) bassvox([[[:F1], [1], 6], [[:A1], [1], 1], [[:B1], [1], 1], [[:C2], [1], 5], [[:D2], [1], 2], [[:F2], [1], 2], [[:Bb1], [1], 7], [[:A1], [1], 8]], 3) end # SECONDARY PIANO in_thread do use_synth :piano sleep 184 with_fx :reverb, reps: 2, mix: 0.5, room: 0.7, damp: 0.9 do play_pattern_timed [:C5, :E5, :F5, :C5, :C5, :E5, :G5, :C5, :Bb4, :A4, :C5, :G4, :G4, :F4, :F4], [1, 1, 1, 5, 1, 1, 1, 5, 1, 1, 1, 4, 0.5, 7.5, 1], amp: 0.8, attack: 0.1 play_pattern_timed [:C5, :E5, :F5, :C5, :C5, :E5, :G5, :C5, :Bb4, :A4, :C5, :G4, :G4, :F4], [1, 1, 1, 5, 1, 1, 1, 5, 1, 1, 1, 4, 0.5, 72.5], amp: 0.8, attack: 0.1 end sleep 48 play_pattern_timed [:C5, :E5, :F5, :C5, :C5, :E5, :G5, :C5, :Bb4, :A4, :C5, :G4], [1, 1, 1, 5], amp: 0.8, attack: 0.1 play_pattern_timed [:C5, :E5, :F5, :C5, :C5, :E5, :G5, :C5, :Bb4, :A4, :C5, :G4], [1, 1, 1, 5], amp: 0.8, attack: 0.1 end # GUITAR RIFF in_thread do use_synth :fm use_synth_defaults sustain: 0.35, release: 0.1 sleep 440.5 with_fx :distortion, distort: 0.8, pre_amp: 10, amp: 0.125 do with_fx :bitcrusher, cutoff: 120, reps: 4 do play_pattern_timed [:F3, :F4, :F4, :F4, :F4, :F4, :F4, :F4, :F4, :E4, :F3, :E4, :E4, :E4, :E4, :E4, :E4, :F4, :E4, :D4, :F3, :D4, :D4, :D4, :D4, :D4, :D4, :C4, :C4, :C4], [0.5, 1, 1, 1, 1, 1, 0.5, 0.5, 0.5, 1] end end end <file_sep># such-great-heights A Sonic Pi rendition of "Such Great Heights" by The Postal Service
954a969656e99ae9c2e487b899717af48d86866f
[ "Markdown", "Ruby" ]
3
Ruby
aviflombaum/such-great-heights
de6939cbdd29e94fa223fd05f41f500f9aee4bd3
e4c97ed79a9bf9c25665f1c18401d5c827a43b55
refs/heads/master
<file_sep>def main(): data_range = [387638, 919123] candidates = range(data_range[0], data_range[1]+1) candidates1 = map(str, candidates) print(len(candidates)) candidates2 = filter(lambda x: all(map(lambda y, z: z>=y, x[:-1], x[1:])), candidates1) print(len(candidates2)) candidates3 = filter(lambda x: any(map(lambda y, z: int(z) - int(y) == 0, x[:-1], x[1:])), candidates2) print(len(candidates3)) print(candidates3) candidates4 = filter(lambda x: { x.count(i): i for i in set(x)}.get(2, None) != None, candidates3) print(len(candidates4)) print(candidates4) if __name__=="__main__": main()<file_sep>import urllib2 import math def read_input(url): for line in urllib2.urlopen(url): yield line def get_data2(): mem = "1,1,1,4,99,5,6,0,99" mem = map(lambda x: int(x), mem.split(',') ) return mem def get_data(): mem = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,6,19,23,2,23,6,27,1,5,27,31,1,31,9,35,2,10,35,39,1,5,39,43,2,43,10,47,1,47,6,51,2,51,6,55,2,55,13,59,2,6,59,63,1,63,5,67,1,6,67,71,2,71,9,75,1,6,75,79,2,13,79,83,1,9,83,87,1,87,13,91,2,91,10,95,1,6,95,99,1,99,13,103,1,13,103,107,2,107,10,111,1,9,111,115,1,115,10,119,1,5,119,123,1,6,123,127,1,10,127,131,1,2,131,135,1,135,10,0,99,2,14,0,0" mem = map(lambda x: int(x), mem.split(',') ) return mem def run_comp(noun, verb): memory = get_data() memory[1] = noun memory[2] = verb for i in range(0, len(memory)-4, 4): code = memory[i] ops = memory[i+1:i+4] if code == 1: memory[ops[2]] = memory[ops[0]] + memory[ops[1]] elif code == 2: memory[ops[2]] = memory[ops[0]] * memory[ops[1]] elif code == 99: break return memory[0] def main(): for noun in range(100): for verb in range(100): out = run_comp(noun, verb) if out == 19690720: print(noun) print(verb) print(100 * noun + verb) #print(fn()) if __name__=="__main__": main()
eb2b34a551bf70844d7425456a6c9bc48caeb2e4
[ "Python" ]
2
Python
rudehn/adventofcode
5c841377ecf070e12c7eb3a8f4ba896b2febea17
47bc81a4c19ebcd3bd888e682754899888f9e0d7
refs/heads/master
<repo_name>AkiChen/Shallow-visual-features<file_sep>/ShallowFeature/ExampleSiftBowTraining.py from visualFeatures import dataHandle from visualFeatures import featureOpencvSiftBoW as sift_bow import os import getopt import sys opts, args = getopt.getopt( sys.argv[1:] , "hi:o:", ["dic_name=", "file_dic="] ) dic_name = None file_dic = [] for op, value in opts: if op == "--dic_name": print "diction saved in folder : ./",value dic_name = value elif op == "--file_dic": file_dic.append( value ) ###################################################### ## An example program of train sift feature with bow ## PCA isn't used in this example. ###################################################### ###################################################### ## Editable params are listed here ###################################################### '''If your computer doesn't have enough main memory, you have \ no choice but to select part of them for training.''' ###################################################### DICTION_IMAGE_PATH_FOR_TRAINING = file_dic N = 200 #size of diction, in another word, the output length of our feature vector BOW_DICTION_NAME = dic_name ###################################################### ###################################################### image_paths = dataHandle.read_only_image_paths( DICTION_IMAGE_PATH_FOR_TRAINING ) #Compute descriptors and save on disk. sift_bow.computANDsaveRawSiftFeatures(image_paths) #Train the bow model. sift_desc_paths = map(lambda each_img_path : os.path.join(dataHandle.splitImgPath(each_img_path)[0] \ , 'opencvSiftDescriptors', dataHandle.splitImgPath(each_img_path)[1]+'.npy') , image_paths) sift_bow.generate_bow( sift_desc_paths , N , BOW_DICTION_NAME ) ######################################################<file_sep>/ShallowFeature/playground.py import featureCalculater image_path = ['./sample_dress.jpg'] ############################################ # #if you have serveral folders of images # from visualFeatures import dataHandle # image_path = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\0\\images'] ) print featureCalculater.calculateFeatureAndSave( image_path , 'dressFeatureConfig.txt' , feature_output_dir = None )[0] <file_sep>/ShallowFeature/visualFeatures/dataHandle.py import os import cv2 import numpy as np def normalize(v): norm=np.linalg.norm(v) if norm==0: return v return v/norm def readableImage( s ): img_name, extension_name = os.path.splitext(s) if not extension_name in ['.jpg', '.jpeg', '.png']: return False elif img_name.endswith('mask'): return False else: return True def read_only_image_paths( input_images_base_dirs ): res_all_paths = [] for each_base_path in input_images_base_dirs: paths = os.listdir(each_base_path) res_paths = map(lambda each_valid_name : os.path.join(each_base_path, each_valid_name) , [each_name for each_name in paths if readableImage(each_name)]) res_all_paths.extend(res_paths) return res_all_paths def transfrom_img_2_256X256_png( original_path , destination_path=None ): original_paths = os.listdir(original_path) des_path = destination_path if des_path == None: des_path = original_path des_path = des_path+'_256X256_png' if not os.path.exists(des_path): os.makedirs(des_path) for each_img in original_paths: (img_name, extension_name) = os.path.splitext(each_img) original_img = cv2.imread(os.path.join(original_path, each_img)) original_img = cv2.resize(original_img, (256, 256), interpolation = cv2.INTER_CUBIC) cv2.imwrite(os.path.join(des_path, img_name+'.png'), original_img) if original_path == des_path and extension_name!='.png': os.remove(os.path.join(original_path, each_img)) def transfrom_img_2_origin_png( original_path , destination_path=None ): original_paths = os.listdir(original_path) des_path = destination_path if des_path == None: des_path = original_path des_path = des_path+'_or_png' if not os.path.exists(des_path): os.makedirs(des_path) for each_img in original_paths: (img_name, extension_name) = os.path.splitext(each_img) original_img = cv2.imread(os.path.join(original_path, each_img)) cv2.imwrite(os.path.join(des_path, img_name+'.png'), original_img) def splitImgPath( img_absolute_path ): dir_path, file_name = os.path.split(img_absolute_path) item_name, extension_name = os.path.splitext(file_name) return dir_path,item_name,extension_name def imgPreProcessing_Rescale( input_image ): #Make the max dim of image to be 256 image_shape = input_image.shape h = image_shape[0] w = image_shape[1] scale_rate = (256+0.0)/(max(h,w)+0.0) return cv2.resize(input_image, (int(h*scale_rate), int(w*scale_rate)), interpolation = cv2.INTER_CUBIC) def imgPreProcessing_BackgroundMask( input_img , kernel_size = 15, is_luv = False): #Take a memory image, and remove the color similar to the background h,w,c = input_img.shape luv_image = input_img if not is_luv: luv_image = cv2.cvtColor( luv_image, cv2.COLOR_BGR2LUV ) blur_kernel = np.ones((kernel_size, kernel_size), np.float32)/(kernel_size*kernel_size) blur_res = cv2.filter2D(luv_image, -1, blur_kernel) blur_res = np.array(blur_res, 'float32') target_values = [] target_values.append(blur_res[5][5]) target_values.append(blur_res[5][-5]) target_values.append(blur_res[-5][5]) target_values.append(blur_res[-5][-5]) #we calculate the color distance between each pixel and 4 corners all_distances = np.zeros((4,h, w, c)); bool_mask = np.ones((h,w))*True for k in range(0, 4): all_distances[k] = np.reshape(np.tile(target_values[k], (h,w)), (h,w,c)) all_distances[k] = all_distances[k]-blur_res square_res = np.square(all_distances[k]) dis_map = np.sqrt(square_res.sum(axis = 2)) thres_hold = np.mean(dis_map)/3 bool_map = dis_map>thres_hold bool_mask = np.logical_and(bool_mask, bool_map) final_mask_image = np.ones((h,w,c))*255 for i in range(0,c): final_mask_image[:,:,i] = final_mask_image[:,:,i]*bool_mask return final_mask_image <file_sep>/ShallowFeature/visualFeatures/featureOpencvSiftBoW.py import cv2 import dataHandle import numpy as np import os def siftDescriptorForOneImg( input_image ): #Input a cv image. extractor = cv2.DescriptorExtractor_create("SIFT") detector = cv2.FeatureDetector_create("SIFT") gray_image = input_image if len(gray_image.shape)==2 : gray_image = input_image else: gray_image = cv2.cvtColor(input_image , cv2.COLOR_BGR2GRAY) gray_image = dataHandle.imgPreProcessing_Rescale( gray_image ) kps = detector.detect(gray_image) _,descs = extractor.compute(gray_image, kps) #Shape of descs is len(kps)*128 return descs def computANDsaveRawSiftFeatures( image_path_list ): #Read images with their absolute path. counter = 0 for each_img_path in image_path_list: dir_name, item_name, extension_name = dataHandle.splitImgPath(each_img_path) feature_base_path = os.path.join(dir_name, 'opencvSiftDescriptors') print 'Processing image '+str(counter)+'# '+item_name+extension_name if not os.path.exists(feature_base_path): os.makedirs(feature_base_path) np.save(os.path.join(feature_base_path, item_name+'.npy'), siftDescriptorForOneImg(cv2.imread(each_img_path))) counter+=1 def loadSiftDescriptor( file_path ): numeric_feature = np.load(file_path) return numeric_feature def dictionary( descriptors, N ): BOW = cv2.BOWKMeansTrainer(N) print 'Start to generate a bow diction with size of N='+str(N) for each_descriptor in descriptors: BOW.add(each_descriptor) print 'Start of cluster.' dictionary = BOW.cluster() print 'End of cluster.' return dictionary def generate_bow(input_feature_paths, N, exp_name_prefix): words = [loadSiftDescriptor(each_feature_path) for each_feature_path in input_feature_paths] my_diction = dictionary(words, N) model_base_path = os.path.join('.', exp_name_prefix) if not os.path.exists(model_base_path): os.makedirs(model_base_path) np.save(os.path.join(model_base_path, 'bow_diction'), my_diction) return my_diction def load_bow(folder = ""): return np.load(os.path.join(folder, 'bow_diction.npy')) def bow_feature_vector( sample_image_path , bow_diction ): FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) search_params = dict(checks=50) matcher = cv2.FlannBasedMatcher(index_params, search_params) detector = cv2.FeatureDetector_create("SIFT") extractor = cv2.DescriptorExtractor_create("SIFT") bowDE = cv2.BOWImgDescriptorExtractor(extractor, matcher) bowDE.setVocabulary(bow_diction) gray_image = dataHandle.imgPreProcessing_Rescale( cv2.cvtColor( cv2.imread(sample_image_path) , cv2.COLOR_BGR2GRAY ) ) kps = detector.detect(gray_image) descriptor = bowDE.compute( gray_image , kps ) return np.array(descriptor.flatten()) ##################################################### '''Here are some sample programs for explaining the usage of Opencv's sift feature and bow''' ##################################################### ################### '''Step One, generate sift descriptors for a set images.''' '''For each image, its sift descriptors would be saved as 'image_name.npy' in the folder of 'opencvSiftDescriptors' ''' # ################# # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\1\\images'] ) # computANDsaveRawSiftFeatures(image_paths) # ################# ################### '''Step Two, train a bow model for these samples as train dataset.''' '''The trained result is only one dictionary file, \ saved in the sub-directory of source folder, whose name is specified. ''' # # ################# # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\1\\images'] ) # sift_desc_paths = map(lambda each_img_path : os.path.join(dataHandle.splitImgPath(each_img_path)[0] \ # , 'opencvSiftDescriptors', dataHandle.splitImgPath(each_img_path)[1]+'.npy') , image_paths) # N = 200 # generate_bow( sift_desc_paths , N , 'my_opencvSiftBow_Model' ) # ################# ################### '''Step Three, now that the model is trained, we can generate meaningful feature vectors(or called as bow descriptor) for images now.''' '''Only one version is given here: input of raw images are supported, not sift descriptors.''' # ################# # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\1\\images'] ) # my_bow = load_bow('my_opencvSiftBow_Model') # sift_feature_list = np.concatenate([map(lambda each_image_path: bow_feature_vector( each_image_path , my_bow ), image_paths )]) # #################<file_sep>/ShallowFeature/visualFeatures/imageQuality.py import cv2 import sys if __name__ == "__main__": image_path = sys.argv[1] image = cv2.imread( image_path )<file_sep>/ShallowFeature/objectRecgonitionTask.py import os import glob import numpy as np import featureCalculater from sklearn.svm import LinearSVC from sklearn.externals import joblib from visualFeatures import dataHandle from sklearn.metrics import classification_report from sklearn import metrics ###################################################### ## Training svm classifier ###################################################### base_path = 'C:\\Users\\peiqchen\\Desktop' folder_names = ['normal_train', 'sextoys_train'] folders = map( lambda each_name: base_path+'\\'+each_name, folder_names ) name_2_label_dict = {'sextoys_train':0, 'normal_train':1} label_array = None #the label array for each_folder in folders: length = len(glob.glob(each_folder+'\\*.jpg')) _ , folder_name = os.path.split(each_folder) label = int(name_2_label_dict[folder_name]) folder_label_array = np.ones((length))*label if label_array is None: label_array = folder_label_array else: label_array = np.concatenate((label_array, folder_label_array)) image_paths = dataHandle.read_only_image_paths( folders ) all_features = featureCalculater.calculateFeatureAndSave( image_paths , 'featureConfig.txt' ) clf = LinearSVC() print 'Training svm.' clf.fit( all_features, label_array ) joblib.dump(clf, 'tmp_sextoys_normal.pkl', compress=3) ###################################################### ##################################################### # Testing with our svm classifier ##################################################### print 'Generate testing features an test svm.' base_path = 'C:\\Users\\peiqchen\\Desktop' folder_names = ['normal_test', 'sextoys_test'] folders = map( lambda each_name: base_path+'\\'+each_name, folder_names ) name_2_label_dict = {'sextoys_test':0, 'normal_test':1} label_array = None #the label array for each_folder in folders: length = len(glob.glob(each_folder+'\\*.jpg')) _ , folder_name = os.path.split(each_folder) label = int(name_2_label_dict[folder_name]) folder_label_array = np.ones((length))*label if label_array is None: label_array = folder_label_array else: label_array = np.concatenate((label_array, folder_label_array)) image_paths = dataHandle.read_only_image_paths( folders ) all_features = featureCalculater.calculateFeatureAndSave( image_paths , 'featureConfig.txt' ) clf = joblib.load('tmp_sextoys_normal.pkl') predicted_labels = [] for each_feature in all_features: each_prediction = clf.predict(each_feature.reshape(1, -1)) predicted_labels.append(each_prediction) pred_labels = np.array(predicted_labels, 'int') labels = label_array.reshape((len(pred_labels),1)) precision=dict() recall=dict() average_precision=dict() target_names = ['sextoys', 'normal'] print(classification_report(labels, pred_labels, target_names=target_names)) print(metrics.confusion_matrix(labels, pred_labels)) ###################################################### <file_sep>/ShallowFeature/trainAllModels.sh #!/usr/bin/env sh DATASET_NAME="dress" #Diction image path and pca image path don't have to be different. #The best feature vectors would be get, if you use all dataset images to train diction and pca. DICTION_IMAGE_PATH = "C:\\Users\\peiqchen\\Desktop\\dresses_diction_images" PCA_IMAGE_PATH = "C:\\Users\\peiqchen\\Desktop\\dresses_pca_images" #Train gmm model python ./ExampleSiftGmmTraining.py \ --dic=${DATASET_NAME}_diction \ --pca=${DATASET_NAME}_sift_gmm_pca \ --file_dic=${DICTION_IMAGE_PATH} \ --file_pca=${PCA_IMAGE_PATH} #Train bow model python ./ExampleSiftBowTraining.py \ --dic=${DATASET_NAME}_diction \ --file_dic=${DICTION_IMAGE_PATH} #Train hog model python ./ExampleHogTraining.py \ --pca=${DATASET_NAME}_hog_pca \ --file_pca=${PCA_IMAGE_PATH} #Train colorHis model python ./ExampleColorHisTraining.py \ --pca=${DATASET_NAME}_colorHis_pca \ --file_pca=${PCA_IMAGE_PATH} #python ExampleSiftGmmTraining.py --dic=dress_diction --pca=dress_sift_gmm_pca --file_dic=C:\\Users\\peiqchen\\Desktop\\dresses_diction_images --file_pca=C:\\Users\\peiqchen\\Desktop\\dresses_pca_images #python ExampleSiftBowTraining.py --dic=dress_diction --file_dic=C:\\Users\\peiqchen\\Desktop\\dresses_diction_images #python ExampleHogTraining.py --pca=dress_hog_pca --file_pca=C:\\Users\\peiqchen\\Desktop\\dresses_pca_images #python ExampleColorHisTraining.py --pca=dress_colorHis_pca --file_pca=C:\\Users\\peiqchen\\Desktop\\dresses_pca_images<file_sep>/ShallowFeature/ExampleHogTraining.py from visualFeatures import featureSklearnHog as skHog from visualFeatures import dataHandle from visualFeatures import pcaTrainer import getopt import sys opts, args = getopt.getopt( sys.argv[1:] , "hi:o:", ["pca_name=", "file_pca="] ) pca_name = None file_pca = [] for op, value in opts: if op == "--pca_name": print "pca saved in file : ./pcaDataBase/",value,".pkl" pca_name = value elif op == "--file_pca": file_pca.append( value ) ###################################################### ## An example program of train hog feature ## In fact, hog doesn't need training , its PCA needs ###################################################### ###################################################### ## Editable params are listed here ###################################################### '''If your computer doesn't have enough main memory, you have \ no choice but to select part of your train dataset for training.''' ###################################################### PCA_IMAGE_PATH_FOR_TRAINING = file_pca OUTPUT_DIMENSION = 200 #size of pca output dimension OUTPUT_PCA_NAME = pca_name ###################################################### ###################################################### image_paths = dataHandle.read_only_image_paths( PCA_IMAGE_PATH_FOR_TRAINING ) hog_feature_list = skHog.hogFeatureForImgSet( image_paths ) print 'Done with loading hog features' ###################################################### pcaTrainer.trainPCAwithRawFeatures( hog_feature_list , OUTPUT_DIMENSION , OUTPUT_PCA_NAME ) print 'Done with pca training' ###################################################### <file_sep>/ShallowFeature/visualFeatures/featureOpencvSiftFisherVector.py import cv2 import dataHandle import numpy as np import os from scipy.stats import multivariate_normal def siftDescriptorForOneImg( input_image ): #Input a cv image. extractor = cv2.DescriptorExtractor_create("SIFT") detector = cv2.FeatureDetector_create("SIFT") gray_image = input_image if len(gray_image.shape)==2 : gray_image = input_image else: gray_image = cv2.cvtColor(input_image , cv2.COLOR_BGR2GRAY) gray_image = dataHandle.imgPreProcessing_Rescale( gray_image ) kps = detector.detect(gray_image) _,descs = extractor.compute(gray_image, kps) #Shape of descs is len(kps)*128 return np.array(descs , 'float32') def computANDsaveRawSiftFeatures( image_path_list ): #Read images with their absolute path. counter = 0 for each_img_path in image_path_list: dir_name, item_name, extension_name = dataHandle.splitImgPath(each_img_path) feature_base_path = os.path.join(dir_name, 'opencvSiftDescriptors') print 'Processing image '+str(counter)+'# '+item_name+extension_name if not os.path.exists(feature_base_path): os.makedirs(feature_base_path) np.save(os.path.join(feature_base_path, item_name+'.npy'), siftDescriptorForOneImg(cv2.imread(each_img_path))) counter+=1 def loadSiftDescriptor( file_path ): numeric_feature = np.load(file_path) return numeric_feature def dictionary(descriptors, N): em = cv2.EM(N) em.train(descriptors) return np.float32(em.getMat("means")), \ np.float32(em.getMatVector("covs")), np.float32(em.getMat("weights"))[0] def generate_gmm(input_feature_paths, N, exp_name_prefix): words = np.concatenate([loadSiftDescriptor(each_feature_path) for each_feature_path in input_feature_paths]) print("Training GMM of size", N) means, covs, weights = dictionary(words, N) #Throw away gaussians with weights that are too small: th = 1.0 / N means = np.float32([m for k,m in zip(range(0, len(weights)), means) if weights[k] > th]) covs = np.float32([m for k,m in zip(range(0, len(weights)), covs) if weights[k] > th]) weights = np.float32([m for k,m in zip(range(0, len(weights)), weights) if weights[k] > th]) model_base_path = os.path.join('.', exp_name_prefix) if not os.path.exists(model_base_path): os.makedirs(model_base_path) np.save(os.path.join(model_base_path, 'means.gmm'), means) np.save(os.path.join(model_base_path, 'covs.gmm'), covs) np.save(os.path.join(model_base_path, 'weights.gmm'), weights) return means, covs, weights def load_gmm(folder = ""): files = ["means.gmm.npy", "covs.gmm.npy", "weights.gmm.npy"] return map(lambda file: np.load(file), map(lambda s : os.path.join(folder, s) , files)) def likelihood_moment(x, ytk, moment): x_moment = np.power(np.float32(x), moment) if moment > 0 else np.float32([1]) return x_moment * ytk def likelihood_statistics(samples, means, covs, weights): gaussians, s0, s1,s2 = {}, {}, {}, {} samples = zip(range(0, len(samples)), samples) g = [multivariate_normal(mean=means[k], cov=covs[k], allow_singular = True) for k in range(0, len(weights)) ] for index, x in samples: gaussians[index] = np.array([g_k.pdf(x) for g_k in g]) for k in range(0, len(weights)): s0[k], s1[k], s2[k] = 0, 0, 0 for index, x in samples: probabilities = np.multiply(gaussians[index], weights) probabilities = probabilities / np.sum(probabilities) s0[k] = s0[k] + likelihood_moment(x, probabilities[k], 0) s1[k] = s1[k] + likelihood_moment(x, probabilities[k], 1) s2[k] = s2[k] + likelihood_moment(x, probabilities[k], 2) return s0, s1, s2 def fisher_vector_weights(s0, s1, s2, means, covs, w, T): return np.float32([((s0[k] - T * w[k]) / np.sqrt(w[k]) ) for k in range(0, len(w))]) def fisher_vector_means(s0, s1, s2, means, sigma, w, T): return np.float32([(s1[k] - means[k] * s0[k]) / (np.sqrt(w[k] * sigma[k])) for k in range(0, len(w))]) def fisher_vector_sigma(s0, s1, s2, means, sigma, w, T): return np.float32([(s2[k] - 2 * means[k]*s1[k] + (means[k]*means[k] - sigma[k]) * s0[k]) / (np.sqrt(2*w[k])*sigma[k]) for k in range(0, len(w))]) def normalize(fisher_vector): v = np.sqrt(abs(fisher_vector)) * np.sign(fisher_vector) return v / np.sqrt(np.dot(v, v)) def fisher_vector(samples, means, covs, w): s0, s1, s2 = likelihood_statistics(samples, means, covs, w) T = samples.shape[0] covs = np.float32([np.diagonal(covs[k]) for k in range(0, covs.shape[0])]) a = fisher_vector_weights(s0, s1, s2, means, covs, w, T) b = fisher_vector_means(s0, s1, s2, means, covs, w, T) c = fisher_vector_sigma(s0, s1, s2, means, covs, w, T) fv = np.concatenate([np.concatenate(a), np.concatenate(b), np.concatenate(c)]) fv = normalize(fv) return fv ##################################################### '''Here are some sample programs for explaining the usage of Opencv's sift feature and gmm''' ##################################################### ################### '''Step One, generate sift descriptors for a set images.''' '''For each image, its sift descriptors would be saved as 'image_name.npy' in the folder of 'opencvSiftDescriptors' ''' # ################# # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\1\\images'] ) # computANDsaveRawSiftFeatures(image_paths) # ################# ################### '''Step Two, train a gmm model for these samples as train dataset.''' '''The trained result of three files 'convs.gmm.npy, means.gmm.npy, weights.pmm.npy' are \ saved in the sub-directory of source folder, whose name is specified. ''' # ################# # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\1\\images'] ) # sift_desc_paths = map(lambda each_img_path : os.path.join(dataHandle.splitImgPath(each_img_path)[0] \ # , 'opencvSiftDescriptors', dataHandle.splitImgPath(each_img_path)[1]+'.npy') , image_paths) # N = 20 # generate_gmm( sift_desc_paths , N , 'my_opencvSiftGmm_Model' ) # ################# ################### '''Step Three, now that the model is trained, we can generate meaningful feature vectors(or called as fisher vectors) for images now.''' '''Two versions are given here: ''' '''Version 1 is used for processing descriptors existing on the disk''' '''Version 2 is used for unprocessed images, one step of calculating descriptors is appended.''' # ################# # # Version 1 # ################# # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\1\\images'] ) # sift_desc_paths = map(lambda each_img_path : os.path.join(dataHandle.splitImgPath(each_img_path)[0] \ # , dataHandle.splitImgPath(each_img_path)[1]+'.npy') , image_paths) # my_gmm = load_gmm('my_opencvSiftGmm_Model') # sift_feature_list = np.concatenate([map(lambda s: fisher_vector( loadSiftDescriptor( s ), *my_gmm ), sift_desc_paths)]) # ################# # # Version 2 # ################# # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\dresses_warehouse\\1\\images'] ) # my_gmm = load_gmm('my_opencvSiftGmm_Model') # sift_feature_list = np.concatenate([map(lambda each_image_path: fisher_vector( \ # siftDescriptorForOneImg(cv2.imread(each_image_path)) , *my_gmm ) , image_paths )]) # #################<file_sep>/ShallowFeature/visualFeatures/featureColorHistogram.py import cv2 import dataHandle import numpy as np def colorHisFeatureForOneImg( input_image , use_mask = True ): hist = [] if use_mask: mask = dataHandle.imgPreProcessing_BackgroundMask( input_image )[:,:,0] mask = np.array( mask , 'uint8' ) hist = cv2.calcHist([input_image], [0,1,2], mask , [12,12,12], [0,256,0,256,0,256]) else: hist = cv2.calcHist([input_image], [0,1,2], None , [12,12,12], [0,256,0,256,0,256]) return dataHandle.normalize(hist.flatten()) def colorHisFeatureForImgSet( input_image_paths , use_mask = True): return np.concatenate([map( lambda each_image_path: colorHisFeatureForOneImg( cv2.imread( each_image_path ) , use_mask) , input_image_paths )])<file_sep>/ShallowFeature/featureCalculater.py from visualFeatures import simpleIO from visualFeatures import featureOpencvSiftFisherVector as sift_fv from visualFeatures import featureOpencvSiftBoW as sift_bow from visualFeatures import featureSklearnHog as skHog from visualFeatures import featureColorHistogram as colorHis from visualFeatures import dataHandle from visualFeatures import pcaTrainer import numpy as np import cv2 import os def calculateFeatureAndSave( input_image_paths , configur_file , feature_output_dir = None): config_table = simpleIO.read_arraylist_from_txt(configur_file) feature_selected_list = np.ones(4)*False feature_name_list = [ 'sift_fisher_vector' , 'sift_bow' , 'hog' , 'colorHis'] pca_names = [ None , None , None , None] diction_names = ['' , '' , '' , ''] name_2_idx_dict = dict(zip( feature_name_list , range(0,4) )) for each_row in config_table: if each_row[0].startswith('#'): continue feature_name = each_row[0].split(':')[1] if not feature_name in name_2_idx_dict: print 'Feature called as #'+feature_name+'# is currently not available.' continue the_idx = name_2_idx_dict[feature_name] feature_selected_list[the_idx] = True print 'Use feature called '+feature_name for i in range(1, len(each_row)): attribute = each_row[i].split(':') if attribute[0].startswith('#'): continue if attribute[0] == 'diction': diction_names[the_idx] = attribute[1] print '#load diction from '+diction_names[the_idx] elif attribute[0] == 'PCA': pca_names[the_idx] = attribute[1] print '#load pca from '+pca_names[the_idx] else: print 'Sorry, I do not understand #'+each_row[i]+'#' print '\n\n#####################################' print '###Done with model loading.' print '#####################################\n\n' general_feature_list = [] for i in range(0, 4): if feature_selected_list[i]: print 'Loading feature type: '+feature_name_list[i] if i==0:#sift_fisher_vector my_gmm = sift_fv.load_gmm( diction_names[i] ) sift_fv_list = np.concatenate([map(lambda each_image_path: sift_fv.fisher_vector(\ sift_fv.siftDescriptorForOneImg(cv2.imread(each_image_path)) , *my_gmm ) , input_image_paths )]) if pca_names[i]: print 'Feature sift_fisher_vector is applied with pca.' sift_fv_list = pcaTrainer.transformRawFeatures( sift_fv_list , pca_names[i] ) general_feature_list.append(sift_fv_list) elif i==1:#sift_bow my_bow = sift_bow.load_bow( diction_names[i] ) sift_bow_list = np.concatenate([map(lambda each_image_path: sift_bow.bow_feature_vector( each_image_path , my_bow ), input_image_paths )]) general_feature_list.append(sift_bow_list) elif i==2:#hog hog_feature_list = skHog.hogFeatureForImgSet( input_image_paths ) if pca_names[i]: print 'Feature hog is applied with pca.' hog_feature_list = pcaTrainer.transformRawFeatures( hog_feature_list , pca_names[i] ) general_feature_list.append(hog_feature_list) elif i==3:#color colorHis_feature_list = colorHis.colorHisFeatureForImgSet( input_image_paths ) if pca_names[i]: print 'Feature colorHis is applied with pca.' colorHis_feature_list = pcaTrainer.transformRawFeatures( colorHis_feature_list , pca_names[i] ) general_feature_list.append(colorHis_feature_list) final_feature_vectors = np.column_stack(general_feature_list) if feature_output_dir: if not os.path.exists(feature_output_dir): os.makedirs( feature_output_dir ) for i in range(0, len(input_image_paths)): each_path = input_image_paths[i] _,item_id,_ = dataHandle.splitImgPath( each_path ) np.save(os.path.join( feature_output_dir , item_id+'.npy' ), final_feature_vectors[i]) return final_feature_vectors <file_sep>/ShallowFeature/visualFeatures/simpleIO.py def read_arraylist_from_txt( file_path ): arraylist_file = open(file_path) list_of_all_the_lines = arraylist_file.readlines() table_in_men = [] for each_line in list_of_all_the_lines: each_line = each_line.strip('\n') attri_list = each_line.split('\t') table_in_men.append(attri_list) return table_in_men def save_array_in_txt( save_file_path , table_in_mem ): output_file = open(save_file_path, 'w') for each_row in table_in_mem: each_line = '' for each_attri in each_row: if not len(each_line)==0: each_line = each_line + '\t' each_line = each_line + str(each_attri) each_line = each_line + '\n' output_file.write(each_line) output_file.close()<file_sep>/ShallowFeature/visualFeatures/featureSklearnHog.py from skimage.feature import hog import dataHandle import cv2 import numpy as np def hogFeatureForOneImg( input_image ): gray_image = input_image if len(gray_image.shape)==2 : gray_image = input_image else: gray_image = cv2.cvtColor(input_image , cv2.COLOR_BGR2GRAY) gray_image = dataHandle.imgPreProcessing_Rescale( gray_image ) feature = np.array( gray_image, 'int16' ) h,w = feature.shape cell_width = w/16.0 cell_height = h/16.0 fd = hog(feature, orientations=9, pixels_per_cell=(cell_width , cell_height), cells_per_block=(1, 1), visualise=False) fd = np.array(fd, 'float32') fd = dataHandle.normalize(fd) return fd def hogFeatureForImgSet( input_image_paths ): return np.concatenate([map( lambda each_image_path: hogFeatureForOneImg( cv2.imread( each_image_path ) ) , input_image_paths )]) <file_sep>/README.md # Shallow visual features Shallow visual features, is a computer vision project made with simplicity and modularity in mind. It's primitive version comes as a part of our hackweek project, which wins the **first prize** of **ebay CCOE HACKWEEK 2016**. Generally speaking, this projct tries to provide an elegant way to create and share digital representation of visual images, even for people with little knowledge of computer vision. Once all the dependencies have been installed, you can - Train visual features for your images with one line of ```./trainAllModels.sh``` - Select features you like in your configuration file - Calculate feature vectors using ```featureCalculater.calculateFeatureAndSave(image_paths , 'config.txt')``` - These numerical 1D vectors are capable of classification , clustering, regression or other machine learning tasks. Table of Contents : - [Background knowledge](#background-knowledge) - [Installation](#installation) - [Usage guide](#usage-guide) - [Experimental results](#experimental-results) - [Appendix](#appendix) ## Background knowledge > In this part, we talk about some basic knowledge of computer vision. > If you are unfamiliar with how people treat with visual data, this section helps you get a > brief sketch of the work flow. ### What is feature ? The phrase of [feature vector/feature](https://en.wikipedia.org/wiki/Feature_vector) is widely used in the research field of computer vision. In most cases, the feature vector of an image/video usually stands for a one-dimesion numerical vector(composed of float values, mostly). This vector is capable of various vision tasks including object recognition, image segmentation, face recognition, video action understanding, etc. So, why we need this vector ? Because the image encoding of raw pixels doesn't work. ![alt text](https://github.com/AkiChen/Shallow-visual-features/raw/master/doc_images/pic1.png) Just like other pattern recognition tasks, to make computer 'see' things, we first collect sample images as the training dataset. Then, we define a specific encoding method for training samples and apply these numerical vectors to our classifiers or clusters. Taking the gray scale image as example, the most naive encoding method is flattening the 2D pixel matrix, so that image's representation of 1D vector is achieved. Nevertheless, a rotated/shifted/rescaled image would make completely different raw pixel vector, compared with its original one. Such sorts of simple transformation should never change the meaning of an image, in our human's eyes. To address this issue, we need a more well-designed way of encoding images which is invariant to affine transformation, shift of viewpoint, shift of luminance, and so on. Feature vector is assumed to meet the conditions above. ### Why shallow ? Shallow feature means the opposite of deep learning feature. These two types of algorithms differ at who makes the main effort of selecting effective feature, people or machine(data) ? Are shallow methods simpler than deep learning methods ? No, in most cases, shallow methods have much more complicated mathmatical expressions. It's true that deep learning have ruled almost every state-of-the-art result in computer vision, and all of them are some sort of [convolutional neural networks](https://en.wikipedia.org/wiki/Convolutional_neural_network). However, I would still say these two types of methods have their own pros and cons. ![alt text](https://github.com/AkiChen/Shallow-visual-features/raw/master/doc_images/pic2.png) As shown in the picture above, shallow methods take only one logical step to generate our target feature vector which seems to be some sort of magic. All shallow methods are manually designed by scientists and they must have done enormous times of experiments. A little disadvantage of these methods is that you might need to design new descriptor every time you come to a new task. But it's also OK, since we are able to publish more articles then (●′ω`●). Not until [G.Hinton's work](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) supassed the 2nd place more than 10 percent accuracy in ILSVRC-2012, shallow method is the most widely used image representation. As illustrated in the picture above, deep learning methods use a iterative structure. By image convolution layer by layer, we can see the images in each layer are becoming more and more fuzzy and abstract. That's because convolution kernel selects only part of the information carried by input image, and different images generated by different kernels would emphasize on various types of visual information. For example, some images might concentrate on object shape in picture and some others might focus on texture info, which is a sort of feature extraction. To extract more specified information , we do another round of convolution and finally images are abstract enough to form a 1D feature vector. You may wonder why this strange algorithm works. The answer is simple, because you see things with similar preocedures in your brain. Here is the comparison between two methods: * Shallow methods are handcrafted and need few trainning, while deep learning methods are highly dependent on training data and need long time of training. That's why GPUs are necessary. * Shallow methods only take charge of generating feature vector, while deep learning method usually trains its model with samples' labels which leads to an end-to-end system. * Deep learning's neural network structure makes it a flexible online learning system and easy to learn with large-scale data, while shallow methods aren't. ## Installation > The simplest guide of installation guide is given here. You can also manually install dependencies one by one, good luck. Dependency list: [opencv](http://opencv.org/downloads.html) (v2.4.9 or higher, the v3.0 serial is evil), [python](https://www.python.org/downloads/), [numpy](http://www.numpy.org/), [sklearn](http://scikit-learn.org/), [skimage](http://scikit-image.org/), [pillow](https://pillow.readthedocs.io/en/latest/installation.html). ### For windows * Step 1: Install Anaconda with [windows-installer](https://www.continuum.io/downloads). All the python dependencies are included. * Step 2: Install opencv with [windows-installer](https://sourceforge.net/projects/opencvlibrary/files/opencv-win/2.4.12/). Make sure the opencv directory has been add to your system paths. * Step 3: Copy the file of ```C:\opencv\build\python\2.7\x86\cv2.pyd``` (or x64) to ```C:\Users\YourUserName\Anaconda2\Lib\site-packages```. You should edit the routes above to fit your own installation path. ### For Ubuntu * Step 1: Install opencv following instructions [here](http://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html). * Step 2: Install Anaconda with instructions [here](http://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html). ### Your first run Go to the directory of ShallowFeature, and execute ```sh $ python playground.py ``` It will print a feature vector of the 'sample_dress.jpg' , using model config in 'dressFeatureConfig.txt'. ## Usage guide > In this section, we talk about how to use the implemented apis. ### Features avaliable * Sift with Bow * Sift with fisher vector * Hog * Color histogram ### Model defination Feature vectors generated by different methods can be concated as one feature. You select features in a config file like: ``` #feature:sift_fisher_vector diction:dress_diction PCA:dress_sift_gmm_pca feature:sift_bow diction:dress_diction feature:hog #PCA:dress_hog_pca feature:colorHis #PCA:dress_colorHis_pca ``` All setup are written in plaine text. In the config file above, each line represents one specific feature and you can put a '#' at head of line to let model parser ignore this line. The components of each line are **seperated by '\t'**. For the component starts with 'PCA', you can also use '#' to ignore it. For the detail information of model defined above: * feature:sift_fisher_vector, it alerts to use sift descriptor together with fisher vector. Its diction is saved in the directory './dress_diction', its pca transformer is saved in './pcaDataBase/dress_sift_gmm_pca.pkl' * feature:sift_bow, it alerts to use sift descriptor together with bag of words. Its diction is saved in the directory './dress_diction'. * feature:hog, it alerts to use hog. Its pca transformet is saved in './pcaDataBase/dress_hog_pca.pkl' * feature:colorHis, it alerts to use color historgram. Its pca transformet is saved in './pcaDataBase/dress_colorHis_pca.pkl' ### Get feature vectors with a trained model If you have a trained model and a folder of images, you can transform these images to feature vectors with python code like: ```python import featureCalculater from visualFeatures import dataHandle image_folder_path = 'image_folder_path' image_paths = dataHandle.read_only_image_paths( [image_folder_path] ) featureCalculater.calculateFeatureAndSave( image_paths , 'dressFeatureConfig.txt' , 'your_output_dir' ) ``` Make sure the model folder and files locate in the right place as described in ```dressFeatureConfig.txt```. The function of ```calculateFeatureAndSave``` always return a 2D matrix and each line is one feature vector. You can set the third parameter to save features as a lot of ```image_name.npy``` files in target directory. If the third parameter is set to **None**, features wouldn't be saved. ### Train your own model A simple example of training all features available is given in ```trainAllModels.sh```. Let's analyze the training command of sift_fisher_vector as example. ```sh #!/usr/bin/env sh DATASET_NAME="dress" DICTION_IMAGE_PATH = "C:\\Users\\peiqchen\\Desktop\\dresses_diction_images" PCA_IMAGE_PATH = "C:\\Users\\peiqchen\\Desktop\\dresses_pca_images" #Train gmm model python ./ExampleSiftGmmTraining.py \ --dic=${DATASET_NAME}_diction \ --pca=${DATASET_NAME}_sift_gmm_pca \ --file_dic=${DICTION_IMAGE_PATH} \ --file_pca=${PCA_IMAGE_PATH} ``` The feature called ```sift_fisher_vector``` needs two steps of training. Firstly, a gmm model is trained to transform raw sift descriptors to meaningful feature vector(fisher vector). Then, a PCA model is trained to reduce the feature vector's dimension. Hence, you should provide the image folder paths with parameter ```--file_dic=``` to train the diction of GMM. Multiple ```--file_dic=``` attributes are also acceptable, all images in these folders would be taken as training samples. Parameters for PCA training are similar, except their training results would be saved in different folder. ```DATASET_NAME``` is set for identification and diction files are saved in folder ```./{DATASET_NAME}_diction```. The pca files, however, are saved seperate from dicstions, in ```./pcaDataBase```, named as ```{DATASET_NAME}_sift_gmm_pca.pkl```. You may also edit paramters in ```./ExampleSiftGmmTraining.py```, it's not that painful. ## Experimental results > Which feature is the best ? Currently, I have only conducted experiments on a small image recognition dataset. This dataset is composed with two classes : normal and sextoys. Each class has 900 samples for training and 200 for testing. | Method | Average accuracy | | ------------- |:-------------:| | SiftBow+Hog+ColorHis | 0.90 | | SiftBow+Hog&PCA+ColorHis&PCA | 0.89 | | SiftBow+Hog&PCA | 0.89 | | SiftFisher+Hog+ColorHis | 0.88 | | SiftFisher&PCA+Hog&PCA+ColorHis&PCA | 0.88 | | Hog&PCA | 0.88 | | ColorHis&PCA | 0.81 | | SiftBow | 0.74 | ## Appendix > Other things. Features waiting for implemention * Color Correlogram * Surf If you have any problems or bug reports, please contact me <EMAIL>.com. <file_sep>/ShallowFeature/visualFeatures/pcaTrainer.py import os from sklearn.decomposition import PCA from sklearn.externals import joblib def trainPCAwithRawFeatures( feature_numpy_array , dimension , name_of_feature ): my_pca = PCA(n_components=dimension) my_pca.fit(feature_numpy_array) save_path = os.path.join( '.', 'pcaDataBase' ) if not os.path.exists(save_path): os.makedirs(save_path) joblib.dump(my_pca, os.path.join(save_path, name_of_feature+'.pkl'), compress=3) return my_pca def transformRawFeatures( feature_numpy_array , name_of_feature ): my_pca = joblib.load(os.path.join( '.' , 'pcaDataBase' , name_of_feature+'.pkl')) return my_pca.transform( feature_numpy_array ) <file_sep>/ShallowFeature/visualFeatures/featureHarrisSift.py import numpy as np import os import cv2 from scipy.stats import multivariate_normal def calculateRawSiftFeatures( img_paths ): sift_tool_prefix = 'C:\\Users\\peiqchen\\Desktop\\extract_features\\extract_features -harhes -i ' sift_tool_backfix = ' -sift -pca C:\\Users\\peiqchen\\Desktop\\extract_features\\harhessift.basis' counter = 0 for each_img in img_paths: print 'Calculating img '+str(counter+1)+'#' os.system(sift_tool_prefix+each_img+sift_tool_backfix) counter = counter + 1 print 'Done' def loadSiftDescriptor( file_path ): this_feature_file = open(file_path) #length of feature, 128 line = this_feature_file.readline() #number of features line = this_feature_file.readline() stacked_feature = [] line = this_feature_file.readline() while line: feature_vector = line.split(' ') feature_vector = feature_vector[5:] stacked_feature.append(feature_vector) line = this_feature_file.readline() numeric_feature = np.array(stacked_feature, 'float32') return numeric_feature def dictionary(descriptors, N): em = cv2.EM(N) em.train(descriptors) return np.float32(em.getMat("means")), \ np.float32(em.getMatVector("covs")), np.float32(em.getMat("weights"))[0] def generate_gmm(input_feature_paths, N): words = np.concatenate([loadSiftDescriptor(each_feature_path) for each_feature_path in input_feature_paths]) print("Training GMM of size", N) means, covs, weights = dictionary(words, N) #Throw away gaussians with weights that are too small: th = 1.0 / N means = np.float32([m for k,m in zip(range(0, len(weights)), means) if weights[k] > th]) covs = np.float32([m for k,m in zip(range(0, len(weights)), covs) if weights[k] > th]) weights = np.float32([m for k,m in zip(range(0, len(weights)), weights) if weights[k] > th]) np.save("means.gmm", means) np.save("covs.gmm", covs) np.save("weights.gmm", weights) return means, covs, weights def load_gmm(folder = ""): files = ["means.gmm.npy", "covs.gmm.npy", "weights.gmm.npy"] return map(lambda file: np.load(file), map(lambda s : folder + "\\" + s , files)) def likelihood_moment(x, ytk, moment): x_moment = np.power(np.float32(x), moment) if moment > 0 else np.float32([1]) return x_moment * ytk def likelihood_statistics(samples, means, covs, weights): gaussians, s0, s1,s2 = {}, {}, {}, {} samples = zip(range(0, len(samples)), samples) g = [multivariate_normal(mean=means[k], cov=covs[k]) for k in range(0, len(weights)) ] for index, x in samples: gaussians[index] = np.array([g_k.pdf(x) for g_k in g]) for k in range(0, len(weights)): s0[k], s1[k], s2[k] = 0, 0, 0 for index, x in samples: probabilities = np.multiply(gaussians[index], weights) probabilities = probabilities / np.sum(probabilities) s0[k] = s0[k] + likelihood_moment(x, probabilities[k], 0) s1[k] = s1[k] + likelihood_moment(x, probabilities[k], 1) s2[k] = s2[k] + likelihood_moment(x, probabilities[k], 2) return s0, s1, s2 def fisher_vector_weights(s0, s1, s2, means, covs, w, T): return np.float32([((s0[k] - T * w[k]) / np.sqrt(w[k]) ) for k in range(0, len(w))]) def fisher_vector_means(s0, s1, s2, means, sigma, w, T): return np.float32([(s1[k] - means[k] * s0[k]) / (np.sqrt(w[k] * sigma[k])) for k in range(0, len(w))]) def fisher_vector_sigma(s0, s1, s2, means, sigma, w, T): return np.float32([(s2[k] - 2 * means[k]*s1[k] + (means[k]*means[k] - sigma[k]) * s0[k]) / (np.sqrt(2*w[k])*sigma[k]) for k in range(0, len(w))]) def normalize(fisher_vector): v = np.sqrt(abs(fisher_vector)) * np.sign(fisher_vector) return v / np.sqrt(np.dot(v, v)) def fisher_vector(samples, means, covs, w): s0, s1, s2 = likelihood_statistics(samples, means, covs, w) T = samples.shape[0] covs = np.float32([np.diagonal(covs[k]) for k in range(0, covs.shape[0])]) a = fisher_vector_weights(s0, s1, s2, means, covs, w, T) b = fisher_vector_means(s0, s1, s2, means, covs, w, T) c = fisher_vector_sigma(s0, s1, s2, means, covs, w, T) fv = np.concatenate([np.concatenate(a), np.concatenate(b), np.concatenate(c)]) fv = normalize(fv) return fv # ttp = loadSiftDescriptor('C:\\Users\\peiqchen\\Desktop\\normal_train_png\\111082028584_169280.png.harhes.sift') # print ttp.shape # print ttp[0] # feature_paths = glob.glob("C:\\Users\\peiqchen\\Desktop\\normal_train_png\\*.harhes.sift") # generate_gmm(feature_paths, 20) #files = ["means.gmm.npy", "covs.gmm.npy", "weights.gmm.npy"] #folder = 'C:\Users\peiqchen\workspace\pornRegExp' #print map(lambda s : folder + '\\' +s, files) # my_gmm = load_gmm('C:\\Users\\peiqchen\\workspace\\pornRegExp\\src') # print my_gmm[0].shape # print my_gmm[1].shape # print my_gmm[2].shape # ttp = loadSiftDescriptor('C:\\Users\\peiqchen\\Desktop\\normal_train_png\\111082028584_169280.png.harhes.sift') # ttp2 = loadSiftDescriptor('C:\\Users\\peiqchen\\Desktop\\normal_train_png\\111871497400_169280.png.harhes.sift') # print ttp.shape # print ttp2.shape # my_vector = fisher_vector( ttp , *my_gmm ) # my_vector_2 = fisher_vector( ttp2 , *my_gmm ) # print my_vector.shape # print my_vector_2.shape # base_path = 'C:\\Users\\peiqchen\\Desktop' # folder_names = ['normal_train_png', 'sextoys_train_png'] # folders = map( lambda each_name: base_path+'\\'+each_name, folder_names ) # feature_file_paths = [] # for each_folder in folders: # each_feature_file_paths = glob.glob(each_folder+"\\*.harhes.sift") # feature_file_paths.extend(each_feature_file_paths) # # N = 20 # # generate_gmm( feature_file_paths , N ) # name_2_label_dict = {'sextoys_train_png':0, 'normal_train_png':1} # label_array = None # for each_folder in folders: # length = len(glob.glob(each_folder+'\\*.harhes.sift')) # _ , folder_name = os.path.split(each_folder) # label = int(name_2_label_dict[folder_name]) # folder_label_array = np.ones((length))*label # if label_array is None: # label_array = folder_label_array # else: # label_array = np.concatenate((label_array, folder_label_array)) # my_gmm = load_gmm('C:\\Users\\peiqchen\\eclipse_workspace\\ShallowFeature\\src') # sift_feature_list = np.concatenate([map(lambda s: fisher_vector( loadSiftDescriptor( s ), *my_gmm ), feature_file_paths)]) # print sift_feature_list.shape # clf = LinearSVC() # clf.fit( sift_feature_list, label_array ) # joblib.dump(clf, 'my_harhes_cls.pkl', compress=3) # image_paths = dataHandle.read_only_image_paths( ['C:\\Users\\peiqchen\\Desktop\\sextoys_test_png'] ) # print len(image_paths) # calculateRawSiftFeatures(image_paths)<file_sep>/ShallowFeature/ExampleSiftGmmTraining.py from visualFeatures import dataHandle from visualFeatures import featureOpencvSiftFisherVector as sift_fv from visualFeatures import pcaTrainer import os import numpy as np import cv2 import sys import getopt opts, args = getopt.getopt( sys.argv[1:] , "hi:o:", ["dic_name=", "pca_name=","file_dic=", "file_pca="] ) dic_name = None pca_name = None file_dic = [] file_pca = [] for op, value in opts: if op == "--dic_name": print "diction saved in folder : ./",value dic_name = value elif op == "--pca_name": print "pca saved in file : ./pcaDataBase/",value,".pkl" pca_name = value elif op == "--file_dic": file_dic.append( value ) elif op == "--file_pca": file_pca.append( value ) ###################################################### ## An example program of train sift feature with gmm ## PCA is used here ###################################################### ###################################################### ## Editable params are listed here ###################################################### '''If your computer doesn't have enough main memory, you have \ no choice but to select part of your train dataset for training. The image set \ for training diction and pca, don't need to be the same.''' ###################################################### DICTION_IMAGE_PATH_FOR_TRAINING = file_dic PCA_IMAGE_PATH_FOR_TRAINING = file_pca N = 20 #size of diction, OUTPUT_DIMENSION = 200 #size of pca output dimension OUTPUT_DICTION_NAME = dic_name OUTPUT_PCA_NAME = pca_name ###################################################### ###################################################### image_paths = dataHandle.read_only_image_paths( DICTION_IMAGE_PATH_FOR_TRAINING ) #Compute descriptors and save on disk. sift_fv.computANDsaveRawSiftFeatures(image_paths) #Train the gmm model. sift_desc_paths = map(lambda each_img_path : os.path.join(dataHandle.splitImgPath(each_img_path)[0] \ , 'opencvSiftDescriptors', dataHandle.splitImgPath(each_img_path)[1]+'.npy') , image_paths) sift_fv.generate_gmm( sift_desc_paths , N , OUTPUT_DICTION_NAME ) print 'Done with gmm training' ##################################################### pca_image_paths = dataHandle.read_only_image_paths( PCA_IMAGE_PATH_FOR_TRAINING ) my_gmm = sift_fv.load_gmm(dic_name) #Load sift_gmm features sift_feature_list = np.concatenate([map(lambda each_image_path: sift_fv.fisher_vector(\ sift_fv.siftDescriptorForOneImg(cv2.imread(each_image_path)) , *my_gmm ) , pca_image_paths )]) pcaTrainer.trainPCAwithRawFeatures( sift_feature_list , OUTPUT_DIMENSION , OUTPUT_PCA_NAME ) print 'Done with pca training' ######################################################
77a75c13a640141cdaf13ad6c513440683ce4c34
[ "Markdown", "Python", "Shell" ]
17
Python
AkiChen/Shallow-visual-features
41a64ccd48b881c4ee08d145f2184931b65017b9
49a5a674e91a34f0215cabf2850a81abbd62e80c
refs/heads/master
<repo_name>pregardtzs/DevelopingDataProducts<file_sep>/server.R library(shiny) shinyServer( function(input, output) { output$oid1 <- renderPrint({input$number1}) output$oid2 <- renderPrint({input$number2}) output$oid3 <- renderPrint({input$number3}) output$oid4 <- renderPrint({input$number4}) output$oid5 <- renderPrint({input$number5}) output$oid6 <- renderPrint({input$number6}) output$oid7 <- renderPrint({input$number7}) output$oid8 <- renderPrint({input$number8}) output$oid9 <- renderPrint({input$number9}) output$oid10 <- renderPrint({input$number10}) output$oid11 <- renderPrint({mean(c({input$number1}, {input$number2}, {input$number3}, {input$number4}, {input$number6}, {input$number7}, {input$number8}, {input$number9}, {input$number10}))}) } ) <file_sep>/ui.R library(shiny) shinyUI(pageWithSidebar( headerPanel("Calculate average"), sidebarPanel( numericInput('number1', 'Number 1', 0), numericInput('number2', 'Number 2', 0), numericInput('number3', 'Number 3', 0), numericInput('number4', 'Number 4', 0), numericInput('number5', 'Number 5', 0), numericInput('number6', 'Number 6', 0), numericInput('number7', 'Number 7', 0), numericInput('number8', 'Number 8', 0), numericInput('number9', 'Number 9', 0), numericInput('number10', 'Number 10', 0) ), mainPanel( h3('Numbers:'), verbatimTextOutput("oid1"), verbatimTextOutput("oid2"), verbatimTextOutput("oid3"), verbatimTextOutput("oid4"), verbatimTextOutput("oid5"), verbatimTextOutput("oid6"), verbatimTextOutput("oid7"), verbatimTextOutput("oid8"), verbatimTextOutput("oid9"), verbatimTextOutput("oid10"), h3('Average:'), verbatimTextOutput("oid11"), h6('Documentation: \n This application calculates the average of 10 numbers and display it in the "Average" field. When you write a number in one of the "Numbers" field on the left, the average recalculates immediately.') ) ))
4f595139fb8e05917b581a6960e80eb7a7689ec0
[ "R" ]
2
R
pregardtzs/DevelopingDataProducts
332873ddf498f0a977afb6a3619aab4321b02d89
135c03154507cf770e4d3a038bfa3724d80bdc74
refs/heads/master
<file_sep>package Backend; import java.util.Scanner; import java.util.ArrayList; /** * Class models the text based interface a user is shown */ public class Menu { // create an instance of the ATM class for use in facilitating private final ATM machine = new ATM(); /** * Launches application. Can only continue when correct card is inserted. */ void launch() { ArrayList<Account> accounts = machine.getAccounts(); // get accounts from atm machine data if (machine.verifyLogin()) displayMenu(accounts); // pass in accounts to displayMenu method else machine.verifyLogin(); } /** * Displays menu only if launch conditions were satisfied and handles inputs and outputs. * @param accounts list of accounts */ void displayMenu(ArrayList<Account> accounts) { Scanner in = new Scanner(System.in); int choice = 0; while (choice != 5) { System.out.print("1) Withdraw Funds\n" + "2) Deposit Funds\n" + "3) Transfer Funds\n" + "4) Check Balance\n" + "5) Quit\n" + "-------------------\nEnter selection: "); choice = in.nextInt(); switch(choice) { // switch through user response cases case 1: withdrawFunds(accounts); break; case 2: depositFunds(accounts); break; case 3: transferFunds(accounts); break; case 4: checkBalance(accounts); break; default: break; } } } /** * Withdraw funds from selected account * @param accounts list of accounts */ void withdrawFunds(ArrayList<Account> accounts) { Scanner in = new Scanner(System.in); int choice; double amt; System.out.println("Choose which account to withdraw from: "); for (int i = 0; i < accounts.size(); i++) System.out.println((i + 1) + ") " + accounts.get(i)); // iterate through contained accounts choice = in.nextInt(); // get user response Account temp = accounts.get(choice - 1); // stored selected account object in temp System.out.println("Enter amount to withdraw: "); amt = in.nextDouble(); if (machine.withdrawFunds(temp, amt)) // attempt to use atm class method System.out.println("Successfully withdrew $" + amt + "\nCurrent Balance: " + temp.getBalance()); } //TODO: There was a bug i encountered when moving money back and forth // there was an index out of bounds error, and the 200 withdraw limit was static, even with larger funds /** * Deposits into selected account. * @param accounts list of accounts */ void depositFunds(ArrayList<Account> accounts) { Scanner in = new Scanner(System.in); int choice; double amt; System.out.println("Choose which account to deposit to: "); for (int i = 0; i < accounts.size(); i++) System.out.println((i + 1) + ") " + accounts.get(i)); // iterate through contained accounts choice = in.nextInt(); // get user response Account temp = accounts.get(choice - 1); // stored selected account object in temp System.out.println("Enter amount to deposit: "); amt = in.nextDouble(); if(machine.depositFunds(temp,amt)) { // attempt to use depositFunds() method from atm class System.out.println("Successfully deposited $" + amt + "\nCurrent Balance: " + temp.getBalance()); } } /** * Transfer funds between the specified accounts * @param accounts list of accounts */ void transferFunds(ArrayList<Account> accounts) { Scanner in = new Scanner(System.in); int choice; double amt; System.out.println("Transfer of Funds Selected"); System.out.println("Enter amount to transfer: "); amt = in.nextDouble(); // request origin account to get money from System.out.println("Choose which account to transfer from: "); for (int i = 0; i < accounts.size(); i++) System.out.println((i + 1) + ") " + accounts.get(i)); // iterate through contained accounts choice = in.nextInt(); // get user response Account origin = accounts.get(choice - 1); // stored selected account object in temp // request recipient account to send money to System.out.println("Choose which account to transfer to: "); for (int i = 0; i < accounts.size(); i++) System.out.println((i + 1) + ") " + accounts.get(i)); // iterate through contained accounts choice = in.nextInt(); // get user response Account recipient = accounts.get(choice - 1); // stored selected account object in temp if(machine.transferFunds(origin,recipient,amt)) { // attempt transferFunds() operation System.out.println("Successfully transferred $" + amt); } } /** * Check the current montary balance of the users desired account * @param accounts list of accounts */ void checkBalance(ArrayList<Account> accounts) { Scanner input = new Scanner(System.in); int choice; System.out.println("Choose which account to check balance of: "); for (int i = 0; i < accounts.size(); i++) System.out.println((i + 1) + ") " + accounts.get(i)); // iterate through contained accounts choice = input.nextInt(); // get user response Account temp = accounts.get(choice - 1); // stored selected account object in temp System.out.println(temp); } }
1bea43373034fdbe97a6a05cd3959648fb86b798
[ "Java" ]
1
Java
Mark-Arias/CECS343_FinalEngineeringProject
ad4cd02798c00c05dbc29401ecee3eb53a23f201
a802573ecd0b6b378df3403494888f32346af30b
refs/heads/master
<repo_name>ViriatoOundil/RustInterceptor<file_sep>/RustInterceptor/Forms/Utils/DrawingUtils.cs using Rust_Interceptor.Data; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static Rust_Interceptor.Forms.Structs.WindowStruct; using Vector3DX = SharpDX.Vector3; using Vector2DX = SharpDX.Vector2; using Vector3DU = UnityEngine.Vector3; using Vector2DU = UnityEngine.Vector2; namespace Rust_Interceptor.Forms.Utils { class DrawingUtils { #region Constructor private static DrawingUtils instance; public static DrawingUtils getInstance() { if (instance == null) instance = new DrawingUtils(); return instance; } private Controller manejador; public Controller getController() { return manejador; } private DrawingUtils() { manejador = Controller.getInstance(); manejador.mostrarse(); } #endregion Constructo public void drawCrosshair(Graphics g, Color color, RECTANGULO targetRect, int longitudRecta = 5, bool ignoreOffset = false) { Pen lapiz = new Pen(color); lapiz.Width = 1; //linea horizontal Vector2DX offsetCentro = ignoreOffset ? new Vector2DX() : new Vector2DX(manejador.getXCrosshairOffsetValue(), manejador.getYCrosshairOffsetValue()); Vector2DX centro = targetRect.CenterAbsolute - offsetCentro; POINT middleMinorH = centro - Vector2DX.UnitX * longitudRecta; POINT middleMayorH = centro + Vector2DX.UnitX * longitudRecta; g.DrawLine(lapiz, middleMinorH, middleMayorH); //linea vertical POINT middleMinorV = centro - Vector2DX.UnitY * longitudRecta; POINT middleMayorV = centro + Vector2DX.UnitY * longitudRecta; g.DrawLine(lapiz, middleMinorV, middleMayorV); } #region Radar private int RADAR_RADIUS = 75; private int PLAYER_BOX_SIZE = 4; private int PLAYER_FOV_SIZE = 4; public void drawRadar(Graphics g, Color color, POINT init, Entity localPlayer , out RECTANGULO radarRect) //, List<Entity> players) { radarRect = new RECTANGULO( Convert.ToInt32(init.X), Convert.ToInt32(init.Y), Convert.ToInt32(init.X+(RADAR_RADIUS * 2 - 1) ), Convert.ToInt32(init.Y+(RADAR_RADIUS * 2 - 1) ) ); //DrawingUtils.AddorUpdateRect(clase, rect); //if (filled) //FIXME Se rellena con el color de fondo del form { SolidBrush pincel = new SolidBrush(color); g.FillEllipse(pincel, radarRect); } Pen lapiz = new Pen(color); lapiz.Width = 2; lapiz.Color = Color.FromArgb(255,color.R, color.G, color.B); g.DrawEllipse(lapiz, radarRect); drawCrosshair(g, Color.FromArgb(128,Color.Red), radarRect, RADAR_RADIUS,true); //Para comprobar si el calculo del centro esta Ok } public void drawRadarPlayer(Graphics g, Entity localPlayer, Entity player, Vector2DX worldMid , float escala = 2f) { Brush pincel = Brushes.Red; if (player.Data.basePlayer.modelState.sleeping) pincel = Brushes.Gray; if (player.IsLocalPlayer) pincel = Brushes.Gold; Vector2DX pos = calculateRelativePos(localPlayer, player, worldMid); g.FillEllipse( pincel, pos.X - PLAYER_BOX_SIZE / escala, pos.Y - PLAYER_BOX_SIZE / escala, PLAYER_BOX_SIZE, PLAYER_BOX_SIZE ); //Dibujo metros entre yo y el personaje String metros = player.IsLocalPlayer ? "" : (int)Vector2DX.Distance(Vector3To2(localPlayer.Data.baseEntity.pos), Vector3To2(player.Data.baseEntity.pos) )+" m"; Font fuente = new Font(FontFamily.GenericMonospace, 8); g.DrawString(metros, fuente, pincel, new PointF(pos.X,pos.Y) ); //Prepare FOV. Es decir, la cosa esa tan bonita que nos muestra la direcci´no de pa donde mira el jugador Vector2DX[] fov = new Vector2DX[3]; fov[0] = pos; fov[1] = pos - (Vector2DX.UnitY * PLAYER_FOV_SIZE) + (Vector2DX.UnitX * PLAYER_FOV_SIZE); fov[2] = pos - (Vector2DX.UnitY * PLAYER_FOV_SIZE) - (Vector2DX.UnitX * PLAYER_FOV_SIZE); //Rotate FOV according to this player's and localPlayer's yaw //PReviamente en lugar de z era y fov[1] = RotatePoint(fov[1], pos, localPlayer.Data.baseEntity.rot.y - player.Data.baseEntity.rot.y); fov[2] = RotatePoint(fov[2], pos, localPlayer.Data.baseEntity.rot.y - player.Data.baseEntity.rot.y); //Draw FOV g.FillPolygon( pincel, ConverttoPOINTF(fov) ); } // escala = min/value 0,001 #endregion Radar #region Utils private Vector2DX calculateRelativePos(Entity localPlayer, Entity player, Vector2DX centroRadar) { //Console.WriteLine(player.Data.basePlayer.name + " -> "+player.Data.baseEntity.pos ); Vector2DX screenPos = Vector3To2(player.Data.baseEntity.pos); screenPos = Vector3To2(localPlayer.Data.baseEntity.pos) - screenPos; float distance = screenPos.Length()/manejador.getZoomValue() * RADAR_RADIUS;//float distance = screenPos.Length() * (0.02f * manejador.getZoomValue()); distance = Math.Min( distance, RADAR_RADIUS); screenPos.Normalize(); screenPos *= distance; screenPos += centroRadar; screenPos = RotatePoint(screenPos, centroRadar, localPlayer.Data.baseEntity.rot.y + manejador.getAngleValue()); return screenPos; } private Vector2DX RotatePoint(Vector2DX pointToRotate, Vector2DX centerPoint, float angle, bool angleInRadians = false) { if (!angleInRadians) angle = (float)(angle * (Math.PI / 180f)); float cosTheta = (float)Math.Cos(angle); float sinTheta = (float)Math.Sin(angle); /*Vector2 returnVec = new Vector2( cosTheta * (centerPoint.X - pointToRotate.X) - sinTheta * (centerPoint.Y - pointToRotate.Y) , sinTheta * (centerPoint.X - pointToRotate.X) + cosTheta * (centerPoint.Y - pointToRotate.Y) );*/ Vector2DX returnVec = new Vector2DX( sinTheta * (pointToRotate.Y - centerPoint.Y) - cosTheta * (pointToRotate.X - centerPoint.X), sinTheta * (pointToRotate.X - centerPoint.X) + cosTheta * (pointToRotate.Y - centerPoint.Y) ); returnVec += centerPoint; return returnVec; } private Vector2DX Vector3To2(UnityEngine.Vector3 pos) { return new Vector2DX(pos.x, pos.z); } public PointF[] ConverttoPOINTF(params Vector2DX[] puntos) { PointF[] pts = new PointF[puntos.Length]; for (int i = 0; i < puntos.Length; i++) pts[i] = new PointF(puntos[i].X, puntos[i].Y); return pts; } #endregion Utils #region 3D World public void drawPlayer(Graphics g, Entity localPlayer, Entity player, RECTANGULO windowRect) { /*Translate by - camerapos*/ var camerapos = new Vector3DU(localPlayer.Data.baseEntity.pos.x, localPlayer.Data.baseEntity.pos.y, -localPlayer.Data.baseEntity.pos.z); var point = new Vector3DU(player.Data.baseEntity.pos.x, player.Data.baseEntity.pos.y, -player.Data.baseEntity.pos.z); point = camerapos - point; Vector3DU camRotation = localPlayer.Data.baseEntity.rot; /*Construct rotation matrix Rotations would be negative here to account for opposite direction of rotations in Unity's left-handed coordinate system, but since we're making them negative already this cancels out*/ //Console.WriteLine(camRotation); float P = (float)Math.PI / 180; float cosX = (float)Math.Cos(camRotation.x * P); //Hay que convertir grados a radianes float cosY = (float)Math.Cos(camRotation.y * P); float cosZ = (float)Math.Cos(camRotation.z * P); float sinX = (float)Math.Sin(camRotation.x * P); float sinY = (float)Math.Sin(camRotation.y * P); float sinZ = (float)Math.Sin(camRotation.z * P); float[,] matrix = new float[3, 3]; matrix[0, 0] = cosZ * cosY - sinZ * sinX * sinY; matrix[0, 1] = -cosX * sinZ; matrix[0, 2] = cosZ * sinY + cosY * sinZ * sinX; matrix[1, 0] = cosY * sinZ + cosZ * sinX * sinY; matrix[1, 1] = cosZ * cosX; matrix[1, 2] = sinZ * sinY - cosZ * cosY * sinX; matrix[2, 0] = -cosX * sinY; matrix[2, 1] = sinX; matrix[2, 2] = cosX * cosY; /*Apply rotation matrix to target point*/ Vector3DU rotatedPoint; rotatedPoint.x = matrix[0, 0] * point.x + matrix[0, 1] * point.y + matrix[0, 2] * point.z; rotatedPoint.y = matrix[1, 0] * point.x + matrix[1, 1] * point.y + matrix[1, 2] * point.z; rotatedPoint.z = matrix[2, 0] * point.x + matrix[2, 1] * point.y + matrix[2, 2] * point.z; Vector3DU resultPoint = new Vector3DU(rotatedPoint.x, rotatedPoint.y, -rotatedPoint.z); if (resultPoint.z > 0) { float focalLength = 540f / (float)Math.Tan(85f * P / 2f); float screenX = focalLength * resultPoint.x / resultPoint.z + windowRect.Width / 2; float screenY = focalLength * resultPoint.y / resultPoint.z + windowRect.Height / 2; RECTANGULO rect = new RECTANGULO(screenX, screenY, screenX + 10, screenY + 10); Pen lapiz = new Pen(Color.Red); g.DrawRectangle(lapiz, rect); //device.DrawEllipse(new Ellipse(new RawVector2(screenX, screenY), 6, 6), greenBrush); } } #endregion 3DWorld } } <file_sep>/RustInterceptor/Forms/Overlay.cs using Rust_Interceptor.Data; using Rust_Interceptor.Forms.Hooks; using Rust_Interceptor.Forms.Structs; using Rust_Interceptor.Forms.Utils; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using static Rust_Interceptor.Forms.Structs.WindowStruct; namespace Rust_Interceptor.Forms { public partial class Overlay : Form { //Parametros necesarios para simular el desplazamiento del Form private Point lastLocation; ////////////////////////////////////////// public volatile bool working = false; private RustInterceptor sniffer; private Process targetProcess; private Thread worker, cleaner; private ConcurrentDictionary<String,Entity> listaUsuarios = new ConcurrentDictionary<String, Entity>(); private Entity localPlayer; private Graphics g; private DrawingUtils pintor; private RECTANGULO rectRadar; private static Overlay instance; public static Overlay getInstance(Process targetProcess) { if (instance == null) instance = new Overlay(targetProcess); return instance; } private Overlay(Process targetProcess) { this.targetProcess = targetProcess; InitializeComponent(); } //Oculta todos los elementos para poder tener un overlayForm public void start(String server, int port) { sniffer = RustInterceptor.getInstance(server, port); this.hideControls(); pintor = DrawingUtils.getInstance(); //Hilo que se encargara de ir limpiando las entidades que esten muy lejos o no merezca la pena espiar. cleaner = new Thread( () => { do { if (localPlayer != null) { List<KeyValuePair<String, Entity>> filas = this.listaUsuarios.ToList<KeyValuePair<String, Entity>>(); foreach (KeyValuePair<String, Entity> fila in filas) { if (fila.Value == null) return; Entity entidad = fila.Value; float distance = UnityEngine.Vector2.Distance( new UnityEngine.Vector2(entidad.Data.baseEntity.pos.x, entidad.Data.baseEntity.pos.z) , new UnityEngine.Vector2(this.localPlayer.Data.baseEntity.pos.x, this.localPlayer.Data.baseEntity.pos.z)); if (distance > pintor.getController().getZoomValue() || entidad.Data.basePlayer.modelState.onground && !entidad.Data.basePlayer.modelState.sleeping ) this.listaUsuarios.TryRemove(fila.Key, out entidad); } } Thread.Sleep(5*1000); } while (working); }); cleaner.SetApartmentState(ApartmentState.MTA); cleaner.IsBackground = true; cleaner.CurrentCulture = System.Globalization.CultureInfo.CurrentCulture; cleaner.Priority = ThreadPriority.BelowNormal; cleaner.Name = "OverlayCleanerThread"; //Creo un Hilo que se encargara de hacer todo el curro worker = new Thread( () => { targetProcess.EnableRaisingEvents = true; targetProcess.Exited += new EventHandler( //En cuanto se cierre Rust, cerramos OVerlay (object sender, EventArgs e) => { this.Stop(); }); //¿Porque ha dejado de funcionar de pronto? //Puede ser por el cambio de propiedades de int a float que hice en RECTANGULO //new WindowHook(targetProcess.MainWindowHandle, this); //De momento esta clase se ocupa directamente de redimensionar la ventana this.resizeForm(new RECTANGULO()); sniffer.Start(); while( this.localPlayer == null) //Esperamos hasta que tengamos el localplayer { Thread.Sleep(1000); Console.WriteLine("No me he encontrado...Sigo buscandome"); } Console.WriteLine("Me he encontrado"); working = true; cleaner.Start(); //cleaner.Join(); do { this.worldToScreen(); Thread.Sleep(100); } while (working); }); worker.SetApartmentState(ApartmentState.MTA); worker.IsBackground = true; worker.CurrentCulture = System.Globalization.CultureInfo.CurrentCulture; worker.Priority = ThreadPriority.Highest; worker.Name = "OverlayWorkerThread"; worker.Start(); //worker.Join(); this.Show(); } public void Stop() { if (this.InvokeRequired) this.Invoke(new genericCallback(Stop)); else { this.working = false; if (sniffer != null) { if (sniffer.IsAlive) { sniffer.Stop(); //sniffer.SavePackets(); } } this.Close(); instance = null; } } //Se ocupara de mostrar en el overlay todo las entidades que nos interesa private delegate void genericCallback(); private void worldToScreen() { if (this.InvokeRequired) this.Invoke(new genericCallback(this.worldToScreen)); else { if(g == null) g = this.CreateGraphics(); g.Clear(Color.Black); pintor.drawCrosshair(g, Color.FromArgb(128, Color.Red), this.ClientRectangle); int radio = 75; POINT init = new POINT(this.Right - (radio * 2 + 5), this.Top + 8); //A la derecha con margenes para ver el radar al completo pintor.drawRadar(g, Color.FromArgb(10, Color.Gray), init, this.localPlayer, out this.rectRadar); // this.listaUsuarios.Values.ToList()); if (this.localPlayer == null) return; pintor.drawRadarPlayer(g, this.localPlayer, this.localPlayer, rectRadar.CenterAbsolute); List<Entity> jugadores = this.listaUsuarios.Values.ToList(); foreach(Entity jugador in jugadores) { pintor.drawRadarPlayer(g,this.localPlayer,jugador,rectRadar.CenterAbsolute); //pintor.drawPlayer(g, this.localPlayer, jugador, this.ClientRectangle); } } } private delegate void resizeFormCallback(RECTANGULO rectangulo); public void resizeForm(RECTANGULO rectangulo) { if (this.InvokeRequired) this.Invoke(new resizeFormCallback(resizeForm),rectangulo); else { int offsetWindowBar = 20; this.Size = rectangulo.Size; //this.Size = new Size(SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CXFULLSCREEN), SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CYFULLSCREEN)+ offsetWindowBar); //Setting Window position; this.Top = (int)rectangulo.Top; this.Left = (int)rectangulo.Left; } } private void hideControls() { foreach (Control ctrl in this.Controls) //Oculto todos los controles { ctrl.Visible = false; } this.BackColor = Color.Black; //Seteamos el color de fondo a negro. this.TransparencyKey = Color.Black; //Indicamos que todo lo que se encuentre en negro dentro del formulario sea transparente //Metodo para que pulsar atraves de él sea posible int initialStyle = DLLImports.GetWindowLong(this.Handle, -20); DLLImports.SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20); } private void packetHandler(Packet packet) { Entity entity; switch (packet.rustID) { case Packet.Rust.Entities: ProtoBuf.Entity entityInfo; uint num = Data.Entity.ParseEntity(packet, out entityInfo); entity = Entity.CreateOrUpdate(num, entityInfo); if (entity != null) onEntity(entity); return; case Packet.Rust.EntityPosition: List<Data.Entity.EntityUpdate> updates = Data.Entity.ParsePositions(packet); List<Entity> entities = null; if (updates.Count == 1) { entity = Entity.UpdatePosistion(updates[0]); if (entity != null) (entities = new List<Entity>()).Add(entity); } else if (updates.Count > 1) { entities = Entity.UpdatePositions(updates); } if (entities != null) entities.ForEach(item => onEntity(item)); return; case Packet.Rust.EntityDestroy: EntityDestroy destroyInfo = new EntityDestroy(packet); Entity.CreateOrUpdate(destroyInfo); //onEntityDestroy(destroyInfo); return; } } private delegate void onEntityCallback(Entity entidad); private void onEntity(Entity entidad) { if (this.InvokeRequired) this.Invoke(new onEntityCallback(onEntity), entidad); else { if (entidad.IsPlayer) { if (entidad.IsLocalPlayer) { this.localPlayer = entidad; if (this.localPlayer.Data.basePlayer.metabolism.health == 0) //FIXME . No borra cuando mi vida llega a 0 { this.listaUsuarios.Clear(); } return; } if (this.localPlayer != null) { lock (this.listaUsuarios) { Entity prev = null; //Una especie de OnAcercarse() float distance = UnityEngine.Vector2.Distance( new UnityEngine.Vector2(entidad.Data.baseEntity.pos.x, entidad.Data.baseEntity.pos.z) , new UnityEngine.Vector2(this.localPlayer.Data.baseEntity.pos.x, this.localPlayer.Data.baseEntity.pos.z)); if (distance < pintor.getController().getZoomValue()) { this.listaUsuarios.TryGetValue(entidad.Data.basePlayer.name, out prev); if (prev == null) this.listaUsuarios.TryAdd(entidad.Data.basePlayer.name, entidad); else this.listaUsuarios.TryUpdate(entidad.Data.basePlayer.name, entidad, prev); } } } } } } private delegate void onEntityDestroyCallback(EntityDestroy entidad); private void onEntityDestroy(EntityDestroy entidadDestruida) //Nunca se esta llamando actualmente { if (this.InvokeRequired) this.Invoke(new onEntityDestroyCallback(onEntityDestroy), entidadDestruida); else { } } } } <file_sep>/RustInterceptor/Forms/Utils/DLLImports.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace Rust_Interceptor.Forms.Utils { static class DLLImports { /// <summary> /// Changes an attribute of the specified window. The function also sets the 32-bit (long) value at the specified offset into the extra window memory. /// </summary> /// <param name="hWnd">A handle to the window and, indirectly, the class to which the window belongs..</param> /// <param name="nIndex">The zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus the size of an integer. To set any other value, specify one of the following values: GWL_EXSTYLE, GWL_HINSTANCE, GWL_ID, GWL_STYLE, GWL_USERDATA, GWL_WNDPROC </param> /// <param name="dwNewLong">The replacement value.</param> /// <returns>If the function succeeds, the return value is the previous value of the specified 32-bit integer. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. </returns> [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("user32.dll", SetLastError = true)] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); } } <file_sep>/RustInterceptor/Forms/Structs/WindowStruct.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Rust_Interceptor.Forms.Structs { public static class WindowStruct { #region StructsWindow public enum EnumShowWindowCommands { /// <summary> /// Hides the window and activates another window. /// </summary> Hide = 0, /// <summary> /// Activates and displays a window. If the window is minimized or /// maximized, the system restores it to its original size and position. /// An application should specify this flag when displaying the window /// for the first time. /// </summary> Normal = 1, /// <summary> /// Activates the window and displays it as a minimized window. /// </summary> ShowMinimized = 2, /// <summary> /// Maximizes the specified window. /// </summary> Maximize = 3, // is this the right value? /// <summary> /// Activates the window and displays it as a maximized window. /// </summary> ShowMaximized = 3, /// <summary> /// Displays a window in its most recent size and position. This value /// is similar to <see cref="Win32.ShowWindowCommand.Normal"/>, except /// the window is not activated. /// </summary> ShowNoActivate = 4, /// <summary> /// Activates the window and displays it in its current size and position. /// </summary> Show = 5, /// <summary> /// Minimizes the specified window and activates the next top-level /// window in the Z order. /// </summary> Minimize = 6, /// <summary> /// Displays the window as a minimized window. This value is similar to /// <see cref="Win32.ShowWindowCommand.ShowMinimized"/>, except the /// window is not activated. /// </summary> ShowMinNoActive = 7, /// <summary> /// Displays the window in its current size and position. This value is /// similar to <see cref="Win32.ShowWindowCommand.Show"/>, except the /// window is not activated. /// </summary> ShowNA = 8, /// <summary> /// Activates and displays the window. If the window is minimized or /// maximized, the system restores it to its original size and position. /// An application should specify this flag when restoring a minimized window. /// </summary> Restore = 9, /// <summary> /// Sets the show state based on the SW_* value specified in the /// STARTUPINFO structure passed to the CreateProcess function by the /// program that started the application. /// </summary> ShowDefault = 10, /// <summary> /// <b>Windows 2000/XP:</b> Minimizes a window, even if the thread /// that owns the window is not responding. This flag should only be /// used when minimizing windows from a different thread. /// </summary> ForceMinimize = 11 } /// <summary> /// Contains information about the placement of a window on the screen. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct WINDOWPLACEMENT { /// <summary> /// The length of the structure, in bytes. Before calling the GetWindowPlacement or SetWindowPlacement functions, set this member to sizeof(WINDOWPLACEMENT). /// <para> /// GetWindowPlacement and SetWindowPlacement fail if this member is not set correctly. /// </para> /// </summary> public int length; /// <summary> /// Specifies flags that control the position of the minimized window and the method by which the window is restored. /// </summary> public int flags; /// <summary> /// The current show state of the window. /// </summary> public EnumShowWindowCommands showCmd; /// <summary> /// The coordinates of the window's upper-left corner when the window is minimized. /// </summary> public POINT minPosition; /// <summary> /// The coordinates of the window's upper-left corner when the window is maximized. /// </summary> public POINT maxPosition; /// <summary> /// The window's coordinates when the window is in the restored position. /// </summary> public RECTANGULO normalPosition; /// <summary> /// Gets the default (empty) value. /// </summary> public static WINDOWPLACEMENT Default { get { WINDOWPLACEMENT result = new WINDOWPLACEMENT(); result.length = Marshal.SizeOf(result); return result; } } } #endregion StructsWindow #region StructsHooks /// <summary> /// https://msdn.microsoft.com/en-us/library/windows/desktop/ms644990(v=vs.85).aspx /// </summary> public enum HookType : int { WH_MSGFILTER = -1, WH_JOURNALRECORD = 0, WH_JOURNALPLAYBACK = 1, /// <summary> /// BaseHook que capturara todas las teclas del teclado pulsadas por el usuario en la ventana DE UN PROCESO /// </summary> WH_KEYBOARD = 2, WH_GETMESSAGE = 3, /// <summary> /// Installs a hook procedure that monitors messages before the system sends them to the destination window procedure. For more information, see the CallWndProc hook procedure. /// </summary> WH_CALLWNDPROC = 4, WH_CBT = 5, WH_SYSMSGFILTER = 6, /// <summary> /// BaseHook que capturara todos los botones y movimientos del raton ejecutados por el usuario /// en la ventana dde un PROCESO /// </summary> WH_MOUSE = 7, WH_HARDWARE = 8, WH_DEBUG = 9, WH_SHELL = 10, WH_FOREGROUNDIDLE = 11, /// <summary> /// Installs a hook procedure that monitors messages after they have been processed by the destination window procedure. For more information, see the CallWndRetProc hook procedure. /// </summary> WH_CALLWNDPROCRET = 12, /// <summary> /// BaseHook que capturara todos las teclas del teclado pulsadas por el usuario. Necesario llamar a /// CallNextHookEx para propagar el evento y permitir a otras apliciones seguir capturando el evento /// </summary> WH_KEYBOARD_LL = 13, /// <summary> /// BaseHook que capturara las pulsaciones y movimientos del raton realizadas por el usuario.Necesario llamar a /// CallNextHookEx para propagar el evento y permitir a otras apliciones seguir capturando el evento /// </summary> WH_MOUSE_LL = 14, } public enum MouseEventType : int { //Siempre usar hexadecimales pues se mantiene mejor la compatibilidad entre versiones del SO de Windows NONE = 0, WM_MOUSEMOVE = 0x0200, //512, WM_LBUTTONDOWN = 0x0201, //513, WM_LBUTTONUP = 0x0202, //514, WM_RBUTTONDOWN = 0x0204, //516, WM_RBUTTONUP = 0x0205, //517, WM_MBUTTONDOWN = 0x0207, //519, WM_MBUTTONUP = 0x0208, //520, WM_MOUSEWHEEL = 0x020A, //522, WM_MOUSEHWHEEL = 0x020E, //526 } //https://msdn.microsoft.com/es-es/library/windows/desktop/ms646260(v=vs.85).aspx Parameters section public enum MouseFlags : int { MOUSEEVENTF_MOVE = 0x0001, //1, MOUSEEVENTF_LEFTDOWN = 0x0002, //2, MOUSEEVENTF_LEFTUP = 0x0004, //4, MOUSEEVENTF_RIGHTDOWN = 0x0008, //8, MOUSEEVENTF_RIGHTUP = 0x0010, //16, MOUSEEVENTF_MIDDLEDOWN = 0x0020, //32, MOUSEEVENTF_MIDDLEUP = 0x0040, //64, MOUSEEVENTF_XDOWN = 0x0080, //128, MOUSEEVENTF_XUP = 0x0100, //256, MOUSEEVENTF_WHEEL = 0x0800, //2048, MOUSEEVENTF_HWHEEL = 0x01000, //4096, /// <summary> /// The dx and dy parameters contain normalized absolute coordinates. If not set, those parameters contain /// relative data: the change in position since the last reported position. This flag can be set, or not set, /// regardless of what kind of mouse or mouse-like device, if any, is connected to the system. For further information /// about relative mouse motion, see the following Remarks section. /// </summary> MOUSEEVENTF_ABSOLUTE = 0x8000, //32768, MOUSE_MOVE_ABSOLUTE = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, } //LPARAM --> IntPTr //WPARAM -->UIntrPtr //ULONG_PTR --> IntPtr //DWORD --> uint //LONG --> int //WORD --> ushort //https://msdn.microsoft.com/es-es/library/windows/desktop/ms646270(v=vs.85).aspx [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint tipo; //0 --> MOUSENINPUT, 1 --> KEYBDINPUT, 2 --> HARDWAREINPUT public DataInput data; } [StructLayout(LayoutKind.Explicit)] public struct DataInput { [FieldOffset(0)] public MOUSEINPUT mouse; [FieldOffset(0)] public KEYBDINPUT keyboard; [FieldOffset(0)] public HARDWAREINPUT hardware; } //https://msdn.microsoft.com/es-es/library/windows/desktop/ms646273(v=vs.85).aspx [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } //https://msdn.microsoft.com/es-es/library/windows/desktop/ms646271(v=vs.85).aspx [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort codeVirtualKey; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } //https://msdn.microsoft.com/es-es/library/windows/desktop/ms646269(v=vs.85).aspx [StructLayout(LayoutKind.Sequential)] public struct HARDWAREINPUT { public uint uMsg; public ushort wParamL; public ushort wParamH; } #endregion StructsHooks #region StructGeometry [StructLayout(LayoutKind.Sequential)] public struct RECTANGULO { public float Left, Top, Right, Bottom; public RECTANGULO(float left, float top, float right, float bottom) { Left = left; Top = top; Right = right; Bottom = bottom; } public RECTANGULO(System.Drawing.Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom) { } public float X { get { return Left; } set { Right -= (Left - value); Left = value; } } public float Y { get { return Top; } set { Bottom -= (Top - value); Top = value; } } public float Height { get { return Bottom - Top; } set { Bottom = value + Top; } } public float Width { get { return Right - Left; } set { Right = value + Left; } } public System.Drawing.Point Location { get { return new System.Drawing.Point((int)Left, (int)Top); } set { X = value.X; Y = value.Y; } } public System.Drawing.Size Size { get { return new System.Drawing.Size((int)Width, (int)Height); } set { Width = value.Width; Height = value.Height; } } public SharpDX.Vector2 CenterRelative { get { return new SharpDX.Vector2(this.Width/2, this.Height/2); } } public SharpDX.Vector2 CenterAbsolute { get { return new SharpDX.Vector2( (this.Width / 2)+this.Left , (this.Height / 2)+this.Top ) ; } } public static implicit operator RECTANGULO(System.Drawing.Size r) { return new RECTANGULO(0, 0, r.Width, r.Height); } public static implicit operator System.Drawing.Rectangle(RECTANGULO r) { return new System.Drawing.Rectangle((int)r.Left, (int)r.Top, (int)r.Width, (int)r.Height); } public static implicit operator System.Drawing.RectangleF(RECTANGULO r) { return new System.Drawing.RectangleF(r.Left, r.Top, r.Width, r.Height); } public static implicit operator RECTANGULO(System.Drawing.Rectangle r) { return new RECTANGULO(r); } public static bool operator ==(RECTANGULO r1, RECTANGULO r2) { return r1.Equals(r2); } public static bool operator !=(RECTANGULO r1, RECTANGULO r2) { return !r1.Equals(r2); } public bool Equals(RECTANGULO r) { return r.Left == Left && r.Top == Top && r.Right == Right && r.Bottom == Bottom; } public override bool Equals(object obj) { if (obj is RECTANGULO) return Equals((RECTANGULO)obj); else if (obj is System.Drawing.Rectangle) return Equals(new RECTANGULO((System.Drawing.Rectangle)obj)); return false; } public override int GetHashCode() { return ((System.Drawing.Rectangle)this).GetHashCode(); } public override string ToString() { return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom); } public bool isInArea(POINT a) { return (Left <= a.X && Top <= a.Y && Right >= a.X && Bottom >= a.Y); } } /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public struct POINT { public float X,Y; public POINT(float x, float y) { this.X = x; this.Y = y; } public POINT(System.Drawing.Point pt) : this(pt.X, pt.Y) { } public double Length() { return Math.Sqrt( Math.Pow(this.X,2) + Math.Pow(this.Y,2) ); } public POINT Normalize() { return new POINT(this.X,this.Y) / (float)this.Length(); } public static POINT Vector2Y = new POINT(0,1); public static POINT Vector2X = new POINT(1,0); public static POINT operator -(POINT a, POINT b) { return new POINT(a.X - b.X, a.Y - b.Y); } public static POINT operator *(POINT a,double operador) { return new POINT( (int)(a.X*operador), (int)(a.Y*operador)); } public static POINT operator +(POINT a, POINT b) { return new POINT(a.X + b.X, a.Y + b.Y); } public static POINT operator /(POINT a, double operador) { return new POINT((int)(a.X/operador), (int)(a.Y/operador)); } //Point to POINT and viceversa public static implicit operator System.Drawing.Point(POINT p) { return new System.Drawing.Point( (int)(p.X), (int)(p.Y)); } public static implicit operator POINT(System.Drawing.Point p) { return new POINT(p.X, p.Y); } // //SharpDX.Vector2 to POINT public static implicit operator POINT(SharpDX.Vector2 p) { return new POINT((int)p.X, (int)p.Y); } public static implicit operator System.Drawing.PointF(POINT p) { return new System.Drawing.PointF(p.X, p.Y); } public override string ToString() { return "{X = "+this.X+" , Y = "+this.Y+"}"; } } #endregion StructGeometry } } <file_sep>/RustInterceptor/Data/Entity.cs using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Rust_Interceptor.Data { public class Entity { uint networkOrder = 0; internal ProtoBuf.Entity proto; public ProtoBuf.Entity Data { get { return proto; } private set { proto = value; } } public bool IsPlayer { get { return proto.basePlayer != null; } } public bool IsLocalPlayer { get { return proto.basePlayer.metabolism != null; } } public UInt32 UID { get { return proto.baseNetworkable.uid; } private set { proto.baseNetworkable.uid = value; } } public Vector3 Position { get { return proto.baseEntity.pos;} private set { proto.baseEntity.pos = value; } } public Vector3 Rotation { get { return proto.baseEntity.rot;} private set { proto.baseEntity.rot = value; } } public override string ToString() { return "{" + "\n\tnetworkOrder =" + networkOrder + "\n\t Data = " + Data.ToString() + "\n\t UID = " + UID + "\n\t Position = {\n\t" + Position.ToString() + "\n}" + "\n\t Rotation = {\n\t" + Rotation.ToString() + "\n}" +"}"; } static Dictionary<UInt32, Entity> entities = new Dictionary<uint, Entity>(); public static Entity GetLocalPlayer() { return First(item => item.Value.IsLocalPlayer); } public static List<Entity> GetPlayers() { return Find(item => { return item.Value.IsPlayer; }); } public static bool Has(UInt32 uid) { return entities.ContainsKey(uid); } public static Entity First(Func<KeyValuePair<UInt32, Entity>, bool> predicate) { lock (entities) { return entities.First(predicate).Value; } } public static List<Entity> Find(Func<KeyValuePair<UInt32, Entity>, bool> predicate) { IEnumerable<KeyValuePair<UInt32, Entity>> results; lock (entities) { results = entities.Where(predicate); } return (from item in results select item.Value).ToList(); } public static Entity Find(UInt32 uid) { Entity ent; lock (entities) { if (entities.TryGetValue(uid, out ent)) { return ent; } } return null; } public static Entity CreateOrUpdate(UInt32 networkOrder, ProtoBuf.Entity entityInfo) { uint uid = entityInfo.baseNetworkable.uid; if (Has(uid)) { Entity entity; lock (entities) { entity = entities[uid]; } entity.networkOrder = networkOrder; entity.proto = entityInfo; lock (entities) { entities[uid] = entity; } return entity; } else { Entity entity = new Entity(); entity.networkOrder = networkOrder; entity.proto = entityInfo; lock (entities) { entities.Add(uid, entity); } return entity; } } public static void CreateOrUpdate(EntityDestroy destroyInfo) { lock (entities) { if (Has(destroyInfo.UID)) entities.Remove(destroyInfo.UID); } } public static Entity UpdatePosistion(Data.Entity.EntityUpdate update) { if (!Has(update.uid)) return null; Entity entity; lock (entities) { entity = entities[update.uid]; } entity.Position = update.position; entity.Rotation = update.rotation; lock (entities) { entities[update.uid] = entity; } return entity; } public static List<Entity> UpdatePositions(List<Data.Entity.EntityUpdate> updates) { List<Entity> entities = new List<Entity>(); foreach (var update in updates) { var entity = UpdatePosistion(update); if (entity != null) entities.Add(entity); } return entities.Count > 0 ? entities : null; } public static List<EntityUpdate> ParsePositions(Packet p) { List<EntityUpdate> updates = new List<EntityUpdate>(); /* EntityPosition packets may contain multiple positions */ while (p.unread >= 28L /* Uint32 = 4bytes, Float = 4bytes. Uint32 + (Float * 6) = 28 */) { EntityUpdate update = new EntityUpdate(); /* Entity UID */ update.uid = p.UInt32(); /* Read 2 Vector3, Position and Rotation */ update.position = p.Vector3(); update.rotation = p.Vector3(); updates.Add(update); } return updates; } public static uint ParseEntity(Packet p, out ProtoBuf.Entity entity) { /* Entity Number/Order */ var num = p.UInt32(); entity = ProtoBuf.Entity.Deserialize(p); return num; } public class EntityUpdate { internal uint uid; public uint UID { get { return uid; } } internal Vector3 position; public Vector3 Position { get { return position; } } internal Vector3 rotation; public Vector3 Rotation { get { return rotation; } } } } } <file_sep>/RustInterceptor/Forms/Hooks/IKeyEventsListener.cs using System.Windows.Forms; using static Rust_Interceptor.Forms.Structs.WindowStruct; namespace Rust_Interceptor.Forms.Hooks { interface IKeyEventsListener { bool onMouseMove(object sender, MOUSEINPUT data); bool onLeftMouseButtonDown(object sender, MOUSEINPUT data); bool onLeftMouseButtonUp(object sender, MOUSEINPUT data); bool onRightMouseButtonDown(object sender, MOUSEINPUT data); bool onRightMouseButtonUp(object sender, MOUSEINPUT data); bool onMiddleMouseButtonDown(object sender, MOUSEINPUT data); bool onMiddleMouseButtonUp(object sender, MOUSEINPUT data); bool onVerticalWheelMouseRotation(object sender, MOUSEINPUT data); bool onHorizontalWheelMouseRotation(object sender, MOUSEINPUT data); bool onKeyDown(object sender, KEYBDINPUT data, Keys key); bool onKeyUp(object sender, KEYBDINPUT data, Keys key); } } <file_sep>/README.md ## Rust Interceptor ### Currently Implemented: - **Client - Server "Proxy"** - **Packet Serialization**(JSON formatted) - **Packet Parsers for packets that does not contain Protocol Buffers** - **Basic Entity Handler** ### Dependencies: - Steam\steamapps\common\Rust\RustClient_Data\Managed\Rust.Data.dll - Steam\steamapps\common\Rust\RustClient_Data\Managed\UnityEngine.dll - Steam\steamapps\common\Rust\RustClient_Data\Plugins\RakNet.dll ### Disclaimer - **This is not a packet forger, and never will be.** - This product is meant for educational purposes only. - This is work in progress and subject to change. - Void where prohibited. - No other warranty expressed or implied. - Some assembly required. - Batteries not included. - Use only as directed. - Do not use while operating a motor vehicle or heavy equipment. ### Examples **Advanced Users: [Have a look at this](https://github.com/SharpUmbrella/RustInterceptor/blob/master/RustInterceptor/SimpleInterceptor.cs)** **Example for Beginners(noobs)** ``` csharp using System; using Rust_Interceptor; using Rust_Interceptor.Data; class Program : SimpleInterceptor { public Program() : base() { Interceptor.AddPacketsToFilter(Packet.Rust.ConsoleCommand, Packet.Rust.ConsoleMessage); // Filter packets, you will only receive the packets defined in this function, remove this line to receive all packets Interceptor.ClientPackets = true; // Receive client packets, in this example you would receive both Server and Client Packets Interceptor.CommandPrefix = "RI."; // Command Prefix for "sv" command, in this example you could send a command to this program with "sv RI.randomValue 24" and receive OnCommand("randomValue 24") Interceptor.Start(); } public override void OnCommand(string command) { if (command.StartsWith("randomValue")) { var str = command.Split(' '); Console.WriteLine("{0} = {1}", str[0], int.Parse(str[1])); } } public override void OnPacket(Packet packet) { switch (packet.rustID) { case Packet.Rust.ConsoleMessage: ConsoleMessage message = new ConsoleMessage(packet); Console.WriteLine("Console Message from Server: {0}", message.Message); break; } } public override void OnEntity(Entity entity) { if (entity.IsPlayer) if (entity.IsLocalPlayer) Console.WriteLine("OMG is it really you {0} :O", entity.Data.basePlayer.name); else Console.WriteLine("Meh, you're not that special {0}", entity.Data.basePlayer.name); } public override void OnEntityDestroy(EntityDestroy destroyInfo) { Console.WriteLine("Entity with UID({0}) got destroyed :'(", destroyInfo.UID); } private static void Main(string[] args) { new Program(); } } ``` ## For those fealing generous Do not donate if you feel you need to, donate if you want to :) Paypal.me: paypal.me/LasseSkogland Bitcoin: 3BYt2fDDd1kQUAWVKR51o9fxcU4eggc8Xq Bitcoin QR: ![Bitcoin QR](http://i.imgur.com/Q7S8buL.png) <file_sep>/RustInterceptor/Forms/Utils/SystemInfo.cs using System; using System.Runtime.InteropServices; namespace Rust_Interceptor.Forms.Structs { static class SystemInfo { [DllImport("user32.dll", SetLastError = false)] public static extern IntPtr GetMessageExtraInfo(); [DllImport("user32.dll")] private static extern int GetSystemMetrics(int smIndex); //https://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx /// <summary> /// Enum for available parameters to be pased to GetSystemMetrics /// </summary> public enum SystemMetric : int { /// <summary> /// The width of the screen of the primary display monitor, in pixels. /// This is the same value obtained by calling GetDeviceCaps as follows: /// GetDeviceCaps( hdcPrimaryMonitor, HORZRES). /// </summary> SM_CXSCREEN = 0, /// <summary> /// The height of the screen of the primary display monitor, in pixels. /// This is the same value obtained by calling GetDeviceCaps as follows: /// GetDeviceCaps( hdcPrimaryMonitor, HORZRES). /// </summary> SM_CYSCREEN = 1, /// <summary> /// The width of a vertical scroll bar, in pixels. /// </summary> SM_CXVSCROLL = 2, /// <summary> /// The height of a vertical scroll bar, in pixels. /// </summary> SM_CYVSCROLL = 20, /// <summary> /// Returns the width of a window border, in pixels /// </summary> SM_CXBORDER = 5, /// <summary> /// Returns the height of a window border, in pixels /// </summary> SM_CYBORDER = 6, /// <summary> /// Returns the height of the horizontal border of a frame around the perimeter of a window that has a caption but is not sizable, in pixels /// </summary> SM_CXFIXEDFRAME = 7, /// <summary> /// Returns the width of the vertical border of a frame around the perimeter of a window that has a caption but is not sizable, in pixels /// </summary> SM_CYFIXEDFRAME = 8, /// <summary> /// Returns the width of the thumb box in a horizontal scroll bar, in pixels. /// </summary> SM_CXHTHUMB = 10, /// <summary> /// The default width of an icon, in pixels. /// </summary> SM_CXICON = 11, /// <summary> /// The default height of an icon, in pixels. /// </summary> SM_CYICON = 12, /// <summary> /// Returns the width of a cursor, in pixels. The system cannot create cursors of other sizes. /// </summary> SM_CXCURSOR = 13, /// <summary> /// Returns the width of a cursor, in pixels. The system cannot create cursors of other sizes. /// </summary> SM_CYCURSOR = 14, /// <summary> /// Returns the width for a full-screen window on the primary display monitor, in pixels. /// </summary> SM_CXFULLSCREEN = 16, /// <summary> /// Returns the height for a full-screen window on the primary display monitor, in pixels. /// </summary> SM_CYFULLSCREEN = 17, /// <summary> /// Nonzero if a mouse is installed; otherwise, 0. /// This value is rarely zero, because of support for virtual mice and because some systems detect the presence of the /// port instead of the presence of a mouse. /// </summary> SM_MOUSEPRESENT = 19, /// <summary> /// Returns the width of the arrow bitmap on a horizontal scroll bar, in pixels. /// </summary> SM_CXHSCROLL = 21, /// <summary> /// Returns the height of the arrow bitmap on a horizontal scroll bar, in pixels. /// </summary> SM_CYHSCROLL = 3, /// <summary> /// Nonzero if the debug version of User.exe is installed; otherwise, 0. /// </summary> SM_DEBUG = 22, /// <summary> /// Nonzero if the meanings of the left and right mouse buttons are swapped; otherwise, 0. /// </summary> SM_SWAPBUTTON = 23, /// <summary> /// The minimum width of a window, in pixels. /// </summary> SM_CXMIN = 28, /// <summary> /// The minimum height of a window, in pixels. /// </summary> SM_CYMIN = 29, /// <summary> /// The width of a button in a window caption or title bar, in pixels. /// </summary> SM_CXSIZE = 30, /// <summary> /// The height of a button in a window caption or title bar, in pixels. /// </summary> SM_CYSIZE = 31, /// <summary> /// The thickness(width) of the sizing border around the perimeter of a window that can be resized, in pixels. /// </summary> SM_CXSIZEFRAME = 32, /// <summary> /// The thickness(height) of the sizing border around the perimeter of a window that can be resized, in pixels. /// </summary> SM_CYSIZEFRAME = 33, /// <summary> /// The minimum tracking width of a window, in pixels. /// The user cannot drag the window frame to a size smaller than these dimensions. /// A window can override this value by processing the WM_GETMINMAXINFO message. /// </summary> SM_CXMINTRACK = 34, /// <summary> /// The minimum tracking height of a window, in pixels. /// The user cannot drag the window frame to a size smaller than these dimensions. /// A window can override this value by processing the WM_GETMINMAXINFO message. /// </summary> SM_CYMINTRACK = 35, /// <summary> /// Returns the width of the rectangle that received the clicks. /// To set the width of the double-click rectangle, call SystemParametersInfo with SPI_SETDOUBLECLKWIDTH. /// </summary> SM_CXDOUBLECLK = 36, /// <summary> /// Returns the height of the rectangle that received the clicks. /// </summary> SM_CYDOUBLECLK = 37, /// <summary> /// The width of a grid cell for items in large icon view, in pixels.This value is always greater than or equal to SM_CXICON /// </summary> SM_CXICONSPACING = 38, /// <summary> /// The height of a grid cell for items in large icon view, in pixels.This value is always greater than or equal to SM_CYICON /// </summary> SM_CYICONSPACING = 39, /// <summary> /// Nonzero if drop-down menus are right-aligned with the corresponding menu-bar item; 0 if the menus are left-aligned. /// </summary> SM_MENUDROPALIGNMENT = 40, /// <summary> /// Nonzero if the Microsoft Windows for Pen computing extensions are installed; zero otherwise. /// </summary> SM_PENWINDOWS = 41, /// <summary> /// Nonzero if User32.dll supports DBCS; otherwise, 0. /// </summary> SM_DBCSENABLED = 42, /// <summary> /// Return the number of buttons on a mouse, or zero if no mouse is installed. /// </summary> SM_CMOUSEBUTTONS = 43, /// <summary> /// Returns the width of a 3D border. This metric is the 3D counterpart of SM_CXBORDER. /// </summary> SM_CXEDGE = 45, /// <summary> /// Returns the height of a 3D border. This metric is the 3D counterpart of SM_CXBORDER. /// </summary> SM_CYEDGE = 46, /// <summary> /// The width of a grid cell for a minimized window, in pixels. /// Each minimized window fits into a rectangle this size when arranged. /// This value is always greater than or equal to <seealso cref="SystemMetric.SM_CXMINIMIZED"/> /// </summary> SM_CXMINSPACING = 47, /// <summary> /// The height of a grid cell for a minimized window, in pixels. /// Each minimized window fits into a rectangle this size when arranged. /// This value is always greater than or equal to <seealso cref="SystemMetric.SM_CYMINIMIZED"/> /// </summary> SM_CYMINSPACING = 48, /// <summary> /// The recommended width of a small icon, in pixels. /// Small icons typically appear in window captions and in small icon view. /// </summary> SM_CXSMICON = 49, /// <summary> /// The recommended height of a small icon, in pixels. Small icons typically appear in window captions and in small icon view. /// </summary> SM_CYSMICON = 50, /// <summary> /// The width of small caption buttons, in pixels. /// </summary> SM_CXSMSIZE = 52, /// <summary> /// The height of small caption buttons, in pixels. /// </summary> SM_CYSMSIZE = 53, /// <summary> /// The width of menu bar buttons, such as the child window close button that is used in the multiple document interface, in pixels. /// </summary> SM_CXMENUSIZE = 54, /// <summary> /// The height of menu bar buttons, such as the child window close button that is used in the multiple document interface, in pixels. /// </summary> SM_CYMENUSIZE = 55, /// <summary> /// How the system minimize windows. /// More info about how to handle value returned : /// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724500(v=vs.85).aspx /// </summary> SM_ARRANGE = 56, /// <summary> /// The width of a minimized window, in pixels. /// </summary> SM_CXMINIMIZED = 57, /// <summary> /// The height of a minimized window, in pixels. /// </summary> SM_CYMINIMIZED = 58, /// <summary> /// The default maximum width of a window that has a caption and sizing borders, in pixels. /// This metric refers to the entire desktop. The user cannot drag the window frame to a size larger than these dimensions. /// A window can override this value by processing the WM_GETMINMAXINFO message. /// </summary> SM_CXMAXTRACK = 59, /// <summary> /// The default maximum height of a window that has a caption and sizing borders, in pixels. This metric refers to the entire desktop. /// The user cannot drag the window frame to a size larger than these dimensions. /// A window can override this value by processing the WM_GETMINMAXINFO message. /// </summary> SM_CYMAXTRACK = 60, /// <summary> /// The default width, in pixels, of a maximized top-level window on the primary display monitor. /// </summary> SM_CXMAXIMIZED = 61, /// <summary> /// The default height, in pixels, of a maximized top-level window on the primary display monitor. /// </summary> SM_CYMAXIMIZED = 62, /// <summary> /// The least significant bit is set if a network is present; otherwise, it is cleared. /// The other bits are reserved for future use. /// </summary> SM_NETWORK = 63, /// <summary> /// How the system has started : 0 Normalize boot | 1 Fail-safe boot | 2 Fail-safe with network boot /// </summary> SM_CLEANBOOT = 67, /// <summary> /// Nonzero if the user requires an application to present information visually in situations /// where it would otherwise present the information only in audible form; otherwise, 0. /// </summary> SM_SHOWSOUNDS = 70, /// <summary> /// The width of the default menu check-mark bitmap, in pixels. /// </summary> SM_CXMENUCHECK = 71, /// <summary> /// The height of the default menu check-mark bitmap, in pixels. /// </summary> SM_CYMENUCHECK = 72, /// <summary> /// Nonzero if the computer has a low-end (slow) processor; otherwise, 0. /// </summary> SM_SLOWMACHINE = 73, /// <summary> /// Nonzero if the system is enabled for Hebrew and Arabic languages, 0 if not. /// </summary> SM_MIDEASTENABLED = 74, /// <summary> /// Nonzero if a mouse with a vertical scroll wheel is installed; otherwise 0. /// </summary> SM_MOUSEWHEELPRESENT = 75, /// <summary> /// The coordinates for the left side of the virtual screen. /// The virtual screen is the bounding rectangle of all display monitors. /// The SM_CXVIRTUALSCREEN metric is the width of the virtual screen. /// </summary> SM_XVIRTUALSCREEN = 76, /// <summary> /// The coordinates for the top of the virtual screen. /// The virtual screen is the bounding rectangle of all display monitors. /// The SM_CYVIRTUALSCREEN metric is the height of the virtual screen. /// </summary> SM_YVIRTUALSCREEN = 77, /// <summary> /// The width of the virtual screen, in pixels. /// The virtual screen is the bounding rectangle of all display monitors. /// The SM_XVIRTUALSCREEN metric is the coordinates for the left side of the virtual screen. /// </summary> SM_CXVIRTUALSCREEN = 78, /// <summary> /// The height of the virtual screen, in pixels. /// The virtual screen is the bounding rectangle of all display monitors. /// The SM_YVIRTUALSCREEN metric is the coordinates for the top of the virtual screen. /// </summary> SM_CYVIRTUALSCREEN = 79, /// <summary> /// Return the number of visible display monitors on a desktop. /// </summary> SM_CMONITORS = 80, /// <summary> /// Nonzero if all the display monitors have the same color format, otherwise, 0. /// Two displays can have the same bit depth, but different color formats. /// For example, the red, green, and blue pixels can be encoded with different numbers of bits, /// or those bits can be located in different places in a pixel color value. /// </summary> SM_SAMEDISPLAYFORMAT = 81, /// <summary> /// Nonzero if Input Method Manager/Input Method Editor features are enabled; otherwise, 0. /// SM_IMMENABLED indicates whether the system is ready to use a Unicode-based IME on a Unicode application. /// To ensure that a language-dependent IME works, check SM_DBCSENABLED and the system ANSI code page. /// Otherwise the ANSI-to-Unicode conversion may not be performed correctly, or some components like fonts or registry settings may not be present. /// </summary> SM_IMMENABLED = 82, /// <summary> /// Returns the width from the left to the right edges of the rectangle drawn by DrawFocusRect /// </summary> SM_CXFOCUSBORDER = 83, /// <summary> /// Returns the height from the top to the bottom edges of the rectangle drawn by DrawFocusRect /// </summary> SM_CYFOCUSBORDER = 84, /// <summary> /// Nonzero if the current operating system is the Windows XP Tablet PC edition or if the current operating system is Windows Vista /// or Windows 7 and the Tablet PC Input service is started; otherwise, 0. /// The SM_DIGITIZER setting indicates the type of digitizer input supported by a device running Windows 7 or Windows Server 2008 R2. /// For more information, see Remarks. /// </summary> SM_TABLETPC = 86, /// <summary> /// Nonzero if the current operating system is the Windows XP, Media Center Edition, 0 if not. /// </summary> SM_MEDIACENTER = 87, /// <summary> /// Nonzero if the current operating system is Windows 7 Starter Edition, Windows Vista Starter, or Windows XP Starter Edition; otherwise, 0. /// </summary> SM_STARTER = 88, /// <summary> /// Nonzero if a mouse with a horizontal scroll wheel is installed; otherwise 0. /// </summary> SM_MOUSEHORIZONTALWHEELPRESENT = 91, /// <summary> /// The amount of border padding for captioned windows, in pixels. /// Windows XP/2000: This value is not supported. /// </summary> SM_CXPADDEDBORDER = 92, /// <summary> /// Nonzero if the current operating system is Windows 7 or Windows Server 2008 R2 and the Tablet PC Input service is started; otherwise, 0. /// The return value is a bitmask that specifies the type of digitizer input supported by the device. For more information, see Remarks. /// Windows Server 2008, Windows Vista and Windows XP/2000: This value is not supported. /// </summary> SM_DIGITIZER = 94, /// <summary> /// Nonzero if there are digitizers in the system; otherwise, 0. /// SM_MAXIMUMTOUCHES returns the aggregate maximum of the maximum number of contacts supported by every digitizer in the system. /// If the system has only single-touch digitizers, the return value is 1. If the system has multi-touch digitizers, /// the return value is the number of simultaneous contacts the hardware can provide. /// Windows Server 2008, Windows Vista and Windows XP/2000: This value is not supported. /// </summary> SM_MAXIMUMTOUCHES = 95, /// <summary> /// his system metric is used in a Terminal Services environment. /// If the calling process is associated with a Terminal Services client session, the return value is nonzero. /// If the calling process is associated with the Terminal Services console session, the return value is 0. /// Windows Server 2003 and Windows XP: The console session is not necessarily the physical console. /// For more information, see WTSGetActiveConsoleSessionId. /// </summary> SM_REMOTESESSION = 0x1000, /// <summary> /// Nonzero if the current session is shutting down; otherwise, 0. /// Windows 2000: This value is not supported. /// </summary> SM_SHUTTINGDOWN = 0x2000, /// <summary> /// This system metric is used in a Terminal Services environment to determine if the current Terminal Server session is being remotely controlled. /// Its value is nonzero if the current session is remotely controlled; otherwise, 0. /// You can use terminal services management tools such as Terminal Services Manager (tsadmin.msc) and shadow.exe to control a remote session. /// When a session is being remotely controlled, another user can view the contents of that session and potentially interact with it. /// </summary> SM_REMOTECONTROL = 0x2001, /// <summary> /// Return the state of the LAPTOP. /// 0 = Modo pizzara /// != 0 = Otro estado. /// Inutil para Sobremesas /// </summary> SM_CONVERTIBLESLATEMODE = 0x2003, /// <summary> /// Reflects the state of the docking mode, 0 for Undocked Mode and non-zero otherwise. /// When this system metric changes, the system sends a broadcast message via WM_SETTINGCHANGE /// with "SystemDockMode" in the LPARAM. /// </summary> SM_SYSTEMDOCKED = 0x2004, } public static int getSystemInfo(SystemMetric query) { return GetSystemMetrics((int)query); } } }<file_sep>/RustInterceptor/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Rust_Interceptor.Data; using System.Diagnostics; using System.Windows.Forms; namespace Rust_Interceptor { class Program { public Program() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Forms.LoadForm.getInstance()); } [MTAThread] private static void Main(string[] args) { new Program(); } } } <file_sep>/RustInterceptor/Forms/Hooks/UKeyActions.cs using Rust_Interceptor.Forms.Structs; using System; using System.Runtime.InteropServices; using System.Windows.Forms; using static Rust_Interceptor.Forms.Structs.WindowStruct; namespace Rust_Interceptor.Forms.Hooks { internal class UKeyActions { private const int TIPO_MOUSEVENT = 0; public bool moveMouseToPoint(POINT target, bool absolute = true) { MouseFlags flag = absolute ? MouseFlags.MOUSE_MOVE_ABSOLUTE : MouseFlags.MOUSEEVENTF_MOVE; INPUT inputEvent = createInput(target, flag, true); if (SendInput(1, ref inputEvent, Marshal.SizeOf(typeof(INPUT))) == 0) { MessageBox.Show("Ha fallado el remplazo del evento en MouseHook. Codigo error -->" + Marshal.GetLastWin32Error()); } return false; } public INPUT createInput(POINT pos , MouseFlags flag, bool automated = false) { INPUT mouseEvent = new INPUT() { }; mouseEvent.tipo = TIPO_MOUSEVENT; //Si pongo de la manera directa sin MouseFlags.MOUSEEVENTF_ABSOLUTE en el parametro de flag, resulta que simplemente suma a la posición actual del raton. //La manera correcta es la siguiente mouseEvent.data.mouse.dx = flag == MouseFlags.MOUSE_MOVE_ABSOLUTE ? Convert.ToInt32(pos.X ) : Convert.ToInt32(pos.X * (65536.0f / SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CXSCREEN))); mouseEvent.data.mouse.dy = flag == MouseFlags.MOUSE_MOVE_ABSOLUTE ? Convert.ToInt32(pos.Y ) : Convert.ToInt32(pos.Y * (65536.0f / SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CYSCREEN))); mouseEvent.data.mouse.mouseData = 0; mouseEvent.data.mouse.time = 0; mouseEvent.data.mouse.dwExtraInfo = automated ? new IntPtr(-1) : SystemInfo.GetMessageExtraInfo(); //Coloco esto como flag para saber cuando es automatizado //mouseEvent.data.mouse.dwExtraInfo = ControllerSystemInfo.GetMessageExtraInfo(); mouseEvent.data.mouse.dwFlags = (uint)flag; return mouseEvent; } //MAS INFO --> http://stackoverflow.com/questions/12761169/send-keys-through-sendinput-in-user32-dll [DllImport("user32.dll", SetLastError = true)] internal static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize); } } <file_sep>/RustInterceptor/Forms/Hooks/UKeyHook.cs  using System; using System.Collections.Concurrent; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using static Rust_Interceptor.Forms.Structs.WindowStruct; namespace Rust_Interceptor.Forms.Hooks { class UKeyHook { private static UKeyHook instance; public static UKeyHook getInstance(IKeyEventsListener escuchador) { if (instance == null) instance = new UKeyHook(escuchador); return instance; } private IKeyEventsListener escuchador; public UKeyActions action { get; private set; } private Thread chivato; private ConcurrentDictionary<Keys, byte> keysDown; public bool working { get; private set; } = false; private uint TIPO_MOUSEVENT = 0; public POINT currentPos { get; private set; } private UKeyHook(IKeyEventsListener escuchador) { this.escuchador = escuchador; this.action = new UKeyActions(); init(); } public void start() { if (working) throw new Exception("El hook ya ha sido inicializado"); working = true; chivato.Start(); //chivato.Join(); } public void stop() { working = false; if (chivato.IsAlive) { Thread.Sleep(1000); if (chivato.IsAlive) chivato.Abort(); } } private void init() { keysDown = new ConcurrentDictionary<Keys, byte>(); chivato = new Thread( () => { do { Thread.Sleep(1); POINT oldCurrentPos = currentPos; //GetCursorPos(out currentPos); currentPos = System.Windows.Forms.Cursor.Position; if (!oldCurrentPos.Equals(currentPos)) { INPUT input = action.createInput(currentPos, MouseFlags.MOUSEEVENTF_MOVE); this.createThreadEvent(this.escuchador.onMouseMove, this, input.data.mouse).Start(); Console.WriteLine(currentPos); } byte bit = new byte(); if (GetAsyncKeyState(Keys.LButton) != 0) //PRESSED { if (keysDown.TryAdd(Keys.LButton, bit)) { INPUT input = action.createInput(currentPos, MouseFlags.MOUSEEVENTF_LEFTDOWN); this.createThreadEvent(this.escuchador.onLeftMouseButtonDown, this, input.data.mouse).Start(); } } else if (keysDown.TryRemove(Keys.LButton, out bit))//NOT PRESED { INPUT input = action.createInput(currentPos, MouseFlags.MOUSEEVENTF_LEFTUP); this.createThreadEvent(this.escuchador.onLeftMouseButtonUp, this, input.data.mouse).Start(); } ///////////////////////////////////////////////////////////////////////////////////////// if (GetAsyncKeyState(Keys.RButton) != 0) //PRESSED { if(keysDown.TryAdd(Keys.RButton, bit)) { INPUT input = action.createInput(currentPos, MouseFlags.MOUSEEVENTF_RIGHTDOWN); this.createThreadEvent(this.escuchador.onRightMouseButtonDown, this, input.data.mouse).Start(); } } else if (keysDown.TryRemove(Keys.RButton, out bit))//NOT PRESSED { INPUT input = action.createInput(currentPos, MouseFlags.MOUSEEVENTF_RIGHTUP); this.createThreadEvent(this.escuchador.onRightMouseButtonUp, this, input.data.mouse).Start(); } ///////////////////////////////////////////////////////////////////////////////////////// if (GetAsyncKeyState(Keys.MButton) != 0) //PRESSED { if (keysDown.TryAdd(Keys.MButton, bit)) { INPUT input = action.createInput(currentPos, MouseFlags.MOUSEEVENTF_MIDDLEDOWN); this.createThreadEvent(this.escuchador.onMiddleMouseButtonDown, this, input.data.mouse).Start(); } } else if (keysDown.TryRemove(Keys.MButton, out bit)) //NOT PRESSED { INPUT input = action.createInput(currentPos, MouseFlags.MOUSEEVENTF_MIDDLEUP); this.createThreadEvent(this.escuchador.onMiddleMouseButtonUp, this, input.data.mouse).Start(); } ////////////////////////////////////////////////////////////////////////////////////////////// } while (working); } ); chivato.SetApartmentState(ApartmentState.MTA); chivato.IsBackground = true; chivato.CurrentCulture = System.Globalization.CultureInfo.CurrentCulture; chivato.Priority = ThreadPriority.Highest; chivato.Name = "UMouseWorkerThread"; } private delegate bool eventCallback(object sender, MOUSEINPUT data); private Thread createThreadEvent(eventCallback callback, object sender, MOUSEINPUT data) { Thread hilo = new Thread( () => { callback.Invoke(sender, data); } ); hilo.SetApartmentState(ApartmentState.MTA); hilo.IsBackground = true; hilo.CurrentCulture = System.Globalization.CultureInfo.CurrentCulture; hilo.Priority = ThreadPriority.Normal; hilo.Name = callback.ToString()+"Thread"; return hilo; } /// <summary> /// Deuvelvo 0 si no esta presionada, 1 si lo esta /// </summary> /// <param name="vKey"></param> /// <returns></returns> [DllImport("user32.dll")] static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey); /// <summary> /// DON'T use System.Drawing.Point, the order of the fields in System.Drawing.Point isn't guaranteed to stay the same. /// </summary> /// <param name="lpPoint"></param> /// <returns></returns> [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetCursorPos(out POINT lpPoint); } } <file_sep>/RustInterceptor/Forms/Controller.cs using Rust_Interceptor.Forms.Structs; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Rust_Interceptor.Forms { public partial class Controller : Form { public static Controller getInstance() { if (instance == null) instance = new Controller(); return instance; } private static Controller instance; private Controller() { InitializeComponent(); int maxX = SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CXFULLSCREEN)/2; int maxY = SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CYFULLSCREEN)/2; this.trackBarXCrosshairOffset.Minimum = maxX * -1; this.trackBarXCrosshairOffset.Maximum = maxX; this.trackBarYCrosshairOffset.Minimum = maxY *-1; this.trackBarYCrosshairOffset.Maximum = maxY; this.buttonCerrar.Click += new EventHandler( (object sender, EventArgs e) => { Overlay.getInstance(null).Stop(); this.Close(); }); } public delegate void voidCallback(); public void mostrarse() { if (this.InvokeRequired) this.Invoke(new voidCallback(mostrarse)); else { this.TopMost = true; this.Show(); } } //Sobreescribe WndProc para permitir que el evento de despalzar el Form siga siendo posible protected override void WndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { case 0x84: base.WndProc(ref m); if ((int)m.Result == 0x1) m.Result = (IntPtr)0x2; return; } base.WndProc(ref m); } private delegate int getIntValueCallback(); public int getZoomValue() { if (this.IsDisposed) return 0; if (this.InvokeRequired) return (int)this.Invoke(new getIntValueCallback(getZoomValue)); else { return this.trackBarZoom.Value; } } public int getAngleValue() { if (this.IsDisposed) return 0; if (this.InvokeRequired) return (int)this.Invoke(new getIntValueCallback(getAngleValue)); else { return this.trackBarAngle.Value; } } public int getXCrosshairOffsetValue() { if (this.IsDisposed) return 0; if (this.InvokeRequired) return (int)this.Invoke(new getIntValueCallback(getXCrosshairOffsetValue)); else { return this.trackBarXCrosshairOffset.Value; } } public int getYCrosshairOffsetValue() { if (this.IsDisposed) return 0; if (this.InvokeRequired) return (int)this.Invoke(new getIntValueCallback(getYCrosshairOffsetValue)); else { return this.trackBarYCrosshairOffset.Value; } } private void trackBarZoom_ValueChanged(object sender, EventArgs e) { this.labelZoomValue.Text = this.trackBarZoom.Value.ToString()+" m"; } private void trackBarAngle_ValueChanged(object sender, EventArgs e) { this.labelAngle.Text = this.trackBarAngle.Value.ToString() + " º"; } private void trackBarYCrosshairOffset_ValueChanged(object sender, EventArgs e) { this.labelYOffset.Text = this.trackBarYCrosshairOffset.Value.ToString() + " px"; } private void trackBarXCrosshairOffset_ValueChanged(object sender, EventArgs e) { this.labelXOffset.Text = this.trackBarXCrosshairOffset.Value.ToString() + " px"; } } } <file_sep>/RustInterceptor/Forms/Hooks/Window/WindowHook.cs using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using static Rust_Interceptor.Forms.Structs.WindowStruct; namespace Rust_Interceptor.Forms.Hooks { class WindowHook { [DllImport("user32.dll", SetLastError = true)] static extern bool GetWindowRect(IntPtr hwnd, out RECTANGULO lpRect); /// <summary> /// Retrieves the show state and the restored, minimized, and maximized positions of the specified window. /// </summary> /// <param name="hWnd"> /// A handle to the window. /// </param> /// <param name="lpwndpl"> /// A pointer to the WINDOWPLACEMENT structure that receives the show state and position information. /// <para> /// Before calling GetWindowPlacement, set the length member to sizeof(WINDOWPLACEMENT). GetWindowPlacement fails if lpwndpl-> length is not set correctly. /// </para> /// </param> /// <returns> /// If the function succeeds, the return value is nonzero. /// <para> /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </para> /// </returns> [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl); private IntPtr externalWindowHwnd; private Form windowForm; private Size lastSize; private Thread chivato; public WindowHook(IntPtr externalWindowHwnd, Overlay windowForm) { this.externalWindowHwnd = externalWindowHwnd; this.windowForm = windowForm; chivato = new Thread( () => { while (windowForm.working) { RECTANGULO rectangulo = new RECTANGULO(); GetWindowRect(externalWindowHwnd, out rectangulo); windowForm.resizeForm(rectangulo); Thread.Sleep(250); } }); chivato.SetApartmentState(ApartmentState.MTA); chivato.IsBackground = true; chivato.CurrentCulture = System.Globalization.CultureInfo.CurrentCulture; chivato.Priority = ThreadPriority.Highest; chivato.Name = "WindowHookWorkerThread"; chivato.Start(); //chivato.Join(); } } } <file_sep>/RustInterceptor/Forms/LoadForm.cs using Rust_Interceptor.Data; using Rust_Interceptor.Forms.Hooks; using Rust_Interceptor.Forms.Structs; using Rust_Interceptor.Forms.Utils; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using static Rust_Interceptor.Forms.Structs.WindowStruct; namespace Rust_Interceptor.Forms { public partial class LoadForm : Form { private static LoadForm instance; public static LoadForm getInstance() { if (instance == null) instance = new LoadForm(); return instance; } //Sobreescribe WndProc para permitir que el evento de despalzar el Form siga siendo posible protected override void WndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { case 0x84: base.WndProc(ref m); if ((int)m.Result == 0x1) m.Result = (IntPtr)0x2; return; } base.WndProc(ref m); } //Parametros necesarios para simular el desplazamiento del Form ////////////////////////////////////////// public volatile bool working = false; private Process rustProcess; private readonly String rustProcessName = "RustClient"; private UKeyHook hook; private Overlay overlay; private LoadForm() { this.Location = new Point(0, 0); hook = UKeyHook.getInstance(this); InitializeComponent(); this.listViewRecordatorio.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler( (object sender, ListViewItemSelectionChangedEventArgs e) => { String[] dir = e.Item.Text.Split(':'); this.textBoxIp.Text = dir[0]; this.textBoxPuerto.Text = dir[1]; } ); this.buttonCerrar.Click += new EventHandler( (object sender, EventArgs e) => { this.Cerrar(); }); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler( (object sender, FormClosedEventArgs e) => { this.working = false; } ); this.Load += new System.EventHandler( (object sender, EventArgs e) => { this.LoadForm_Load(sender,e); } ); } private void LoadForm_Load(object sender, EventArgs e) { //this.MaximumSize = this.Size; //g = this.CreateGraphics(); this.labelIp.Click += new EventHandler( (object responsable, EventArgs evento) => { this.textBoxIp.Focus(); }); this.labelPuerto.Click += new EventHandler( (object responsable, EventArgs evento) => { this.textBoxPuerto.Focus(); }); this.buttonEmpezar.Click += new EventHandler( (object responsable, EventArgs evento) => { if (this.textBoxIp.Text.Equals("debug")) { return; } if (this.textBoxIp.Text.Length == 0 && this.textBoxPuerto.Text.Length == 0) return; searchRustProcess(out rustProcess); if(rustProcess == null) { MessageBox.Show("No se ha encontrado ningún proceso de Rust activo ..."); return; } overlay = Overlay.getInstance(rustProcess); overlay.FormClosed += new FormClosedEventHandler( (object enviador, FormClosedEventArgs even) => { this.Show(); }); this.Hide(); overlay.start(this.textBoxIp.Text, Convert.ToInt32(this.textBoxPuerto.Text) ); //this.working = true; }); } private void searchRustProcess(out Process proceso) { Process[] procesos = Process.GetProcessesByName(rustProcessName); proceso = null; if (procesos.Length > 0) { Console.WriteLine("Proceso encontrado"); proceso = procesos[0]; } } private delegate void resetTextCallback(Control elemento); private void resetText(Control elemento) { if (this.InvokeRequired) this.Invoke(new resetTextCallback(resetText), elemento); else { elemento.ResetText(); } } private delegate void appendTextCallback(Control elemento,String cadena); private void appendText(Control elemento, String cadena) { if (this.InvokeRequired) this.Invoke(new appendTextCallback(appendText), elemento, cadena); else { elemento.Text += cadena; } } private delegate void resizeFormCallback(RECTANGULO rectangulo); public void resizeForm(RECTANGULO rectangulo) { if (this.InvokeRequired) this.Invoke(new resizeFormCallback(resizeForm),rectangulo); else { //this.Size = rectangulo.Size; this.Size = new Size(SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CXFULLSCREEN), SystemInfo.getSystemInfo(SystemInfo.SystemMetric.SM_CYFULLSCREEN)); //Setting Window position; this.Top = (int)rectangulo.Top; this.Left = (int)rectangulo.Left; } } private delegate void genericCallback(); public void Cerrar() { if (this.InvokeRequired) this.Invoke(new genericCallback(Cerrar)); else { this.working = false; if (hook != null) { if (hook.working) { hook.stop(); //sniffer.SavePackets(); } } this.Close(); } } } }
d3d0c94a848363255612dc993cb4abf1cedc3f0c
[ "Markdown", "C#" ]
14
C#
ViriatoOundil/RustInterceptor
7e10b82b89a026f45a7e99ddd6d8af9c4f9abc96
24b2c83de181728e76b03f81cded601b3cde4872
refs/heads/master
<repo_name>Gharaibeh/Rheumatology<file_sep>/Assets/Scripts/TimerEnabler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TimerEnabler : MonoBehaviour { public float timer; public GameObject[] disableBtn; public GameObject[] enableBtn; void Start() { Invoke("MakeIt", timer); } void MakeIt() { foreach (GameObject btn in disableBtn) btn.SetActive(false); foreach (GameObject btn in enableBtn) btn.SetActive(true); } } <file_sep>/Assets/Scripts/MultipleChoice.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MultipleChoice : MonoBehaviour { public string question; public GameObject[] disableBtn; public SaveData _data; public bool isGeneral, isJoint, isMorning, isFatigue, isDay; public void ButtonEnabler(GameObject answerName) { print(answerName.name); foreach (GameObject btn in disableBtn) btn.GetComponent<Image>().color = new Color(1.0f, 1.0f, 1.0f, 1.0f); answerName.GetComponent<Image>().color = new Color(0.4f, 0.4f, 0.4f, 0.4f); if (isGeneral) _data.getGeneralFeeling(answerName.name); if (isJoint) _data.getMyJoint(answerName.name); if (isMorning) _data.getMyMorning(answerName.name); if (isFatigue) _data.getMyFatigue(answerName.name); if (isDay) _data.getMyDay(answerName.name); } } <file_sep>/Assets/Scripts/SaveData.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using SimpleJSON; using System.IO; using System.Text; using System; using System.Net; using System.Net.Mail; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public class SaveData : MonoBehaviour { int indexer; void checkIndex() { indexer = PlayerPrefs.GetInt("dataIndex"); if (PlayerPrefs.GetString("my_feeling_" + indexer).Length != 0 && /*PlayerPrefs.GetString("my_joint_" + indexer).Length != 0 &&*/ PlayerPrefs.GetString("my_morning_" + indexer).Length != 0 && PlayerPrefs.GetString("my_fatigue_" + indexer).Length != 0 && PlayerPrefs.GetString("my_myday_" + indexer).Length != 0 ) { indexer++; PlayerPrefs.SetInt("dataIndex", (indexer)); } print(indexer); } void Start() { //PlayerPrefs.DeleteAll(); checkIndex(); } public void getGeneralFeeling(string userInput) { checkIndex(); PlayerPrefs.SetString("my_feeling_" + indexer, userInput); PlayerPrefs.SetString("my_feeling_time_" + indexer, DateTime.Now.ToString()); } public void getMyJoint(string userInput) { checkIndex(); } public void getMyMorning(string userInput) { checkIndex(); PlayerPrefs.SetString("my_morning_" + indexer, userInput); PlayerPrefs.SetString("my_morning_time_" + indexer, DateTime.Now.ToString()); } public void getMyFatigue(string userInput) { checkIndex(); PlayerPrefs.SetString("my_fatigue_" + indexer, userInput); PlayerPrefs.SetString("my_fatigue_time_" + indexer, DateTime.Now.ToString()); } public void getMyDay(string userInput) { checkIndex(); PlayerPrefs.SetString("my_myday_" + indexer, userInput); PlayerPrefs.SetString("my_myday_time_" + indexer, DateTime.Now.ToString()); } public void getMyMedication(string userInput) { checkIndex(); } public void getMyLabs(string userInput) { checkIndex(); } public void getMyCalculator(string userInput) { checkIndex(); } public void sendEmail() { StartCoroutine(SendDailyReportRounds()); } IEnumerator SendDailyReportRounds() { sendingReport.SetActive(true); string desktopPath = Application.persistentDataPath;//.GetFolderPath (System.Environment.SpecialFolder.DesktopDirectory); string ruta = desktopPath + "/" + " Rheumatoid Arthritis Report.csv"; //El archivo existe? lo BORRAMOS if (File.Exists(ruta)) { //File.Delete(ruta); } //Crear el archivo //var sr = File.Create(ruta,1024,FileOptions.None);//,1024, FileOptions.DeleteOnClose);//,1000,FileOptions.DeleteOnClose); //File.SetAttributes (ruta, FileAttributes.ReadOnly); string datosCSV = "Rheumatoid Arthritis Report" + System.Environment.NewLine; datosCSV += System.Environment.NewLine + (System.DateTime.Now.Day).ToString() + "." + (System.DateTime.Now.Month).ToString() + "." + (System.DateTime.Now.Year).ToString() + System.Environment.NewLine + System.Environment.NewLine; datosCSV += "All records, Gender,"+ "General feeling question, general feeling answer, time," + "Morning feeling question, morning feeling answer, time," + "Fatigue question, Fatigue answer, time,"+ "MyDay question, MyDay answer, time,"+System.Environment.NewLine; for (int i = 0; i <= indexer; i++) { string _feeling = PlayerPrefs.GetString("my_feeling_" + i); string _feeling_time = PlayerPrefs.GetString("my_feeling_time_" + i); string _morning = PlayerPrefs.GetString("my_morning_" + i); string _morning_time = PlayerPrefs.GetString("my_morning_time_" + i); string _fatigue = PlayerPrefs.GetString("my_fatigue_" + i); string _fatigue_time = PlayerPrefs.GetString("my_fatigue_time_" + i); string _myDay = PlayerPrefs.GetString("my_myday_" + i); string _myDay_time = PlayerPrefs.GetString("my_myday_time_" + i); datosCSV += i + ","; datosCSV += PlayerPrefs.GetString("Gender") + ","; datosCSV += "How are feeling in general?" + ","; datosCSV += _feeling + ","; datosCSV += _feeling_time + ","; datosCSV += "Do you suffer from morning stiffness?" + ","; datosCSV += _morning + ","; datosCSV += _morning_time + ","; datosCSV += "How fatigued are you today?" + ","; datosCSV += _fatigue + ","; datosCSV += _fatigue_time + ","; datosCSV += "How active were you today?" + ","; datosCSV += _myDay + ","; datosCSV += _myDay_time + ","; datosCSV += System.Environment.NewLine; } datosCSV += System.Environment.NewLine; //sr.Write(datosCSV); if (File.Exists(ruta)) { File.Delete(ruta); } StreamWriter outStream = System.IO.File.CreateText(ruta); outStream.WriteLine(datosCSV); outStream.Close(); //FileInfo fInfo = new FileInfo(ruta); //fInfo.IsReadOnly = false; //sr.Close(); yield return new WaitForSeconds(0.1f); //Application.OpenURL(ruta); SmtpClient SmtpServer = new SmtpClient("smtp.ipage.com"); MailMessage mail = new MailMessage(); mail.From = new MailAddress("<EMAIL>"); // mail.To.Add("<EMAIL>"); /* mail.CC.Add("<EMAIL>");*/ mail.CC.Add("<EMAIL>"); mail.To.Add("<EMAIL>"); mail.Subject = "Rheumatoid Arthritis patient report of " + (System.DateTime.Now.Day).ToString() + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year; mail.Body = "Hi Dear, \nKindly note the attached Rheumatoid Arthritis patient report." + "\n\nThanks,\nOnTheLineSoftworks Team"; SmtpServer.Port = 587; // SmtpServer.Credentials = new System.Net.NetworkCredential("<EMAIL>", "OnTheLine@2018") as ICredentialsByHost; SmtpServer.EnableSsl = true; mail.Attachments.Add(new Attachment(ruta)); ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; SmtpServer.Send(mail); Debug.Log("mail Sent..."); sendingReport.SetActive(false); } public void setGender(string gender) { PlayerPrefs.SetString("Gender", gender); } public GameObject sendingReport; } <file_sep>/README.md Rheumatology # About This Project This is a .... # Features 1. Easy to use. 2. Multilingual. 3. Makes keeping track of your RA easy. 4. Reminder and alert feature for medicine and lab tests. 5. Keep a record of medical results history. 6. IOS and Android compatible # Screenshots: ![splash screen ](https://github.com/Gharaibeh/Rheumatology/blob/master/screenshots/1.png) ![Language selection](https://github.com/Gharaibeh/Rheumatology/blob/master/screenshots/2.png) ![character selection](https://github.com/Gharaibeh/Rheumatology/blob/master/screenshots/3.png) ![Home screen](https://github.com/Gharaibeh/Rheumatology/blob/master/screenshots/4.png) <file_sep>/Assets/Scripts/ButtonStatus.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ButtonStatus : MonoBehaviour { public GameObject[] disableBtn; public GameObject[] enableBtn; public void ButtonEnabler() { foreach (GameObject btn in disableBtn) btn.SetActive(false); foreach (GameObject btn in enableBtn) btn.SetActive(true); } } <file_sep>/Assets/Scripts/SendReport.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.IO; using System.Text; using UnityEngine; using SimpleJSON; using System; using System.Net; using System.Net.Mail; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public class SendReport : MonoBehaviour { public InputField emailInput, nameInput; // Use this for initialization public void sendReport() { StartCoroutine(CombineReport()); } IEnumerator CombineReport() { yield return new WaitForSeconds(.1f); System.DateTime dt = (System.DateTime.Today); string fileName = dt.DayOfWeek + dt.ToString("dd-MMMM"); //StartCoroutine (tryExcel(fileName)); StartCoroutine(SendDailyReportRounds(fileName)); } IEnumerator SendDailyReportRounds(string filename) { yield return new WaitForSeconds(0.1f); SmtpClient SmtpServer = new SmtpClient("smtp.com"); MailMessage mail = new MailMessage(); mail.To.Add(emailInput.text); string surveyStatus = ""; // (SaveToDB.skippedQuestions < 22) ? "\n\n PLEASE NOTE THAT THIS SURVEY WAS COMPLETED SUCCESSFULLY" : "\n\n PLEASE NOTE THAT THIS SURVEY WAS INCOMPLETED"; mail.Subject = "Jordan Society of Rhematology report of " + (System.DateTime.Now.Day).ToString() + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year; mail.Body = "Hey "+ nameInput.text+ " , \nWe are currently working on something awesome. Stay tuned!" + surveyStatus + ". \n\nThanks,\n Rhematology Support"; SmtpServer.Port = 587; // SmtpServer.EnableSsl = true; // mail.Attachments.Add(new Attachment(ruta)); ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; SmtpServer.Send(mail); Debug.Log("mail Sent..."); } }
78c5894d7ded61914743e8edff51a028d1239ecd
[ "Markdown", "C#" ]
6
C#
Gharaibeh/Rheumatology
ff43cf6e48a1109a455a1a2fbfa4e49b25909074
80da98d9d7a38855a3f69d7ad9897ea9eab1543e
refs/heads/master
<repo_name>Python3-project/Show-Me-Code<file_sep>/每日一练/Exercises001.py #!/usr/bin/python3 #-*- coding:utf-8 -*- # Author YANGYUANJIU """ 第0001练习题 将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果 """ #首先,导入必要的库 from PIL import Image,ImageDraw,ImageFont import random import time def put_num_upright(pic,num): im = Image.open(pic) #打开pic文件 draw = ImageDraw.Draw(im) #创建draw对象 x,y = im.size #获取尺寸 #print("{pic},长:{x},高:{y}".format(pic=pic,x=x,y=y)) font = ImageFont.truetype('C:/Windows/Fonts/Arial.ttf', 40)# 字体设置 draw.text([200, 100], text=num, fill=(255, 0, 0), font=font) im.save('pic_get_{name}.png'.format(name=num),'png') #保存修改后的图片,路径没要求则是PY所在的文件夹内 if __name__ == '__main__': pic = '微信截图_20190412160145.png' #图片路径,默认py文件所在位置 for i in range(1000): localtime = time.localtime(time.time()) str1 = str(localtime[0]) + str(localtime[1]) + str(localtime[2]) + str(localtime[3]) + str(localtime[4]) + str(localtime[5]) put_num_upright(pic, str1) #time.sleep(1) print("共保存{num}张图片,正在保存第{cnt}张,还剩{ends}张".format(num=1000,cnt=i,ends=1000-i-1)) <file_sep>/每日一练/Exercises002.py #!/usr/bin/python3 #-*- coding:utf-8 -*- # Author YANGYUANJIU import random """ 第 0002 题: 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? """ def gen_code(length=8): """ :param length: :return: rand_str 将0-9,a-z,A-Z保存到list中,用random.sample从List中选取length位字符 """ code_list =[] for i in range(10): code_list.append(str(i)) for i in range(65,91): code_list.append(chr(i)) for i in range(97,123): code_list.append(chr(i)) # for i in range(0x4e00,0x9fa5): # code_list.append(chr(i)) myslist = random.sample(code_list,length) veri_code = ''.join(myslist) return veri_code if __name__ == '__main__': length=int(input('请输入您需要的随机字符长度:')) num = int(input('请输入您需要的随机字符数量:')) for i in range(num): #print('i:{i}'.format(i=i)) print('{list}\n'.format(list=gen_code(length))) <file_sep>/README.md # Show-Me-Code 项目:Python3 学习 / 每日一练 <file_sep>/每日一练/M1901xls.py #!/usr/bin/python3 #-*- coding:utf-8 -*- # Author YANGYUANJIU import xlwt import xlrd from xlutils.copy import copy import re def read_M1901_ARM_COM_LOG(): NUMERIC_SORT = [] STRING_SORT = [] BITFIELD = [] FP_EMULATION = [] FOURIER = [] IDEA = [] HUFFMAN = [] LU_DECOMPOSITION = [] testdatas = {'NUMERIC_SORT': NUMERIC_SORT, 'STRING_SORT': STRING_SORT, 'BITFIELD': BITFIELD, 'FP_EMULATION': FP_EMULATION, 'FOURIER': FOURIER, 'IDEA': IDEA, 'HUFFMAN': HUFFMAN, 'LU_DECOMPOSITION': LU_DECOMPOSITION } f = open('M1901零下20摄氏度性能测试_0.log', 'r') for line in f: red_log_line = f.readline() searchObj = re.search(r'NUMERIC SORT', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['NUMERIC_SORT'].append(data[0][0]) searchObj = re.search(r'STRING SORT', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['STRING_SORT'].append(data[0][0]) searchObj = re.search(r'BITFIELD', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['BITFIELD'].append(data[0][0]) searchObj = re.search(r'FP EMULATION', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['FP_EMULATION'].append(data[0][0]) searchObj = re.search(r'FOURIER', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['FOURIER'].append(data[0][0]) searchObj = re.search(r'IDEA', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['IDEA'].append(data[0][0]) searchObj = re.search(r'HUFFMAN', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['HUFFMAN'].append(data[0][0]) searchObj = re.search(r'LU DECOMPOSITION', red_log_line, re.M | re.I) if searchObj: data = re.findall('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', red_log_line) testdatas['LU_DECOMPOSITION'].append(data[0][0]) f.close() return testdatas # #只能写不能读 stus = ['NUMERIC SORT', 'STRING SORT', 'BITFIELD', 'FP EMULATION','FOURIER','IDEA','HUFFMAN','LU DECOMPOSITION'] book = xlwt.Workbook()#新建一个excel sheet = book.add_sheet('CPU性能测试-20℃')#添加一个sheet页 row = 0#控制行 col = 0#控制列 for stu in stus: sheet.write(row, col, stu) col+=1 book.save('M1901性能测试.xls')#保存到当前目录下 #xlutils:修改excel book1 = xlrd.open_workbook('M1901性能测试.xls') sheet_r = book1.sheet_by_index(0)#根据顺序获取sheet #sheet2_r = book1.sheet_by_name('CPU性能测试-20℃')#根据sheet页名字获取sheet # print("col={col}".format(col=sheet_r.ncols))#获取excel里面有多少列 # print("row={row}".format(row=sheet_r.nrows))#获取excel里面有多少行 row=sheet_r.nrows col=sheet_r.ncols book2 = copy(book1)#拷贝一份原来的excel # print(dir(book2)) sheet = book2.get_sheet(0)#获取第几个sheet页,book2现在的是xlutils里的方法,不是xlrd的 testdatas=read_M1901_ARM_COM_LOG() print() j=0 tmp_row=row for i in testdatas: for s in testdatas[i]: sheet.write(tmp_row,j,float(s)) tmp_row+=1 tmp_row = row j+=1 book2.save('M1901性能测试.xls') <file_sep>/爬虫/DownLoader_Biqukan_text.py #!/usr/bin/python3 #-*- coding:utf-8 -*- # Author YANGYUANJIU from bs4 import BeautifulSoup import requests,sys """ 类说明:下载《笔趣看》网小说《一念永恒》 Parameters:无 Returns:无 Modify:2019-04-09 """ class downloader(object): def __init__(self): self.server = "http://www.biqukan.com/" self.taget = 'http://www.biqukan.com/1_1094/' self.names = [] #存放章节名 self.urls = [] # 存放章节连接 self.nums = 0 #章节数 """ 函数说明:获取下载链接 parameters:无 Returns:无 Modify:2019-04-09 """ def get_download_url(self): req = requests.get(url=self.taget) html = req.text div_bf = BeautifulSoup(html,"html5lib") div = div_bf.find_all('div',class_= 'listmain') a_bf =BeautifulSoup(str(div[0]),"html5lib") a = a_bf.find_all('a') self.nums = len(a[16:-6]) #删除不必要的章节,并统计章节数 for each in a[16:-6]: self.names.append(each.string) self.urls.append(self.server + each.get('href')) """ 函数说明:获取章节内容 Parameters: target -下载链接(string) Returns: texts -章节内容(string) Modify:2019-04-09 """ def get_contents(self, target): texts = False while texts == False: req = requests.get(url=target) html = req.text bf = BeautifulSoup(html, "html5lib") texts = bf.find_all('div', class_='showtxt') if texts: texts = (texts[0].text.replace('\xa0' * 8, '\n\n')) break else: continue return texts """ 函数说明:将爬取的文章内容写入文件 Parameters: name - 章节名称(string) path - 当前路径下,小说保存名称(string) text - 章节内容 Returns: 无 Modify:2019-04-09 """ def writer(self,name,path,text): write_flag = True with open(path,'a',encoding='utf-8') as f: f.write(name + '\n') f.writelines(text) f.write('\n\n') if __name__ == "__main__": dl = downloader() dl.get_download_url() dl.get_contents(dl.urls[0]) for i in range(dl.nums): print(dl.names[i],end=':') print(dl.urls[i]) print("《一念永恒》开始下载:") for i in range(dl.nums): dl.writer(dl.names[i], '一念永恒.txt',dl.get_contents(dl.urls[i])) sys.stdout.write(" 已下载:{:.2%}{}" .format(i/dl.nums,'\r')) sys.stdout.flush() print("《一念永恒》下载完成")
92579e61035233b56196fa08949c006eb4458894
[ "Markdown", "Python" ]
5
Python
Python3-project/Show-Me-Code
bdad293cd5e26e20f1a825b96b8b98f2551193d9
3a800d27cc3a742e459ba3984f78327f72fb91a1
refs/heads/master
<repo_name>spaghetticode/mover<file_sep>/helpers.rb class String def blank? gsub(/\s+/, '').empty? end end class NilClass def blank? true end end module FileAdapter SPLITTER = "\n" class << self def convert(files) files.split(SPLITTER).map {|filename| filename.strip}.compact.uniq end def codes(values) values.split(' ').map {|code| code.strip}.compact.uniq end def same_dir?(target, origin) if mswindows? target.gsub!('\\', '/') origin.gsub!('\\', '/') end target =~ /^#{origin}(\/|$)/ end def tainted?(*dirs) tainted = false dirs.each do |dir| tainted = true if dir =~ /(\\|\/)$/ end tainted end def mswindows? RUBY_PLATFORM =~ /mingw32/ end end end<file_sep>/spec/validator_spec.rb describe Validator do let(:validator) { Validator.new(['D-01-A-1', 'D-01-A-8-11', 'D-01-A-8-15']) } describe '#validate' do it 'should return an array of invalid codes' do validator.validate.should be_an(Array) end it 'should return expected invalid codes quantity' do validator.validate.size.should == 2 end end describe '#invalid_codes' do before { validator.validate } it 'should return expected string' do validator.invalid_codes.should == 'D-01-A-8-11 D-01-A-8-15' end end it 'should validate all codes, even if invalid, if they have no control code' do validator = Validator.new(['C-11-ROB-31', 'C-11-YY-27']) validator.validate validator.invalid_codes.should be_blank end end<file_sep>/app_config.rb require 'yaml' module AppConfig class << self attr_accessor :path def dirs @dirs ||= YAML.load_file(path) rescue Hash.new end %w[source_dir target_dir second_target_dir].each do |method| define_method method do dirs[method] end end def save(source_dir, target_dir, second_target_dir) config = { 'source_dir' => dir_for(source_dir), 'target_dir' => dir_for(target_dir), 'second_target_dir' => dir_for(second_target_dir), :path => path } File.open(path, 'w') do |file| YAML.dump config, file end end private def dir_for(dir) dir.blank? ? nil : dir end end end<file_sep>/mover.rb require 'rubygems' require File.expand_path('../movable_file', __FILE__) require File.expand_path('../helpers', __FILE__) require File.expand_path('../app_config', __FILE__) class Mover attr_reader :files, :source_dir, :target_dir, :second_target_dir, :moved_count def initialize(prog_bar, files, source_dir, target_dir, second_target_dir=nil) @files = files @prog_bar = prog_bar @source_dir = source_dir @target_dir = target_dir @second_target_dir = second_target_dir unless second_target_dir.blank? @moved_hash = {} @moved_count = 0 @files_count = files.size end def mv recursive_mv(source_dir) end def not_moved files - @moved_hash.keys end def moved @moved_hash.values end private def remaining_count @files_count - @moved_count end def progress_count ((100.0 / @files_count) * @moved_count).to_i end def recursive_mv(dir) dir.gsub!('\\', '/') if FileAdapter.mswindows? Dir["#{dir}/*"].each do |entry| if File.file?(entry) basename_without_ext = File.basename(entry).chomp(File.extname(entry)) if files.include?(basename_without_ext) file = MovableFile.new(entry, @target_dir, @second_target_dir) if file.mv && @moved_hash[basename_without_ext].nil? @moved_hash[basename_without_ext] = File.basename(entry) @moved_count += 1 if @moved_count % 5 == 0 @prog_bar.update(progress_count, "#{@moved_count} files spostati, #{remaining_count} files ancora da spostare") end end end else recursive_mv(entry) if File.directory?(entry) end end end end<file_sep>/spec/mover_spec.rb describe Mover do def basename_path File.dirname(__FILE__) end def prog_bar @prog_bar ||= mock end def prepare_fs @file_path = File.join(@source_dir, @file) @not_moved_file_path = File.join(@source_dir, @not_moved_file) @nested_file_path = File.join(@source_dir, 'nested/down', @nested_file) # creo i file: [@file_path, @not_moved_file_path, @nested_file_path].each do |file| FileUtils.touch file File.file?(file).should be_true end end before do @file = 'test.txt' @not_moved_file = 'not_moved.pdf' @file_without_ext = @file.chomp(File.extname(@file)) @nested_file = 'nested.jpg' @nested_file_without_ext = @nested_file.chomp(File.extname(@nested_file)) @source_dir, @target_dir, @second_target_dir = "#{basename_path}/origin", "#{basename_path}/target", "#{basename_path}/second_target" prepare_fs end after do [@target_dir, @second_target_dir].each do |dir| [@file, @not_moved_file, @nested_file].each do |file| path = File.join(dir, file) FileUtils.rm(path) if File.file?(path) end end end context 'a mover with both target directories set' do before { @mover = Mover.new(prog_bar, [@file_without_ext], @source_dir, @target_dir, @second_target_dir) } it 'should set attributes as expected' do @mover.files.should == [@file.chomp(File.extname(@file))] @mover.source_dir.should == @source_dir @mover.target_dir.should == @target_dir @mover.second_target_dir.should == @second_target_dir end it 'should set second_target_dir to nil' do @mover = Mover.new(prog_bar, [@file], @source_dir, @target_dir, '') @mover.second_target_dir.should be_nil end it 'should create expected file' do @mover.mv (File.join(@target_dir, @file)).should be_a_file (File.join(@second_target_dir, @file)).should be_a_file end it 'shoould not remove files that should not be moved' do @mover.mv @not_moved_file_path.should be_a_file end it 'moved should include expected file' do @mover.mv @mover.moved.should include(@file) end it 'moved should not include file not to be moved' do @mover.mv @mover.moved.should_not include(@not_moved_file) end it 'not_moved should include expected file' do @mover.instance_variable_set('@file', @mover.files << 'unexisting') @mover.mv @mover.not_moved.should include('unexisting') end it 'not_moved should include only one item' do @mover.instance_variable_set('@file', @mover.files << 'unexisting') @mover.mv @mover.not_moved.should have(1).item end it 'should remove expected file' do @mover.mv File.file?(File.join(@source_dir, @file)).should be_false end context 'when files include a file in a nested dir' do before do @mover.instance_variable_set('@files', [@file_without_ext, @nested_file_without_ext]) end it 'should create expected file from nested one' do @mover.mv File.join(@target_dir, @nested_file).should be_a_file end it 'should remove source nested file' do @mover.mv @nested_file_path.should_not be_a_file end end end context 'a mover with only one target directory set' do before { @mover = Mover.new(prog_bar, [@file_without_ext], @source_dir, @target_dir) } it 'should create expected file' do @mover.mv File.join(@target_dir, @file).should be_a_file end it 'should remove expected file' do @mover.mv File.join(@source_dir, @file).should_not be_a_file end it 'should not remove files to to be moved' do @mover.mv @not_moved_file_path.should be_a_file @nested_file_path.should be_a_file end end end<file_sep>/movable_file.rb require 'rubygems' require 'fileutils' class MovableFile attr_reader :basename, :source_file, :target_file, :second_target_file def initialize(source_file, target, second_target=nil) @basename = File.basename(source_file) @source_file = source_file @target_file = File.join(target, basename) @second_target_file = File.join(second_target, basename) if second_target end def copied? if second_target_file File.file?(target_file) && same_size? && File.file?(second_target_file) else File.file?(target_file) && same_size? end end def same_size? File.size(target_file) == File.size(source_file) end def copy FileUtils.cp(source_file, target_file) FileUtils.cp(source_file, second_target_file) if second_target_file end def rm FileUtils.rm(source_file) end def mv copy if copied? rm return true end false end end<file_sep>/validator.rb class Validator def initialize(codes) @codes = codes.map { |code| Code.new(code) } @invalid = [] end def get_invalid_codes validate invalid_codes end def validate @codes.inject(@invalid) do |invalid, code| invalid << code unless code.valid? invalid end end def invalid_codes @invalid.map { |code| code.value }.join(' ') end end<file_sep>/code.rb class Code SEPARATOR = '-' LETTERS = ('A'..'Z').to_a # value is a string with format A-01-C-123 attr_accessor :value def initialize(value) @value = value @parts = value.split(SEPARATOR) end def clean @parts[0..3].join(SEPARATOR) end def valid? unless control_code true else unless @parts.size > 3 and parts_valid? false else year_number + month + designer_number + count == control_code end end end def year @parts[0].upcase end def designer @parts[2].upcase end def month @parts[1] =~ /^\d+$/ && @parts[1].to_i || 0 end def count @parts[3] =~ /^\d+$/ && @parts[3].to_i || 0 end def control_code @parts[4] && @parts[4].to_i end def parts_valid? year_valid? and month_valid? and designer_valid? and count_valid? end def count_valid? count > 0 end def month_valid? month > 0 and month <= 12 end def year_number LETTERS.index(year) + 1 end def designer_number designer.split(//).inject 0 do |total, letter| total += LETTERS.index(letter) + 1 end end def year_valid? LETTERS.include?(year) end def designer_valid? if control_code return false if designer.size > 2 designer.split(//).map do |letter| LETTERS.include?(letter) end.uniq == [true] else true end end end<file_sep>/spec/spec_helper.rb require 'rspec' require File.dirname(__FILE__) + '/../mover' require File.dirname(__FILE__) + '/../code' require File.dirname(__FILE__) + '/../cleaner' require File.dirname(__FILE__) + '/../validator' Dir['*.rb'].each do |file| require file end Rspec::Matchers.define :be_a_file do match do |path| File.file?(path) end failure_message_for_should do |path| files = Dir["#{File.dirname(path)}/*"] files.map!{|f| f if File.file?(f)}.compact! "expected #{path} to be a file among #{files.join(', ')}" end failure_message_for_should_not do |path| files = Dir["#{File.dirname(path)}/*"] files.map!{|f| f if File.file?(f)}.compact! "expected #{path} not to be a file among #{files.join(', ')}" end end<file_sep>/cleaner.rb class Cleaner NEW_LINE = "\n" # use windows newlines def initialize(codes) @codes = codes.map {|code| Code.new(code)} end def remove_control_codes @codes.map do |code| code.clean end.join(NEW_LINE) end end<file_sep>/gui.rb # encoding: utf-8 #!/usr/bin/env arch -i386 ruby require 'rubygems' require 'wx' require File.expand_path('../movable_file', __FILE__) require File.expand_path('../mover', __FILE__) require File.expand_path('../code', __FILE__) require File.expand_path('../cleaner', __FILE__) require File.expand_path('../validator', __FILE__) require File.expand_path('../main_frame', __FILE__) include Wx class MovedFrame < Frame def initialize(parent, moved, not_moved) super(parent, -1, 'Report', :size => Size.new(300, 200)) panel = Panel.new(self) panel.sizer = BoxSizer.new(VERTICAL) moved_caption = StaticText.new panel, :label => 'Ho spostato i seguenti files:' moved_box = TextCtrl.new panel, -1, moved, DEFAULT_POSITION, DEFAULT_SIZE, TE_MULTILINE not_moved_box = TextCtrl.new panel, -1, not_moved, DEFAULT_POSITION, DEFAULT_SIZE, TE_MULTILINE not_moved_caption = StaticText.new panel, :label => 'Non ho trovato i seguenti files:' panel.sizer.add not_moved_caption, 0 panel.sizer.add not_moved_box, 1, GROW|ALL, 10 panel.sizer.add moved_caption, 0 panel.sizer.add moved_box, 1, GROW|ALL, 10 end end class InvalidFrame < Frame def initialize(parent, message) super(parent, -1, 'Report', :size => Size.new(300, 200)) panel = Panel.new(self) panel.sizer = BoxSizer.new(VERTICAL) invalid_caption = StaticText.new panel, :label => 'Le seguenti sigle sono invalide:' invalid_box = TextCtrl.new panel, -1, message, DEFAULT_POSITION, DEFAULT_SIZE, TE_MULTILINE panel.sizer.add invalid_caption, 0 panel.sizer.add invalid_box, 1, GROW|ALL, 10 end end class MoverFrame < TextFrameBase def initialize AppConfig.path = File.join(get_home_dir, '.file_mover.yml') super source_dir_txt.value = AppConfig.source_dir if AppConfig.source_dir target_dir_txt.value = AppConfig.target_dir if AppConfig.target_dir second_target_dir_txt.value = AppConfig.second_target_dir if AppConfig.second_target_dir bind_events end def on_source_button(event) dir_home = AppConfig.source_dir || get_home_dir dialog = DirDialog.new(self, "Scegli la directory di origine", dir_home) source_dir_txt.value = dialog.path if dialog.show_modal == ID_OK end def on_first_choose_button(event) dir_home = AppConfig.target_dir || get_home_dir dialog = DirDialog.new(self, "Scegli la directory di destinazione", dir_home) target_dir_txt.value = dialog.path if dialog.show_modal == ID_OK end def on_second_choose_button(event) dir_home = AppConfig.second_target_dir || get_home_dir dialog = DirDialog.new(self, "Scegli la directory di destinazione", dir_home) second_target_dir_txt.value = dialog.path if dialog.show_modal == ID_OK end def on_save_config_button(event) AppConfig.save(source_dir_txt.value, target_dir_txt.value, second_target_dir_txt.value) end def on_validate_button(event) if file_names_txt.value.empty? log_message 'Devi inserire una lista di sigle' else codes = FileAdapter.codes(file_names_txt.value) validator = Validator.new(codes) invalid_codes = validator.get_invalid_codes message = invalid_codes.empty? && 'Le sigle sono valide o non hanno codice di controllo' || invalid_codes InvalidFrame.new(self, message).show end end def on_clean_button(event) if file_names_txt.value.empty? log_message 'Devi inserire una lista di sigle' else codes = FileAdapter.codes(file_names_txt.value) cleaner = Cleaner.new(codes) file_names_txt.value = cleaner.remove_control_codes end end def on_submit_button(event) if required_fields_empty? log_message error_message elsif origin_and_targets_are_same? log_message same_folder elsif dirs_tainted? log_message tainted_dirs else prog_bar = ProgressDialog.new('', start_message, 100, self, PD_APP_MODAL|PD_ELAPSED_TIME) files = FileAdapter.convert(file_names_txt.value) mover = Mover.new(prog_bar, files, source_dir_txt.value, target_dir_txt.value, second_target_dir_txt.value) mover.mv prog_bar.update(100, "#{mover.moved_count} files spostati. Operazione terminata.") moved = mover.moved.join("\n") not_moved = mover.not_moved.join("\n") MovedFrame.new(self, moved, not_moved).show end end private def bind_events evt_button(clean_bt) {|e| on_clean_button(e)} evt_button(save_config_bt) {|e| on_save_config_button(e)} evt_button(validate_bt) {|e| on_validate_button(e)} evt_button(submit_bt) {|e| on_submit_button(e)} evt_button(source_dir_bt) {|e| on_source_button(e)} evt_button(target_dir_bt) {|e| on_first_choose_button(e)} evt_button(second_target_dir_bt) {|e| on_second_choose_button(e)} end def required_fields_empty? source_dir_txt.value.empty? || target_dir_txt.value.empty? || file_names_txt.value.empty? end def error_message "Devi fornire tutti i dati obbligatori:\ncartella sorgente, destinazione, e file da spostare" end def same_folder "La cartella di destinazione non è valida:\ndevi scegliere una cartella esterna a quella di origine" end def start_message 'Inizio spostamento files, per favore attendere...' end def origin_and_targets_are_same? FileAdapter.same_dir?(target_dir_txt.value, source_dir_txt.value) or FileAdapter.same_dir?(second_target_dir_txt.value, source_dir_txt.value) end def dirs_tainted? FileAdapter.tainted?(target_dir_txt.value, source_dir_txt.value, second_target_dir_txt.value) end def tainted_dirs "le directory non sono valide\n(rimuovi gli slash/backslash dalla fine delle directory)" end end class MoverApp < App def on_init MoverFrame.new.show end end MoverApp.new.main_loop<file_sep>/spec/movable_file_spec.rb describe MovableFile do def current_path File.dirname(__FILE__) end before do @first_file = 'test.txt' @second_file = 'sample.pdf' @source_file, @target, @second_target = "#{current_path}/origin/#{@first_file}", "#{current_path}/target", "#{current_path}/second_target" FileUtils.touch @source_file @file = MovableFile.new(@source_file, @target, @second_target) File.file?(@file.source_file).should be_true end after do [@target, @second_target].each do |dir| [@first_file, @second_file].each do |file| path = File.join(dir, file) FileUtils.rm(path) if File.exist?(path) end end end it 'should set all attributes' do @file.basename.should == 'test.txt' @file.target_file.should == "#{@target}/#{@file.basename}" @file.source_file.should == @source_file @file.second_target_file.should == "#{@second_target}/#{@file.basename}" end it 'should leave second_target_file blank' do file = MovableFile.new(@source_file, @target) file.second_target_file.should be_nil end it 'should not be copied' do @file.should_not be_copied end context 'when the file has been copied to the target folders' do before do File.should_receive(:file?).with(@file.target_file).and_return(true) File.should_receive(:file?).with(@file.second_target_file).and_return(true) @file.should_receive(:same_size?).and_return(true) end it 'it should be copied' do @file.should be_copied end end context 'when the file has been copied to the target forlder' do before do @file.should_receive(:second_target_file).and_return(nil) File.should_receive(:file?).with(@file.target_file).and_return(true) @file.should_receive(:same_size?).and_return(true) end it 'should be copied' do @file.should be_copied end end describe '#rm' do it 'should delete source_file file' do @file.rm @file.source_file.should_not be_a_file end end describe '#copy' do it 'should create copy files' do @file.copy @file.target_file.should be_a_file @file.second_target_file.should be_a_file end end describe '#mv' do it 'should copy file' do @file.mv @file.target_file.should be_a_file @file.second_target_file.should be_a_file end it 'should remove original file' do @file.mv @file.source_file.should_not be_a_file end it 'should return true' do @file.mv.should be_true end it 'should return false if files were not copied' do @file.stub!(:copied? => false) @file.mv.should be_false end end end<file_sep>/spec/config_spec.rb describe AppConfig do context 'when there is no config file to load' do context 'when there is no default dir set' do it { AppConfig.source_dir.should be_nil } it { AppConfig.target_dir.should be_nil } it { AppConfig.second_target_dir.should be_nil } end end context 'when there is a config file to load' do it 'should load expected paths' do AppConfig.path = File.dirname(__FILE__) + '/app_config.yml' AppConfig.source_dir.should == '/Users/andrea/source' AppConfig.target_dir.should == '/Users/andrea/target' AppConfig.second_target_dir.should == '/Users/andrea/second_target' end end context 'save config' do before do @path = File.dirname(__FILE__) + '/custom_config.yml' AppConfig.path = @path AppConfig.save('source_path', 'target_path', 'second_target_path') end after do FileUtils.rm(@path) if File.file?(@path) end it 'should create config file' do @path.should be_a_file end it 'config file should include expected strings' do File.read(@path).should include('source_path') end end end <file_sep>/Gemfile source 'https://rubygems.org' RUBY_19 = RUBY_VERSION.to_f > 1.8 if RUBY_19 gem 'wxruby-ruby19' else gem 'wxruby' end gem 'rspec' gem 'pry'<file_sep>/spec/helpers_spec.rb describe String do it { String.new.should be_blank } it { ' '.should be_blank } it { ' '.should be_blank } it { 'asd'.should_not be_blank } end describe NilClass do it { nil.should be_blank } end describe FileAdapter do it { FileAdapter::SPLITTER.should == "\n" } describe '.convert' do it 'should return expected array' do files = "B-09-M-32 A-08-C-42 A-02-WW-73" FileAdapter.convert(files).should == %w[B-09-M-32 A-08-C-42 A-02-WW-73] end it 'should remove duplicate entries' do files = 'ABC BCA ABC ABC' FileAdapter.convert(files).should have(2).items end end describe '.codes' do before do @codes = 'A-01-C-12 C-12-L-1 B-10-K-666' end it 'should split the codes string' do FileAdapter.codes(@codes).size.should == 3 end it 'should return expected values' do FileAdapter.codes(@codes).should == %w[A-01-C-12 C-12-L-1 B-10-K-666] end end describe 'same_dir?' do it 'should be false when origin and target dirs are not same/nested' do origin = Dir.pwd target = Dir.pwd.split('//')[0..-2] FileAdapter.same_dir?(target, origin).should be_false end it 'should be true when origin and target dirs are same' do origin = target = Dir.pwd FileAdapter.same_dir?(target, origin).should be_true end it 'should be true when target is nested in origin' do origin = Dir.pwd target = File.join(origin, 'pizza') FileAdapter.same_dir?(target, origin).should be_true end end describe 'tainted?' do it 'should be true when dirs end with slash or backslashes' do ['dir\\', 'dir\/'].each do |dir| FileAdapter.tainted?(dir).should be_true end end it 'should be false when dirs end with valid chars' do ['\/pizza', '\\asd'].each do |dir| FileAdapter.tainted?(dir).should be_false end end end end<file_sep>/spec/code_spec.rb require 'rubygems' require 'pry' require File.expand_path('../../code', __FILE__) describe Code do before do @invalid = 'A-12-C' @with_control_number = 'D-01-A-8-14' @without_control_number = 'D-01-A-15' @with_double_letter = 'F-01-AB-10-20' end describe 'a code instance' do let(:invalid) { Code.new('A-12-C-1-123') } let(:valid) { Code.new(@with_control_number) } let(:valid_without_control) { Code.new(@without_control_number)} let(:valid_with_double_letter) { Code.new(@with_double_letter)} describe '#clean' do context 'when code has control number' do it 'should remove it' do valid.clean.should == 'D-01-A-8' end end context 'when code has no control number' do it 'should return the original code value' do valid_without_control.clean.should == @without_control_number end end end context 'when using a double letter designer' do subject { valid_with_double_letter } it { should be_valid } it 'has expected designer' do subject.designer.should == 'AB' end it 'has valid designer' do subject.should be_designer_valid end it 'has expected designer_number' do subject.designer_number.should == 3 end end describe '#valid?' do context 'when code is valid' do it { valid.should be_valid } end context 'when code is invalid' do it { invalid.should_not be_valid } end it 'when code format is invalid but there is no control code' do Code.new('DA-01-A-15').should be_valid end context 'the code 07-09-T-2' do it { Code.new('07-09-T-2').should be_valid } end end describe '#year_number' do it { valid.year_number.should be_a(Integer) } it 'should be the position of letter in the alphabet' do valid.year_number.should == 4 end end describe '#month' do it { valid.month.should be_a(Integer) } it 'should be as expected' do valid.month.should == 1 end end describe '#designer_number' do it { valid.designer_number.should be_a(Integer) } it { valid.designer.should == 'A' } it 'should be the position of letter in the alphabet' do valid.designer_number.should == 1 end end describe '#control_code' do context 'when there is a control code' do it { valid.control_code.should be_a(Integer) } it 'should be as expected' do valid.control_code.should == 14 end end context 'when there is no control code' do it 'should be nil' do valid_without_control.control_code.should be_nil end end end end describe 'parts validations' do context 'when year format is not valid' do it 'year should be invalid' do ['a1-12-c-11', '2-12-c-11', 'aa-12-c-11'].each do |code| Code.new(code).should_not be_year_valid end end end context 'when month format is not valid' do it 'month should be invalid' do ['A-13-c-12', 'A-a1-c-12', 'A-1c-c-12', 'a-0-c-12'].each do |code| Code.new(code).should_not be_month_valid end end end context 'when designer is not valid but there is no control code' do it 'designer should be valid' do ['a-12-c1-11', 'a-12-2-11', 'a-12-cc-11'].each do |code| Code.new(code).should be_designer_valid end end end context 'when designer is not valid and there is control code' do it 'designer should be valid' do Code.new('D-01-AAAA-8-14').should_not be_designer_valid end end context 'when count is not valid' do it 'count should be invalid' do ['a-12-c-0', 'a-12-c-c1', 'a-12-c-1c'].each do |code| Code.new(code).should_not be_count_valid end end end end end<file_sep>/spec/cleaner_spec.rb describe Cleaner do describe '#remove_control_codes' do let(:cleaner) { Cleaner.new(['A-01-C-12-123', 'C-12-L-1-4', 'B-10-K-666']) } it 'should return a string with codes with control code removed' do cleaner.remove_control_codes.should == "A-01-C-12\nC-12-L-1\nB-10-K-666" end end end
e9b44e686a522f73d8c545e728cd5760085b4d6b
[ "Ruby" ]
17
Ruby
spaghetticode/mover
f17c1b845143d2f0b880911dd104d90a94c0c4de
0061a55dbfa2973abc951b612c4032b9e4e55631
refs/heads/master
<file_sep>// // ViewController.swift // SpeechRecognition // // Created by <NAME> on 14/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import Speech enum SpeechRecognitionState { case requiresAuthorization case ready case recording } class ViewController: UIViewController { private let recognizer: SpeechRecognizer = SpeechRecognizer() private var recognitionState: SpeechRecognitionState override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { recognitionState = ViewController.currentSpeechRecognitionState() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { recognitionState = ViewController.currentSpeechRecognitionState() super.init(coder: aDecoder) } private static func currentSpeechRecognitionState() -> SpeechRecognitionState { return (SFSpeechRecognizer.authorizationStatus() == .authorized) ? .ready : .requiresAuthorization } // MARK: - IBOutlets @IBOutlet var transcriptTextView: UITextView! @IBOutlet var recordButton: UIButton! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() updateInterfaceState() } // MARK: - IBActions @IBAction func recordButtonTapped() { handleSpeechRecognitionState(state: recognitionState) } // MARK: - Private private func requestSpeechRecognitionAuthorization() { SFSpeechRecognizer.requestAuthorization { authStatus in OperationQueue.main().addOperation { switch authStatus { case .authorized: self.recognitionState = .ready default: self.recognitionState = .requiresAuthorization } self.updateInterfaceState() } } } private func updateInterfaceState() { displaySpeechRecognitionState(state: recognitionState) } private func displaySpeechRecognitionState(state: SpeechRecognitionState) { switch state { case .requiresAuthorization: recordButton.setTitle("Authorize", for: []) case .ready: recordButton.setTitle("Record", for: []) case .recording: recordButton.setTitle("Stop Recording", for: []) } } private func handleSpeechRecognitionState(state: SpeechRecognitionState) { switch state { case .requiresAuthorization: requestSpeechRecognitionAuthorization() case .ready: try! startRecording() self.recognitionState = .recording updateInterfaceState() case .recording: self.recognitionState = .ready updateInterfaceState() } } // MARK: Recording private func startRecording() throws { try recognizer.startRecording() { (result, stoppedRecording, error) in if let text = result { self.transcriptTextView.text = text } if stoppedRecording { self.stopRecording() } } } private func stopRecording() { self.recognitionState = .ready self.updateInterfaceState() } } <file_sep>// // SpeechRecognizer.swift // SpeechRecognition // // Created by <NAME> on 14/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import Speech typealias SpeechRecognizerResultHandler = ((String?, Bool, NSError?) -> Swift.Void) class SpeechRecognizer { private let speechRecognizer = SFSpeechRecognizer(locale: Locale(localeIdentifier: "en-US"))! private let audioEngine = AVAudioEngine() private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? private var recognitionTask: SFSpeechRecognitionTask? internal func startRecording(resultHandler: SpeechRecognizerResultHandler) throws { guard let inputNode = audioEngine.inputNode else { return } if let recognitionTask = recognitionTask { recognitionTask.cancel() self.recognitionTask = nil } // Set up the recognition request: recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let recognitionRequest = recognitionRequest else { return } recognitionRequest.shouldReportPartialResults = true // Set up the audio session: try configureAudioSession() // Configure the recognition task: recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in var stopRecording = false if let result = result { let transcript = result.bestTranscription.formattedString print("Transcript: \(transcript)") resultHandler(transcript, result.isFinal, error) stopRecording = result.isFinal } if (error != nil) || stopRecording { self.stopRecording() resultHandler(nil, true, error) } } let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, _) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() try audioEngine.start() } private func configureAudioSession() throws { let audioSession = AVAudioSession.sharedInstance() try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) } private func stopRecording() { self.audioEngine.stop() audioEngine.inputNode?.removeTap(onBus: 0) self.recognitionRequest = nil self.recognitionTask = nil } }
935abb94b6fb18b2bba2f38846f64d112121e581
[ "Swift" ]
2
Swift
mohd14shoeb/SpeechRecognition
1b9289aa51ed8958276e967062d95f5cca2733b5
194c1a3c1f720b02e069512ab294033e2ced166d
refs/heads/master
<repo_name>tservi/clubluttecottens2014<file_sep>/clubluttefete2014jeunes.php <html> <head> <title>Fêtes de luttes 2014 - Jeunes </title> <meta charset="utf-8" /> </head> <body> <?php $lutteurs =array( array( "Responsable", " de la Fête", "jeune" ), array( "Responsable", "du Club", "jeune" ), array( "Transport", "", "" ), array( "Bel", "Yannick", "jeune" ), array( "Bigler", "Samuel", "jeune" ), array( "Brodard", "Ewan", "jeune" ), array( "Chatagny" , "Michaël" , "actif+jeune") , array( "Crottaz" , "Yves" , "jeune") , array( "Felder" , "Lucien", "jeune" ), array( "Gachet", "Romain" , "jeune" ), array( "Grandjean", "Xavier" , "actif+jeune" ), array( "Jaquier", "Pierre" , "jeune" ), array( "Jaquier", "Simon" , "jeune" ), array( "Nicolet", "Bastien" , "jeune" ), array( "Python", "Benjamin" , "jeune" ), array( "Vaucher", "Rémy" , "jeune") , array( "Wenger" , "Killian" , "actif+jeune" ) , array( "Zanardi" , "Alex" , "jeune" ) , ); $fetes2014 = array( array( "Sam 26 avril", "Villarlod" , "démonstration<br/><font style=\"color:red;\">obligatoire</font>") , array( "Dim 27 avril", "Estavayer-le-Gibloux", "régionale" ), array( "Dim 11 mai", "Ried" , "régionale" ), array( "Dim 18 mai", "Vessy" , "cantonale GE" ), array( "Dim 24 mai", "Le Locle" , "cantonale NE" ), array( "Jeu 29 mai" , "Le Mouret", "régionale (90)"), array( "Dim 1 juin" , "Oron" , "cantonale VD"), array( "Dim 15 juin" , "Mont-sur-Rolle" , "régionale"), array( "Dim 29 juin" , "Collombey" , "cantonale VS"), array( "Dim 20 juillet" , "Riaz" , "cantonale FR"), array( "Dim 27 juillet", "Lac des joncs", "alpestre"), array( "Dim 10 août" , "Boveresse", "régionale") , array( "Dim 17 août" , "Heitenried", "romande") , array( "Dim 7 décembre" , "Plaffeien", "en salle") , ); ?> <center> <h1> Liste pour les fêtes de lutte - Saison 2014 - <i>jeunes</i> </h1> <!-- <p style="width:800px; text-align: left">Comment remplir le tableau ci-dessous : dans la case correspondant à votre nom et à la fête faites un "X" pour indiquer votre participation ou bien un "T" pour indiquer que vous viendrez et que en plus vous serez motorisé. </p> --> <table border="0" style="border:1px solid black; border-collapse: collapse; font-size: 13px;"> <thead style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: black;"> <tr> <td style="border-right-width: 1px; border-right-style: solid; border-right-color: black;"> </td> <?php foreach( $lutteurs as $val ) { echo "<td style=\"-webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); height: 80px; width:30px; border-right-width: 1px; border-right-style: solid; border-right-color: black;\"><strong>" . $val[0] . "</strong><br/>" . $val[1] . "</td>\r\n"; } ?> </tr> </thead> <?php foreach($fetes2014 as $val) { echo "<tr style=\"border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: black;\">\r\n"; echo "<td style=\"border-right-width: 1px; border-right-style: solid; border-right-color: black;\">\r\n"; echo $val[0] ; echo "<br/>"; echo $val[1]; echo "<br/>"; echo "<i>" . $val[2] . "</i>"; echo "</td>\r\n"; foreach( $lutteurs as $val ) { echo "<td style=\"border-right-width: 1px; border-right-style: solid; border-right-color: black; text-align: center;\">&nbsp;</td>"; } echo "</tr>\r\n"; } ?> </table> <p style="color: red; width: 800px; text-align: left; font-size: 22px; "> <strong> Chaque lutteur est responsable de son inscription.<br/> Il a la responsabilité d'appeler la personne responsable de la fête en cas d'empêchement ( au plus tard le vendredi avant la fête ).<br/> Toute amende en cas de non présence à la fête lui sera factureé CHF 100.- !!! </br> </strong> </p> </center> </body> </html> <file_sep>/clubluttefete2014.php <html> <head> <title>Fêtes de luttes 2014 - Actifs </title> <meta charset="utf-8" /> </head> <body> <?php $lutteurs =array( array( "Responsable", " de la Fête", "jeune" ), array( "Responsable", "du Club", "jeune" ), array( "Transport", "", "" ), array( "Balmat", "Lucien", "actif" ), array( "Chatagny" , "Michaël" , "actif+jeune") , array( "Felder" , "Flavian", "actif" ), array( "Felder" , "Joris" , "actif" ), array( "Glauser" , "Thomas", "actif" ), array( "Grandjean", "Xavier" , "actif+jeune" ), /*array( "Jacquat" , "Alain", "actif" ),*/ array( "Pittet" , "Guillaume" , "actif" ) , array( "Tenthorey" , "Matthieu", "actif" ) , array( "<NAME>", "Jean" , "actif") , array( "Wenger" , "Killian" , "actif+jeune" ) , ); $fetes2014 = array( /*array( "Dim 16 fev" , "Lausanne" , "régionale" ),*/ array( "Sam 26 avril", "Villarlod" , "démonstration<br/><font style=\"color:red;\">obligatoire</font>" ) , array( "Dim 27 avril", "Estavayer-le-Gibloux", "régionale" ), array( "Dim 11 mai", "Ried" , "régionale" ), array( "Dim 25 mai", "Le Locle", "cantonale NE"), array( "Jeu 29 mai" , "Le Mouret", "régionale (90)"), array( "Dim 15 juin" , "Mont-sur-Rolle" , "régionale"), array( "Dim 6 juillet" , "<NAME>", "cantonale VS" ), array( "Dim 13 juillet", "St.-Germain", "romande") , array( "Sam 19 juillet", "Riaz", "régionale (90)") , array( "Dim 27 juillet", "Lac des joncs", "alpestre"), array( "Dim 10 août" , "Boveresse", "régionale non-cour.") , array( "Dim 24 août" , "Estavayer-le-Lac" , "cantonale FR" ) , array( "Dim 31 août" , "Aubonne", "cantonale VD") , ); ?> <center> <h1> Liste pour les fêtes de lutte - Saison 2014 - <i> actifs</i> </h1> <!-- <p style="width:800px; text-align: left">Dans le tableau ci-dessous : <br/>faites un "X" pour indiquer votre participation à la fêtre <br/>ou bien un "T" pour indiquer que vous serez motorisé. </p> --> <table border="0" style="border:1px solid black; border-collapse: collapse; font-size: 13px;"> <thead style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: black;"> <tr> <td style="border-right-width: 1px; border-right-style: solid; border-right-color: black;"> </td> <?php foreach( $lutteurs as $val ) { echo "<td style=\"-webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); height: 80px; width:60px; border-right-width: 1px; border-right-style: solid; border-right-color: black;\"><strong>" . $val[0] . "</strong><br/>" . $val[1] . "</td>\r\n"; } ?> </tr> </thead> <?php foreach($fetes2014 as $val) { echo "<tr style=\"border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: black;\">\r\n"; echo "<td style=\"border-right-width: 1px; border-right-style: solid; border-right-color: black;\">\r\n"; echo $val[0] ; echo "<br/>"; echo $val[1]; echo "<br/>"; echo "<i>" . $val[2] . "</i>"; echo "</td>\r\n"; foreach( $lutteurs as $val ) { echo "<td style=\"border-right-width: 1px; border-right-style: solid; border-right-color: black; text-align: center;\">&nbsp;</td>"; } echo "</tr>\r\n"; } ?> </table> <ul style="width: 800px; text-align: left;"> <li>Lun 9 juin : fête alpestre du Stoss : 10 sélectionnés</li> <li>Dim 22 juin : fête alpestre au Lac-Noir : 40 sélectionnés</li> <li>Dim 7 sept : fête alpestre au Kilchberg(ZH) : 4 sélectionnés</li> <li>Sam 13 sept : fête alpestre St-Nicolas à Gornergrat</li> </ul> <p style="color: red; width: 800px; text-align: left; font-size: 22px; "> <strong> Chaque lutteur est responsable de son inscription.<br/> Il a la responsabilité d'appeler la personne responsable de la fête en cas d'empêchement ( au plus tard le vendredi avant la fête ).<br/> Toute amende en cas de non présence à la fête lui sera factureé CHF 100.- !!! </br> </strong> </p> </center> </body> </html>
a7f9752bc26d06c0a4af9ee54c5df3fe513ee4ea
[ "PHP" ]
2
PHP
tservi/clubluttecottens2014
e8954044ad087ab3d7debfaba76125e93c0b214f
6b122d04aea503bd25e0795fbf8f4ba698c62575
refs/heads/main
<repo_name>NYCPlanning/td-tdm<file_sep>/safegraph.py import s3fs import pandas as pd import numpy as np import sqlalchemy as sal import geopandas as gpd import shapely import json pd.set_option('display.max_columns', None) df=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SAFEGRAPH/20190809.csv',dtype=str,converters={'D20190809':float}) df=df[np.logical_or([x[0:5] in ['36005','36047','36061','36081','36085'] for x in df['origin']], [x[0:5] in ['36005','36047','36061','36081','36085'] for x in df['destination']])].reset_index(drop=True) df=df.sort_values('D20190809',ascending=False).reset_index(drop=True) nta=gpd.read_file('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/ntaclippedadj.shp') nta.crs=4326 <file_sep>/pums.py import pandas as pd import numpy as np pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' bpm=['36005','36047','36061','36081','36085','36059','36103','36119','36087','36079','36071','36027', '09001','09009','34017','34003','34031','34013','34039','34027','34035','34023','34025','34029', '34037','34041','34019','34021'] geoxwalk=pd.read_csv(path+'POP/GEOIDCROSSWALK.csv',dtype=str) # Clean up PUMS Household pumshh=[] for i in ['09','34','36']: pumshh+=[pd.read_csv(path+'PUMS/psam_h'+i+'.csv',dtype=str)] pumshh=pd.concat(pumshh,axis=0,ignore_index=True) pumshh['HHID']=pumshh['SERIALNO'].copy() pumshh['PUMA']=pumshh['ST']+pumshh['PUMA'] pumshh=pd.merge(pumshh,geoxwalk[['PUMA2010','StateCounty']].drop_duplicates(keep='first'),how='left',left_on='PUMA',right_on='PUMA2010') pumshh=pumshh[np.isin(pumshh['StateCounty'],bpm)].reset_index(drop=True) pumshhgq=pumshh.loc[pumshh['TYPE']!='1',['HHID','PUMA']].reset_index(drop=True) pumshhgq=pumshhgq.drop_duplicates(keep='first').reset_index(drop=True) pumshhgq.to_csv(path+'PUMS/pumshhgq.csv',index=False) pumshh=pumshh[pumshh['TYPE']=='1'].reset_index(drop=True) pumshh['HHSIZE']=np.where(pumshh['NP']=='0','VAC', np.where(pumshh['NP']=='1','SIZE1', np.where(pumshh['NP']=='2','SIZE2', np.where(pumshh['NP']=='3','SIZE3','SIZE4')))) pumshh['HHTYPE']=np.where(pumshh['NP']=='0','VAC', np.where(pumshh['HHT2']=='02','TYPE1', np.where(pumshh['HHT2']=='04','TYPE1', np.where(pumshh['HHT2']=='01','TYPE2', np.where(pumshh['HHT2']=='03','TYPE2', np.where(pumshh['HHT2']=='05','TYPE3', np.where(pumshh['HHT2']=='09','TYPE3', np.where(pumshh['HHT2']=='06','TYPE4', np.where(pumshh['HHT2']=='10','TYPE4','TYPE5'))))))))) pumshh['HHINC']=pd.to_numeric(pumshh['HINCP']) pumshh['HHINC']=np.where(pumshh['NP']=='0','VAC', np.where(pumshh['HHINC']<5000,'INC01', np.where(pumshh['HHINC']<10000,'INC02', np.where(pumshh['HHINC']<15000,'INC03', np.where(pumshh['HHINC']<20000,'INC04', np.where(pumshh['HHINC']<25000,'INC05', np.where(pumshh['HHINC']<35000,'INC06', np.where(pumshh['HHINC']<50000,'INC07', np.where(pumshh['HHINC']<75000,'INC08', np.where(pumshh['HHINC']<100000,'INC09', np.where(pumshh['HHINC']<150000,'INC10','INC11'))))))))))) pumshh['HHTEN']=np.where(pumshh['NP']=='0','VAC', np.where(pumshh['TEN']=='3','RENTER','OWNER')) pumshh['HHSTR']=np.where(pumshh['NP']=='0','VAC', np.where(pumshh['BLD']=='02','STR1D', np.where(pumshh['BLD']=='03','STR1A', np.where(pumshh['BLD']=='04','STR2', np.where(pumshh['BLD']=='05','STR34', np.where(pumshh['BLD']=='06','STR59', np.where(pumshh['BLD']=='07','STR10', np.where(pumshh['BLD']=='08','STR10', np.where(pumshh['BLD']=='09','STR10','STRO'))))))))) pumshh['HHBLT']=np.where(pumshh['YBL']=='01','B39', np.where(pumshh['YBL']=='02','B40', np.where(pumshh['YBL']=='03','B50', np.where(pumshh['YBL']=='04','B60', np.where(pumshh['YBL']=='05','B70', np.where(pumshh['YBL']=='06','B80', np.where(pumshh['YBL']=='07','B90', np.where(pumshh['YBL']=='08','B00', np.where(pumshh['YBL']=='09','B00', np.where(pumshh['YBL']=='10','B00', np.where(pumshh['YBL']=='11','B00', np.where(pumshh['YBL']=='12','B00', np.where(pumshh['YBL']=='13','B00', np.where(pumshh['YBL']=='14','B10', np.where(pumshh['YBL']=='15','B10', np.where(pumshh['YBL']=='16','B10', np.where(pumshh['YBL']=='17','B10','B14'))))))))))))))))) pumshh['HHBED']=np.where(pumshh['BDSP']=='0','BED0', np.where(pumshh['BDSP']=='1','BED1', np.where(pumshh['BDSP']=='2','BED2', np.where(pumshh['BDSP']=='3','BED3', np.where(pumshh['BDSP']=='4','BED4','BED5'))))) pumshh['HHVEH']=np.where(pumshh['NP']=='0','VAC', np.where(pumshh['VEH']=='0','VEH0', np.where(pumshh['VEH']=='1','VEH1', np.where(pumshh['VEH']=='2','VEH2', np.where(pumshh['VEH']=='3','VEH3','VEH4'))))) pumshh=pumshh[['HHID','PUMA','WGTP','HHSIZE','HHTYPE','HHINC','HHTEN','HHSTR','HHBLT','HHBED','HHVEH']].reset_index(drop=True) pumshh=pumshh.drop_duplicates(keep='first').reset_index(drop=True) pumshh.to_csv(path+'PUMS/pumshh.csv',index=False) # Clean up PUMS Person pumspp=[] for i in ['09','34','36']: pumspp+=[pd.read_csv(path+'PUMS/psam_p'+i+'.csv',dtype=str)] pumspp=pd.concat(pumspp,axis=0,ignore_index=True) pumspp['PPID']=pumspp['SERIALNO']+'|'+pumspp['SPORDER'] pumspp['HHID']=pumspp['SERIALNO'].copy() pumspp['PUMA']=pumspp['ST']+pumspp['PUMA'] pumspp=pd.merge(pumspp,geoxwalk[['PUMA2010','StateCounty']].drop_duplicates(keep='first'),how='left',left_on='PUMA',right_on='PUMA2010') pumspp=pumspp[np.isin(pumspp['StateCounty'],bpm)].reset_index(drop=True) pumspp['POWPUMA']=np.where(pd.isna(pumspp['POWPUMA']),'',pumspp['POWSP']+pumspp['POWPUMA']) pumspp['POWPUMA']=[str(x)[1:] for x in pumspp['POWPUMA']] pumspp['POWPUMA']=np.where(pumspp['POWPUMA']=='','NW',pumspp['POWPUMA']) pumspp['PPSEX']=np.where(pumspp['SEX']=='1','MALE','FEMALE') pumspp['AGEP']=pd.to_numeric(pumspp['AGEP']) pumspp['PPAGE']=np.where(pumspp['AGEP']<=5,'AGE01', np.where(pumspp['AGEP']<=9,'AGE02', np.where(pumspp['AGEP']<=14,'AGE03', np.where(pumspp['AGEP']<=19,'AGE04', np.where(pumspp['AGEP']<=24,'AGE05', np.where(pumspp['AGEP']<=29,'AGE06', np.where(pumspp['AGEP']<=34,'AGE07', np.where(pumspp['AGEP']<=39,'AGE08', np.where(pumspp['AGEP']<=44,'AGE09', np.where(pumspp['AGEP']<=49,'AGE10', np.where(pumspp['AGEP']<=54,'AGE11', np.where(pumspp['AGEP']<=59,'AGE12', np.where(pumspp['AGEP']<=64,'AGE13', np.where(pumspp['AGEP']<=69,'AGE14', np.where(pumspp['AGEP']<=74,'AGE15', np.where(pumspp['AGEP']<=79,'AGE16', np.where(pumspp['AGEP']<=84,'AGE17','AGE18'))))))))))))))))) pumspp['PPRACE']=np.where(pumspp['HISP']!='01','HSP', np.where(pumspp['RAC1P']=='1','WHT', np.where(pumspp['RAC1P']=='2','BLK', np.where(pumspp['RAC1P']=='3','NTV', np.where(pumspp['RAC1P']=='4','NTV', np.where(pumspp['RAC1P']=='5','NTV', np.where(pumspp['RAC1P']=='6','ASN', np.where(pumspp['RAC1P']=='7','PCF', np.where(pumspp['RAC1P']=='8','OTH', np.where(pumspp['RAC1P']=='9','TWO','OT')))))))))) pumspp['PPEDU']=np.where(pumspp['AGEP']<18,'U18', np.where((pumspp['AGEP']<=24)&(np.isin(pumspp['SCHL'],['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15'])),'U24LH', np.where((pumspp['AGEP']<=24)&(np.isin(pumspp['SCHL'],['16','17'])),'U24HS', np.where((pumspp['AGEP']<=24)&(np.isin(pumspp['SCHL'],['18','19','20'])),'U24AD', np.where((pumspp['AGEP']<=24)&(np.isin(pumspp['SCHL'],['21','22','23','24'])),'U24BD', np.where((pumspp['AGEP']>=25)&(np.isin(pumspp['SCHL'],['01','02','03','04','05','06','07','08','09','10','11'])),'O25G9', np.where((pumspp['AGEP']>=25)&(np.isin(pumspp['SCHL'],['12','13','14','15'])),'O25LH', np.where((pumspp['AGEP']>=25)&(np.isin(pumspp['SCHL'],['16','17'])),'O25HS', np.where((pumspp['AGEP']>=25)&(np.isin(pumspp['SCHL'],['18','19'])),'O25SC', np.where((pumspp['AGEP']>=25)&(np.isin(pumspp['SCHL'],['20'])),'O25AD', np.where((pumspp['AGEP']>=25)&(np.isin(pumspp['SCHL'],['21'])),'O25BD', np.where((pumspp['AGEP']>=25)&(np.isin(pumspp['SCHL'],['22','23','24'])),'O25GD','OT')))))))))))) pumspp['PPSCH']=np.where(pumspp['SCHG']=='01','PR', np.where(pumspp['SCHG']=='02','KG', np.where(pumspp['SCHG']=='03','G14', np.where(pumspp['SCHG']=='04','G14', np.where(pumspp['SCHG']=='05','G14', np.where(pumspp['SCHG']=='06','G14', np.where(pumspp['SCHG']=='07','G58', np.where(pumspp['SCHG']=='08','G58', np.where(pumspp['SCHG']=='09','G58', np.where(pumspp['SCHG']=='10','G58', np.where(pumspp['SCHG']=='11','HS', np.where(pumspp['SCHG']=='12','HS', np.where(pumspp['SCHG']=='13','HS', np.where(pumspp['SCHG']=='14','HS', np.where(pumspp['SCHG']=='15','CL', np.where(pumspp['SCHG']=='16','GS','NS')))))))))))))))) pumspp['NAICS']=[str(x)[:2] for x in pumspp['NAICSP']] pumspp['PPIND']=np.where(pumspp['AGEP']<16,'U16', np.where(pumspp['ESR']=='6','NLF', np.where(pumspp['ESR']=='6','NLF', np.where(pumspp['ESR']=='4','MIL', np.where(pumspp['ESR']=='5','MIL', np.where(pumspp['ESR']=='3','CUP', np.where(pumspp['NAICS']=='11','AGR', np.where(pumspp['NAICS']=='21','EXT', np.where(pumspp['NAICS']=='23','CON', np.where(pumspp['NAICS']=='31','MFG', np.where(pumspp['NAICS']=='32','MFG', np.where(pumspp['NAICS']=='33','MFG', np.where(pumspp['NAICS']=='3M','MFG', np.where(pumspp['NAICS']=='42','WHL', np.where(pumspp['NAICS']=='44','RET', np.where(pumspp['NAICS']=='45','RET', np.where(pumspp['NAICS']=='4M','RET', np.where(pumspp['NAICS']=='48','TRN', np.where(pumspp['NAICS']=='49','TRN', np.where(pumspp['NAICS']=='22','UTL', np.where(pumspp['NAICS']=='51','INF', np.where(pumspp['NAICS']=='52','FIN', np.where(pumspp['NAICS']=='53','RER', np.where(pumspp['NAICS']=='54','PRF', np.where(pumspp['NAICS']=='55','MNG', np.where(pumspp['NAICS']=='56','WMS', np.where(pumspp['NAICS']=='61','EDU', np.where(pumspp['NAICS']=='62','MED', np.where(pumspp['NAICS']=='71','ENT', np.where(pumspp['NAICS']=='72','ACC', np.where(pumspp['NAICS']=='81','SRV', np.where(pumspp['NAICS']=='92','ADM','OTH')))))))))))))))))))))))))))))))) pumspp['PPMODE']=np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='1'),'DA', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='2'),'CP2', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='3'),'CP3', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='4'),'CP4', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='5'),'CP56', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='6'),'CP56', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='7'),'CP7', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='8'),'CP7', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='9'),'CP7', np.where((pumspp['JWTRNS']=='01')&(pumspp['JWRIP']=='10'),'CP7', np.where(pumspp['JWTRNS']=='02','BS', np.where(pumspp['JWTRNS']=='03','SW', np.where(pumspp['JWTRNS']=='04','CR', np.where(pumspp['JWTRNS']=='05','LR', np.where(pumspp['JWTRNS']=='06','FB', np.where(pumspp['JWTRNS']=='07','TC', np.where(pumspp['JWTRNS']=='08','MC', np.where(pumspp['JWTRNS']=='09','BC', np.where(pumspp['JWTRNS']=='10','WK', np.where(pumspp['JWTRNS']=='11','HM', np.where(pumspp['JWTRNS']=='12','OT','NW'))))))))))))))))))))) pumspp['JWMNP']=pd.to_numeric(pumspp['JWMNP']) pumspp['PPTIME']=np.where(pd.isna(pumspp['JWMNP']),'NWHM', np.where(pumspp['JWMNP']<5,'TM01', np.where(pumspp['JWMNP']<10,'TM02', np.where(pumspp['JWMNP']<15,'TM03', np.where(pumspp['JWMNP']<20,'TM04', np.where(pumspp['JWMNP']<25,'TM05', np.where(pumspp['JWMNP']<30,'TM06', np.where(pumspp['JWMNP']<35,'TM07', np.where(pumspp['JWMNP']<40,'TM08', np.where(pumspp['JWMNP']<45,'TM09', np.where(pumspp['JWMNP']<60,'TM10', np.where(pumspp['JWMNP']<90,'TM11','TM12')))))))))))) pumspp['JWDP']=pd.to_numeric(pumspp['JWDP']) pumspp['PPDEPART']=np.where(pd.isna(pumspp['JWDP']),'NWHM', np.where(pumspp['JWDP']<=18,'DP01', np.where(pumspp['JWDP']<=24,'DP02', np.where(pumspp['JWDP']<=30,'DP03', np.where(pumspp['JWDP']<=36,'DP04', np.where(pumspp['JWDP']<=42,'DP05', np.where(pumspp['JWDP']<=48,'DP06', np.where(pumspp['JWDP']<=54,'DP07', np.where(pumspp['JWDP']<=60,'DP08', np.where(pumspp['JWDP']<=66,'DP09', np.where(pumspp['JWDP']<=78,'DP10', np.where(pumspp['JWDP']<=84,'DP11', np.where(pumspp['JWDP']<=90,'DP12', np.where(pumspp['JWDP']<=114,'DP13', np.where(pumspp['JWDP']<=150,'DP14','OTH'))))))))))))))) pumsppgq=pumspp[np.isin(pumspp['RELSHIPP'],['37','38'])].reset_index(drop=True) pumsppgq=pumsppgq[['PPID','HHID','PUMA','POWPUMA','PWGTP','PPSEX','PPAGE','PPRACE','PPEDU','PPSCH', 'PPIND','PPMODE','PPTIME','PPDEPART']].reset_index(drop=True) pumsppgq=pumsppgq.drop_duplicates(keep='first').reset_index(drop=True) pumsppgq.to_csv(path+'PUMS/pumsppgq.csv',index=False) pumspp=pumspp[~np.isin(pumspp['RELSHIPP'],['37','38'])].reset_index(drop=True) pumspp=pumspp[['PPID','HHID','PUMA','POWPUMA','PWGTP','PPSEX','PPAGE','PPRACE','PPEDU','PPSCH', 'PPIND','PPMODE','PPTIME','PPDEPART']].reset_index(drop=True) pumspp=pumspp.drop_duplicates(keep='first').reset_index(drop=True) pumspp.to_csv(path+'PUMS/pumspp.csv',index=False) <file_sep>/fhv.py import urllib.request import shutil import os import pandas as pd import numpy as np import datetime import pytz import geopandas as gpd import shapely pd.set_option('display.max_columns', None) pu=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/FHV/weekdaypunta.csv') d=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/FHV/days.csv') d=len(d) nta=gpd.read_file('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/ntaclippedadj.shp') nta.crs=4326 pu=pd.merge(nta,pu,how='inner',left_on='NTACode',right_on='puntaid') pu['trip']=pu['trip']/d pu.to_file('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/FHV/weekdaypunta.shp') do=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/FHV/weekdaydonta.csv') d=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/FHV/days.csv') d=len(d) nta=gpd.read_file('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/ntaclippedadj.shp') nta.crs=4326 do=pd.merge(nta,do,how='inner',left_on='NTACode',right_on='dontaid') do['trip']=do['trip']/d do.to_file('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/FHV/weekdaydonta.shp') <file_sep>/ipf.py import ipfn import pandas as pd import numpy as np import sklearn.linear_model import statsmodels.api as sm import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' pio.renderers.default='browser' bpm=['36005','36047','36061','36081','36085','36059','36103','36119','36087','36079','36071','36027', '09001','09009','34017','34003','34031','34013','34039','34027','34035','34023','34025','34029', '34037','34041','34019','34021'] geoxwalk=pd.read_csv(path+'POP/GEOIDCROSSWALK.csv',dtype=str) bpmpuma=geoxwalk.loc[np.isin(geoxwalk['StateCounty'],bpm),'PUMA2010'].unique() bpmct=geoxwalk.loc[np.isin(geoxwalk['StateCounty'],bpm),'CensusTract2010'].unique() # IPF pumshh=pd.read_csv(path+'PUMS/pumshh.csv',dtype=str,converters={'WGTP':float}) pumsppgq=pd.read_csv(path+'PUMS/pumsppgq.csv',dtype=str,converters={'PWGTP':float}) pumsppgq=pumsppgq.groupby(['HHID','PUMA'],as_index=False).agg({'PWGTP':'sum'}).reset_index(drop=True) # i='3603903' 142 for i in bpmpuma: ct=geoxwalk.loc[geoxwalk['PUMA2010']==i,'CensusTract2010'].unique() # ct=ct[ct!='36085008900'] # Households tphh=pumshh[pumshh['PUMA']==i].reset_index(drop=True) tphh=pd.DataFrame(ipfn.ipfn.product(tphh['HHID'].unique(),ct),columns=['HHID','CT']) tphh=pd.merge(tphh,pumshh[['HHID','HHINC']],how='left',on='HHID') tphh['TOTAL']=1 hhwt=pumshh[['HHID','WGTP']].reset_index(drop=True) hhwt['WGTP']=pd.to_numeric(hhwt['WGTP']) hhwt=hhwt.set_index(['HHID']) hhwt=hhwt.iloc[:,0] cthhinc=pd.read_csv(path+'ACS/hhinc.csv',dtype=float,converters={'CT':str}) cthhinc=cthhinc.loc[np.isin(cthhinc['CT'],ct),['CT','VAC','INC01','INC02','INC03','INC04','INC05', 'INC06','INC07','INC08','INC09','INC10','INC11']].reset_index(drop=True) cthhinc=cthhinc.melt(id_vars=['CT'],value_vars=['VAC','INC01','INC02','INC03','INC04','INC05','INC06', 'INC07','INC08','INC09','INC10','INC11'],var_name='HHINC',value_name='TOTAL') cthhinc=cthhinc.set_index(['CT','HHINC']) cthhinc=cthhinc.iloc[:,0] aggregates=[hhwt,cthhinc] dimensions=[['HHID'],['CT','HHINC']] tphh=ipfn.ipfn.ipfn(tphh,aggregates,dimensions,weight_col='TOTAL',max_iteration=1000000).iteration() # tphh['TOTAL']=[round(x) for x in tphh['TOTAL']] tphh.to_csv(path+'POP/tphh/'+i+'.csv',index=False) # Group Quarter tpgq=pumsppgq[pumsppgq['PUMA']==i].reset_index(drop=True) tpgq=pd.DataFrame(ipfn.ipfn.product(tpgq['HHID'].unique(),ct),columns=['HHID','CT']) tpgq['TOTAL']=1 gqwt=pumsppgq[['HHID','PWGTP']].reset_index(drop=True) gqwt['PWGTP']=pd.to_numeric(gqwt['PWGTP']) gqwt=gqwt.set_index(['HHID']) gqwt=gqwt.iloc[:,0] gqtt=pd.read_csv(path+'ACS/gqtt.csv',dtype=float,converters={'CT':str}) gqtt=gqtt.loc[np.isin(gqtt['CT'],ct),['CT','GQTT']].reset_index(drop=True) gqtt=gqtt.set_index(['CT']) gqtt=gqtt.iloc[:,0] aggregates=[gqwt,gqtt] dimensions=[['HHID'],['CT']] tpgq=ipfn.ipfn.ipfn(tpgq,aggregates,dimensions,weight_col='TOTAL',max_iteration=1000000).iteration() # tpgq['TOTAL']=[round(x) for x in tpgq['TOTAL']] tpgq.to_csv(path+'POP/tpgq/'+i+'.csv',index=False) dfhh=[] for i in bpmpuma: tphh=pd.read_csv(path+'POP/tphh/'+i+'.csv',dtype=str,converters={'TOTAL':float}) dfhh+=[tphh] dfhh=pd.concat(dfhh,axis=0,ignore_index=True) # dfhh=dfhh.loc[dfhh['TOTAL']!=0,['HHID','CT','HHINC','TOTAL']].reset_index(drop=True) dfhh['HHGQ']='HH' dfhh=dfhh.drop_duplicates(keep='first').reset_index(drop=True) dfhh=dfhh[['HHID','CT','HHGQ','HHINC','TOTAL']].reset_index(drop=True) dfhh.to_csv(path+'POP/dfhh.csv',index=False) dfhhgq=[] for i in bpmpuma: tpgq=pd.read_csv(path+'POP/tpgq/'+i+'.csv',dtype=str,converters={'TOTAL':float}) dfhhgq+=[tpgq] dfhhgq=pd.concat(dfhhgq,axis=0,ignore_index=True) # dfhhgq=dfhhgq.loc[dfhhgq['TOTAL']!=0,['HHID','CT','TOTAL']].reset_index(drop=True) dfhhgq['HHGQ']='GQ' dfhhgq=dfhhgq.drop_duplicates(keep='first').reset_index(drop=True) dfhhgq=dfhhgq[['HHID','CT','HHGQ','TOTAL']].reset_index(drop=True) dfhhgq.to_csv(path+'POP/dfhhgq.csv',index=False) pumspp=pd.read_csv(path+'PUMS/pumspp.csv',dtype=str,converters={'PWGTP':float}) dfpphh=pd.merge(pumspp,dfhh[['HHID','CT','HHGQ','TOTAL']],how='inner',on=['HHID']) dfpphh=pd.merge(dfpphh,pumshh,how='inner',on=['HHID','PUMA']) dfpphh=dfpphh[['PPID','HHID','PUMA','CT','POWPUMA','HHGQ','HHSIZE','HHTYPE','HHINC','HHTEN','HHSTR', 'HHBLT','HHBED','HHVEH','PPSEX','PPAGE','PPRACE','PPEDU','PPSCH','PPIND','PPMODE', 'PPTIME','PPDEPART','TOTAL']].reset_index(drop=True) pumsppgq=pd.read_csv(path+'PUMS/pumsppgq.csv',dtype=str,converters={'PWGTP':float}) dfppgq=pd.merge(pumsppgq,dfhhgq[['HHID','CT','HHGQ','TOTAL']],how='inner',on=['HHID']) dfppgq=dfppgq[['PPID','HHID','PUMA','CT','POWPUMA','HHGQ','PPSEX','PPAGE','PPRACE','PPEDU','PPSCH', 'PPIND','PPMODE','PPTIME','PPDEPART','TOTAL']].reset_index(drop=True) dfpp=pd.concat([dfpphh,dfppgq],axis=0,ignore_index=True) dfpp=dfpp.fillna('GQ') dfpp.to_csv(path+'POP/dfpp.csv',index=False) # Validation val=pd.DataFrame(columns=['FIELD','ACCURACY','RMSE']) val['FIELD']=['HHID','HHTT','HHOCC','HHSIZE','HHTYPE','HHINC','HHTEN','HHSTR','HHBLT','HHBED', 'HHVEH','HHGQ','GQTT','PPID','PPTT','PPSEX','PPAGE','PPRACE','PPEDU','PPSCH','PPIND', 'PPMODE','PPTIME','PPDEPART'] # Check Household pumshh=pd.read_csv(path+'PUMS/pumshh.csv',dtype=str,converters={'WGTP':float}) dfhh=pd.read_csv(path+'POP/dfhh.csv',dtype=str,converters={'TOTAL':float}) # Check HHID Weight Sum k=pd.merge(dfhh.groupby(['HHID']).agg({'TOTAL':'sum'}),pumshh[['HHID','WGTP']],how='inner',on='HHID') k['HOVER']='HHID: '+k['HHID']+'<br>'+'MODEL: '+k['TOTAL'].astype(int).astype(str)+'<br>'+'PUMS: '+k['WGTP'].astype(int).astype(str) acc=np.nan rmse=np.sqrt(sum((k['TOTAL']-k['WGTP'])**2)/len(k)) val.loc[val['FIELD']=='HHID','ACCURACY']=acc val.loc[val['FIELD']=='HHID','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='PUMS vs MODEL', x=k['TOTAL'], y=k['WGTP'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL'])], y=[0,max(k['TOTAL'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHID WEIGHT SUM (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'PUMS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhidpt.html',include_plotlyjs='cdn') # Check HHTT k=pd.read_csv(path+'ACS/hhtt.csv',dtype=float,converters={'CT':str}) k.columns=['CT','TOTAL','MOE'] k=pd.merge(dfhh.groupby(['CT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHTT','ACCURACY']=acc val.loc[val['FIELD']=='HHTT','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHTT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhttpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHTT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhttci.html',include_plotlyjs='cdn') # Check HHOCC tptest=dfhh.copy() tptest['HHOCC']=np.where(tptest['HHINC']=='VAC','VAC','OCC') k=pd.read_csv(path+'ACS/hhocc.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','OCC','OCCM'],var_name='HHOCC',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHOCC'],['VAC','OCC'])], k[np.isin(k['HHOCC'],['VACM','OCCM'])],how='inner',on='CT') k=k[(k['HHOCC_x']+'M')==k['HHOCC_y']].reset_index(drop=True) k=k[['CT','HHOCC_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHOCC','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHOCC'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHOCC']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHOCC: '+k['HHOCC']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHOCC','ACCURACY']=acc val.loc[val['FIELD']=='HHOCC','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHOCC (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhoccpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHOCC (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhoccci.html',include_plotlyjs='cdn') # Check HHSIZE tptest=pd.merge(dfhh,pumshh[['HHID','HHSIZE']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhsize.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','SIZE1','SIZE1M','SIZE2','SIZE2M','SIZE3','SIZE3M', 'SIZE4','SIZE4M'],var_name='HHSIZE',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHSIZE'],['VAC','SIZE1','SIZE2','SIZE3','SIZE4'])], k[np.isin(k['HHSIZE'],['VACM','SIZE1M','SIZE2M','SIZE3M','SIZE4M'])],how='inner',on='CT') k=k[(k['HHSIZE_x']+'M')==k['HHSIZE_y']].reset_index(drop=True) k=k[['CT','HHSIZE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHSIZE','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHSIZE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHSIZE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHSIZE: '+k['HHSIZE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHSIZE','ACCURACY']=acc val.loc[val['FIELD']=='HHSIZE','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHSIZE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhsizept.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHSIZE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhsizeci.html',include_plotlyjs='cdn') # Check HHTYPE tptest=pd.merge(dfhh,pumshh[['HHID','HHTYPE']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhtype.csv',dtype=float,converters={'CT':str}) k['TYPE1']=k['MC']-k['MCC']+k['CC']-k['CCC'] k['TYPE1M']=np.sqrt(k['MCM']**2+k['MCCM']**2+k['CCM']**2+k['CCCM']**2) k['TYPE2']=k['MCC']+k['CCC'] k['TYPE2M']=np.sqrt(k['MCCM']**2+k['CCCM']**2) k['TYPE3']=k['MHA']+k['FHA'] k['TYPE3M']=np.sqrt(k['MHAM']**2+k['FHAM']**2) k['TYPE4']=k['MHC']+k['FHC'] k['TYPE4M']=np.sqrt(k['MHCM']**2+k['FHCM']**2) k['TYPE5']=k['MH']-k['MHC']-k['MHA']+k['FH']-k['FHC']-k['FHA'] k['TYPE5M']=np.sqrt(k['MHM']**2+k['MHCM']**2+k['MHAM']**2+k['FHM']**2+k['FHCM']**2+k['FHAM']**2) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','TYPE1','TYPE1M','TYPE1','TYPE2M','TYPE3','TYPE3M', 'TYPE4','TYPE4M','TYPE5','TYPE5M'],var_name='HHTYPE',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHTYPE'],['VAC','TYPE1','TYPE2','TYPE3','TYPE4','TYPE5'])], k[np.isin(k['HHTYPE'],['VACM','TYPE1M','TYPE2M','TYPE3M','TYPE4M','TYPE5M'])],how='inner',on='CT') k=k[(k['HHTYPE_x']+'M')==k['HHTYPE_y']].reset_index(drop=True) k=k[['CT','HHTYPE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHTYPE','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHTYPE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHTYPE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHTYPE: '+k['HHTYPE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHTYPE','ACCURACY']=acc val.loc[val['FIELD']=='HHTYPE','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHTYPE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhtypept.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHTYPE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhtypeci.html',include_plotlyjs='cdn') # Check HHINC k=pd.read_csv(path+'ACS/hhinc.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','INC01','INC01M','INC02','INC02M','INC03','INC03M', 'INC04','INC04M','INC05','INC05M','INC06','INC06M','INC07','INC07M', 'INC08','INC08M','INC09','INC09M','INC10','INC10M', 'INC11','INC11M'],var_name='HHINC',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHINC'],['VAC','INC01','INC02','INC03','INC04','INC05','INC06','INC07','INC08','INC09','INC10','INC11'])], k[np.isin(k['HHINC'],['VACM','INC01M','INC02M','INC03M','INC04M','INC05M','INC06M','INC07M','INC08M','INC09M','INC10M','INC11M'])],how='inner',on='CT') k=k[(k['HHINC_x']+'M')==k['HHINC_y']].reset_index(drop=True) k=k[['CT','HHINC_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHINC','TOTAL','MOE'] k=pd.merge(dfhh.groupby(['CT','HHINC'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHINC']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHINC: '+k['HHINC']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHINC','ACCURACY']=acc val.loc[val['FIELD']=='HHINC','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHINC (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhincpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHINC (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhincci.html',include_plotlyjs='cdn') # Check HHTEN tptest=pd.merge(dfhh,pumshh[['HHID','HHTEN']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhten.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','OWNER','OWNERM','RENTER','RENTERM'],var_name='HHTEN',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHTEN'],['VAC','OWNER','RENTER'])], k[np.isin(k['HHTEN'],['VACM','OWNERM','RENTERM'])],how='inner',on='CT') k=k[(k['HHTEN_x']+'M')==k['HHTEN_y']].reset_index(drop=True) k=k[['CT','HHTEN_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHTEN','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHTEN'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHTEN']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHTEN: '+k['HHTEN']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHTEN','ACCURACY']=acc val.loc[val['FIELD']=='HHTEN','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHTEN (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhtenpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHTEN (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhtenci.html',include_plotlyjs='cdn') # Check HHSTR tptest=pd.merge(dfhh,pumshh[['HHID','HHSTR']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhstr.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','STR1D','STR1DM','STR1A','STR1AM','STR2','STR2M', 'STR34','STR34M','STR59','STR59M','STR10','STR10M', 'STRO','STROM'],var_name='HHSTR',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHSTR'],['VAC','STR1D','STR1A','STR2','STR34','STR59','STR10','STRO'])], k[np.isin(k['HHSTR'],['VACM','STR1DM','STR1AM','STR2M','STR34M','STR59M','STR10M','STROM'])],how='inner',on='CT') k=k[(k['HHSTR_x']+'M')==k['HHSTR_y']].reset_index(drop=True) k=k[['CT','HHSTR_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHSTR','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHSTR'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHSTR']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHSTR: '+k['HHSTR']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHSTR','ACCURACY']=acc val.loc[val['FIELD']=='HHSTR','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHSTR (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhstrpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHSTR (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhstrci.html',include_plotlyjs='cdn') # Check HHBLT tptest=pd.merge(dfhh,pumshh[['HHID','HHBLT']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhblt.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['B14','B14M','B10','B10M','B00','B00M','B90','B90M','B80','B80M', 'B70','B70M','B60','B60M','B50','B50M','B40','B40M','B39','B39M'],var_name='HHBLT',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHBLT'],['B14','B10','B00','B90','B80','B70','B60','B50','B40','B39'])], k[np.isin(k['HHBLT'],['B14M','B10M','B00M','B90M','B80M','B70M','B60M','B50M','B40M','B39M'])],how='inner',on='CT') k=k[(k['HHBLT_x']+'M')==k['HHBLT_y']].reset_index(drop=True) k=k[['CT','HHBLT_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHBLT','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHBLT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHBLT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHBLT: '+k['HHBLT']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHBLT','ACCURACY']=acc val.loc[val['FIELD']=='HHBLT','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHBLT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhbltpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHBLT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhbltci.html',include_plotlyjs='cdn') # Check HHBED tptest=pd.merge(dfhh,pumshh[['HHID','HHBED']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhbed.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['BED0','BED0M','BED1','BED1M','BED2','BED2M','BED3','BED3M', 'BED4','BED4M','BED5','BED5M'],var_name='HHBED',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHBED'],['BED0','BED1','BED2','BED3','BED4','BED5'])], k[np.isin(k['HHBED'],['BED0M','BED1M','BED2M','BED3M','BED4M','BED5M'])],how='inner',on='CT') k=k[(k['HHBED_x']+'M')==k['HHBED_y']].reset_index(drop=True) k=k[['CT','HHBED_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHBED','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHBED'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHBED']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHBED: '+k['HHBED']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHBED','ACCURACY']=acc val.loc[val['FIELD']=='HHBED','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHBED (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhbedpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHBED (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhbedci.html',include_plotlyjs='cdn') # Check HHVEH tptest=pd.merge(dfhh,pumshh[['HHID','HHVEH']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhveh.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','VEH0','VEH0M','VEH1','VEH1M','VEH2','VEH2M', 'VEH3','VEH3M','VEH4','VEH4M'],var_name='HHVEH',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHVEH'],['VAC','VEH0','VEH1','VEH2','VEH3','VEH4'])], k[np.isin(k['HHVEH'],['VACM','VEH0M','VEH1M','VEH2M','VEH3M','VEH4M'])],how='inner',on='CT') k=k[(k['HHVEH_x']+'M')==k['HHVEH_y']].reset_index(drop=True) k=k[['CT','HHVEH_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHVEH','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHVEH'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHVEH']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'HHVEH: '+k['HHVEH']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='HHVEH','ACCURACY']=acc val.loc[val['FIELD']=='HHVEH','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'HHVEH (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhvehpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'HHVEH (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhvehci.html',include_plotlyjs='cdn') # Check Group Quarter pumsppgq=pd.read_csv(path+'PUMS/pumsppgq.csv',dtype=str,converters={'PWGTP':float}) pumsppgq=pumsppgq.groupby(['HHID'],as_index=False).agg({'PWGTP':'sum'}).reset_index(drop=True) dfhhgq=pd.read_csv(path+'POP/dfhhgq.csv',dtype=str,converters={'TOTAL':float}) # Check GQ Weight Sum k=pd.merge(dfhhgq.groupby(['HHID']).agg({'TOTAL':'sum'}),pumsppgq[['HHID','PWGTP']],how='inner',on='HHID') k['HOVER']='HHID: '+k['HHID']+'<br>'+'MODEL: '+k['TOTAL'].astype(int).astype(str)+'<br>'+'PUMS: '+k['PWGTP'].astype(int).astype(str) acc=np.nan rmse=np.sqrt(sum((k['TOTAL']-k['PWGTP'])**2)/len(k)) val.loc[val['FIELD']=='HHGQ','ACCURACY']=acc val.loc[val['FIELD']=='HHGQ','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='PUMS vs MODEL', x=k['TOTAL'], y=k['PWGTP'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL'])], y=[0,max(k['TOTAL'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'GQ WEIGHT SUM (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'PUMS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/hhgqpt.html',include_plotlyjs='cdn') # Check GQTT k=pd.read_csv(path+'ACS/gqtt.csv',dtype=float,converters={'CT':str}) k.columns=['CT','TOTAL','MOE'] k=pd.merge(dfhhgq.groupby(['CT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='GQTT','ACCURACY']=acc val.loc[val['FIELD']=='GQTT','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'GQTT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/gqttpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'GQTT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/gqttci.html',include_plotlyjs='cdn') # Check Person pumspp=pd.read_csv(path+'PUMS/pumspp.csv',dtype=str,converters={'PWGTP':float}) pumsppgq=pd.read_csv(path+'PUMS/pumsppgq.csv',dtype=str,converters={'PWGTP':float}) dfpp=pd.read_csv(path+'POP/dfpp.csv',dtype=str,converters={'PWGTP':float,'TOTAL':float}) # Check PPID Weight Sum k=pd.merge(dfpp.groupby(['PPID']).agg({'TOTAL':'sum'}),pd.concat([pumspp[['PPID','PWGTP']],pumsppgq[['PPID','PWGTP']]]),how='inner',on='PPID') k['HOVER']='PPID: '+k['PPID']+'<br>'+'MODEL: '+k['TOTAL'].astype(int).astype(str)+'<br>'+'PUMS: '+k['PWGTP'].astype(int).astype(str) acc=np.nan rmse=np.sqrt(sum((k['TOTAL']-k['PWGTP'])**2)/len(k)) val.loc[val['FIELD']=='PPID','ACCURACY']=acc val.loc[val['FIELD']=='PPID','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='PUMS vs MODEL', x=k['TOTAL'], y=k['PWGTP'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL'])], y=[0,max(k['TOTAL'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPID WEIGHT SUM (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'PUMS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppidpt.html',include_plotlyjs='cdn') # Check PPTT k=pd.read_csv(path+'ACS/pptt.csv',dtype=float,converters={'CT':str}) k.columns=['CT','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPTT','ACCURACY']=acc val.loc[val['FIELD']=='PPTT','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPTT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppttpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPTT (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppttci.html',include_plotlyjs='cdn') # Check PPSEX k=pd.read_csv(path+'ACS/ppsex.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['MALE','MALEM','FEMALE','FEMALEM'],var_name='PPSEX',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPSEX'],['MALE','FEMALE'])], k[np.isin(k['PPSEX'],['MALEM','FEMALEM'])],how='inner',on='CT') k=k[(k['PPSEX_x']+'M')==k['PPSEX_y']].reset_index(drop=True) k=k[['CT','PPSEX_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPSEX','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPSEX'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPSEX']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPSEX: '+k['PPSEX']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPSEX','ACCURACY']=acc val.loc[val['FIELD']=='PPSEX','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPSEX (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppsexpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPSEX (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppsexci.html',include_plotlyjs='cdn') # Check PPAGE k=pd.read_csv(path+'ACS/ppage.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['AGE01','AGE01M','AGE02','AGE02M','AGE03','AGE03M','AGE04','AGE04M', 'AGE05','AGE05M','AGE06','AGE06M','AGE07','AGE07M','AGE08','AGE08M', 'AGE09','AGE09M','AGE10','AGE10M','AGE11','AGE11M','AGE12','AGE12M', 'AGE13','AGE13M','AGE14','AGE14M','AGE15','AGE15M','AGE16','AGE16M', 'AGE17','AGE17M','AGE18','AGE18M'],var_name='PPAGE',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPAGE'],['AGE01','AGE02','AGE03','AGE04','AGE05','AGE06','AGE07','AGE08', 'AGE09','AGE10','AGE11','AGE12','AGE13','AGE14','AGE15','AGE16', 'AGE17','AGE18'])], k[np.isin(k['PPAGE'],['AGE01M''AGE02M','AGE03M','AGE04M','AGE05M','AGE06M','AGE07M', 'AGE08M','AGE09M','AGE10M','AGE11M','AGE12M','AGE13M','AGE14M', 'AGE15M','AGE16M','AGE17M','AGE18M'])],how='inner',on='CT') k=k[(k['PPAGE_x']+'M')==k['PPAGE_y']].reset_index(drop=True) k=k[['CT','PPAGE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPAGE','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPAGE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPAGE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPAGE: '+k['PPAGE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPAGE','ACCURACY']=acc val.loc[val['FIELD']=='PPAGE','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPAGE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppagept.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPAGE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppageci.html',include_plotlyjs='cdn') # Check PPRACE k=pd.read_csv(path+'ACS/pprace.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['HSP','HSPM','WHT','WHTM','BLK','BLKM','NTV','NTVM','ASN','ASNM', 'PCF','PCFM','OTH','OTHM','TWO','TWOM'],var_name='PPRACE',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPRACE'],['HSP','WHT','BLK','NTV','ASN','PCF','OTH','TWO'])], k[np.isin(k['PPRACE'],['HSPM','WHTM','BLKM','NTVM','ASNM','PCFM','OTHM','TWOM'])],how='inner',on='CT') k=k[(k['PPRACE_x']+'M')==k['PPRACE_y']].reset_index(drop=True) k=k[['CT','PPRACE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPRACE','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPRACE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPRACE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPRACE: '+k['PPRACE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPRACE','ACCURACY']=acc val.loc[val['FIELD']=='PPRACE','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPRACE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppracept.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPRACE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppraceci.html',include_plotlyjs='cdn') # Check PPEDU k=pd.read_csv(path+'ACS/ppedu.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['U18','U18M','U24LH','U24LHM','U24HS','U24HSM','U24AD','U24ADM', 'U24BD','U24BDM','O25G9','O25G9M','O25LH','O25LHM','O25HS','O25HSM', 'O25SC','O25SCM','O25AD','O25ADM','O25BD','O25BDM','O25GD','O25GDM'],var_name='PPEDU',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPEDU'],['U18','U24LH','U24HS','U24AD','U24BD','O25G9','O25LH','O25HS','O25SC', 'O25AD','O25BD','O25GD'])], k[np.isin(k['PPEDU'],['U18M','U24LHM','U24HSM','U24ADM','U24BDM','O25G9M','O25LHM','O25HSM', 'O25SCM','O25ADM','O25BDM','O25GDM'])],how='inner',on='CT') k=k[(k['PPEDU_x']+'M')==k['PPEDU_y']].reset_index(drop=True) k=k[['CT','PPEDU_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPEDU','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPEDU'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPEDU']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPEDU: '+k['PPEDU']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPEDU','ACCURACY']=acc val.loc[val['FIELD']=='PPEDU','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPEDU (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppedupt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPEDU (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppeduci.html',include_plotlyjs='cdn') # Check PPSCH k=pd.read_csv(path+'ACS/ppsch.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['NS','NSM','PR','PRM','KG','KGM','G14','G14M','G58','G58M', 'HS','HSM','CL','CLM','GS','GSM'],var_name='PPSCH',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPSCH'],['NS','PR','KG','G14','G58','HS','CL','GS'])], k[np.isin(k['PPSCH'],['NSM','PRM','KGM','G14M','G58M','HSM','CLM','GSM'])],how='inner',on='CT') k=k[(k['PPSCH_x']+'M')==k['PPSCH_y']].reset_index(drop=True) k=k[['CT','PPSCH_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPSCH','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPSCH'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPSCH']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPSCH: '+k['PPSCH']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPSCH','ACCURACY']=acc val.loc[val['FIELD']=='PPSCH','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPSCH (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppschpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPSCH (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppschci.html',include_plotlyjs='cdn') # Check PPIND k=pd.read_csv(path+'ACS/ppind.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['U16','U16M','AGR','AGRM','EXT','EXTM','CON','CONM','MFG','MFGM', 'WHL','WHLM','RET','RETM','TRN','TRNM','UTL','UTLM','INF','INFM', 'FIN','FINM','RER','RERM','PRF','PRFM','MNG','MNGM','WMS','WMSM', 'EDU','EDUM','MED','MEDM','ENT','ENTM','ACC','ACCM','SRV','SRVM', 'ADM','ADMM','CUP','CUPM','MIL','MILM','NLF','NLFM'],var_name='PPIND',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPIND'],['U16','AGR','EXT','CON','MFG','WHL','RET','TRN','UTL','INF','FIN', 'RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM','CUP', 'MIL','NLF'])], k[np.isin(k['PPIND'],['U16M','AGRM','EXTM','CONM','MFGM','WHLM','RETM','TRNM','UTLM','INFM', 'FINM','RERM','PRFM','MNGM','WMSM','EDUM','MEDM','ENTM','ACCM','SRVM', 'ADMM','CUPM','MILM','NLFM'])],how='inner',on='CT') k=k[(k['PPIND_x']+'M')==k['PPIND_y']].reset_index(drop=True) k=k[['CT','PPIND_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPIND','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPIND'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPIND']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPIND: '+k['PPIND']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPIND','ACCURACY']=acc val.loc[val['FIELD']=='PPIND','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPIND (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppindpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPIND (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppindci.html',include_plotlyjs='cdn') # Check PPMODE k=pd.read_csv(path+'ACS/ppmode.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['NW','NWM','DA','DAM','CP2','CP2M','CP3','CP3M','CP4','CP4M', 'CP56','CP56M','CP7','CP7M','BS','BSM','SW','SWM','CR','CRM', 'LR','LRM','FB','FBM','TC','TCM','MC','MCM','BC','BCM','WK','WKM', 'OT','OTM','HM','HMM'],var_name='PPMODE',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPMODE'],['NW','DA','CP2','CP3','CP4','CP56','CP7','BS','SW','CR','LR','FB', 'TC','MC','BC','WK','OT','HM'])], k[np.isin(k['PPMODE'],['NWM','DAM','CP2M','CP3M','CP4M','CP56M','CP7M','BSM','SWM','CRM', 'LRM','FBM','TCM','MCM','BCM','WKM','OTM','HMM'])],how='inner',on='CT') k=k[(k['PPMODE_x']+'M')==k['PPMODE_y']].reset_index(drop=True) k=k[['CT','PPMODE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPMODE','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPMODE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPMODE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPMODE: '+k['PPMODE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPMODE','ACCURACY']=acc val.loc[val['FIELD']=='PPMODE','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPMODE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppmodept.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPMODE (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppmodeci.html',include_plotlyjs='cdn') # Check PPTIME k=pd.read_csv(path+'ACS/pptime.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['NWHM','NWHMM','TM01','TM01M','TM02','TM02M','TM03','TM03M', 'TM04','TM04M','TM05','TM05M','TM06','TM06M','TM07','TM07M', 'TM08','TM08M','TM09','TM09M','TM10','TM10M','TM11','TM11M', 'TM12','TM12M'],var_name='PPTIME',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPTIME'],['NWHM','TM01','TM02','TM03','TM04','TM05','TM06','TM07','TM08', 'TM09','TM10','TM11','TM12'])], k[np.isin(k['PPTIME'],['NWHMM','TM01M','TM02M','TM03M','TM04M','TM05M','TM06M','TM07M', 'TM08M','TM09M','TM10M','TM11M','TM12M'])],how='inner',on='CT') k=k[(k['PPTIME_x']+'M')==k['PPTIME_y']].reset_index(drop=True) k=k[['CT','PPTIME_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPTIME','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPTIME'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPTIME']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPTIME: '+k['PPTIME']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPTIME','ACCURACY']=acc val.loc[val['FIELD']=='PPTIME','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPTIME (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/pptimept.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPTIME (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/pptimeci.html',include_plotlyjs='cdn') # Check PPDEPART k=pd.read_csv(path+'ACS/ppdepart.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['NWHM','NWHMM','DP01','DP01M','DP02','DP02M','DP03','DP03M', 'DP04','DP04M','DP05','DP05M','DP06','DP06M','DP07','DP07M', 'DP08','DP08M','DP09','DP09M','DP10','DP10M','DP11','DP11M', 'DP12','DP12M','DP13','DP13M','DP14','DP14M'],var_name='PPDEPART',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPDEPART'],['NWHM','DP01','DP02','DP03','DP04','DP05','DP06','DP07','DP08', 'DP09','DP10','DP11','DP12','DP13','DP14'])], k[np.isin(k['PPDEPART'],['NWHMM','DP01M','DP02M','DP03M','DP04M','DP05M','DP06M','DP07M', 'DP08M','DP09M','DP10M','DP11M','DP12M','DP13M','DP14M'])],how='inner',on='CT') k=k[(k['PPDEPART_x']+'M')==k['PPDEPART_y']].reset_index(drop=True) k=k[['CT','PPDEPART_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPDEPART','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPDEPART'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPDEPART']) k=k.sort_values('TOTAL_y').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'PPDEPART: '+k['PPDEPART']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'ACS: '+k['TOTAL_y'].astype(int).astype(str)+'<br>'+'MOE: '+k['MOE'].astype(int).astype(str) acc=len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) val.loc[val['FIELD']=='PPDEPART','ACCURACY']=acc val.loc[val['FIELD']=='PPDEPART','RMSE']=rmse fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'PPDEPART (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppdepartpt.html',include_plotlyjs='cdn') fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(44,127,184,1)', line={'color':'rgba(255,255,255,0)'}, hoverinfo='skip')) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='markers', marker={'color':'rgba(215,25,28,1)', 'size':1.5}, hoverinfo='text', hovertext=k['HOVER'])) fig.update_layout( template='plotly_white', title={'text':'PPDEPART (ACCURACY: '+format(acc*100,'.2f')+'%; '+'RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'INDEX', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'VALUE', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ppdepartci.html',include_plotlyjs='cdn') val.to_csv(path+'POP/validation/validation.csv',index=False) <file_sep>/skim.py import ipfn import pandas as pd import geopandas as gpd import shapely import numpy as np import requests import time import datetime import sklearn.linear_model import statsmodels.api as sm import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' pio.renderers.default='browser' bpm=['36005','36047','36061','36081','36085','36059','36103','36119','36087','36079','36071','36027', '09001','09009','34017','34003','34031','34013','34039','34027','34035','34023','34025','34029', '34037','34041','34019','34021'] geoxwalk=pd.read_csv(path+'POP/GEOIDCROSSWALK.csv',dtype=str) bpmpuma=geoxwalk.loc[np.isin(geoxwalk['StateCounty'],bpm),'PUMA2010'].unique() bpmct=geoxwalk.loc[np.isin(geoxwalk['StateCounty'],bpm),'CensusTract2010'].unique() quadstatebkpt=gpd.read_file('C:/Users/mayij/Desktop/DOC/DCP2018/TRAVELSHEDREVAMP/shp/quadstatebkpt.shp') quadstatebkpt.crs=4326 # Res Tract Centroid res=[] for i in ['ct','nj','ny']: res+=[pd.read_csv(path+'LEHD/'+i+'_rac_S000_JT01_2018.csv',dtype=float,converters={'h_geocode':str})] res=pd.concat(res,axis=0,ignore_index=True) res['RESCOUNTY']=[str(x)[0:5] for x in res['h_geocode']] res['RESCT']=[str(x)[0:11] for x in res['h_geocode']] res=res[np.isin(res['RESCOUNTY'],bpm)].reset_index(drop=True) res=pd.merge(res,quadstatebkpt,how='inner',left_on='h_geocode',right_on='blockid') res['lattt']=res['C000']*res['lat'] res['longtt']=res['C000']*res['long'] res=res.groupby(['RESCT'],as_index=False).agg({'lattt':'sum','longtt':'sum','C000':'sum'}).reset_index(drop=True) res['RESLAT']=res['lattt']/res['C000'] res['RESLONG']=res['longtt']/res['C000'] res=res[['RESCT','RESLAT','RESLONG']].reset_index(drop=True) # Work Tract Centroid work=[] for i in ['ct','nj','ny']: work+=[pd.read_csv(path+'LEHD/'+i+'_wac_S000_JT01_2018.csv',dtype=float,converters={'w_geocode':str})] work=pd.concat(work,axis=0,ignore_index=True) work['WORKCOUNTY']=[str(x)[0:5] for x in work['w_geocode']] work['WORKCT']=[str(x)[0:11] for x in work['w_geocode']] work=work[np.isin(work['WORKCOUNTY'],bpm)].reset_index(drop=True) work=pd.merge(work,quadstatebkpt,how='inner',left_on='w_geocode',right_on='blockid') work['lattt']=work['C000']*work['lat'] work['longtt']=work['C000']*work['long'] work=work.groupby(['WORKCT'],as_index=False).agg({'lattt':'sum','longtt':'sum','C000':'sum'}).reset_index(drop=True) work['WORKLAT']=work['lattt']/work['C000'] work['WORKLONG']=work['longtt']/work['C000'] work=work[['WORKCT','WORKLAT','WORKLONG']].reset_index(drop=True) # Skim skim=pd.DataFrame(ipfn.ipfn.product(res['RESCT'].unique(),work['WORKCT'].unique()),columns=['RESCT','WORKCT']) skim=pd.merge(skim,res,how='inner',on='RESCT') skim=pd.merge(skim,work,how='inner',on='WORKCT') skim=skim[['RESCT','RESLAT','RESLONG','WORKCT','WORKLAT','WORKLONG']].reset_index(drop=True) skim['DIST']=np.nan skim['CAR']=np.nan skim.to_csv(path+'SKIM/skim.csv',index=False) skim=pd.read_csv(path+'SKIM/skim.csv',dtype=str) doserver='http://172.16.58.3:8801/' cutoffinterval=2 # in minutes cutoffstart=0 cutoffend=60 cutoffincrement=cutoffstart cutoff='' while cutoffincrement<cutoffend: cutoff+='&cutoffSec='+str((cutoffincrement+cutoffinterval)*60) cutoffincrement+=cutoffinterval i=20000000 skim.loc[i] url=doserver+'otp/routers/default/isochrone?batch=true&mode=CAR' url+='&fromPlace='+str(skim.loc[i,'RESLAT'])+','+str(skim.loc[i,'RESLONG']) url+=cutoff headers={'Accept':'application/json'} req=requests.get(url=url,headers=headers) js=req.json() iso=gpd.GeoDataFrame.from_features(js,crs={4326}) bk['T'+arrt[0:2]+arrt[3:5]]=999 cut=range(cutoffend,cutoffstart,-cutoffinterval) start=datetime.datetime.now() for i in skim.index[0:100]: url=doserver+'otp/routers/default/plan?fromPlace=' url+=str(skim.loc[i,'RESLAT'])+','+str(skim.loc[i,'RESLONG']) url+='&toPlace='+str(skim.loc[i,'WORKLAT'])+','+str(skim.loc[i,'WORKLONG'])+'&mode=CAR' headers={'Accept':'application/json'} req=requests.get(url=url,headers=headers) js=req.json() if list(js.keys())[1]=='error': skim.loc[i,'DIST']=np.nan skim.loc[i,'CAR']=np.nan else: skim.loc[i,'DIST']=js['plan']['itineraries'][0]['legs'][0]['distance'] skim.loc[i,'CAR']=js['plan']['itineraries'][0]['legs'][0]['duration'] time.sleep(0.1) print(datetime.datetime.now()-start) rhtstrip=pd.read_csv(path+'RHTS/LINKED_Public.csv',dtype=str) rhtstrip['TRIPID']=rhtstrip['SAMPN']+'|'+rhtstrip['PERNO']+'|'+rhtstrip['PLANO'] rhtstrip['TOURID']=rhtstrip['SAMPN']+'|'+rhtstrip['PERNO']+'|'+rhtstrip['TOUR_ID'] rhtstrip['PPID']=rhtstrip['SAMPN']+'|'+rhtstrip['PERNO'] rhtstrip['HHID']=rhtstrip['SAMPN'].copy() rhtstrip=rhtstrip[rhtstrip['ODTPURP']=='1'].reset_index(drop=True) rhtstrip['RESCT']=[str(x).zfill(11) for x in rhtstrip['OTRACT']] rhtstrip['WORKCT']=[str(x).zfill(11) for x in rhtstrip['DTRACT']] rhtstrip['DIST']=pd.to_numeric(rhtstrip['TRPDIST_HN']) rhtstrip=rhtstrip[['PPID','RESCT','WORKCT','DIST']].drop_duplicates(keep='first').reset_index(drop=True) rhtspp=pd.read_csv(path+'RHTS/rhtspp.csv',dtype=str,converters={'PWGTP':float}) rhtstrip=pd.merge(rhtstrip,rhtspp,how='inner',on='PPID') rhtstrip=rhtstrip[['PPID','PPIND','RESCT','WORKCT']].drop_duplicates(keep='first').reset_index(drop=True) rhtstrip=rhtstrip[~np.isin(rhtstrip['PPIND'],['U16','NLF','CUP'])].reset_index(drop=True) wacct=pd.read_csv(path+'LEHD/wacct.csv',dtype=float,converters={'CT':str}) wacct=wacct[['CT','AGR','EXT','UTL','CON','MFG','WHL','RET','TRN','INF','FIN','RER','PRF','MNG','WMS','EDU', 'MED','ENT','ACC','SRV','ADM']].reset_index(drop=True) wacct=wacct.melt(id_vars=['CT'],value_vars=['AGR','EXT','UTL','CON','MFG','WHL','RET','TRN','INF','FIN','RER', 'PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM'],var_name='PPIND',value_name='WAC') wacct=wacct[wacct['WAC']>100].reset_index(drop=True) wacct.columns=['WORKCT','PPIND','WAC'] rhtstrip=pd.merge(rhtstrip,wacct,how='inner',on=['PPIND']) rhtstrip['DEC']=np.where(rhtstrip['WORKCT_x']==rhtstrip['WORKCT_y'],1,0) k=rhtstrip.loc[:,:].reset_index(drop=True) k.DEC.value_counts() k=k[['PPID','PPIND','RESCT','WORKCT_y','WAC','DEC']].reset_index(drop=True) k.columns=['PPID','PPIND','RESCT','WORKCT','WAC','DEC'] s=k[['RESCT','WORKCT']].drop_duplicates(keep='first').reset_index(drop=True) s=pd.merge(s,res,how='inner',on='RESCT') s=pd.merge(s,work,how='inner',on='WORKCT') s=s[['RESCT','RESLAT','RESLONG','WORKCT','WORKLAT','WORKLONG']].reset_index(drop=True) # s['DIST']=np.nan # s['CAR']=np.nan s['DIST']=np.sqrt((s['RESLAT']-s['WORKLAT'])**2+(s['RESLONG']-s['WORKLONG'])**2) # s.to_csv(path+'SKIM/s.csv',index=False) s=s[['RESCT','WORKCT','DIST']].reset_index(drop=True) k=pd.merge(k,s,how='inner',on=['RESCT','WORKCT']) # MNL reg=sklearn.linear_model.LogisticRegression().fit(k[['DIST','WAC']],k['DEC']) sm.MNLogit(k['DEC'],sm.add_constant(k[['DIST','WAC']])).fit().summary() ypred=pd.DataFrame({'train':k['DEC'],'pred':reg.predict(k[['DIST','WAC']]), 'prob':[x[1] for x in reg.predict_proba(k[['DIST','WAC']])], 'problog':[x[1] for x in reg.predict_log_proba(k[['DIST','WAC']])]}) print(sklearn.metrics.classification_report(ypred['train'],ypred['pred'])) k['PROB']=[x[1] for x in reg.predict_proba(k[['DIST','WAC']])] l=k.groupby('PPID').agg({'PROB':'sum'}) k=pd.merge(k,l,how='inner',on='PPID') k['PROB']=k['PROB_x']/k['PROB_y'] k=k.sort_values(['PROB'],ascending=False).reset_index(drop=True) k=k.drop_duplicates(['PPID'],keep='first').reset_index(drop=True) k.groupby('WORKCT').count().sort_values(['PPID'],ascending=False) s=pd.read_csv(path+'SKIM/s.csv',dtype=str) doserver='http://172.16.58.3:8801/' start=datetime.datetime.now() for i in s.index: url=doserver+'otp/routers/default/plan?fromPlace=' url+=str(s.loc[i,'RESLAT'])+','+str(s.loc[i,'RESLONG']) url+='&toPlace='+str(s.loc[i,'WORKLAT'])+','+str(s.loc[i,'WORKLONG'])+'&mode=CAR' headers={'Accept':'application/json'} req=requests.get(url=url,headers=headers) js=req.json() if list(js.keys())[1]=='error': s.loc[i,'DIST']=np.nan s.loc[i,'CAR']=np.nan else: s.loc[i,'DIST']=js['plan']['itineraries'][0]['legs'][0]['distance'] s.loc[i,'CAR']=js['plan']['itineraries'][0]['legs'][0]['duration'] time.sleep(0.1) print(datetime.datetime.now()-start) s.to_csv(path+'SKIM/s.csv',index=False) <file_sep>/od.py import ipfn import pandas as pd import numpy as np import sklearn.linear_model import statsmodels.api as sm import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' pio.renderers.default='browser' bpm=['36005','36047','36061','36081','36085','36059','36103','36119','36087','36079','36071','36027', '09001','09009','34017','34003','34031','34013','34039','34027','34035','34023','34025','34029', '34037','34041','34019','34021'] geoxwalk=pd.read_csv(path+'POP/GEOIDCROSSWALK.csv',dtype=str) bpmpuma=geoxwalk.loc[np.isin(geoxwalk['StateCounty'],bpm),'PUMA2010'].unique() bpmct=geoxwalk.loc[np.isin(geoxwalk['StateCounty'],bpm),'CensusTract2010'].unique() dfpp=pd.read_csv(path+'POP/dfpp.csv',dtype=str,converters={'TOTAL':float}) dfpp.PPMODE.value_counts(dropna=False) # IPF pumshh=pd.read_csv(path+'PUMS/pumshh.csv',dtype=str,converters={'WGTP':float}) pumsppgq=pd.read_csv(path+'PUMS/pumsppgq.csv',dtype=str,converters={'PWGTP':float}) pumsppgq=pumsppgq.groupby(['HHID','PUMA'],as_index=False).agg({'PWGTP':'sum'}).reset_index(drop=True) # i='3603101' 127 # i='3603903' 142 for i in bpmpuma: ct=geoxwalk.loc[geoxwalk['PUMA2010']==i,'CensusTract2010'].unique() # ct=ct[ct!='36085008900'] # Households tphh=pumshh[pumshh['PUMA']==i].reset_index(drop=True) tphh=pd.DataFrame(ipfn.ipfn.product(tphh['HHID'].unique(),ct),columns=['HHID','CT']) tphh=pd.merge(tphh,pumshh[['HHID','HHINC']],how='left',on='HHID') tphh['TOTAL']=1 hhwt=pumshh[['HHID','WGTP']].reset_index(drop=True) hhwt['WGTP']=pd.to_numeric(hhwt['WGTP']) hhwt=hhwt.set_index(['HHID']) hhwt=hhwt.iloc[:,0] cthhinc=pd.read_csv(path+'ACS/hhinc.csv',dtype=float,converters={'CT':str}) cthhinc=cthhinc.loc[np.isin(cthhinc['CT'],ct),['CT','VAC','INC01','INC02','INC03','INC04','INC05', 'INC06','INC07','INC08','INC09','INC10','INC11']].reset_index(drop=True) cthhinc=cthhinc.melt(id_vars=['CT'],value_vars=['VAC','INC01','INC02','INC03','INC04','INC05','INC06', 'INC07','INC08','INC09','INC10','INC11'],var_name='HHINC',value_name='TOTAL') cthhinc=cthhinc.set_index(['CT','HHINC']) cthhinc=cthhinc.iloc[:,0] aggregates=[hhwt,cthhinc] dimensions=[['HHID'],['CT','HHINC']] tphh=ipfn.ipfn.ipfn(tphh,aggregates,dimensions,weight_col='TOTAL',max_iteration=1000000).iteration() tphh['TOTAL']=[round(x) for x in tphh['TOTAL']] tphh.to_csv(path+'POP/tphh/'+i+'.csv',index=False) # Group Quarter tpgq=pumsppgq[pumsppgq['PUMA']==i].reset_index(drop=True) tpgq=pd.DataFrame(ipfn.ipfn.product(tpgq['HHID'].unique(),ct),columns=['HHID','CT']) tpgq['TOTAL']=1 gqwt=pumsppgq[['HHID','PWGTP']].reset_index(drop=True) gqwt['PWGTP']=pd.to_numeric(gqwt['PWGTP']) gqwt=gqwt.set_index(['HHID']) gqwt=gqwt.iloc[:,0] gqtt=pd.read_csv(path+'ACS/gqtt.csv',dtype=float,converters={'CT':str}) gqtt=gqtt.loc[np.isin(gqtt['CT'],ct),['CT','GQTT']].reset_index(drop=True) gqtt=gqtt.set_index(['CT']) gqtt=gqtt.iloc[:,0] aggregates=[gqwt,gqtt] dimensions=[['HHID'],['CT']] tpgq=ipfn.ipfn.ipfn(tpgq,aggregates,dimensions,weight_col='TOTAL',max_iteration=1000000).iteration() tpgq['TOTAL']=[round(x) for x in tpgq['TOTAL']] tpgq.to_csv(path+'POP/tpgq/'+i+'.csv',index=False) dfhh=[] for i in bpmpuma: tphh=pd.read_csv(path+'POP/tphh/'+i+'.csv',dtype=str) dfhh+=[tphh] dfhh=pd.concat(dfhh,axis=0,ignore_index=True) dfhh=dfhh.loc[dfhh['TOTAL']!=0,['HHID','CT','HHINC','TOTAL']].reset_index(drop=True) dfhh=dfhh.drop_duplicates(keep='first').reset_index(drop=True) dfhh.to_csv(path+'POP/dfhh.csv',index=False) dfgq=[] for i in bpmpuma: tpgq=pd.read_csv(path+'POP/tpgq/'+i+'.csv',dtype=str) dfgq+=[tpgq] dfgq=pd.concat(dfgq,axis=0,ignore_index=True) dfgq=dfgq.loc[dfgq['TOTAL']!=0,['HHID','CT','TOTAL']].reset_index(drop=True) dfgq=dfgq.drop_duplicates(keep='first').reset_index(drop=True) dfgq.to_csv(path+'POP/dfgq.csv',index=False) # Validation # Check Household pumshh=pd.read_csv(path+'PUMS/pumshh.csv',dtype=str,converters={'WGTP':float}) dfhh=pd.read_csv(path+'POP/dfhh.csv',dtype=str,converters={'TOTAL':float}) # Check HHID Weight Sum k=pd.merge(dfhh.groupby(['HHID']).agg({'TOTAL':'sum'}),pumshh[['HHID','WGTP']],how='inner',on='HHID') p=px.scatter(k,x='TOTAL',y='WGTP') p.show() # Check HHTT k=pd.read_csv(path+'ACS/hhtt.csv',dtype=float,converters={'CT':str}) k.columns=['CT','TOTAL','MOE'] k=pd.merge(dfhh.groupby(['CT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHOCC tptest=dfhh.copy() tptest['HHOCC']=np.where(tptest['HHINC']=='VAC','VAC','OCC') k=pd.read_csv(path+'ACS/hhocc.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','OCC','OCCM'],var_name='HHOCC',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHOCC'],['VAC','OCC'])], k[np.isin(k['HHOCC'],['VACM','OCCM'])],how='inner',on='CT') k=k[(k['HHOCC_x']+'M')==k['HHOCC_y']].reset_index(drop=True) k=k[['CT','HHOCC_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHOCC','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHOCC'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHOCC']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHSIZE tptest=pd.merge(dfhh,pumshh[['HHID','HHSIZE']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhsize.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','SIZE1','SIZE1M','SIZE2','SIZE2M','SIZE3','SIZE3M', 'SIZE4','SIZE4M'],var_name='HHSIZE',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHSIZE'],['VAC','SIZE1','SIZE2','SIZE3','SIZE4'])], k[np.isin(k['HHSIZE'],['VACM','SIZE1M','SIZE2M','SIZE3M','SIZE4M'])],how='inner',on='CT') k=k[(k['HHSIZE_x']+'M')==k['HHSIZE_y']].reset_index(drop=True) k=k[['CT','HHSIZE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHSIZE','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHSIZE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHSIZE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHTYPE tptest=pd.merge(dfhh,pumshh[['HHID','HHTYPE']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhtype.csv',dtype=float,converters={'CT':str}) k['TYPE1']=k['MC']-k['MCC']+k['CC']-k['CCC'] k['TYPE1M']=np.sqrt(k['MCM']**2+k['MCCM']**2+k['CCM']**2+k['CCCM']**2) k['TYPE2']=k['MCC']+k['CCC'] k['TYPE2M']=np.sqrt(k['MCCM']**2+k['CCCM']**2) k['TYPE3']=k['MHA']+k['FHA'] k['TYPE3M']=np.sqrt(k['MHAM']**2+k['FHAM']**2) k['TYPE4']=k['MHC']+k['FHC'] k['TYPE4M']=np.sqrt(k['MHCM']**2+k['FHCM']**2) k['TYPE5']=k['MH']-k['MHC']-k['MHA']+k['FH']-k['FHC']-k['FHA'] k['TYPE5M']=np.sqrt(k['MHM']**2+k['MHCM']**2+k['MHAM']**2+k['FHM']**2+k['FHCM']**2+k['FHAM']**2) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','TYPE1','TYPE1M','TYPE1','TYPE2M','TYPE3','TYPE3M', 'TYPE4','TYPE4M','TYPE5','TYPE5M'],var_name='HHTYPE',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHTYPE'],['VAC','TYPE1','TYPE2','TYPE3','TYPE4','TYPE5'])], k[np.isin(k['HHTYPE'],['VACM','TYPE1M','TYPE2M','TYPE3M','TYPE4M','TYPE5M'])],how='inner',on='CT') k=k[(k['HHTYPE_x']+'M')==k['HHTYPE_y']].reset_index(drop=True) k=k[['CT','HHTYPE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHTYPE','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHTYPE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHTYPE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHINC k=pd.read_csv(path+'ACS/hhinc.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','INC01','INC01M','INC02','INC02M','INC03','INC03M', 'INC04','INC04M','INC05','INC05M','INC06','INC06M','INC07','INC07M', 'INC08','INC08M','INC09','INC09M','INC10','INC10M', 'INC11','INC11M'],var_name='HHINC',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHINC'],['VAC','INC01','INC02','INC03','INC04','INC05','INC06','INC07','INC08','INC09','INC10','INC11'])], k[np.isin(k['HHINC'],['VACM','INC01M','INC02M','INC03M','INC04M','INC05M','INC06M','INC07M','INC08M','INC09M','INC10M','INC11M'])],how='inner',on='CT') k=k[(k['HHINC_x']+'M')==k['HHINC_y']].reset_index(drop=True) k=k[['CT','HHINC_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHINC','TOTAL','MOE'] k=pd.merge(dfhh.groupby(['CT','HHINC'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHINC']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHTEN tptest=pd.merge(dfhh,pumshh[['HHID','HHTEN']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhten.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','OWNER','OWNERM','RENTER','RENTERM'],var_name='HHTEN',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHTEN'],['VAC','OWNER','RENTER'])], k[np.isin(k['HHTEN'],['VACM','OWNERM','RENTERM'])],how='inner',on='CT') k=k[(k['HHTEN_x']+'M')==k['HHTEN_y']].reset_index(drop=True) k=k[['CT','HHTEN_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHTEN','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHTEN'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHTEN']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHSTR tptest=pd.merge(dfhh,pumshh[['HHID','HHSTR']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhstr.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','STR1D','STR1DM','STR1A','STR1AM','STR2','STR2M', 'STR34','STR34M','STR59','STR59M','STR10','STR10M', 'STRO','STROM'],var_name='HHSTR',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHSTR'],['VAC','STR1D','STR1A','STR2','STR34','STR59','STR10','STRO'])], k[np.isin(k['HHSTR'],['VACM','STR1DM','STR1AM','STR2M','STR34M','STR59M','STR10M','STROM'])],how='inner',on='CT') k=k[(k['HHSTR_x']+'M')==k['HHSTR_y']].reset_index(drop=True) k=k[['CT','HHSTR_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHSTR','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHSTR'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHSTR']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHBLT tptest=pd.merge(dfhh,pumshh[['HHID','HHBLT']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhblt.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['B14','B14M','B10','B10M','B00','B00M','B90','B90M','B80','B80M', 'B70','B70M','B60','B60M','B50','B50M','B40','B40M','B39','B39M'],var_name='HHBLT',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHBLT'],['B14','B10','B00','B90','B80','B70','B60','B50','B40','B39'])], k[np.isin(k['HHBLT'],['B14M','B10M','B00M','B90M','B80M','B70M','B60M','B50M','B40M','B39M'])],how='inner',on='CT') k=k[(k['HHBLT_x']+'M')==k['HHBLT_y']].reset_index(drop=True) k=k[['CT','HHBLT_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHBLT','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHBLT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHBLT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHBED tptest=pd.merge(dfhh,pumshh[['HHID','HHBED']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhbed.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['BED0','BED0M','BED1','BED1M','BED2','BED2M','BED3','BED3M', 'BED4','BED4M','BED5','BED5M'],var_name='HHBED',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHBED'],['BED0','BED1','BED2','BED3','BED4','BED5'])], k[np.isin(k['HHBED'],['BED0M','BED1M','BED2M','BED3M','BED4M','BED5M'])],how='inner',on='CT') k=k[(k['HHBED_x']+'M')==k['HHBED_y']].reset_index(drop=True) k=k[['CT','HHBED_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHBED','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHBED'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHBED']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check HHVEH tptest=pd.merge(dfhh,pumshh[['HHID','HHVEH']],how='inner',on='HHID') k=pd.read_csv(path+'ACS/hhveh.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['VAC','VACM','VEH0','VEH0M','VEH1','VEH1M','VEH2','VEH2M', 'VEH3','VEH3M','VEH4','VEH4M'],var_name='HHVEH',value_name='TOTAL') k=pd.merge(k[np.isin(k['HHVEH'],['VAC','VEH0','VEH1','VEH2','VEH3','VEH4'])], k[np.isin(k['HHVEH'],['VACM','VEH0M','VEH1M','VEH2M','VEH3M','VEH4M'])],how='inner',on='CT') k=k[(k['HHVEH_x']+'M')==k['HHVEH_y']].reset_index(drop=True) k=k[['CT','HHVEH_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','HHVEH','TOTAL','MOE'] k=pd.merge(tptest.groupby(['CT','HHVEH'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','HHVEH']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check Group Quarter pumsppgq=pd.read_csv(path+'PUMS/pumsppgq.csv',dtype=str,converters={'PWGTP':float}) pumsppgq=pumsppgq.groupby(['HHID'],as_index=False).agg({'PWGTP':'sum'}).reset_index(drop=True) dfgq=pd.read_csv(path+'POP/dfgq.csv',dtype=str,converters={'TOTAL':float}) # Check GQ Weight Sum k=pd.merge(dfgq.groupby(['HHID']).agg({'TOTAL':'sum'}),pumsppgq[['HHID','PWGTP']],how='inner',on='HHID') p=px.scatter(k,x='TOTAL',y='PWGTP') p.show() # Check GQTT k=pd.read_csv(path+'ACS/gqtt.csv',dtype=float,converters={'CT':str}) k.columns=['CT','TOTAL','MOE'] k=pd.merge(dfgq.groupby(['CT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check Person pumspp=pd.read_csv(path+'PUMS/pumspp.csv',dtype=str,converters={'PWGTP':float}) dfpp=pd.concat([dfhh[['HHID','CT','TOTAL']],dfgq[['HHID','CT','TOTAL']]],axis=0,ignore_index=True) dfpp=pd.merge(pumspp,dfpp,how='inner',on=['HHID']) # Check PPID Weight Sum k=pd.merge(dfpp.groupby(['PPID']).agg({'TOTAL':'sum'}),pumspp[['PPID','PWGTP']],how='inner',on='PPID') p=px.scatter(k,x='TOTAL',y='PWGTP') p.show() # Check PPTT k=pd.read_csv(path+'ACS/pptt.csv',dtype=float,converters={'CT':str}) k.columns=['CT','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check PPSEX k=pd.read_csv(path+'ACS/ppsex.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['MALE','MALEM','FEMALE','FEMALEM'],var_name='PPSEX',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPSEX'],['MALE','FEMALE'])], k[np.isin(k['PPSEX'],['MALEM','FEMALEM'])],how='inner',on='CT') k=k[(k['PPSEX_x']+'M')==k['PPSEX_y']].reset_index(drop=True) k=k[['CT','PPSEX_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPSEX','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPSEX'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPSEX']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check PPAGE k=pd.read_csv(path+'ACS/ppage.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['AGE01','AGE01M','AGE02','AGE02M','AGE03','AGE03M','AGE04','AGE04M', 'AGE05','AGE05M','AGE06','AGE06M','AGE07','AGE07M','AGE08','AGE08M', 'AGE09','AGE09M','AGE10','AGE10M','AGE11','AGE11M','AGE12','AGE12M', 'AGE13','AGE13M','AGE14','AGE14M','AGE15','AGE15M','AGE16','AGE16M', 'AGE17','AGE17M','AGE18','AGE18M'],var_name='PPAGE',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPAGE'],['AGE01','AGE02','AGE03','AGE04','AGE05','AGE06','AGE07','AGE08', 'AGE09','AGE10','AGE11','AGE12','AGE13','AGE14','AGE15','AGE16', 'AGE17','AGE18'])], k[np.isin(k['PPAGE'],['AGE01M''AGE02M','AGE03M','AGE04M','AGE05M','AGE06M','AGE07M', 'AGE08M','AGE09M','AGE10M','AGE11M','AGE12M','AGE13M','AGE14M', 'AGE15M','AGE16M','AGE17M','AGE18M'])],how='inner',on='CT') k=k[(k['PPAGE_x']+'M')==k['PPAGE_y']].reset_index(drop=True) k=k[['CT','PPAGE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPAGE','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPAGE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPAGE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check PPSCH k=pd.read_csv(path+'ACS/ppsch.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['NS','NSM','PR','PRM','KG','KGM','G14','G14M','G58','G58M', 'HS','HSM','CL','CLM','GS','GSM'],var_name='PPSCH',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPSCH'],['NS','PR','KG','G14','G58','HS','CL','GS'])], k[np.isin(k['PPSCH'],['NSM','PRM','KGM','G14M','G58M','HSM','CLM','GSM'])],how='inner',on='CT') k=k[(k['PPSCH_x']+'M')==k['PPSCH_y']].reset_index(drop=True) k=k[['CT','PPSCH_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPSCH','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPSCH'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPSCH']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Check PPMODE k=pd.read_csv(path+'ACS/ppmode.csv',dtype=float,converters={'CT':str}) k=k.melt(id_vars=['CT'],value_vars=['NW','NWM','DA','DAM','CP2','CP2M','CP3','CP3M','CP4','CP4M', 'CP56','CP56M','CP7','CP7M','BS','BSM','SW','SWM','CR','CRM', 'LR','LRM','FB','FBM','TC','TCM','MC','MCM','BC','BCM','WK','WKM', 'OT','OTM','HM','HMM'],var_name='PPMODE',value_name='TOTAL') k=pd.merge(k[np.isin(k['PPMODE'],['NW','DA','CP2','CP3','CP4','CP56','CP7','BS','SW','CR','LR','FB', 'TC','MC','BC','WK','OT','HM'])], k[np.isin(k['PPMODE'],['NWM','DAM','CP2M','CP3M','CP4M','CP56M','CP7M','BSM','SWM','CRM', 'LRM','FBM','TCM','MCM','BCM','WKM','OTM','HMM'])],how='inner',on='CT') k=k[(k['PPMODE_x']+'M')==k['PPMODE_y']].reset_index(drop=True) k=k[['CT','PPMODE_x','TOTAL_x','TOTAL_y']].reset_index(drop=True) k.columns=['CT','PPMODE','TOTAL','MOE'] k=pd.merge(dfpp.groupby(['CT','PPMODE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPMODE']) k=k.sort_values('TOTAL_y').reset_index(drop=True) p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') p.show() fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='ACS', x=list(k.index)+list(k.index[::-1]), y=list(k['TOTAL_y']+k['MOE'])+list((k['TOTAL_y']-k['MOE'])[::-1]), fill='toself', fillcolor='rgba(0,0,255,0.5)', line=dict(color='rgba(255,255,255,0)'))) fig=fig.add_trace(go.Scattergl(name='MODEL', x=k.index, y=k['TOTAL_x'], mode='lines')) fig.show() print(len(k[(k['TOTAL_x']<=k['TOTAL_y']+k['MOE'])&(k['TOTAL_x']>=k['TOTAL_y']-k['MOE'])])/len(k)) print(np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k))) # Backup # pums=pd.read_csv(path+'POP/psam_h36.csv',dtype=str) # pums['PUMA']=pums['ST']+pums['PUMA'] # pums=pums.loc[pums['WGTP']!='0',['PUMA','WGTP','NP','HINCP','BLD']].reset_index(drop=True) # pums=pd.merge(pums,geoxwalk[['PUMA2010','StateCounty']].drop_duplicates(keep='first'),how='left',left_on='PUMA',right_on='PUMA2010') # pums=pums[np.isin(pums['StateCounty'],bpm)].reset_index(drop=True) # pums=pums[pums['NP']!='0'].reset_index(drop=True) # pums['WGTP']=pd.to_numeric(pums['WGTP']) # pums['NP']=pd.to_numeric(pums['NP']) # pums['HHSIZE']=np.where(pums['NP']==1,'SIZE1', # np.where(pums['NP']==2,'SIZE2', # np.where(pums['NP']==3,'SIZE3','SIZE4'))) # pums['HINCP']=pd.to_numeric(pums['HINCP']) # pums['HHINC']=np.where(pums['HINCP']<5000,'INC01', # np.where(pums['HINCP']<10000,'INC02', # np.where(pums['HINCP']<15000,'INC03', # np.where(pums['HINCP']<20000,'INC04', # np.where(pums['HINCP']<25000,'INC05', # np.where(pums['HINCP']<35000,'INC06', # np.where(pums['HINCP']<50000,'INC07', # np.where(pums['HINCP']<75000,'INC08', # np.where(pums['HINCP']<100000,'INC09', # np.where(pums['HINCP']<150000,'INC10','INC11')))))))))) # # pums['HHINC']=np.where(pums['HINCP']<25000,'INC201', # # np.where(pums['HINCP']<50000,'INC202', # # np.where(pums['HINCP']<75000,'INC203', # # np.where(pums['HINCP']<100000,'INC204', # # np.where(pums['HINCP']<150000,'INC205','INC206'))))) # # pums['HHINC']=np.where(pums['HINCP']<35000,'INC201', # # np.where(pums['HINCP']<75000,'INC202', # # np.where(pums['HINCP']<150000,'INC203','INC204'))) # pums['HHSTR']=np.where(np.isin(pums['BLD'],['02','03']),'STR1', # np.where(np.isin(pums['BLD'],['04','05','06','07','08','09']),'STR2','STR3')) # pums=pums[['PUMA','StateCounty','HHSIZE','HHINC','HHSTR','WGTP']].reset_index(drop=True) # # pumstp=pums.groupby(['PUMA','HHSIZE','HHINC'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True) # # pums=pd.merge(pums,pumstp,how='inner',on=['PUMA','HHSIZE','HHINC']) # # pums['WGTP']=pums['WGTP_x'].copy() # # pums['HHSTRPCT']=pums['WGTP_x']/pums['WGTP_y'] # # pums=pums[['PUMA','HHSIZE','HHINC','HHSTR','WGTP','HHSTRPCT']].reset_index(drop=True) # predstr=pd.concat([pums[['HHSTR','WGTP']],pd.get_dummies(pums[['PUMA','HHSIZE','HHINC']],drop_first=True)],axis=1,ignore_index=False) # predstrx=predstr.drop(['HHSTR','WGTP'],axis=1) # predstry=predstr['HHSTR'] # predstrwt=predstr['WGTP'] # predstrreg=sklearn.linear_model.LogisticRegression(max_iter=1000).fit(predstrx,predstry,predstrwt) # predstrreg.score(predstrx,predstry,predstrwt) # # ypred=pd.DataFrame({'true':y,'pred':reg.predict(x)}) # # sm.MNLogit(predstry,sm.add_constant(predstrx)).fit().summary() # i='3603805' # for i in puma: # hhsize=pd.read_csv(path+'POP/hhsize.csv',dtype=float,converters={'CT':str}) # hhsize=pd.merge(hhsize,geoxwalk[['CensusTract2010','PUMA2010']].drop_duplicates(keep='first'),how='left',left_on='CT',right_on='CensusTract2010') # hhsize=hhsize[hhsize['PUMA2010']==i].reset_index(drop=True) # hhsize=hhsize.melt(id_vars=['CT'],value_vars=['SIZE1','SIZE2','SIZE3','SIZE4'],var_name='HHSIZE',value_name='TOTAL') # hhsize.groupby('HHSIZE').agg({'TOTAL':'sum'}) # hhinc=pd.read_csv(path+'POP/hhinc.csv',dtype=float,converters={'CT':str}) # # hhinc['INC201']=hhinc['INC01']+hhinc['INC02']+hhinc['INC03']+hhinc['INC04']+hhinc['INC05'] #<25k # # hhinc['INC202']=hhinc['INC06']+hhinc['INC07'] #25k~50k # # hhinc['INC203']=hhinc['INC08'].copy() #50k~75k # # hhinc['INC204']=hhinc['INC09'].copy() #75k~100k # # hhinc['INC205']=hhinc['INC10'].copy() #100k~150k # # hhinc['INC206']=hhinc['INC11'].copy() #>150k # # hhinc['INC201']=hhinc['INC01']+hhinc['INC02']+hhinc['INC03']+hhinc['INC04']+hhinc['INC05']+hhinc['INC06'] #<35k # # hhinc['INC202']=hhinc['INC07']+hhinc['INC08'] #35k~75k # # hhinc['INC203']=hhinc['INC09']+hhinc['INC10'] #75k~150k # # hhinc['INC204']=hhinc['INC11'].copy() #>150k # hhinc=pd.merge(hhinc,geoxwalk[['CensusTract2010','PUMA2010']].drop_duplicates(keep='first'),how='left',left_on='CT',right_on='CensusTract2010') # hhinc=hhinc[hhinc['PUMA2010']==i].reset_index(drop=True) # hhinc=hhinc.melt(id_vars=['CT'],value_vars=['INC01','INC02','INC03','INC04','INC05','INC06','INC07','INC08','INC09','INC10','INC11'],var_name='HHINC',value_name='TOTAL') # # hhinc=hhinc.melt(id_vars=['CT'],value_vars=['INC201','INC202','INC203','INC204','INC205','INC206'],var_name='HHINC',value_name='TOTAL') # # hhinc=hhinc.melt(id_vars=['CT'],value_vars=['INC201','INC202','INC203','INC204'],var_name='HHINC',value_name='TOTAL') # hhinc.groupby('HHINC').agg({'TOTAL':'sum'}) # pumsszinc=pd.DataFrame(ipfn.ipfn.product(hhsize['HHSIZE'].unique(),hhinc['HHINC'].unique())) # pumsszinc.columns=['HHSIZE','HHINC'] # pumsszinctp=pums[pums['PUMA']==i].reset_index(drop=True) # pumsszinctp=pumsszinctp.groupby(['HHSIZE','HHINC'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True) # pumsszinc=pd.merge(pumsszinc,pumsszinctp,how='left',on=['HHSIZE','HHINC']) # pumsszinc['TOTAL']=pumsszinc['WGTP'].fillna(0) # pumsszinc=pumsszinc[['HHSIZE','HHINC','TOTAL']].reset_index(drop=True) # # pumsszstr=pd.DataFrame(ipfn.ipfn.product(hhsize['HHSIZE'].unique(),hhstr['HHSTR'].unique())) # # pumsszstr.columns=['HHSIZE','HHSTR'] # # pumsszstrtp=pums[pums['PUMA']==i].reset_index(drop=True) # # pumsszstrtp=pumsszstrtp.groupby(['HHSIZE','HHSTR'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True) # # pumsszstr=pd.merge(pumsszstr,pumsszstrtp,how='left',on=['HHSIZE','HHSTR']) # # pumsszstr['TOTAL']=pumsszstr['WGTP'].fillna(0) # # pumsszstr=pumsszstr[['HHSIZE','HHSTR','TOTAL']].reset_index(drop=True) # # pumsincstr=pd.DataFrame(ipfn.ipfn.product(hhinc['HHINC'].unique(),hhstr['HHSTR'].unique())) # # pumsincstr.columns=['HHINC','HHSTR'] # # pumsincstrtp=pums[pums['PUMA']==i].reset_index(drop=True) # # pumsincstrtp=pumsincstrtp.groupby(['HHINC','HHSTR'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True) # # pumsincstr=pd.merge(pumsincstr,pumsincstrtp,how='left',on=['HHINC','HHSTR']) # # pumsincstr['TOTAL']=pumsincstr['WGTP'].fillna(0) # # pumsincstr=pumsincstr[['HHINC','HHSTR','TOTAL']].reset_index(drop=True) # tp=pd.DataFrame(ipfn.ipfn.product(hhsize['CT'].unique(),hhsize['HHSIZE'].unique(),hhinc['HHINC'].unique())) # tp.columns=['CT','HHSIZE','HHINC'] # tp['TOTAL']=np.random.randint(1,10,len(tp)) # # tp['TOTAL']=1 # tp=tp[['CT','HHSIZE','HHINC','TOTAL']].reset_index(drop=True) # hhsize=hhsize.set_index(['CT','HHSIZE']) # hhsize=hhsize.iloc[:,0] # hhinc=hhinc.set_index(['CT','HHINC']) # hhinc=hhinc.iloc[:,0] # pumsszinc=pumsszinc.set_index(['HHSIZE','HHINC']) # pumsszinc=pumsszinc.iloc[:,0] # aggregates=[hhsize,hhinc,pumsszinc] # dimensions=[['CT','HHSIZE'],['CT','HHINC'],['HHSIZE','HHINC']] # tp=ipfn.ipfn.ipfn(tp,aggregates,dimensions,weight_col='TOTAL',max_iteration=1000000000).iteration() # k=pd.merge(hhsize,tp.groupby(['CT','HHSIZE'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True),how='inner',on=['CT','HHSIZE']) # p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') # p.show() # k=pd.merge(hhinc,tp.groupby(['CT','HHINC'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True),how='inner',on=['CT','HHINC']) # p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') # p.show() # k=pd.merge(pumsszinc,tp.groupby(['HHSIZE','HHINC'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True),how='inner',on=['HHSIZE','HHINC']) # p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') # p.show() # tp=pd.concat([tp[['CT','TOTAL']],pd.get_dummies(tp[['HHSIZE','HHINC']],drop_first=True)],axis=1,ignore_index=False) # for j in predstrx.columns[:94]: # tp[j]=0 # tp['PUMA_'+i]=1 # tp['PREDHHSTR']=predstrreg.predict(tp.drop(['CT','TOTAL'],axis=1)) # tp['HHSIZE']=np.where((tp['HHSIZE_SIZE2']==0)&(tp['HHSIZE_SIZE3']==0)&(tp['HHSIZE_SIZE4']==0),'SIZE1', # np.where((tp['HHSIZE_SIZE2']==1)&(tp['HHSIZE_SIZE3']==0)&(tp['HHSIZE_SIZE4']==0),'SIZE2', # np.where((tp['HHSIZE_SIZE2']==0)&(tp['HHSIZE_SIZE3']==1)&(tp['HHSIZE_SIZE4']==0),'SIZE3', # np.where((tp['HHSIZE_SIZE2']==0)&(tp['HHSIZE_SIZE3']==0)&(tp['HHSIZE_SIZE4']==1),'SIZE4','OTHER')))) # tp['HHINC']=np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC01', # np.where((tp['HHINC_INC02']==1)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC02', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==1)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC03', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==1)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC04', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==1)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC05', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==1)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC06', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==1)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC07', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==1)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC08', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==1)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==0),'INC09', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==1)&(tp['HHINC_INC11']==0),'INC10', # np.where((tp['HHINC_INC02']==0)&(tp['HHINC_INC03']==0)&(tp['HHINC_INC04']==0)&(tp['HHINC_INC05']==0)&(tp['HHINC_INC06']==0)&(tp['HHINC_INC07']==0)&(tp['HHINC_INC08']==0)&(tp['HHINC_INC09']==0)&(tp['HHINC_INC10']==0)&(tp['HHINC_INC11']==1),'INC11','OTHER'))))))))))) # tp=tp[['CT','TOTAL','HHSIZE','HHINC','PREDHHSTR']].reset_index(drop=True) # tp.groupby('PREDHHSTR').agg({'TOTAL':'sum'}) # hhstr=pd.read_csv(path+'POP/hhstr.csv',dtype=float,converters={'CT':str}) # hhstr=pd.merge(hhstr,geoxwalk[['CensusTract2010','PUMA2010']].drop_duplicates(keep='first'),how='left',left_on='CT',right_on='CensusTract2010') # hhstr=hhstr[hhstr['PUMA2010']==i].reset_index(drop=True) # k=tp.groupby(['CT','PREDHHSTR'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True) # k=k.pivot(index='CT',columns='PREDHHSTR',values='TOTAL').reset_index(drop=False) # k=pd.merge(hhstr,k,how='inner',on=['CT']) # k['STR1']=np.where((k['STR1_y']<=k['STR1_x']+k['STR1M'])&(k['STR1_y']>=k['STR1_x']-k['STR1M']),1,0) # k['STR2']=np.where((k['STR2_y']<=k['STR2_x']+k['STR2M'])&(k['STR2_y']>=k['STR2_x']-k['STR2M']),1,0) # k['STR']=np.where((k['STR1']==1)&(k['STR2']==1),1,0) # sum(k['STR'])/len(k) # k=tp.groupby(['CT','PREDHHSTR'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True) # k=pd.merge(hhstr.melt(id_vars=['CT'],value_vars=['STR1','STR2'],var_name='HHSTR',value_name='TOTAL'),k,how='inner',left_on=['CT','HHSTR'],right_on=['CT','PREDHHSTR']) # p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') # p.show() # pumsszincstr=pd.DataFrame(ipfn.ipfn.product(tp['HHSIZE'].unique(),tp['HHINC'].unique(),tp['PREDHHSTR'].unique())) # pumsszincstr.columns=['HHSIZE','HHINC','HHSTR'] # pumsszincstrtp=pums[pums['PUMA']==i].reset_index(drop=True) # pumsszincstrtp=pumsszincstrtp.groupby(['HHSIZE','HHINC','HHSTR'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True) # pumsszincstr=pd.merge(pumsszincstr,pumsszincstrtp,how='left',on=['HHSIZE','HHINC','HHSTR']) # pumsszincstr['TOTAL']=pumsszincstr['WGTP'].fillna(0) # pumsszincstr=pumsszincstr[['HHSIZE','HHINC','HHSTR','TOTAL']].reset_index(drop=True) # k=tp.groupby(['HHSIZE','HHINC','PREDHHSTR'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True) # k=pd.merge(pumsszincstr,k,how='inner',left_on=['HHSIZE','HHINC','HHSTR'],right_on=['HHSIZE','HHINC','PREDHHSTR']) # p=px.scatter(k,x='TOTAL_x',y='TOTAL_y',hover_data=['HHSIZE','HHINC','HHSTR']) # p.show() # tp.to_csv(path+'POP/test1.csv',index=False) # # k=pd.merge(hhsize,df.groupby(['CT','HHSIZE'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True),how='inner',on=['CT','HHSIZE']) # # k['ERR2']=np.square(k['TOTAL_y']-k['TOTAL_x']) # # print(np.sqrt(sum(k['ERR2'])/len(k))) # # p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') # # p.show() # # k=pd.merge(hhinc,df.groupby(['CT','HHINC'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True),how='inner',on=['CT','HHINC']) # # k['ERR2']=np.square(k['TOTAL_y']-k['TOTAL_x']) # # print(np.sqrt(sum(k['ERR2'])/len(k))) # # p=px.scatter(k,x='TOTAL_x',y='TOTAL_y') # # p.show() # # k=pd.merge(pumsszic,df.groupby(['HHSIZE','HHINC'],as_index=False).agg({'TOTAL':'sum'}).reset_index(drop=True),how='inner',on=['HHSIZE','HHINC']) # # k['ERR2']=np.square(k['TOTAL']-k['WGTP']) # # print(np.sqrt(sum(k['ERR2'])/len(k))) # # p=px.scatter(k,x='WGTP',y='TOTAL') # # p.show()<file_sep>/rhts.py import urllib.request import shutil import os import pandas as pd import numpy as np import datetime import pytz import geopandas as gpd import shapely pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' # Map Population by Time of Day # Trips rhtstrip=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/RHTS/LINKED_Public.csv',dtype=str) rhtstrip['pid']=rhtstrip['SAMPN']+'|'+rhtstrip['PERNO'] df=[] for i in rhtstrip['pid'].unique(): tp=rhtstrip[rhtstrip['pid']==i].reset_index(drop=True) tp['hour']=pd.to_numeric(tp['TRP_ARR_HR']) tp['min']=pd.to_numeric(tp['TRP_ARR_MIN']) tp=tp.sort_values(['hour','min']).reset_index(drop=True) tp['dest']=tp['DTRACT'] tp=tp[['hour','dest']].reset_index(drop=True) tp['hour']=['h'+str(x).zfill(2) for x in tp['hour']] tp=tp.drop_duplicates(['hour'],keep='last').reset_index(drop=True) tp=pd.merge(pd.DataFrame(data=['h'+str(x).zfill(2) for x in range(0,24)],columns=['hour']),tp,how='left',on='hour') tp=pd.concat([tp]*2,axis=0,ignore_index=True) for j in tp.index[1:]: if pd.isna(tp.loc[j,'dest']): tp.loc[j,'dest']=tp.loc[j-1,'dest'] tp=tp[pd.notna(tp['dest'])].drop_duplicates(keep='first').sort_values(['hour']).reset_index(drop=True) tp['pid']=i tp['wt']=pd.to_numeric(list(rhtstrip.loc[rhtstrip['pid']==i,'HH_WHT2'])[0]) tp=tp[['pid','wt','hour','dest']].reset_index(drop=True) df+=[tp] df=pd.concat(df,axis=0,ignore_index=True) df=df.groupby(['dest','hour'],as_index=False).agg({'wt':'sum'}).reset_index(drop=True) df=df.pivot(index='dest',columns='hour',values='wt').reset_index(drop=False) df.to_csv('C:/Users/mayij/Desktop/DOC/GITHUB/td-tdm/rhtstrip.csv',index=False) # Non-trips rhtsps=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/RHTS/PER_Public.csv',dtype=str,encoding='latin-1') rhtshh=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/RHTS/HH_Public.csv',dtype=str,encoding='latin-1') df=pd.merge(rhtsps,rhtshh,how='inner',on='SAMPN') df['pid']=df['SAMPN']+'|'+df['PERNO'] df['wt']=pd.to_numeric(df['HH_WHT2_x']) df['dest']=df['HTRACT'].copy() df=df.loc[df['PTRIPS']=='0',['pid','wt','dest']].reset_index(drop=True) df=df.groupby(['dest'],as_index=False).agg({'wt':'sum'}).reset_index(drop=True) for i in ['h'+str(x).zfill(2) for x in range(0,24)]: df[i]=df['wt'].copy() df=df[['dest']+['h'+str(x).zfill(2) for x in range(0,24)]].reset_index(drop=True) df.to_csv('C:/Users/mayij/Desktop/DOC/GITHUB/td-tdm/rhtsnontrip.csv',index=False) # Combine rhtstrip=pd.read_csv('C:/Users/mayij/Desktop/DOC/GITHUB/td-tdm/rhtstrip.csv') rhtsnontrip=pd.read_csv('C:/Users/mayij/Desktop/DOC/GITHUB/td-tdm/rhtsnontrip.csv') df=pd.merge(rhtstrip,rhtsnontrip,how='outer',on='dest') df=df.fillna(0) for i in ['h'+str(x).zfill(2) for x in range(0,24)]: df[i]=df[i+'_x']+df[i+'_y'] df['tractid']=[str(x).zfill(11) for x in df['dest']] df['county']=[x[0:5] for x in df['tractid']] df=df[np.isin(df['county'],['36005','36047','36061','36081','36085'])].reset_index(drop=True) quadstatect=gpd.read_file('C:/Users/mayij/Desktop/DOC/DCP2018/TRAVELSHEDREVAMP/shp/quadstatectclipped.shp') quadstatect.crs=4326 df=pd.merge(quadstatect,df,how='inner',on='tractid') df=df[['tractid','h00','h01','h02','h03','h04','h05','h06','h07','h08','h09','h10','h11','h12','h13','h14','h15', 'h16','h17','h18','h19','h20','h21','h22','h23','geometry']].reset_index(drop=True) # df=df.melt(id_vars=['tractid','geometry'],value_vars=['h'+str(x).zfill(2) for x in range(0,24)]) # df['h17'].describe(percentiles=np.arange(0.2,1,0.2)) for i in ['h'+str(x).zfill(2) for x in range(0,24)]: df[i+'cat']=np.where(df[i]>10000,'> 10,000', np.where(df[i]>8000,'8,001 ~ 10,000', np.where(df[i]>6000,'6,001 ~ 8,000', np.where(df[i]>4000,'4,001 ~ 6,000', np.where(df[i]>2000,'2,001 ~ 4,000','<= 2,000'))))) df.to_file('C:/Users/mayij/Desktop/DOC/GITHUB/td-tdm/rhts.geojson',driver='GeoJSON') # Clean Household rhtshh=pd.read_csv(path+'RHTS/HH_Public.csv',dtype=str) rhtshh['HHID']=rhtshh['SAMPN'].copy() rhtshh['WGTP']=pd.to_numeric(rhtshh['HH_WHT2']) rhtshh['HHSIZE']=np.where(rhtshh['HHSIZ']=='1','SIZE1', np.where(rhtshh['HHSIZ']=='2','SIZE2', np.where(rhtshh['HHSIZ']=='3','SIZE3','SIZE4'))) rhtshh['HHTYPE']=np.where(rhtshh['HHSTRUC']=='1','TYPE1', np.where(rhtshh['HHSTRUC']=='2','TYPE2', np.where(rhtshh['HHSTRUC']=='3','TYPE3', np.where(rhtshh['HHSTRUC']=='4','TYPE4', np.where(rhtshh['HHSTRUC']=='5','TYPE5', np.where(rhtshh['HHSTRUC']=='6','TYPE6','OTH')))))) rhtshh=rhtshh[rhtshh['INCOM']!='99'].reset_index(drop=True) rhtshh['HHINC']=np.where(rhtshh['INCOM']=='1','INC201', np.where(rhtshh['INCOM']=='2','INC202', np.where(rhtshh['INCOM']=='3','INC203', np.where(rhtshh['INCOM']=='4','INC204', np.where(rhtshh['INCOM']=='5','INC205', np.where(rhtshh['INCOM']=='6','INC206', np.where(rhtshh['INCOM']=='7','INC207', np.where(rhtshh['INCOM']=='8','INC207','OTH')))))))) rhtshh=rhtshh[rhtshh['RESTY']!='8'].reset_index(drop=True) rhtshh=rhtshh[rhtshh['RESTY']!='9'].reset_index(drop=True) rhtshh['HHSTR']=np.where(rhtshh['RESTY']=='1','STR1', np.where(rhtshh['RESTY']=='2','STRM', np.where(rhtshh['RESTY']=='3','STRO','OTH'))) rhtshh['HHVEH']=np.where(rhtshh['HHVEH']=='0','VEH0', np.where(rhtshh['HHVEH']=='1','VEH1', np.where(rhtshh['HHVEH']=='2','VEH2', np.where(rhtshh['HHVEH']=='3','VEH3','VEH4')))) rhtshh=rhtshh[['HHID','WGTP','HHSIZE','HHTYPE','HHINC','HHSTR','HHVEH']].reset_index(drop=True) rhtshh.to_csv(path+'RHTS/rhtshh.csv',index=False) # Clean Person rhtspp=pd.read_csv(path+'RHTS/PER_Public.csv',dtype=str,encoding='latin-1') rhtspp['PPID']=rhtspp['SAMPN']+'|'+rhtspp['PERNO'] rhtspp['HHID']=rhtspp['SAMPN'].copy() rhtspp['PWGTP']=pd.to_numeric(rhtspp['HH_WHT2']) rhtspp=rhtspp[rhtspp['GENDER']!='RF'].reset_index(drop=True) rhtspp['PPSEX']=np.where(rhtspp['GENDER']=='Male','MALE','FEMALE') rhtspp=rhtspp[rhtspp['AGE_R']!='Age not provided'].reset_index(drop=True) rhtspp['PPAGE']=np.where(rhtspp['AGE_R']=='Younger than 16 years','AGE201', np.where(rhtspp['AGE_R']=='16-18 years','AGE202', np.where(rhtspp['AGE_R']=='19-24 years','AGE203', np.where(rhtspp['AGE_R']=='25-34 years','AGE204', np.where(rhtspp['AGE_R']=='35-54 years','AGE205', np.where(rhtspp['AGE_R']=='55-64 years','AGE206', np.where(rhtspp['AGE_R']=='65 years or older','AGE207','OTHER'))))))) rhtspp=rhtspp[rhtspp['HISP']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['HISP']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['RACE']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['RACE']!='DK'].reset_index(drop=True) rhtspp['PPRACE']=np.where(rhtspp['HISP']=='Yes','HSP', np.where(rhtspp['RACE']=='White','WHT', np.where(rhtspp['RACE']=='African American, Black','BLK', np.where(rhtspp['RACE']=='American Indian, Alaskan Native','NTV', np.where(rhtspp['RACE']=='Asian','ASN', np.where(rhtspp['RACE']=='Pacific Islander','PCF', np.where(rhtspp['RACE']=='Other (Specify)','OTH', np.where(rhtspp['RACE']=='Multiracial','TWO','OT')))))))) rhtspp=rhtspp[rhtspp['STUDE']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['STUDE']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['SCHOL']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['SCHOL']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['SCHOL']!='Other (Specify)'].reset_index(drop=True) rhtspp['PPSCH']=np.where(pd.isna(rhtspp['SCHOL']),'NS', np.where(rhtspp['SCHOL']=='Daycare','PR', np.where(rhtspp['SCHOL']=='Nursery/Pre-school','PR', np.where(rhtspp['SCHOL']=='Kindergarten to Grade 8','G8', np.where(rhtspp['SCHOL']=='Grade 9 to 12','HS', np.where(rhtspp['SCHOL']=='4-Year College or University','CL', np.where(rhtspp['SCHOL']=='2-Year College (Community College)','CL', np.where(rhtspp['SCHOL']=='Vocational/Technical School','CL', np.where(rhtspp['SCHOL']=='Graduate School/Professional','GS','OT'))))))))) rhtspp=rhtspp[rhtspp['EMPLY']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['EMPLY']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['VOLUN']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['VOLUN']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['WKSTAT']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['WKSTAT']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['INDUS']!='DON’T KNOW'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['INDUS']!='REFUSED'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['INDUS']!='OTHER (SPECIFY __________)'].reset_index(drop=True) rhtspp['PPIND']=np.where(pd.isna(rhtspp['EMPLY']),'U16', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Retired'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Homemaker'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Student (Part-time or Full-time)'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Unemployed, Not Seeking Employment'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Unemployed but Looking for Work'),'CUP', np.where(rhtspp['OCCUP']=='MILITARY SPECIFIC OCCUPATIONS','MIL', np.where(rhtspp['INDUS']=='AGRICULTURE, FORESTRY, FISHING AND HUNTING','AGR', np.where(rhtspp['INDUS']=='MINING, QUARRYING, AND OIL AND GAS EXTRACTION','EXT', np.where(rhtspp['INDUS']=='CONSTRUCTION','CON', np.where(rhtspp['INDUS']=='MANUFACTURING','MFG', np.where(rhtspp['INDUS']=='WHOLESALE TRADE','WHL', np.where(rhtspp['INDUS']=='RETAIL TRADE','RET', np.where(rhtspp['INDUS']=='TRANSPORTATION AND WAREHOUSING','TRN', np.where(rhtspp['INDUS']=='UTILITIES','UTL', np.where(rhtspp['INDUS']=='INFORMATION','INF', np.where(rhtspp['INDUS']=='FINANCE AND INSURANCE','FIN', np.where(rhtspp['INDUS']=='REAL ESTATE, RENTAL AND LEASING','RER', np.where(rhtspp['INDUS']=='PROFESSIONAL, SCIENTIFIC AND TECHNICAL SERVICES','PRF', np.where(rhtspp['INDUS']=='MANAGEMENT OF COMPANIES AND ENTERPRISES','MNG', np.where(rhtspp['INDUS']=='ADMINISTRATION AND SUPPORT AND WARE MANAGEMENT AND REMEDIATION SERVICES','WMS', np.where(rhtspp['INDUS']=='EDUCATIONAL SERVICES','EDU', np.where(rhtspp['INDUS']=='HEALTH CARE AND SOCIAL ASSISTANCE','MED', np.where(rhtspp['INDUS']=='ARTS, ENTERTAINMENT, AND RECREATION','ENT', np.where(rhtspp['INDUS']=='ACCOMODATION AND FOOD SERVICES','ACC', np.where(rhtspp['INDUS']=='OTHER SERVICES (EXCEPT PUBLIC ADMINISTRATION)','SRV', np.where(rhtspp['INDUS']=='PUBLIC ADMINISTRATION','ADM','OTH'))))))))))))))))))))))))))) rhtspp=rhtspp[rhtspp['LIC']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['LIC']!='RF'].reset_index(drop=True) rhtspp['PPLIC']=np.where(pd.isna(rhtspp['LIC']),'U16', np.where(rhtspp['LIC']=='Yes','YES', np.where(rhtspp['LIC']=='No','NO','OTH'))) rhtspp['PPTRIPS']=np.where(rhtspp['PTRIPS']=='0','TRIP0', np.where(rhtspp['PTRIPS']=='2','TRIP2', np.where(rhtspp['PTRIPS']=='3','TRIP3', np.where(rhtspp['PTRIPS']=='4','TRIP4','TRIPO')))) # rhtspp['PPTRIPS']=pd.to_numeric(rhtspp['PTRIPS']) rhtspp=rhtspp[['PPID','HHID','PWGTP','PPSEX','PPAGE','PPRACE','PPSCH','PPIND','PPLIC','PPTRIPS']].reset_index(drop=True) rhtspp.to_csv(path+'RHTS/rhtspp.csv',index=False) <file_sep>/acs.py import requests import pandas as pd import numpy as np pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' apikey=pd.read_csv('C:/Users/mayij/Desktop/DOC/GITHUB/td-acsapi/apikey.csv',header=None).loc[0,0] nyc=['36005','36047','36061','36081','36085'] nymtc=['36005','36047','36061','36081','36085','36059','36103','36119','36087','36079'] bpm=['36005','36047','36061','36081','36085','36059','36103','36119','36087','36079','36071','36027', '09001','09009','34017','34003','34031','34013','34039','34027','34035','34023','34025','34029', '34037','34041','34019','34021'] # Household Total df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B25002)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B25002_001E','B25002_001M']].reset_index(drop=True) rs.columns=['CT','TT','TTM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/hhtt.csv',index=False) # Household Occupancy df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B25002)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B25002_001E','B25002_001M','B25002_002E','B25002_002M', 'B25002_003E','B25002_003M']].reset_index(drop=True) rs.columns=['CT','TT','TTM','OCC','OCCM','VAC','VACM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/hhocc.csv',index=False) # Household Size hhocc=pd.read_csv(path+'ACS/hhocc.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S2501)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S2501_C01_002E','S2501_C01_002M','S2501_C01_003E','S2501_C01_003M', 'S2501_C01_004E','S2501_C01_004M','S2501_C01_005E','S2501_C01_005M']].reset_index(drop=True) rs.columns=['CT','SIZE1','SIZE1M','SIZE2','SIZE2M','SIZE3','SIZE3M','SIZE4','SIZE4M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(df,hhocc,how='inner',on='CT') df=df[['CT','TT','TTM','VAC','VACM','SIZE1','SIZE1M','SIZE2','SIZE2M','SIZE3','SIZE3M', 'SIZE4','SIZE4M']].reset_index(drop=True) df.to_csv(path+'ACS/hhsize.csv',index=False) # Household Type hhocc=pd.read_csv(path+'ACS/hhocc.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/profile?get=NAME,group(DP02)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','DP02_0002E','DP02_0002M','DP02_0003E','DP02_0003M', 'DP02_0004E','DP02_0004M','DP02_0005E','DP02_0005M', 'DP02_0006E','DP02_0006M','DP02_0007E','DP02_0007M', 'DP02_0008E','DP02_0008M','DP02_0010E','DP02_0010M', 'DP02_0011E','DP02_0011M','DP02_0012E','DP02_0012M']].reset_index(drop=True) rs.columns=['CT','MC','MCM','MCC','MCCM','CC','CCM','CCC','CCCM','MH','MHM','MHC','MHCM', 'MHA','MHAM','FH','FHM','FHC','FHCM','FHA','FHAM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(df,hhocc,how='inner',on='CT') df=df[['CT','TT','TTM','VAC','VACM','MC','MCM','MCC','MCCM','CC','CCM','CCC','CCCM','MH','MHM', 'MHC','MHCM','MHA','MHAM','FH','FHM','FHC','FHCM','FHA','FHAM']].reset_index(drop=True) df.to_csv(path+'ACS/hhtype.csv',index=False) # Household Income hhocc=pd.read_csv(path+'ACS/hhocc.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S2503)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S2503_C01_002E','S2503_C01_002M','S2503_C01_003E','S2503_C01_003M', 'S2503_C01_004E','S2503_C01_004M','S2503_C01_005E','S2503_C01_005M', 'S2503_C01_006E','S2503_C01_006M','S2503_C01_007E','S2503_C01_007M', 'S2503_C01_008E','S2503_C01_008M','S2503_C01_009E','S2503_C01_009M', 'S2503_C01_010E','S2503_C01_010M','S2503_C01_011E','S2503_C01_011M', 'S2503_C01_012E','S2503_C01_012M']].reset_index(drop=True) rs.columns=['CT','INC01','INC01M','INC02','INC02M','INC03','INC03M','INC04','INC04M', 'INC05','INC05M','INC06','INC06M','INC07','INC07M','INC08','INC08M','INC09','INC09M', 'INC10','INC10M','INC11','INC11M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(df,hhocc,how='inner',on='CT') df=df[['CT','TT','TTM','VAC','VACM','INC01','INC01M','INC02','INC02M','INC03','INC03M','INC04','INC04M', 'INC05','INC05M','INC06','INC06M','INC07','INC07M','INC08','INC08M','INC09','INC09M', 'INC10','INC10M','INC11','INC11M']].reset_index(drop=True) df.to_csv(path+'ACS/hhinc.csv',index=False) # Household Tenure hhocc=pd.read_csv(path+'ACS/hhocc.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B25003)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B25003_002E','B25003_002M','B25003_003E','B25003_003M']].reset_index(drop=True) rs.columns=['CT','OWNER','OWNERM','RENTER','RENTERM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(df,hhocc,how='inner',on='CT') df=df[['CT','TT','TTM','VAC','VACM','OWNER','OWNERM','RENTER','RENTERM']].reset_index(drop=True) df.to_csv(path+'ACS/hhten.csv',index=False) # Household Structure hhocc=pd.read_csv(path+'ACS/hhocc.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S2504)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S2504_C01_002E','S2504_C01_002M','S2504_C01_003E','S2504_C01_003M', 'S2504_C01_004E','S2504_C01_004M','S2504_C01_005E','S2504_C01_005M', 'S2504_C01_006E','S2504_C01_006M','S2504_C01_007E','S2504_C01_007M', 'S2504_C01_008E','S2504_C01_008M']].reset_index(drop=True) rs.columns=['CT','STR1D','STR1DM','STR1A','STR1AM','STR2','STR2M','STR34','STR34M', 'STR59','STR59M','STR10','STR10M','STRO','STROM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(df,hhocc,how='inner',on='CT') df=df[['CT','TT','TTM','VAC','VACM','STR1D','STR1DM','STR1A','STR1AM','STR2','STR2M','STR34','STR34M', 'STR59','STR59M','STR10','STR10M','STRO','STROM']].reset_index(drop=True) df.to_csv(path+'ACS/hhstr.csv',index=False) # Household Built df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B25034)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B25034_001E','B25034_001M','B25034_002E','B25034_002M', 'B25034_003E','B25034_003M','B25034_004E','B25034_004M', 'B25034_005E','B25034_005M','B25034_006E','B25034_006M', 'B25034_007E','B25034_007M','B25034_008E','B25034_008M', 'B25034_009E','B25034_009M','B25034_010E','B25034_010M', 'B25034_011E','B25034_011M']].reset_index(drop=True) rs.columns=['CT','TT','TTM','B14','B14M','B10','B10M','B00','B00M','B90','B90M','B80','B80M', 'B70','B70M','B60','B60M','B50','B50M','B40','B40M','B39','B39M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/hhblt.csv',index=False) # Household Bedroom df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B25041)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B25041_001E','B25041_001M','B25041_002E','B25041_002M', 'B25041_003E','B25041_003M','B25041_004E','B25041_004M', 'B25041_005E','B25041_005M','B25041_006E','B25041_006M', 'B25041_007E','B25041_007M']].reset_index(drop=True) rs.columns=['CT','TT','TTM','BED0','BED0M','BED1','BED1M','BED2','BED2M','BED3','BED3M', 'BED4','BED4M','BED5','BED5M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/hhbed.csv',index=False) # Household Vehicles hhocc=pd.read_csv(path+'ACS/hhocc.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B08203)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B08203_002E','B08203_002M','B08203_003E','B08203_003M', 'B08203_004E','B08203_004M','B08203_005E','B08203_005M', 'B08203_006E','B08203_006M']].reset_index(drop=True) rs.columns=['CT','VEH0','VEH0M','VEH1','VEH1M','VEH2','VEH2M','VEH3','VEH3M','VEH4','VEH4M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(df,hhocc,how='inner',on='CT') df=df[['CT','TT','TTM','VAC','VACM','VEH0','VEH0M','VEH1','VEH1M','VEH2','VEH2M','VEH3','VEH3M', 'VEH4','VEH4M']].reset_index(drop=True) df.to_csv(path+'ACS/hhveh.csv',index=False) # Group Quarter Population df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B26001)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B26001_001E','B26001_001M']].reset_index(drop=True) rs.columns=['CT','GQTT','GQTTM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/gqtt.csv',index=False) # Total Population df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S0101)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S0101_C01_001E','S0101_C01_001M']].reset_index(drop=True) rs.columns=['CT','TT','TTM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/pptt.csv',index=False) # Sex df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S0101)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S0101_C01_001E','S0101_C01_001M','S0101_C03_001E','S0101_C03_001M', 'S0101_C05_001E','S0101_C05_001M']].reset_index(drop=True) rs.columns=['CT','TT','TTM','MALE','MALEM','FEMALE','FEMALEM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/ppsex.csv',index=False) # Age df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S0101)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S0101_C01_001E','S0101_C01_001M','S0101_C01_002E','S0101_C01_002M', 'S0101_C01_003E','S0101_C01_003M','S0101_C01_004E','S0101_C01_004M', 'S0101_C01_005E','S0101_C01_005M','S0101_C01_006E','S0101_C01_006M', 'S0101_C01_007E','S0101_C01_007M','S0101_C01_008E','S0101_C01_008M', 'S0101_C01_009E','S0101_C01_009M','S0101_C01_010E','S0101_C01_010M', 'S0101_C01_011E','S0101_C01_011M','S0101_C01_012E','S0101_C01_012M', 'S0101_C01_013E','S0101_C01_013M','S0101_C01_014E','S0101_C01_014M', 'S0101_C01_015E','S0101_C01_015M','S0101_C01_016E','S0101_C01_016M', 'S0101_C01_017E','S0101_C01_017M','S0101_C01_018E','S0101_C01_018M', 'S0101_C01_019E','S0101_C01_019M']].reset_index(drop=True) rs.columns=['CT','TT','TTM','AGE01','AGE01M','AGE02','AGE02M','AGE03','AGE03M','AGE04','AGE04M', 'AGE05','AGE05M','AGE06','AGE06M','AGE07','AGE07M','AGE08','AGE08M','AGE09','AGE09M', 'AGE10','AGE10M','AGE11','AGE11M','AGE12','AGE12M','AGE13','AGE13M','AGE14','AGE14M', 'AGE15','AGE15M','AGE16','AGE16M','AGE17','AGE17M','AGE18','AGE18M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/ppage.csv',index=False) # Race df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B03002)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B03002_001E','B03002_001M','B03002_012E','B03002_012M', 'B03002_003E','B03002_003M','B03002_004E','B03002_004M', 'B03002_005E','B03002_005M','B03002_006E','B03002_006M', 'B03002_007E','B03002_007M','B03002_008E','B03002_008M', 'B03002_009E','B03002_009M']].reset_index(drop=True) rs.columns=['CT','TT','TTM','HSP','HSPM','WHT','WHTM','BLK','BLKM','NTV','NTVM','ASN','ASNM', 'PCF','PCFM','OTH','OTHM','TWO','TWOM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df.to_csv(path+'ACS/pprace.csv',index=False) # Education pptt=pd.read_csv(path+'ACS/pptt.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S1501)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S1501_C01_001E','S1501_C01_001M','S1501_C01_002E','S1501_C01_002M', 'S1501_C01_003E','S1501_C01_003M','S1501_C01_004E','S1501_C01_004M', 'S1501_C01_005E','S1501_C01_005M','S1501_C01_006E','S1501_C01_006M', 'S1501_C01_007E','S1501_C01_007M','S1501_C01_008E','S1501_C01_008M', 'S1501_C01_009E','S1501_C01_009M','S1501_C01_010E','S1501_C01_010M', 'S1501_C01_011E','S1501_C01_011M','S1501_C01_012E','S1501_C01_012M', 'S1501_C01_013E','S1501_C01_013M']].reset_index(drop=True) rs.columns=['CT','U24TT','U24TTM','U24LH','U24LHM','U24HS','U24HSM','U24AD','U24ADM', 'U24BD','U24BDM','O25TT','O25TTM','O25G9','O25G9M','O25LH','O25LHM','O25HS','O25HSM', 'O25SC','O25SCM','O25AD','O25ADM','O25BD','O25BDM','O25GD','O25GDM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(pptt,df,how='left',on='CT') df=df.fillna(0) df['TT']=pd.to_numeric(df['TT']) df['TTM']=pd.to_numeric(df['TTM']) df['U24TT']=pd.to_numeric(df['U24TT']) df['U24TTM']=pd.to_numeric(df['U24TTM']) df['O25TT']=pd.to_numeric(df['O25TT']) df['O25TTM']=pd.to_numeric(df['O25TTM']) df['U18']=df['TT']-df['U24TT']-df['O25TT'] df['U18M']=np.sqrt(df['TTM']**2+df['U24TTM']**2+df['O25TTM']**2) df=df[['CT','TT','TTM','U18','U18M','U24LH','U24LHM','U24HS','U24HSM','U24AD','U24ADM', 'U24BD','U24BDM','O25G9','O25G9M','O25LH','O25LHM','O25HS','O25HSM','O25SC','O25SCM', 'O25AD','O25ADM','O25BD','O25BDM','O25GD','O25GDM']].reset_index(drop=True) df.to_csv(path+'ACS/ppedu.csv',index=False) # School pptt=pd.read_csv(path+'ACS/pptt.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S1401)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S1401_C01_001E','S1401_C01_001M','S1401_C01_002E','S1401_C01_002M', 'S1401_C01_004E','S1401_C01_004M','S1401_C01_005E','S1401_C01_005M', 'S1401_C01_006E','S1401_C01_006M','S1401_C01_007E','S1401_C01_007M', 'S1401_C01_008E','S1401_C01_008M','S1401_C01_009E','S1401_C01_009M']].reset_index(drop=True) rs.columns=['CT','TS','TSM','PR','PRM','KG','KGM','G14','G14M','G58','G58M','HS','HSM','CL','CLM', 'GS','GSM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(pptt,df,how='left',on='CT') df=df.fillna(0) df['TT']=pd.to_numeric(df['TT']) df['TTM']=pd.to_numeric(df['TTM']) df['TS']=pd.to_numeric(df['TS']) df['TSM']=pd.to_numeric(df['TSM']) df['NS']=df['TT']-df['TS'] df['NSM']=np.sqrt(df['TTM']**2+df['TSM']**2) df=df[['CT','TT','TTM','NS','NSM','PR','PRM','KG','KGM','G14','G14M','G58','G58M','HS','HSM','CL','CLM', 'GS','GSM']].reset_index(drop=True) df.to_csv(path+'ACS/ppsch.csv',index=False) # Industry pptt=pd.read_csv(path+'ACS/pptt.csv',dtype=str) df1=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/subject?get=NAME,group(S2403)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','S2403_C01_001E','S2403_C01_001M','S2403_C01_003E','S2403_C01_003M', 'S2403_C01_004E','S2403_C01_004M','S2403_C01_005E','S2403_C01_005M', 'S2403_C01_006E','S2403_C01_006M','S2403_C01_007E','S2403_C01_007M', 'S2403_C01_008E','S2403_C01_008M','S2403_C01_010E','S2403_C01_010M', 'S2403_C01_011E','S2403_C01_011M','S2403_C01_012E','S2403_C01_012M', 'S2403_C01_014E','S2403_C01_014M','S2403_C01_015E','S2403_C01_015M', 'S2403_C01_017E','S2403_C01_017M','S2403_C01_018E','S2403_C01_018M', 'S2403_C01_019E','S2403_C01_019M','S2403_C01_021E','S2403_C01_021M', 'S2403_C01_022E','S2403_C01_022M','S2403_C01_024E','S2403_C01_024M', 'S2403_C01_025E','S2403_C01_025M','S2403_C01_026E','S2403_C01_026M', 'S2403_C01_027E','S2403_C01_027M']].reset_index(drop=True) rs.columns=['CT','CEP','CEPM','AGR','AGRM','EXT','EXTM','CON','CONM','MFG','MFGM','WHL','WHLM', 'RET','RETM','TRN','TRNM','UTL','UTLM','INF','INFM','FIN','FINM','RER','RERM', 'PRF','PRFM','MNG','MNGM','WMS','WMSM','EDU','EDUM','MED','MEDM','ENT','ENTM', 'ACC','ACCM','SRV','SRVM','ADM','ADMM'] df1+=[rs] df1=pd.concat(df1,axis=0,ignore_index=True) df2=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B23025)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B23025_001E','B23025_001M','B23025_005E','B23025_005M', 'B23025_006E','B23025_006M','B23025_007E','B23025_007M']].reset_index(drop=True) rs.columns=['CT','O16','O16M','CUP','CUPM','MIL','MILM','NLF','NLFM'] df2+=[rs] df2=pd.concat(df2,axis=0,ignore_index=True) df=pd.merge(pptt,df1,how='left',on='CT') df=pd.merge(df,df2,how='left',on='CT') df=df.fillna(0) df['TT']=pd.to_numeric(df['TT']) df['TTM']=pd.to_numeric(df['TTM']) df['O16']=pd.to_numeric(df['O16']) df['O16M']=pd.to_numeric(df['O16M']) df['U16']=df['TT']-df['O16'] df['U16M']=np.sqrt(df['TTM']**2+df['O16M']**2) df=df[['CT','TT','TTM','U16','U16M','AGR','AGRM','EXT','EXTM','CON','CONM','MFG','MFGM','WHL','WHLM', 'RET','RETM','TRN','TRNM','UTL','UTLM','INF','INFM','FIN','FINM','RER','RERM','PRF','PRFM', 'MNG','MNGM','WMS','WMSM','EDU','EDUM','MED','MEDM','ENT','ENTM','ACC','ACCM','SRV','SRVM', 'ADM','ADMM','CUP','CUPM','MIL','MILM','NLF','NLFM']].reset_index(drop=True) df.to_csv(path+'ACS/ppind.csv',index=False) # Mode pptt=pd.read_csv(path+'ACS/pptt.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B08301)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B08301_001E','B08301_001M','B08301_003E','B08301_003M', 'B08301_005E','B08301_005M','B08301_006E','B08301_006M', 'B08301_007E','B08301_007M','B08301_008E','B08301_008M', 'B08301_009E','B08301_009M','B08301_011E','B08301_011M', 'B08301_012E','B08301_012M','B08301_013E','B08301_013M', 'B08301_014E','B08301_014M','B08301_015E','B08301_015M', 'B08301_016E','B08301_016M','B08301_017E','B08301_017M', 'B08301_018E','B08301_018M','B08301_019E','B08301_019M', 'B08301_020E','B08301_020M','B08301_021E','B08301_021M']].reset_index(drop=True) rs.columns=['CT','TW','TWM','DA','DAM','CP2','CP2M','CP3','CP3M','CP4','CP4M','CP56','CP56M', 'CP7','CP7M','BS','BSM','SW','SWM','CR','CRM','LR','LRM','FB','FBM','TC','TCM', 'MC','MCM','BC','BCM','WK','WKM','OT','OTM','HM','HMM'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(pptt,df,how='left',on='CT') df=df.fillna(0) df['TT']=pd.to_numeric(df['TT']) df['TTM']=pd.to_numeric(df['TTM']) df['TW']=pd.to_numeric(df['TW']) df['TWM']=pd.to_numeric(df['TWM']) df['NW']=df['TT']-df['TW'] df['NWM']=np.sqrt(df['TTM']**2+df['TWM']**2) df=df[['CT','TT','TTM','NW','NWM','DA','DAM','CP2','CP2M','CP3','CP3M','CP4','CP4M','CP56','CP56M', 'CP7','CP7M','BS','BSM','SW','SWM','CR','CRM','LR','LRM','FB','FBM','TC','TCM','MC','MCM', 'BC','BCM','WK','WKM','OT','OTM','HM','HMM']].reset_index(drop=True) df.to_csv(path+'ACS/ppmode.csv',index=False) # Time pptt=pd.read_csv(path+'ACS/pptt.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B08303)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B08303_001E','B08303_001M','B08303_002E','B08303_002M', 'B08303_003E','B08303_003M','B08303_004E','B08303_004M', 'B08303_005E','B08303_005M','B08303_006E','B08303_006M', 'B08303_007E','B08303_007M','B08303_008E','B08303_008M', 'B08303_009E','B08303_009M','B08303_010E','B08303_010M', 'B08303_011E','B08303_011M','B08303_012E','B08303_012M', 'B08303_013E','B08303_013M']].reset_index(drop=True) rs.columns=['CT','TNHW','TNHWM','TM01','TM01M','TM02','TM02M','TM03','TM03M','TM04','TM04M', 'TM05','TM05M','TM06','TM06M','TM07','TM07M','TM08','TM08M','TM09','TM09M', 'TM10','TM10M','TM11','TM11M','TM12','TM12M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(pptt,df,how='left',on='CT') df=df.fillna(0) df['TT']=pd.to_numeric(df['TT']) df['TTM']=pd.to_numeric(df['TTM']) df['TNHW']=pd.to_numeric(df['TNHW']) df['TNHWM']=pd.to_numeric(df['TNHWM']) df['NWHM']=df['TT']-df['TNHW'] df['NWHMM']=np.sqrt(df['TTM']**2+df['TNHWM']**2) df=df[['CT','TT','TTM','NWHM','NWHMM','TM01','TM01M','TM02','TM02M','TM03','TM03M','TM04','TM04M', 'TM05','TM05M','TM06','TM06M','TM07','TM07M','TM08','TM08M','TM09','TM09M','TM10','TM10M', 'TM11','TM11M','TM12','TM12M']].reset_index(drop=True) df.to_csv(path+'ACS/pptime.csv',index=False) # Departure pptt=pd.read_csv(path+'ACS/pptt.csv',dtype=str) df=[] for i in bpm: rs=requests.get('https://api.census.gov/data/2019/acs/acs5/?get=NAME,group(B08302)&for=tract:*&in=state:'+i[:2]+' county:'+i[2:]+'&key='+apikey).json() rs=pd.DataFrame(rs) rs.columns=rs.loc[0] rs=rs.loc[1:].reset_index(drop=True) rs['geoid']=[x[9:] for x in rs['GEO_ID']] rs=rs[['geoid','B08302_001E','B08302_001M','B08302_002E','B08302_002M', 'B08302_003E','B08302_003M','B08302_004E','B08302_004M', 'B08302_005E','B08302_005M','B08302_006E','B08302_006M', 'B08302_007E','B08302_007M','B08302_008E','B08302_008M', 'B08302_009E','B08302_009M','B08302_010E','B08302_010M', 'B08302_011E','B08302_011M','B08302_012E','B08302_012M', 'B08302_013E','B08302_013M','B08302_014E','B08302_014M', 'B08302_015E','B08302_015E']].reset_index(drop=True) rs.columns=['CT','TNHW','TNHWM','DP01','DP01M','DP02','DP02M','DP03','DP03M','DP04','DP04M', 'DP05','DP05M','DP06','DP06M','DP07','DP07M','DP08','DP08M','DP09','DP09M', 'DP10','DP10M','DP11','DP11M','DP12','DP12M','DP13','DP13M','DP14','DP14M'] df+=[rs] df=pd.concat(df,axis=0,ignore_index=True) df=pd.merge(pptt,df,how='left',on='CT') df=df.fillna(0) df['TT']=pd.to_numeric(df['TT']) df['TTM']=pd.to_numeric(df['TTM']) df['TNHW']=pd.to_numeric(df['TNHW']) df['TNHWM']=pd.to_numeric(df['TNHWM']) df['NWHM']=df['TT']-df['TNHW'] df['NWHMM']=np.sqrt(df['TTM']**2+df['TNHWM']**2) df=df[['CT','TT','TTM','NWHM','NWHMM','DP01','DP01M','DP02','DP02M','DP03','DP03M','DP04','DP04M', 'DP05','DP05M','DP06','DP06M','DP07','DP07M','DP08','DP08M','DP09','DP09M','DP10','DP10M', 'DP11','DP11M','DP12','DP12M','DP13','DP13M','DP14','DP14M']].reset_index(drop=True) df.to_csv(path+'ACS/ppdepart.csv',index=False) <file_sep>/mnl.py import ipfn import pandas as pd import numpy as np import sklearn.model_selection import sklearn.linear_model import sklearn.tree import sklearn.ensemble import sklearn.neural_network import sklearn.cluster import sklearn.decomposition import statsmodels.api as sm import statsmodels.formula.api as smf import matplotlib.pyplot as plt import seaborn as sns import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' pio.renderers.default = "browser" dfpp=pd.read_csv(path+'POP/dfpp.csv',dtype=str,converters={'PWGTP':float,'TOTAL':float},nrows=100) dfpp['ODIND']=np.where(np.isin(dfpp['PPIND'],['AGR','EXT','CON','MFG']),'IND1', np.where(np.isin(dfpp['PPIND'],['UTL','WHL','RET','TRN']),'IND2', np.where(np.isin(dfpp['PPIND'],['INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM']),'IND3','OTH'))) odctct=pd.read_csv(path+'LEHD/odctct.csv',dtype=float,converters={'RACCT':str,'WACCT':str}) odctct=odctct.melt(id_vars=['RACCT','WACCT'],value_vars=['IND1','IND2','IND3'],var_name='ODIND',value_name='TOTAL') dfpp['TOTALRD']=[round(x) for x in dfpp['TOTAL']] sum(dfpp.TOTALRD)/sum(dfpp.TOTAL) k=pd.merge(dfpp,odctct,how='inner',left_on=['CT','ODIND'],right_on=['RACCT','ODIND']) # Household rhtshh=pd.read_csv(path+'RHTS/HH_Public.csv',dtype=str) rhtshh['HHID']=rhtshh['SAMPN'].copy() rhtshh['WGTP']=pd.to_numeric(rhtshh['HH_WHT2']) rhtshh['HHSIZE']=np.where(rhtshh['HHSIZ']=='1','SIZE1', np.where(rhtshh['HHSIZ']=='2','SIZE2', np.where(rhtshh['HHSIZ']=='3','SIZE3','SIZE4'))) rhtshh['HHTYPE']=np.where(rhtshh['HHSTRUC']=='1','TYPE1', np.where(rhtshh['HHSTRUC']=='2','TYPE2', np.where(rhtshh['HHSTRUC']=='3','TYPE3', np.where(rhtshh['HHSTRUC']=='4','TYPE4', np.where(rhtshh['HHSTRUC']=='5','TYPE5', np.where(rhtshh['HHSTRUC']=='6','TYPE6','OTH')))))) rhtshh=rhtshh[rhtshh['INCOM']!='99'].reset_index(drop=True) rhtshh['HHINC']=np.where(rhtshh['INCOM']=='1','INC201', np.where(rhtshh['INCOM']=='2','INC202', np.where(rhtshh['INCOM']=='3','INC203', np.where(rhtshh['INCOM']=='4','INC204', np.where(rhtshh['INCOM']=='5','INC205', np.where(rhtshh['INCOM']=='6','INC206', np.where(rhtshh['INCOM']=='7','INC207', np.where(rhtshh['INCOM']=='8','INC207','OTH')))))))) rhtshh=rhtshh[rhtshh['RESTY']!='8'].reset_index(drop=True) rhtshh=rhtshh[rhtshh['RESTY']!='9'].reset_index(drop=True) rhtshh['HHSTR']=np.where(rhtshh['RESTY']=='1','STR1', np.where(rhtshh['RESTY']=='2','STRM', np.where(rhtshh['RESTY']=='3','STRO','OTH'))) rhtshh['HHVEH']=np.where(rhtshh['HHVEH']=='0','VEH0', np.where(rhtshh['HHVEH']=='1','VEH1', np.where(rhtshh['HHVEH']=='2','VEH2', np.where(rhtshh['HHVEH']=='3','VEH3','VEH4')))) rhtshh=rhtshh[['HHID','WGTP','HHSIZE','HHTYPE','HHINC','HHSTR','HHVEH']].reset_index(drop=True) # Person rhtspp=pd.read_csv(path+'RHTS/PER_Public.csv',dtype=str,encoding='latin-1') rhtspp['PPID']=rhtspp['SAMPN']+'|'+rhtspp['PERNO'] rhtspp['HHID']=rhtspp['SAMPN'].copy() rhtspp['PWGTP']=pd.to_numeric(rhtspp['HH_WHT2']) rhtspp=rhtspp[rhtspp['GENDER']!='RF'].reset_index(drop=True) rhtspp['PPSEX']=np.where(rhtspp['GENDER']=='Male','MALE','FEMALE') rhtspp=rhtspp[rhtspp['AGE_R']!='Age not provided'].reset_index(drop=True) rhtspp['PPAGE']=np.where(rhtspp['AGE_R']=='Younger than 16 years','AGE201', np.where(rhtspp['AGE_R']=='16-18 years','AGE202', np.where(rhtspp['AGE_R']=='19-24 years','AGE203', np.where(rhtspp['AGE_R']=='25-34 years','AGE204', np.where(rhtspp['AGE_R']=='35-54 years','AGE205', np.where(rhtspp['AGE_R']=='55-64 years','AGE206', np.where(rhtspp['AGE_R']=='65 years or older','AGE207','OTHER'))))))) rhtspp=rhtspp[rhtspp['HISP']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['HISP']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['RACE']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['RACE']!='DK'].reset_index(drop=True) rhtspp['PPRACE']=np.where(rhtspp['HISP']=='Yes','HSP', np.where(rhtspp['RACE']=='White','WHT', np.where(rhtspp['RACE']=='African American, Black','BLK', np.where(rhtspp['RACE']=='American Indian, Alaskan Native','NTV', np.where(rhtspp['RACE']=='Asian','ASN', np.where(rhtspp['RACE']=='Pacific Islander','PCF', np.where(rhtspp['RACE']=='Other (Specify)','OTH', np.where(rhtspp['RACE']=='Multiracial','TWO','OT')))))))) rhtspp=rhtspp[rhtspp['STUDE']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['STUDE']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['SCHOL']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['SCHOL']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['SCHOL']!='Other (Specify)'].reset_index(drop=True) rhtspp['PPSCH']=np.where(pd.isna(rhtspp['SCHOL']),'NS', np.where(rhtspp['SCHOL']=='Daycare','PR', np.where(rhtspp['SCHOL']=='Nursery/Pre-school','PR', np.where(rhtspp['SCHOL']=='Kindergarten to Grade 8','G8', np.where(rhtspp['SCHOL']=='Grade 9 to 12','HS', np.where(rhtspp['SCHOL']=='4-Year College or University','CL', np.where(rhtspp['SCHOL']=='2-Year College (Community College)','CL', np.where(rhtspp['SCHOL']=='Vocational/Technical School','CL', np.where(rhtspp['SCHOL']=='Graduate School/Professional','GS','OT'))))))))) rhtspp=rhtspp[rhtspp['EMPLY']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['EMPLY']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['VOLUN']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['VOLUN']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['WKSTAT']!='RF'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['WKSTAT']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['INDUS']!='DON’T KNOW'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['INDUS']!='REFUSED'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['INDUS']!='OTHER (SPECIFY __________)'].reset_index(drop=True) rhtspp['PPIND']=np.where(pd.isna(rhtspp['EMPLY']),'U16', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Retired'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Homemaker'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Student (Part-time or Full-time)'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Unemployed, Not Seeking Employment'),'NLF', np.where((rhtspp['WORKS']=='Not a Worker')&(rhtspp['WKSTAT']=='Unemployed but Looking for Work'),'CUP', np.where(rhtspp['OCCUP']=='MILITARY SPECIFIC OCCUPATIONS','MIL', np.where(rhtspp['INDUS']=='AGRICULTURE, FORESTRY, FISHING AND HUNTING','AGR', np.where(rhtspp['INDUS']=='MINING, QUARRYING, AND OIL AND GAS EXTRACTION','EXT', np.where(rhtspp['INDUS']=='CONSTRUCTION','CON', np.where(rhtspp['INDUS']=='MANUFACTURING','MFG', np.where(rhtspp['INDUS']=='WHOLESALE TRADE','WHL', np.where(rhtspp['INDUS']=='RETAIL TRADE','RET', np.where(rhtspp['INDUS']=='TRANSPORTATION AND WAREHOUSING','TRN', np.where(rhtspp['INDUS']=='UTILITIES','UTL', np.where(rhtspp['INDUS']=='INFORMATION','INF', np.where(rhtspp['INDUS']=='FINANCE AND INSURANCE','FIN', np.where(rhtspp['INDUS']=='REAL ESTATE, RENTAL AND LEASING','RER', np.where(rhtspp['INDUS']=='PROFESSIONAL, SCIENTIFIC AND TECHNICAL SERVICES','PRF', np.where(rhtspp['INDUS']=='MANAGEMENT OF COMPANIES AND ENTERPRISES','MNG', np.where(rhtspp['INDUS']=='ADMINISTRATION AND SUPPORT AND WARE MANAGEMENT AND REMEDIATION SERVICES','WMS', np.where(rhtspp['INDUS']=='EDUCATIONAL SERVICES','EDU', np.where(rhtspp['INDUS']=='HEALTH CARE AND SOCIAL ASSISTANCE','MED', np.where(rhtspp['INDUS']=='ARTS, ENTERTAINMENT, AND RECREATION','ENT', np.where(rhtspp['INDUS']=='ACCOMODATION AND FOOD SERVICES','ACC', np.where(rhtspp['INDUS']=='OTHER SERVICES (EXCEPT PUBLIC ADMINISTRATION)','SRV', np.where(rhtspp['INDUS']=='PUBLIC ADMINISTRATION','ADM','OTH'))))))))))))))))))))))))))) rhtspp=rhtspp[rhtspp['LIC']!='DK'].reset_index(drop=True) rhtspp=rhtspp[rhtspp['LIC']!='RF'].reset_index(drop=True) rhtspp['PPLIC']=np.where(pd.isna(rhtspp['LIC']),'U16', np.where(rhtspp['LIC']=='Yes','YES', np.where(rhtspp['LIC']=='No','NO','OTH'))) rhtspp['PPTRIPS']=np.where(rhtspp['PTRIPS']=='0','TRIP0', np.where(rhtspp['PTRIPS']=='2','TRIP2', np.where(rhtspp['PTRIPS']=='3','TRIP3', np.where(rhtspp['PTRIPS']=='4','TRIP4','TRIPO')))) # rhtspp['PPTRIPS']=pd.to_numeric(rhtspp['PTRIPS']) rhtspp=rhtspp[['PPID','HHID','PWGTP','PPSEX','PPAGE','PPRACE','PPSCH','PPIND','PPLIC','PPTRIPS']].reset_index(drop=True) rhtstrip=pd.read_csv(path+'RHTS/LINKED_Public.csv',dtype=str) rhtstrip['TRIPID']=rhtstrip['SAMPN']+'|'+rhtstrip['PERNO']+'|'+rhtstrip['PLANO'] rhtstrip['TOURID']=rhtstrip['SAMPN']+'|'+rhtstrip['PERNO']+'|'+rhtstrip['TOUR_ID'] rhtstrip['PPID']=rhtstrip['SAMPN']+'|'+rhtstrip['PERNO'] rhtstrip['HHID']=rhtstrip['SAMPN'].copy() rhtstrip=rhtstrip[rhtstrip['ODTPURP']=='1'].reset_index(drop=True) rhtstrip['RESCT']=[str(x).zfill(11) for x in rhtstrip['OTRACT']] rhtstrip['WORKCT']=[str(x).zfill(11) for x in rhtstrip['DTRACT']] rhtstrip['PPMODE']=np.where(np.isin(rhtstrip['PMODE_R3'],['1']),'CAR', np.where(np.isin(rhtstrip['PMODE_R3'],['2']),'TRANSIT','OTHER')) rhtstrip['PPTIME']=pd.to_numeric(rhtstrip['TRPDUR']) # AM PEAK k=rhtstrip[rhtstrip['TOD_R']=='1'].reset_index(drop=True) k=k[k['PPMODE']=='TRANSIT'].reset_index(drop=True) k=k[['PPID','RESCT','WORKCT','PPTIME']].reset_index(drop=True) # resct=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2018/TRAVELSHEDREVAMP/tableau/resct.csv',dtype=str,converters={'time':float}) resct=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2018/TRAVELSHEDREVAMP/nyctract/resct3.csv',dtype=float,converters={'tractid':str}) resct=pd.melt(resct,id_vars=['tractid']) resct=resct[resct['value']!=999].reset_index(drop=True) resct['RESCT']=[x.replace('RES','') for x in resct['variable']] resct['WORKCT']=resct['tractid'].copy() resct['TRANSIT']=pd.to_numeric(resct['value']) resct=resct[['RESCT','WORKCT','TRANSIT']].reset_index(drop=True) k=pd.merge(k,resct,how='inner',on=['RESCT','WORKCT']) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='RHTS vs TRAVELSHED', x=k['PPTIME'], y=k['TRANSIT'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5})) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['PPTIME'])], y=[0,max(k['PPTIME'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2})) fig.update_layout( template='plotly_white', legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'ACS', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) k=pd.merge(k,resct,how='left',on=['RESCT']) k=k[pd.notna(k['TRANSIT'])].reset_index(drop=True) k['DEC']=np.where(k['WORKCT_x']==k['WORKCT_y'],1,0) xtrain=k[['PPTIME']] ytrain=k[['DEC']] sm.MNLogit(ytrain,sm.add_constant(xtrain)).fit().summary() rhtstrip.PMODE_R3.value_counts(dropna=False) k=rhtstrip[(rhtstrip['OTPURP_AGG']=='0')&(rhtstrip['DTPURP_AGG']=='1')] k=rhtstrip.groupby('TRIPID').agg({'PLANO':'count'}) k=rhtstrip[(rhtstrip['SAMPN']=='4133756')&(rhtstrip['PERNO']=='2')&(rhtstrip['TOUR_ID']=='1')] df=pd.merge(rhtspp,rhtshh,how='inner',on='HHID') p=sklearn.decomposition.PCA(n_components=0.99,svd_solver='full') p.fit_transform(pd.get_dummies(df[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHTYPE','HHINC','HHSTR','HHVEH']],drop_first=True)) n=p.n_components_ p=pd.DataFrame(data=p.fit_transform(pd.get_dummies(df[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHTYPE','HHINC','HHSTR','HHVEH']],drop_first=True)),columns=['PCA'+str(x) for x in range(1,n+1)]) pcakm=sklearn.cluster.KMeans(n_clusters=5) p['PCAKKM5']=pcakm.fit_predict(p) k=pd.concat([df[['PPTRIPS']],p[['PCAKKM5']]],axis=1,ignore_index=False) k['COUNT']=1 k.groupby(['PPTRIPS','PCAKKM5']).agg({'COUNT':'count'}) df['PPIND']=np.where(df['PPIND']=='U16','U16', np.where(df['PPIND']=='NLF','NLF', np.where(df['PPIND']=='CUP','CUP','EMP'))) xtrain=pd.get_dummies(df[['PPIND']],drop_first=True) ytrain=df[['PPTRIPS']] sm.MNLogit(ytrain,sm.add_constant(xtrain)).fit().summary() df=df.groupby(['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH'],as_index=False).agg({'PPID':'count'}).reset_index(drop=True) df.PPID.value_counts(dropna=False) # LIC # Data Split df=pd.merge(rhtspp,rhtshh,how='inner',on='HHID') xtrain,xtest,ytrain,ytest=sklearn.model_selection.train_test_split(df[['PPSEX','PPAGE','PPRACE', 'PPSCH','PPIND','HHSIZE', 'HHINC','HHSTR','HHVEH']], df['PPLIC'],test_size=0.5) xtrain=pd.get_dummies(xtrain[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH']],drop_first=True) xtest=pd.get_dummies(xtest[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH']],drop_first=True) # NN nn=sklearn.neural_network.MLPClassifier().fit(xtrain,ytrain) ypred=pd.DataFrame({'train':ytrain,'pred':nn.predict(xtrain)}) print(sklearn.metrics.classification_report(ytrain,ypred['pred'])) ypred=pd.DataFrame({'test':ytest,'pred':nn.predict(xtest)}) print(sklearn.metrics.classification_report(ytest,ypred['pred'])) # MNL reg=sklearn.linear_model.LogisticRegression().fit(xtrain,ytrain) sm.MNLogit(ytrain,sm.add_constant(xtrain)).fit().summary() ypred=pd.DataFrame({'train':ytrain,'pred':reg.predict(xtrain)}) print(sklearn.metrics.classification_report(ytrain,ypred['pred'])) ypred=pd.DataFrame({'test':ytest,'pred':reg.predict(xtest)}) print(sklearn.metrics.classification_report(ytest,ypred['pred'])) # TRIPS # Data Split df=pd.merge(rhtspp,rhtshh,how='inner',on='HHID') xtrain,xtest,ytrain,ytest=sklearn.model_selection.train_test_split(df[['PPSEX','PPAGE','PPRACE', 'PPSCH','PPIND','HHSIZE', 'HHINC','HHSTR','HHVEH']], df['PPTRIPS'],test_size=0.5) xtrain=pd.get_dummies(xtrain[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH']],drop_first=True) xtest=pd.get_dummies(xtest[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH']],drop_first=True) # NN nn=sklearn.neural_network.MLPClassifier().fit(xtrain,ytrain) ypred=pd.DataFrame({'train':ytrain,'pred':nn.predict(xtrain)}) print(sklearn.metrics.classification_report(ytrain,ypred['pred'])) ypred=pd.DataFrame({'test':ytest,'pred':nn.predict(xtest)}) print(sklearn.metrics.classification_report(ytest,ypred['pred'])) # MNL reg=sklearn.linear_model.LogisticRegression().fit(xtrain,ytrain) sm.MNLogit(ytrain,sm.add_constant(xtrain)).fit().summary() ypred=pd.DataFrame({'train':ytrain,'pred':reg.predict(xtrain)}) print(sklearn.metrics.classification_report(ytrain,ypred['pred'])) ypred=pd.DataFrame({'test':ytest,'pred':reg.predict(xtest)}) print(sklearn.metrics.classification_report(ytest,ypred['pred'])) # MNL xtrain=pd.get_dummies(df[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH']],drop_first=True) ytrain=df[['PPTRIPS']] reg=sklearn.linear_model.LogisticRegression(max_iter=1000).fit(xtrain,ytrain) sm.MNLogit(ytrain,sm.add_constant(xtrain)).fit().summary() ypred=pd.DataFrame({'train':ytrain,'pred':reg.predict(xtrain)}) print(sklearn.metrics.classification_report(ytrain,ypred['pred'])) df.PPTRIPS.value_counts(dropna=False) df=pd.merge(rhtspp,rhtshh,how='inner',on='HHID') df=df[df['PPTRIPS']<=6].reset_index(drop=True) xtrain,xtest,ytrain,ytest=sklearn.model_selection.train_test_split(df[['PPSEX','PPAGE','PPRACE', 'PPSCH','PPIND','HHSIZE', 'HHINC','HHSTR','HHVEH']], df['PPTRIPS'],test_size=0.5) xtrain=pd.get_dummies(xtrain[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH']],drop_first=True) xtest=pd.get_dummies(xtest[['PPSEX','PPAGE','PPRACE','PPSCH','PPIND','HHSIZE','HHINC','HHSTR','HHVEH']],drop_first=True) reg=sklearn.linear_model.LinearRegression().fit(xtrain,ytrain) sm.OLS(ytrain,sm.add_constant(xtrain)).fit().summary() ypred=pd.DataFrame({'train':ytrain,'pred':[round(x) for x in reg.predict(xtrain)]}) print(sklearn.metrics.classification_report(ytrain,ypred['pred'])) ypred=pd.DataFrame({'test':ytest,'pred':[round(x) for x in reg.predict(xtest)]}) print(sklearn.metrics.classification_report(ytest,ypred['pred'])) # Backup # pumshh=pd.read_csv(path+'PUMS/pumshh.csv',dtype=str,converters={'WGTP':float}) # pumabed=pumshh[np.isin(pumshh['HHBLT'],['B00','B10','B14'])].reset_index(drop=True) # pumabed=pumabed.groupby(['PUMA','HHBED'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True) # pumabed=pd.merge(pumabed,pumabed.groupby(['PUMA'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True),how='inner',on='PUMA') # pumabed['PCT']=pumabed['WGTP_x']/pumabed['WGTP_y'] # pumabed=pumabed[['PUMA','HHBED','PCT']].reset_index(drop=True) # tp=pd.DataFrame(columns=['PUMA','CT','UNIT']) # tp.loc[0]=['3603805','36005020000',100] # tpbed=pd.DataFrame(ipfn.ipfn.product(tp['CT'],pumshh['HHBED'].unique()),columns=['CT','HHBED']) # tpbed=pd.merge(tp,tpbed,how='inner',on='CT') # tpbed=pd.merge(tpbed,pumabed,how='inner',on=['PUMA','HHBED']) # tpbed['UNIT']=tpbed['UNIT']*tpbed['PCT'] # tpbed=tpbed[['PUMA','CT','HHBED','UNIT']].reset_index(drop=True) # # MNL # df=pd.concat([pumshh[['WGTP','HHSIZE']],pd.get_dummies(pumshh['HHBED'],drop_first=True)],axis=1,ignore_index=False) # df['WGTP']=pd.to_numeric(df['WGTP']) # trainx=df.drop(['WGTP','HHSIZE'],axis=1) # trainy=df['HHSIZE'] # trainwt=df['WGTP'] # reg=sklearn.linear_model.LogisticRegression(max_iter=1000).fit(trainx,trainy,trainwt) # # sm.MNLogit(trainy,sm.add_constant(trainx)).fit().summary() # tpbedsize=pd.DataFrame(ipfn.ipfn.product(sorted(pumshh['HHBED'].unique()),sorted(pumshh['HHSIZE'].unique())),columns=['HHBED','HHSIZE']) # tpbedsize=pd.concat([tpbedsize[['HHSIZE']],pd.get_dummies(tpbedsize['HHBED'],drop_first=True)],axis=1,ignore_index=False) # tpbedsize['MNL']=np.nan # modelx=tpbedsize.drop(['HHSIZE','MNL'],axis=1).drop_duplicates(keep='first') # tpbedsize['MNL']=np.ndarray.flatten(reg.predict_proba(modelx)) # tpbedsize['HHBED']=np.where(tpbedsize['BED1']==1,'BED1', # np.where(tpbedsize['BED2']==1,'BED2', # np.where(tpbedsize['BED3']==1,'BED3', # np.where(tpbedsize['BED4']==1,'BED4', # np.where(tpbedsize['BED5']==1,'BED5','BED0'))))) # tpbedsize=tpbedsize[['HHBED','HHSIZE','MNL']].reset_index(drop=True) # # Proportional Allocation # df=pumshh[['HHBED','HHSIZE','WGTP']].reset_index(drop=True) # df['WGTP']=pd.to_numeric(df['WGTP']) # df=df.groupby(['HHBED','HHSIZE'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True) # df=pd.merge(df,df.groupby(['HHBED'],as_index=False).agg({'WGTP':'sum'}).reset_index(drop=True),how='inner',on='HHBED') # df['PCT']=df['WGTP_x']/df['WGTP_y'] # df=df[['HHBED','HHSIZE','PCT']].reset_index(drop=True) # tpbedsize=pd.merge(tpbed,tpbedsize,how='inner',on='HHBED') # tpbedsize=pd.merge(tpbedsize,df,how='inner',on=['HHBED','HHSIZE']) # df=pd.read_csv(path+'RHTS/HH_Public.csv') # df=df[['RESTY','HHSIZ','INCOM','HHVEH','HHSTU','HHWRK','HHLIC','HHCHD','HTRIPS_GPS','HH_WHT2']].reset_index(drop=True) # df['RESTY']=np.where(df['RESTY']==1,'SG', # np.where(df['RESTY']==2,'MT','OT')) # df['INCOM']=np.where(df['INCOM']==1,'1', # np.where(df['INCOM']==2,'2', # np.where(df['INCOM']==3,'3', # np.where(df['INCOM']==4,'4', # np.where(df['INCOM']==5,'5', # np.where(df['INCOM']==6,'6', # np.where(df['INCOM']==7,'7', # np.where(df['INCOM']==8,'8','NA')))))))) # df['HHVEH']=np.where(df['HHVEH']==0,'0', # np.where(df['HHVEH']==1,'1', # np.where(df['HHVEH']==2,'2','3+'))) # df=pd.concat([df[['HHSIZ','HHVEH','HHSTU','HHWRK','HHLIC','HHCHD','HTRIPS_GPS','HH_WHT2']],pd.get_dummies(df[['RESTY','INCOM']],drop_first=True)],axis=1,ignore_index=False) # x=df[['RESTY_OT','RESTY_SG','HHSIZ','INCOM_2','INCOM_3','INCOM_4','INCOM_5','INCOM_6','INCOM_7', # 'INCOM_8','INCOM_NA','HHSTU','HHWRK','HHLIC','HHCHD']] # y=df['HHVEH'] # wt=df['HH_WHT2'] # reg=sklearn.linear_model.LogisticRegression(max_iter=1000).fit(x,y,wt) # cm=sklearn.metrics.confusion_matrix(y,reg.predict(x)) # sns.heatmap(cm,annot=True) # plt.ylabel('True Label') # plt.xlabel('Predicted Label') # dt=sklearn.tree.DecisionTreeClassifier().fit(x,y,wt) # cm=sklearn.metrics.confusion_matrix(y,dt.predict(x)) # sns.heatmap(cm,annot=True) # plt.ylabel('True Label') # plt.xlabel('Predicted Label') # gbdt=sklearn.ensemble.GradientBoostingClassifier(learning_rate=1).fit(x,y,wt) # cm=sklearn.metrics.confusion_matrix(y,gbdt.predict(x)) # sns.heatmap(cm,annot=True) # plt.ylabel('True Label') # plt.xlabel('Predicted Label') # xtrain,xtest,ytrain,ytest=sklearn.model_selection.train_test_split(df[['SEX','RACE1','RACE2','RACE3','AGE1','AGE2','AGE3','AGE4','EMP']],df['TRIP'],test_size=0.4) # reg=sklearn.linear_model.LogisticRegression().fit(xtrain,ytrain) # ypred=pd.DataFrame({'test':ytest,'pred':reg.predict(xtest)}) # sm.MNLogit(y,sm.add_constant(x)).fit().summary() # # Confusion Matrix # cm=sklearn.metrics.confusion_matrix(ytest,reg.predict(xtest)) # sns.heatmap(cm,annot=True) # plt.ylabel('True Label') # plt.xlabel('Predicted Label') <file_sep>/turnstile.py import urllib.request import shutil import os import pandas as pd import numpy as np import datetime import pytz import geopandas as gpd import shapely pd.set_option('display.max_columns', None) rc=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/RemoteComplex.csv',dtype=str,converters={'CplxID':float,'CplxLat':float,'CplxLong':float,'Hub':float}) df=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/OUTPUT/dfunitentry.csv',dtype=str,converters={'entries':float,'gooducs':float,'flagtime':float,'flagentry':float}) df=df.groupby(['unit','firstdate'],as_index=False).agg({'entries':'sum'}).reset_index(drop=True) df['wkd']=[datetime.datetime.strptime(x,'%m/%d/%Y').weekday() for x in df['firstdate']] df=df[np.isin(df['wkd'],[0,1,2,3,4])].reset_index(drop=True) df['year']=[x[6:] for x in df['firstdate']] df=df[df['year']=='2019'].reset_index(drop=True) df=df.groupby(['unit'],as_index=False).agg({'entries':'mean'}).reset_index(drop=True) df.columns=['Remote','Entries'] df=pd.merge(df,rc,how='left',on='Remote') df=df.groupby(['CplxID'],as_index=False).agg({'Entries':'sum'}).reset_index(drop=True) df=pd.merge(rc.drop('Remote',axis=1).drop_duplicates(keep='first').reset_index(drop=True),df,how='left',on='CplxID') df=df[['CplxID','CplxLat','CplxLong','Entries']].reset_index(drop=True) df=gpd.GeoDataFrame(df,geometry=[shapely.geometry.Point(x,y) for x,y in zip(df['CplxLong'],df['CplxLat'])],crs=4326) df=df.to_crs(6539) df['geometry']=df.buffer(2640) nta=gpd.read_file('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/ntaclippedadj.shp') nta.crs=4326 nta=nta.to_crs(6539) df=gpd.overlay(df,nta,how='intersection') df['area']=[x.area for x in df['geometry']] dfsum=df.groupby(['CplxID'],as_index=False).agg({'area':'sum'}).reset_index(drop=True) df=pd.merge(df,dfsum,how='inner',on='CplxID') df['pct']=df['area_x']/df['area_y'] df=df[['CplxID','NTACode','pct','Entries']].reset_index(drop=True) df['Entries']=df['Entries']*df['pct'] df=df.groupby(['NTACode'],as_index=False).agg({'Entries':'sum'}).reset_index(drop=True) df=pd.merge(nta,df,how='inner',on='NTACode') df=df.to_crs(4326) df.to_file('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/TURNSTILE/turnstile.shp') rc=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/RemoteComplex.csv',dtype=str,converters={'CplxID':float,'CplxLat':float,'CplxLong':float,'Hub':float}) df=pd.read_csv('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/OUTPUT/dfunitentry.csv',dtype=str,converters={'entries':float,'gooducs':float,'flagtime':float,'flagentry':float}) df=df.groupby(['unit','firstdate'],as_index=False).agg({'entries':'sum'}).reset_index(drop=True) df['wkd']=[datetime.datetime.strptime(x,'%m/%d/%Y').weekday() for x in df['firstdate']] df=df[np.isin(df['wkd'],[0,1,2,3,4])].reset_index(drop=True) df['month']=[x.split('/')[0] for x in df['firstdate']] df['year']=[x.split('/')[-1] for x in df['firstdate']] dfpre=df[df['month']=='04'].reset_index(drop=True) dfpre=dfpre[dfpre['year']=='2019'].reset_index(drop=True) dfpre=dfpre.groupby(['unit'],as_index=False).agg({'entries':'mean'}).reset_index(drop=True) dfpre.columns=['Remote','E201904'] dfpost=df[df['month']=='04'].reset_index(drop=True) dfpost=dfpost[dfpost['year']=='2020'].reset_index(drop=True) dfpost=dfpost.groupby(['unit'],as_index=False).agg({'entries':'mean'}).reset_index(drop=True) dfpost.columns=['Remote','E202004'] df=pd.merge(dfpre,dfpost,how='inner',on='Remote') df=pd.merge(df,rc,how='left',on='Remote') df=df.groupby(['CplxID'],as_index=False).agg({'E201904':'sum','E202004':'sum'}).reset_index(drop=True) df=pd.merge(rc.drop('Remote',axis=1).drop_duplicates(keep='first').reset_index(drop=True),df,how='left',on='CplxID') df=df[['CplxID','CplxLat','CplxLong','E201904','E202004']].reset_index(drop=True) df=gpd.GeoDataFrame(df,geometry=[shapely.geometry.Point(x,y) for x,y in zip(df['CplxLong'],df['CplxLat'])],crs=4326) df=df.to_crs(6539) df['geometry']=df.buffer(2640) nta=gpd.read_file('C:/Users/mayij/Desktop/DOC/DCP2020/COVID19/SUBWAY/TURNSTILE/ntaclippedadj.shp') nta.crs=4326 nta=nta.to_crs(6539) df=gpd.overlay(df,nta,how='intersection') df['area']=[x.area for x in df['geometry']] dfsum=df.groupby(['CplxID'],as_index=False).agg({'area':'sum'}).reset_index(drop=True) df=pd.merge(df,dfsum,how='inner',on='CplxID') df['pct']=df['area_x']/df['area_y'] df=df[['CplxID','NTACode','pct','E201904','E202004']].reset_index(drop=True) df['E201904']=df['E201904']*df['pct'] df['E202004']=df['E202004']*df['pct'] df=df.groupby(['NTACode'],as_index=False).agg({'E201904':'sum','E202004':'sum'}).reset_index(drop=True) df=pd.merge(nta,df,how='inner',on='NTACode') df=df.to_crs(4326) df=df.drop('geometry',axis=1) df.to_csv('C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/TURNSTILE/turnstile2.csv',index=False) <file_sep>/lehd.py import ipfn import pandas as pd import numpy as np import sklearn.linear_model import statsmodels.api as sm import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pd.set_option('display.max_columns', None) path='C:/Users/mayij/Desktop/DOC/DCP2021/TRAVEL DEMAND MODEL/' pio.renderers.default='browser' bpm=['36005','36047','36061','36081','36085','36059','36103','36119','36087','36079','36071','36027', '09001','09009','34017','34003','34031','34013','34039','34027','34035','34023','34025','34029', '34037','34041','34019','34021'] geoxwalk=pd.read_csv(path+'POP/GEOIDCROSSWALK.csv',dtype=str) # Clean up RAC CT rac=[] for i in ['ct','nj','ny']: rac+=[pd.read_csv(path+'LEHD/'+i+'_rac_S000_JT01_2018.csv',dtype=float,converters={'h_geocode':str})] rac=pd.concat(rac,axis=0,ignore_index=True) rac.columns=['BK','TW','AGE301','AGE302','AGE303','EARN1','EARN2','EARN3','AGR','EXT','UTL','CON','MFG', 'WHL','RET','TRN','INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM', 'WHT','BLK','NTV','ASN','PCF','TWO','NHS','HSP','LH','HS','SCAD','BDGD','MALE','FEMALE', 'DATE'] rac=pd.merge(rac,geoxwalk,how='inner',left_on='BK',right_on='Block2010') rac=rac[np.isin(rac['StateCounty'],bpm)].reset_index(drop=True) rac=rac.groupby(['CensusTract2010'],as_index=False).agg({'TW':'sum','AGE301':'sum','AGE302':'sum', 'AGE303':'sum','AGR':'sum','EXT':'sum', 'UTL':'sum','CON':'sum','MFG':'sum','WHL':'sum', 'RET':'sum','TRN':'sum','INF':'sum','FIN':'sum', 'RER':'sum','PRF':'sum','MNG':'sum','WMS':'sum', 'EDU':'sum','MED':'sum','ENT':'sum','ACC':'sum', 'SRV':'sum','ADM':'sum','LH':'sum','HS':'sum', 'SCAD':'sum','BDGD':'sum','MALE':'sum', 'FEMALE':'sum'}).reset_index(drop=True) rac.columns=['CT','TW','AGE301','AGE302','AGE303','AGR','EXT','UTL','CON','MFG','WHL','RET','TRN', 'INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM','LH','HS','SCAD', 'BDGD','MALE','FEMALE'] rac.to_csv(path+'LEHD/racct.csv',index=False) # Validation dfpp=pd.read_csv(path+'POP/dfpp.csv',dtype=str,converters={'PWGTP':float,'TOTAL':float}) dfppwk=dfpp[(dfpp['PPMODE']!='NW')&(dfpp['PPIND']!='MIL')].reset_index(drop=True) dfppwk['RACAGE']=np.where(np.isin(dfppwk['PPAGE'],['AGE04','AGE05','AGE06']),'AGE301', np.where(np.isin(dfppwk['PPAGE'],['AGE07','AGE08','AGE09','AGE10','AGE11']),'AGE302', np.where(np.isin(dfppwk['PPAGE'],['AGE12','AGE13','AGE14','AGE15','AGE16','AGE17','AGE18']),'AGE303','OTH'))) rac=pd.read_csv(path+'LEHD/racct.csv',dtype=float,converters={'CT':str}) # RAC missing off-the-book residents # Check RACTW k=pd.merge(dfppwk.groupby(['CT'],as_index=False).agg({'TOTAL':'sum'}),rac[['CT','TW']],how='inner',on=['CT']) k=k.sort_values('TW').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'MODEL: '+k['TOTAL'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TW'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL']-k['TW'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL'], y=k['TW'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL'])], y=[0,max(k['TOTAL'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'RACTW (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/ractwpt.html',include_plotlyjs='cdn') # Check RACSEX k=rac.melt(id_vars=['CT'],value_vars=['MALE','FEMALE'],var_name='PPSEX',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['CT','PPSEX'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPSEX']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'RACSEX: '+k['PPSEX']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'RACSEX (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/racsexpt.html',include_plotlyjs='cdn') # Check RACAGE k=rac.melt(id_vars=['CT'],value_vars=['AGE301','AGE302','AGE303'],var_name='RACAGE',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['CT','RACAGE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','RACAGE']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'RACAGE: '+k['RACAGE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'RACAGE (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/racagept.html',include_plotlyjs='cdn') # Check RACIND k=rac.melt(id_vars=['CT'],value_vars=['AGR','EXT','UTL','CON','MFG','WHL','RET','TRN','INF','FIN', 'RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM'],var_name='PPIND',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['CT','PPIND'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','PPIND']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'RACIND: '+k['PPIND']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'RACIND (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/racindpt.html',include_plotlyjs='cdn') # Clean up WAC PUMA wac=[] for i in ['ct','nj','ny']: wac+=[pd.read_csv(path+'LEHD/'+i+'_wac_S000_JT01_2018.csv',dtype=float,converters={'w_geocode':str})] wac=pd.concat(wac,axis=0,ignore_index=True) wac.columns=['BK','TW','AGE301','AGE302','AGE303','EARN1','EARN2','EARN3','AGR','EXT','UTL','CON','MFG', 'WHL','RET','TRN','INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM', 'WHT','BLK','NTV','ASN','PCF','TWO','NHS','HSP','LH','HS','SCAD','BDGD','MALE','FEMALE', 'CFA01','CFA02','CFA03','CFA04','CFA05','CFS01','CFS02','CFS03','CFS04','CFS05','DATE'] wac=pd.merge(wac,geoxwalk,how='inner',left_on='BK',right_on='Block2010') wac=wac[np.isin(wac['StateCounty'],bpm)].reset_index(drop=True) wac=wac.groupby(['POWPUMA2010'],as_index=False).agg({'TW':'sum','AGE301':'sum','AGE302':'sum', 'AGE303':'sum','AGR':'sum','EXT':'sum', 'UTL':'sum','CON':'sum','MFG':'sum','WHL':'sum', 'RET':'sum','TRN':'sum','INF':'sum','FIN':'sum', 'RER':'sum','PRF':'sum','MNG':'sum','WMS':'sum', 'EDU':'sum','MED':'sum','ENT':'sum','ACC':'sum', 'SRV':'sum','ADM':'sum','LH':'sum','HS':'sum', 'SCAD':'sum','BDGD':'sum','MALE':'sum', 'FEMALE':'sum'}).reset_index(drop=True) wac.columns=['POWPUMA','TW','AGE301','AGE302','AGE303','AGR','EXT','UTL','CON','MFG','WHL','RET', 'TRN','INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM','LH','HS', 'SCAD','BDGD','MALE','FEMALE'] wac.to_csv(path+'LEHD/wacpuma.csv',index=False) # Validation dfpp=pd.read_csv(path+'POP/dfpp.csv',dtype=str,converters={'PWGTP':float,'TOTAL':float}) dfppwk=dfpp[(dfpp['PPMODE']!='NW')&(dfpp['PPIND']!='MIL')].reset_index(drop=True) dfppwk['WACAGE']=np.where(np.isin(dfppwk['PPAGE'],['AGE04','AGE05','AGE06']),'AGE301', np.where(np.isin(dfppwk['PPAGE'],['AGE07','AGE08','AGE09','AGE10','AGE11']),'AGE302', np.where(np.isin(dfppwk['PPAGE'],['AGE12','AGE13','AGE14','AGE15','AGE16','AGE17','AGE18']),'AGE303','OTH'))) wac=pd.read_csv(path+'LEHD/wacpuma.csv',dtype=float,converters={'POWPUMA':str}) # WAC missing off-the-book workers # Model missing residents outside BPM working in POWPUMAs # Check WACTW k=pd.merge(dfppwk.groupby(['POWPUMA'],as_index=False).agg({'TOTAL':'sum'}),wac[['POWPUMA','TW']],how='inner',on=['POWPUMA']) k=k.sort_values('TW').reset_index(drop=True) k['HOVER']='POWPUMA: '+k['POWPUMA']+'<br>'+'MODEL: '+k['TOTAL'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TW'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL']-k['TW'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL'], y=k['TW'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL'])], y=[0,max(k['TOTAL'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'WACTW (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/wactwpt.html',include_plotlyjs='cdn') # Check WACSEX k=wac.melt(id_vars=['POWPUMA'],value_vars=['MALE','FEMALE'],var_name='PPSEX',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['POWPUMA','PPSEX'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['POWPUMA','PPSEX']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='POWPUMA: '+k['POWPUMA']+'<br>'+'WACSEX: '+k['PPSEX']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'WACSEX (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/wacsexpt.html',include_plotlyjs='cdn') # Check WACAGE k=wac.melt(id_vars=['POWPUMA'],value_vars=['AGE301','AGE302','AGE303'],var_name='WACAGE',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['POWPUMA','WACAGE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['POWPUMA','WACAGE']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='POWPUMA: '+k['POWPUMA']+'<br>'+'WACAGE: '+k['WACAGE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'WACAGE (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/wacagept.html',include_plotlyjs='cdn') # Check WACIND k=wac.melt(id_vars=['POWPUMA'],value_vars=['AGR','EXT','UTL','CON','MFG','WHL','RET','TRN','INF', 'FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC', 'SRV','ADM'],var_name='PPIND',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['POWPUMA','PPIND'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['POWPUMA','PPIND']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='POWPUMA: '+k['POWPUMA']+'<br>'+'WACIND: '+k['PPIND']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'WACIND (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/wacindpt.html',include_plotlyjs='cdn') # Clean up ODCTPUMA od=[] for i in ['ct','nj','ny']: od+=[pd.read_csv(path+'LEHD/'+i+'_od_main_JT01_2018.csv',dtype=float,converters={'w_geocode':str,'h_geocode':str})] od+=[pd.read_csv(path+'LEHD/'+i+'_od_aux_JT01_2018.csv',dtype=float,converters={'w_geocode':str,'h_geocode':str})] od=pd.concat(od,axis=0,ignore_index=True) od.columns=['WBK','HBK','TW','AGE301','AGE302','AGE303','EARN1','EARN2','EARN3','IND1','IND2','IND3', 'DATE'] od=pd.merge(od,geoxwalk,how='inner',left_on='HBK',right_on='Block2010') od=od[np.isin(od['StateCounty'],bpm)].reset_index(drop=True) od=pd.merge(od,geoxwalk,how='inner',left_on='WBK',right_on='Block2010') od=od[np.isin(od['StateCounty_y'],bpm)].reset_index(drop=True) od=od.groupby(['CensusTract2010_x','POWPUMA2010_y'],as_index=False).agg({'TW':'sum', 'AGE301':'sum', 'AGE302':'sum', 'AGE303':'sum', 'IND1':'sum', 'IND2':'sum', 'IND3':'sum'}).reset_index(drop=True) od.columns=['CT','POWPUMA','TW','AGE301','AGE302','AGE303','IND1','IND2','IND3'] od.to_csv(path+'LEHD/odctpuma.csv',index=False) # Validation dfpp=pd.read_csv(path+'POP/dfpp.csv',dtype=str,converters={'PWGTP':float,'TOTAL':float}) dfppwk=dfpp[(dfpp['PPMODE']!='NW')&(dfpp['PPIND']!='MIL')].reset_index(drop=True) dfppwk=pd.merge(dfppwk,geoxwalk[['POWPUMA2010','StateCounty']].drop_duplicates(keep='first'),how='inner',left_on='POWPUMA',right_on='POWPUMA2010') dfppwk=dfppwk[np.isin(dfppwk['StateCounty'],bpm)].reset_index(drop=True) dfppwk=dfppwk.drop(['StateCounty'],axis=1).reset_index(drop=True) dfppwk=dfppwk.drop_duplicates(keep='first').reset_index(drop=True) dfppwk['ODAGE']=np.where(np.isin(dfppwk['PPAGE'],['AGE04','AGE05','AGE06']),'AGE301', np.where(np.isin(dfppwk['PPAGE'],['AGE07','AGE08','AGE09','AGE10','AGE11']),'AGE302', np.where(np.isin(dfppwk['PPAGE'],['AGE12','AGE13','AGE14','AGE15','AGE16','AGE17','AGE18']),'AGE303','OTH'))) dfppwk['ODIND']=np.where(np.isin(dfppwk['PPIND'],['AGR','EXT','CON','MFG']),'IND1', np.where(np.isin(dfppwk['PPIND'],['UTL','WHL','RET','TRN']),'IND2', np.where(np.isin(dfppwk['PPIND'],['INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM']),'IND3','OTH'))) od=pd.read_csv(path+'LEHD/odctpuma.csv',dtype=float,converters={'CT':str,'POWPUMA':str}) # OD missing off-the-book residents # Check ODTW k=pd.merge(dfppwk.groupby(['CT','POWPUMA'],as_index=False).agg({'TOTAL':'sum'}),od[['CT','POWPUMA','TW']],how='inner',on=['CT','POWPUMA']) k=k.sort_values('TW').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'POWPUMA: '+k['POWPUMA']+'<br>'+'MODEL: '+k['TOTAL'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TW'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL']-k['TW'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL'], y=k['TW'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL'])], y=[0,max(k['TOTAL'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'ODTW (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/odtwpt.html',include_plotlyjs='cdn') # Check ODAGE k=od.melt(id_vars=['CT','POWPUMA'],value_vars=['AGE301','AGE302','AGE303'],var_name='ODAGE',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['CT','POWPUMA','ODAGE'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','POWPUMA','ODAGE']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'POWPUMA: '+k['POWPUMA']+'<br>'+'ODAGE: '+k['ODAGE']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'ODAGE (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/odagept.html',include_plotlyjs='cdn') # Check ODIND k=od.melt(id_vars=['CT','POWPUMA'],value_vars=['IND1','IND2','IND3'],var_name='ODIND',value_name='TOTAL') k=pd.merge(dfppwk.groupby(['CT','POWPUMA','ODIND'],as_index=False).agg({'TOTAL':'sum'}),k,how='inner',on=['CT','POWPUMA','ODIND']) k=k.sort_values('TOTAL_x').reset_index(drop=True) k['HOVER']='CT: '+k['CT']+'<br>'+'POWPUMA: '+k['POWPUMA']+'<br>'+'ODIND: '+k['ODIND']+'<br>'+'MODEL: '+k['TOTAL_x'].astype(int).astype(str)+'<br>'+'LEHD: '+k['TOTAL_y'].astype(int).astype(str) rmse=np.sqrt(sum((k['TOTAL_x']-k['TOTAL_y'])**2)/len(k)) fig=go.Figure() fig=fig.add_trace(go.Scattergl(name='LEHD vs MODEL', x=k['TOTAL_x'], y=k['TOTAL_y'], mode='markers', marker={'color':'rgba(44,127,184,1)', 'size':5}, hoverinfo='text', hovertext=k['HOVER'])) fig=fig.add_trace(go.Scattergl(name='OPTIMAL', x=[0,max(k['TOTAL_x'])], y=[0,max(k['TOTAL_x'])], mode='lines', line={'color':'rgba(215,25,28,1)', 'width':2}, hoverinfo='skip')) fig.update_layout( template='plotly_white', title={'text':'ODIND (RMSE: '+format(rmse,'.2f')+')', 'font_size':20, 'x':0.5, 'xanchor':'center'}, legend={'orientation':'h', 'title_text':'', 'font_size':16, 'x':0.5, 'xanchor':'center', 'y':1, 'yanchor':'bottom'}, xaxis={'title':{'text':'MODEL', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, yaxis={'title':{'text':'LEHD', 'font_size':14}, 'tickfont_size':12, 'rangemode':'nonnegative', 'showgrid':True}, font={'family':'Arial', 'color':'black'}, ) fig.write_html(path+'POP/validation/odindpt.html',include_plotlyjs='cdn') # Clean up WAC CT wac=[] for i in ['ct','nj','ny']: wac+=[pd.read_csv(path+'LEHD/'+i+'_wac_S000_JT01_2018.csv',dtype=float,converters={'w_geocode':str})] wac=pd.concat(wac,axis=0,ignore_index=True) wac.columns=['BK','TW','AGE301','AGE302','AGE303','EARN1','EARN2','EARN3','AGR','EXT','UTL','CON','MFG', 'WHL','RET','TRN','INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM', 'WHT','BLK','NTV','ASN','PCF','TWO','NHS','HSP','LH','HS','SCAD','BDGD','MALE','FEMALE', 'CFA01','CFA02','CFA03','CFA04','CFA05','CFS01','CFS02','CFS03','CFS04','CFS05','DATE'] wac=pd.merge(wac,geoxwalk,how='inner',left_on='BK',right_on='Block2010') wac=wac[np.isin(wac['StateCounty'],bpm)].reset_index(drop=True) wac=wac.groupby(['CensusTract2010'],as_index=False).agg({'TW':'sum','AGE301':'sum','AGE302':'sum', 'AGE303':'sum','AGR':'sum','EXT':'sum', 'UTL':'sum','CON':'sum','MFG':'sum','WHL':'sum', 'RET':'sum','TRN':'sum','INF':'sum','FIN':'sum', 'RER':'sum','PRF':'sum','MNG':'sum','WMS':'sum', 'EDU':'sum','MED':'sum','ENT':'sum','ACC':'sum', 'SRV':'sum','ADM':'sum','LH':'sum','HS':'sum', 'SCAD':'sum','BDGD':'sum','MALE':'sum', 'FEMALE':'sum'}).reset_index(drop=True) wac.columns=['CT','TW','AGE301','AGE302','AGE303','AGR','EXT','UTL','CON','MFG','WHL','RET', 'TRN','INF','FIN','RER','PRF','MNG','WMS','EDU','MED','ENT','ACC','SRV','ADM','LH','HS', 'SCAD','BDGD','MALE','FEMALE'] wac.to_csv(path+'LEHD/wacct.csv',index=False) # Clean up ODCTCT od=[] for i in ['ct','nj','ny']: od+=[pd.read_csv(path+'LEHD/'+i+'_od_main_JT01_2018.csv',dtype=float,converters={'w_geocode':str,'h_geocode':str})] od+=[pd.read_csv(path+'LEHD/'+i+'_od_aux_JT01_2018.csv',dtype=float,converters={'w_geocode':str,'h_geocode':str})] od=pd.concat(od,axis=0,ignore_index=True) od.columns=['WBK','HBK','TW','AGE301','AGE302','AGE303','EARN1','EARN2','EARN3','IND1','IND2','IND3', 'DATE'] od=pd.merge(od,geoxwalk,how='inner',left_on='HBK',right_on='Block2010') od=od[np.isin(od['StateCounty'],bpm)].reset_index(drop=True) od=pd.merge(od,geoxwalk,how='inner',left_on='WBK',right_on='Block2010') od=od[np.isin(od['StateCounty_y'],bpm)].reset_index(drop=True) od=od.groupby(['CensusTract2010_x','CensusTract2010_y'],as_index=False).agg({'TW':'sum', 'AGE301':'sum', 'AGE302':'sum', 'AGE303':'sum', 'IND1':'sum', 'IND2':'sum', 'IND3':'sum'}).reset_index(drop=True) od.columns=['RACCT','WACCT','TW','AGE301','AGE302','AGE303','IND1','IND2','IND3'] od.to_csv(path+'LEHD/odctct.csv',index=False)
233525424fda83cab2c2be7a3a32ea1f162ef23e
[ "Python" ]
11
Python
NYCPlanning/td-tdm
64b34059c5a3629e301b05d2fea169978fbf44e8
844da0300cb77cdc8bc8211eca2929b6ec71363f
refs/heads/master
<file_sep>package com.gdpi.groups.pojo; import java.util.Date; public class Product { private Integer productId; //商品名称 private String productName; //市场价格 private Double marketPrice; //商品价格 private Double productPrice; //商品图片 private String productImg; //商品详情 private String productDesc; //是否秒杀,0:否,1:是 private Integer isSeckill; //是否团购,0:否,1:是 private Integer isGroup; //日期 private Date productDate; //分类id private Integer csId; public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName == null ? null : productName.trim(); } public Double getMarketPrice() { return marketPrice; } public void setMarketPrice(Double marketPrice) { this.marketPrice = marketPrice; } public Double getProductPrice() { return productPrice; } public void setProductPrice(Double productPrice) { this.productPrice = productPrice; } public String getProductImg() { return productImg; } public void setProductImg(String productImg) { this.productImg = productImg == null ? null : productImg.trim(); } public String getProductDesc() { return productDesc; } public void setProductDesc(String productDesc) { this.productDesc = productDesc == null ? null : productDesc.trim(); } public Integer getIsSeckill() { return isSeckill; } public void setIsSeckill(Integer isSeckill) { this.isSeckill = isSeckill; } public Integer getIsGroup() { return isGroup; } public void setIsGroup(Integer isGroup) { this.isGroup = isGroup; } public Date getProductDate() { return productDate; } public void setProductDate(Date productDate) { this.productDate = productDate; } public Integer getCsId() { return csId; } public void setCsId(Integer csId) { this.csId = csId; } }<file_sep>package com.gdpi.groups.controller; import com.gdpi.groups.pojo.PageResult; import com.gdpi.groups.pojo.Result; import com.gdpi.groups.pojo.User; import com.gdpi.groups.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.Map; /** * @author luojianhui * @date 2018/12/10 * 会员管理 */ @Controller @RequestMapping("/user") public class UserController { private final UserService service; @Autowired public UserController(UserService service) { this.service = service; } /*增加用户*/ @RequestMapping(value = "/addUser", method = RequestMethod.POST) @ResponseBody public Result addUser(User user) { return service.insertUser(user); } /*删除用户*/ @RequestMapping(value = "/delUser", method = RequestMethod.POST) @ResponseBody public Result delUser(Integer userid) { return service.deleteUser(userid); } /*分页查找用户*/ @RequestMapping(value = "/searchUser/list") @ResponseBody public PageResult searchUser(@RequestParam() Map<String, String> params) { return service.selectAllUser(params); } /*删除多条用户*/ } <file_sep>package com.gdpi.groups.dao; import com.gdpi.groups.pojo.CategorySecond; import com.gdpi.groups.pojo.CategorySecondExample; import org.apache.ibatis.annotations.Param; import java.util.List; public interface CategorySecondMapper { long countByExample(CategorySecondExample example); int deleteByExample(CategorySecondExample example); int deleteByPrimaryKey(Integer csId); int insert(CategorySecond record); int insertSelective(CategorySecond record); List<CategorySecond> selectByExample(CategorySecondExample example); CategorySecond selectByPrimaryKey(Integer csId); int updateByExampleSelective(@Param("record") CategorySecond record, @Param("example") CategorySecondExample example); int updateByExample(@Param("record") CategorySecond record, @Param("example") CategorySecondExample example); int updateByPrimaryKeySelective(CategorySecond record); int updateByPrimaryKey(CategorySecond record); }<file_sep>package com.gdpi.groups; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.gdpi.groups.dao") public class GroupsApplication { public static void main(String[] args) { SpringApplication.run(GroupsApplication.class, args); } }
21f67815dbeebd45fddfdc9f1263817715b06d1a
[ "Java" ]
4
Java
cralyhuo/groups
86941d73ef2ecc864110734373cf5c6883d69e7e
1f8b345a808e75f4ec7ea37fe3e77bd9150a94bb
refs/heads/main
<repo_name>ctrepka/pomodoro_bash<file_sep>/pomodoro.sh #!/bin/sh beep() { _alarm 800 400 && sleep .20 } _alarm() { ( \speaker-test --frequency $1 --test sine )& pid=$! \sleep 0.${2}s \kill -9 $pid } beep_3x() { beep && beep && beep } work_25m() { beep_3x notify-send "get to work, peasant!" sleep 1500 } break_5m() { beep_3x notify-send "starting short_break" && sleep 300 } break_15m() { beep_3x notify-send "starting long_break" && sleep 900 } short_cycle() { work_25m break_5m } long_cycle() { work_25m break_15m } start_pomo() { short_cycle short_cycle short_cycle long_cycle notify-send "cycle complete" }
f46eb84d15b28b139d1d386db6976adf0aba3ff0
[ "Shell" ]
1
Shell
ctrepka/pomodoro_bash
e2b8a27c6cd7256eda83200f5f5cf0592bd7d417
afc1bdc593e781b47b083a5e2ccb2da89efb77ba
refs/heads/master
<repo_name>longyf/exer-13<file_sep>/main.cpp #include <iostream> #include "findPath.h" #include "findPath_2.h" using namespace std; void test1() { int rows=6; int cols=6; int k=5; cout<<findPath(rows,cols,k)<<" "<<func(rows,cols,k)<<endl; cout<<endl; } void test2() { int rows=1; int cols=6; int k=5; cout<<findPath(rows,cols,k)<<" "<<func(rows,cols,k)<<endl; cout<<endl; } void test3() { int rows=4; int cols=1; int k=3; cout<<findPath(rows,cols,k)<<" "<<func(rows,cols,k)<<endl; cout<<endl; } void test4() { int rows=1; int cols=6; int k=0; cout<<findPath(rows,cols,k)<<" "<<func(rows,cols,k)<<endl; cout<<endl; } void test5() { int rows=1; int cols=6; int k=-1; cout<<findPath(rows,cols,k)<<" "<<func(rows,cols,k)<<endl; cout<<endl; } int main() { test1(); test2(); test3(); test4(); try {test5();} catch (invalid_argument e) { cout<<e.what()<<endl; } return 0; } <file_sep>/README.md # exer-13 机器人的运动范围。 <file_sep>/test_1.cpp #include <iostream> using namespace std; int main() { int a=14203; int sum=0; while (a!=0) { sum+=a%10; a/=10; } cout<<sum<<endl; return 0; } <file_sep>/test_3.cpp #include <iostream> using namespace std; int func(int rows, int cols, int k) { int count=0; for (int i=0; i!=rows; ++i) { for (int j=0; j!=cols; ++j) { int temp_row=i; int temp_col=j; int sum=0; while (temp_row!=0) { sum+=temp_row%10; temp_row/=10; } while (temp_col!=0) { sum+=temp_col%10; temp_col/=10; } if (sum<=k) count++; cout<<i<<" "<<j<<" "<<sum<<endl; } } return count; } int main() { cout<<func(100,100,100)<<endl; return 0; } <file_sep>/test_2.cpp #include <iostream> using namespace std; void func(int &a) { a++; } int main() { int a=0; func(a); cout<<a<<endl; return 0; } <file_sep>/findPath.h #ifndef find_path_h #define find_path_h #include <iostream> #include <stdexcept> using namespace std; bool findPathCore(int rows, int cols, int k, int row, int col, bool *visited, int &count); int findPath(int rows, int cols, int k) { if (rows<=0||cols<=0||k<0) throw invalid_argument("Pay attention to the inputs."); //初始化bool矩阵,防止重复进入已经访问过的格子。 bool *visited=new bool[rows*cols]; for (int i=0; i!=rows*cols; ++i) visited[i]=false; int count=0; //从(0,0)开始访问。 findPathCore(rows, cols, k, 0, 0, visited, count); delete []visited; return count; } bool findPathCore(int rows, int cols, int k, int row, int col, bool *visited, int &count) { int index=row*cols+col; //求出阈值。 int temp_row=row; int temp_col=col; int sum=0; while (temp_row!=0) { sum+=temp_row%10; temp_row/=10; } while (temp_col!=0) { sum+=temp_col%10; temp_col/=10; } bool mark=false; if (row>=0&&row<rows&&col>=0&&col<cols&&!(visited[index])&&sum<=k) { cout<<row<<" "<<col<<endl; visited[index]=true; count++; if (findPathCore(rows, cols, k, row+1, col, visited, count)|| findPathCore(rows, cols, k, row-1, col, visited, count)|| findPathCore(rows, cols, k, row, col+1, visited, count)|| findPathCore(rows, cols, k, row, col-1, visited, count)) { mark=true; } } return mark; } #endif
db84bb5ca59a3e3401a3c7c261542f68c46e2d4a
[ "Markdown", "C++" ]
6
C++
longyf/exer-13
afa66caae153900e8f3ee5cf8143cce4fce91227
694885709e4526cab43c90380e9b0e72e89375d6
refs/heads/master
<file_sep>#pragma once #include <QtGlobal> #include "ivirus.h" /** * @brief StandartVirus class * Infects randomly */ class StandartVirus : public IVirus { public: StandartVirus(); ~StandartVirus(); int getContagiousness(); }; <file_sep>#pragma once #include "controller.h" class Network; class Tank; /** @brief Handles network input */ class NetworkController : public Controller { public: explicit NetworkController(Network* _network, Tank* _tank); /** @brief Translates messages and commands tank */ void handle(const QString& _message); private: Tank *tank_; }; <file_sep>#include "bigshell.h" BigShell::BigShell(QPointF _position, TankDirection _direction, const double _angle): Shell::Shell(_position, _direction, _angle) { radius_ *= 2; } BigShell::~BigShell() { } Explosion *BigShell::blast() { if (!explosion_) { explosion_ = new Explosion(shellPosition_, radius_*1.5); } return explosion_; } <file_sep>#include "shell.h" Shell::Shell(QPointF _position, TankDirection _direction, const double _angle): shellPosition_(_position), startAngle_(_angle), radius_(4), graviAcceleration_(9.8), speed_(10), timeOfFlight_(0), explosion_(nullptr), shellDirection_(_direction) { setPos(shellPosition_); } Shell::~Shell() { if (explosion_) { delete explosion_; } } void Shell::paint(QPainter *_painter, const QStyleOptionGraphicsItem *_option, QWidget *_widget) { _painter->setBrush(Qt::red); _painter->setPen(Qt::red); _painter->drawEllipse(QPointF(0, 0) , radius_, radius_); } QRectF Shell::boundingRect() const { return QRectF(QPoint(-radius_, radius_), QPoint(radius_, -radius_)); } QPainterPath Shell::shape() const { QPainterPath path; path.addEllipse(QPoint(0, 0) , radius_, radius_); return path; } QPointF Shell::getPosition() const { return shellPosition_; } void Shell::frame() { timeOfFlight_ += 0.05; shellPosition_.rx() = shellPosition_.x() + shellDirection_*speed_*timeOfFlight_*cos(qDegreesToRadians(startAngle_)); shellPosition_.ry() = shellPosition_.y() - speed_*timeOfFlight_*sin(qDegreesToRadians(startAngle_)) + (graviAcceleration_*timeOfFlight_*timeOfFlight_)/2; setPos(shellPosition_.x(), shellPosition_.y()); } Explosion* Shell::blast() { if (!explosion_) { explosion_ = new Explosion(shellPosition_, radius_); } return explosion_; } <file_sep>#pragma once #include <QVector> #include "computer.h" #include "goodvirus.h" #include "killervirus.h" #include "standartvirus.h" /** * @brief The Network class * Simulates the working of defined local network and concrete virus */ class Network { public: /// @brief Create network with vector of computers and adjacency matrix of them Network(const QVector<Computer> &_computersList, bool **_matrix); ~Network(); /// @brief writes network status in console void currentStatus() const; int howManyComputers() const; int howManyInfected() const; /// @brief Try to infect, if possibly; void simulationStep(); /// @brief Setting first infected computer in !pure! network. If (_victim > numberOfComputers), infecting random computer void setFirstVictim(unsigned int _victim); void setVirus(IVirus* _virus); const Computer& operator [](int _i) const; private: IVirus* virus_; QVector<Computer> listOfComputers_; bool **adjacencyMatrix_; unsigned int numberOfComputers_; unsigned int numberOfVictims_; }; <file_sep>#pragma once #include <QtMath> #include <QGraphicsItem> class Landscape; class GameCore; /** @brief Enum for current gun */ enum Gun { standardGun, bigGun }; /** @brief Enum for direction of movement */ enum TankDirection { leftDirection = -1, rightDirection = 1 }; class Tank : public QGraphicsItem { public: /** @brief Creates tank in random place of appropriate landscape */ Tank(GameCore* _gamecore, Landscape* _land); ~Tank(); /** @brief Function for drawing */ void paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget = 0); /** @brief Functions for detecting collisions */ QRectF boundingRect() const; QPainterPath shape() const; QPoint getPosition() const; /** @brief Returns a coordinates of the end of the barrel */ QPointF getGunPosition() const; /** @brief Return the declination angle of the gun */ double getAngle() const; /** @brief Functions for moving on the surface */ void moveLeft(); void moveRight(); /** @brief Functions for changing the declination angle of the gun */ void upGun(); void downGun(); /** @brief Switches gun */ void switchGun(); void shoot(); /** @brief Returns type of the gun */ Gun getGun() const; /** @brief Returns direction of the movement */ TankDirection getDirection() const; private: /** @brief This two parameters only for placing and colouration */ static unsigned int numberOfTanks_; unsigned int numberOfTank_; GameCore* gamecore_; Landscape* land_; /** @brief Position for painting on scene */ QPoint position_; /** @brief Position for movement on the flexures of the surface */ unsigned int currentVertex_; TankDirection currentDirection_; double gunAngle_; /** @brief Position for painting the gun */ QPointF gunPosition_; Gun currentGun_; }; <file_sep>#pragma once #include <QObject> /** @brief Base class for the KeyboardController and NetworkController, describes input of the tank */ class Controller : public QObject { Q_OBJECT public: explicit Controller(QObject* _parent = nullptr); signals: void moveRightPressed(); void moveLeftPressed(); void gunUpPressed(); void gunDownPressed(); void shootPressed(); void changeGunPressed(); protected: Qt::Key pressed_; }; <file_sep>#pragma once #include <QMessageBox> #include <QGraphicsView> #include <QGraphicsScene> #include <QKeyEvent> #include <QTimer> #include "tank.h" #include "landscape.h" #include "bigshell.h" #include "explosion.h" /** @brief GameCore class controls process of game */ class GameCore : public QGraphicsView { Q_OBJECT public: /** @brief Creates scene according to window size, creates appropriate landscape and places tanks on them */ GameCore(unsigned int _width, unsigned int _height, QWidget* _parent = 0); ~GameCore(); /** @brief Handle input from keyboard */ void keyPressEvent(QKeyEvent* _event); /** @brief Launch shell and start timer */ void nextStep(bool _isBigGun); /** @brief Creates message box and close the game */ void checkWinner(Tank* _winner); private: QMessageBox* winnerMessage_; QGraphicsScene* scene_; QTimer* timer_; Landscape* landscape_; Tank* firstTank_; Tank* secondTank_; Tank* currentTank_; Tank* victim_; Shell* shell_; bool shellLaunched_; unsigned int windowWidth_; unsigned int windowHeight_; private slots: /** @brief Updates game, checks collisions */ void frame(); }; <file_sep>#pragma once #include "ivirus.h" /** * @brief GoodVirus class * Can't infect */ class GoodVirus : public IVirus { public: GoodVirus(); ~GoodVirus(); int getContagiousness(); }; <file_sep>#pragma once #include <QtCore/QObject> #include <QtTest/QtTest> #include <QDebug> #include "computer.h" class ComputerTest: public QObject { Q_OBJECT public: explicit ComputerTest(QObject *parent = 0) : QObject(parent) {} private slots: void defaultConsctructor() { computer = new Computer(); QVERIFY(computer->getProbability() == 0); QVERIFY(computer->isInfected() == false); } void probabilityConstructor1() { computer = new Computer(0); QVERIFY(computer->getProbability() == 0); QVERIFY(computer->isInfected() == false); } void probabilityConstructor2() { computer = new Computer(100); QVERIFY(computer->getProbability() == 100); QVERIFY(computer->isInfected() == false); } void probabilityConstructor3() { computer = new Computer(70); QVERIFY(computer->getProbability() == 70); QVERIFY(computer->isInfected() == false); } void infectedConstructor() { computer = new Computer(true); QVERIFY(computer->getProbability() == 0); QVERIFY(computer->isInfected()); } void unInfectedConstructor() { computer = new Computer(false); QVERIFY(computer->getProbability() == 0); QVERIFY(computer->isInfected() == false); } void copyConstruction() { Computer computer2(31); computer = new Computer(computer2); //qDebug() << "Original: " << kompukter.getProbability() << "\nCopy: " << computer->getProbability(); QVERIFY(computer->getProbability() == 31); QVERIFY(computer->isInfected() == false); } void copyOperator() { Computer computer1(42); Computer computer2(66); computer2 = computer1; QVERIFY(computer2.getProbability() == 42); QVERIFY(computer2.isInfected() == false); } void equalityOperator() { Computer computer1(42); Computer computer2(42); QVERIFY(computer1 == computer2); computer2.infect(); QVERIFY(!(computer1 == computer2)); computer1.infect(); QVERIFY(computer1 == computer2); } void inequalityOperator() { Computer computer1(42); Computer computer2(66); QVERIFY(computer1 != computer2); computer2.infect(); QVERIFY(computer1 != computer2); computer1.infect(); QVERIFY(!(computer1 != computer2)); } private: Computer *computer; }; <file_sep>#include "window.h" Window::Window(QWidget *_parent): QWidget(_parent), startButton_(new QPushButton("Start Singleplayer")), label_(new QLabel("Main Menu")), layout_(nullptr), parent_(_parent), core_(nullptr) { setFixedSize(width_, height_); layout_ = new QGridLayout; layout_->addWidget(label_, 0, 0, Qt::AlignCenter); layout_->addWidget(startButton_, 1, 0, Qt::AlignBaseline); setLayout(layout_); connect(startButton_, SIGNAL(clicked()), this, SLOT(startSinglePlayer())); } void Window::startSinglePlayer() { core_ = new GameCore(width_, height_, parent_); core_->show(); } <file_sep>#pragma once #include <QGraphicsItem> #include <QPainter> #include <QtMath> #include "tank.h" #include "explosion.h" /** @brief Shell class describes a projectile and control his flight */ class Shell : public QGraphicsItem { public: Shell(QPointF _position, TankDirection _direction, const double _angle = 0); ~Shell(); /** @brief Function for drawing */ void paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget = 0); /** @brief Functions for detecting collisions */ QRectF boundingRect() const; QPainterPath shape() const; QPointF getPosition() const; /** @brief Updates coordinates of projectile */ void frame(); /** @brief Creates explosion */ virtual Explosion* blast(); protected: QPointF shellPosition_; double startAngle_; /// Size of shell double radius_; double graviAcceleration_; int speed_; double timeOfFlight_; Explosion* explosion_; TankDirection shellDirection_; }; <file_sep>#include "landscape.h" Landscape::Landscape(unsigned int _sceneWidth, unsigned int _sceneHeight) { qsrand(QTime::currentTime().msec()); surface_ = {QPoint(0, _sceneHeight / 2)}; int cursor = 0; int heightOffset = _sceneHeight / 2; while (cursor < _sceneWidth) { int sign = qrand() % 2; int increase = qrand() % 10; if (sign && (heightOffset < ((3*_sceneHeight) / 4))) { heightOffset += increase; cursor += 5; } else if (heightOffset > _sceneHeight / 4) { heightOffset -= increase; cursor += 5; } surface_.append(QPoint(cursor, heightOffset)); } numOfFlexures_ = surface_.length(); surface_.append(QPoint(_sceneWidth, _sceneHeight)); surface_.append(QPoint(0, _sceneHeight)); surface_.append(QPoint(0, _sceneHeight / 2)); path_.moveTo(0, _sceneHeight / 2); for (unsigned int i = 1; i < numOfFlexures_ + 3; ++i) { path_.lineTo(surface_[i]); } } Landscape::~Landscape() { surface_.clear(); } QRectF Landscape::boundingRect() const { return QRectF(QPoint(0, 0), QPoint(600, 480)); } QPainterPath Landscape::shape() const { return path_; } QPoint Landscape::getCoordinates(unsigned int _index) { return surface_[_index]; } unsigned int Landscape::getLength() { return numOfFlexures_; } void Landscape::paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget) { _painter->setBrush(Qt::green); _painter->setPen(Qt::green); _painter->drawPath(path_); } <file_sep>#include "networkcore.h" #include "Game/gamecore.h" #include "Game/tank.h" #include "Input/networkcontroller.h" #include "Input/observercontroller.h" Network::Network(QObject* _parent) : QObject(_parent), networkController_(nullptr), tcpSocket_(nullptr), networkSession_(nullptr), blockSize_(0) { } void Network::observeController(Tank* _tank) { ObserverController* observerController = new ObserverController(this, _tank); connect(observerController, SIGNAL(emitInput(QString)), this, SLOT(sendMessage(QString))); } void Network::initController(Tank* _tank) { networkController_ = new NetworkController(this, _tank); } void Network::newMessage() { QDataStream in(tcpSocket_); if (!blockSize_) { if (tcpSocket_->bytesAvailable() < (int)sizeof(quint16)) { return; } in >> blockSize_; } if (tcpSocket_->bytesAvailable() >= blockSize_) { QString message; in >> message; blockSize_ = 0; decodeMessage(message); } } void Network::decodeMessage(const QString& _message) { if (networkController_ && (_message.size() > 1) && (_message.at(0) == QChar('K'))) { networkController_->handle(_message); } } void Network::sendMessage(const QString& _message) { QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out << (quint16)0; out << _message; out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); tcpSocket_->write(block); } <file_sep>#include "ivirus.h" IVirus::IVirus() { } IVirus::~IVirus() { } int IVirus::getContagiousness() { return contagiousness_; } <file_sep>#pragma once #include "ivirus.h" /** * @brief KillerVirus class * Infect any computer except already infected and computers with probability = 0 */ class KillerVirus : public IVirus { public: KillerVirus(); ~KillerVirus(); int getContagiousness(); }; <file_sep>#include <QCoreApplication> #include "computertest.h" #include "networktest.h" int main(int argc, char *argv[]) { ComputerTest test; QTest::qExec(&test); NetworkTest netTest; QTest::qExec(&netTest); } <file_sep>#pragma once #include <QNetworkConfigurationManager> #include <QNetworkSession> #include <QTcpSocket> #include <QVector> #include "Game/landscape.h" #include "networkcore.h" class Landscape; /** @brief Describes a client */ class Client : public Network { Q_OBJECT public: explicit Client(QObject* _parent = nullptr); void connectToServer(int _port); signals: /** @brief Emitted when the Landscape received by the network */ void gotLandscape(Landscape* _landscape); protected: void decodeMessage(const QString& _message) Q_DECL_OVERRIDE; }; <file_sep>#include "window.h" Window::Window(QWidget *_parent) : QMainWindow(_parent), parent_(_parent), network_(nullptr) { } bool Window::initNetwork() { QMessageBox *networkDialog = new QMessageBox(this); networkDialog->setText("Choose network type"); QPushButton *clientButton = networkDialog->addButton("Client", QMessageBox::ActionRole); QPushButton *serverButton = networkDialog->addButton("Server", QMessageBox::ActionRole); networkDialog->addButton(QMessageBox::Cancel); networkDialog->exec(); QAbstractButton *clickedButton = networkDialog->clickedButton(); networkDialog->deleteLater(); if (clickedButton == serverButton) { Server* server = new Server(this); network_ = server; connect(server, SIGNAL(connected()), this, SLOT(connected())); connect(server, SIGNAL(disconnected()), this, SLOT(disconnected())); if (!server->init()) { return false; } setWindowTitle("Server"); QString message = "\t\tPort: " + server->getPort(); statusBar()->showMessage(message); } else if (clickedButton == clientButton) { Client* client = new Client(this); connect(client, SIGNAL(disconnected()), this, SLOT(disconnected())); network_ = client; ConnectServerDialog *dialog = new ConnectServerDialog(client); if (!dialog->exec()) { return false; } setWindowTitle("Client"); connected(); } else { return false; } return true; } void Window::connected() { GameCore* game = new GameCore(width_, height_, parent_); connect(game, SIGNAL(gameOver(QString)), this, SLOT(gameOver(QString))); setFixedSize(width_ + 30, height_ + 30); setCentralWidget(game); game->startGame(network_); } void Window::disconnected() { QMessageBox::information(this, tr("Bad news"), tr("Disconnected")); close(); } void Window::gameOver(const QString &_string) { disconnect(network_, SIGNAL(disconnected()), this, SLOT(disconnected())); QMessageBox::information(this, tr("Game over"), _string); close(); } <file_sep>#include "network.h" Network::Network(const QVector<Computer> &_computersList, bool **_matrix) { adjacencyMatrix_ = _matrix; numberOfComputers_ = _computersList.length(); numberOfVictims_ = 0; listOfComputers_ = _computersList; for (unsigned int i = 0; i < numberOfComputers_; ++i) { if (listOfComputers_[i].isInfected()) { ++numberOfVictims_; } } virus_ = new StandartVirus(); } Network::~Network() { listOfComputers_.clear(); for (unsigned int i = 0; i < numberOfComputers_; ++i) { delete [] adjacencyMatrix_[i]; } delete [] adjacencyMatrix_; numberOfComputers_ = 0; numberOfVictims_ = 0; if (virus_) { delete virus_; } } void Network::currentStatus() const { for (unsigned int i = 0; i < numberOfComputers_; ++i) { std::cout << i << ": " << listOfComputers_[i]; std::cout << ", connected with"; bool f = true; for (unsigned int j = 0; j < numberOfComputers_; ++j) { if ((i != j) && (adjacencyMatrix_[i][j])) { std::cout << ' ' << j; f = false; } } if (f) { std::cout << " nobody"; } std::cout << std::endl; } } int Network::howManyComputers() const { return numberOfComputers_; } int Network::howManyInfected() const { return numberOfVictims_; } void Network::simulationStep() { int cube = virus_->getContagiousness(); for (unsigned int i = 0; i < numberOfComputers_; ++i) { if (listOfComputers_[i].isInfected()) { for (unsigned int j = 0; j < numberOfComputers_; ++j) { if ((adjacencyMatrix_[i][j]) && (!listOfComputers_[j].isInfected())) { if (listOfComputers_[j].getProbability() > cube) { listOfComputers_[j].infect(); ++numberOfVictims_; } return; } } } } } void Network::setFirstVictim(unsigned int _victim) { if (numberOfVictims_) { return; } if (_victim < numberOfComputers_) { listOfComputers_[_victim].infect(); } else { int first = qrand() % numberOfComputers_; listOfComputers_[first].infect(); } ++numberOfVictims_; } void Network::setVirus(IVirus *_virus) { virus_ = _virus; } const Computer& Network::operator [](int _i) const { return listOfComputers_[_i]; } <file_sep>#pragma once #include <QWidget> #include <QtWidgets> #include <QtNetwork> #include <QNetworkConfigurationManager> #include <QNetworkSession> #include <QTcpServer> #include <QTcpSocket> #include "networkcore.h" #include "Game/landscape.h" /** @brief Describes a server */ class Server : public Network { Q_OBJECT public: explicit Server(QObject* _parent = nullptr); bool init(); QString getPort() const; void sendLandscape(Landscape* _landscape); private slots: void sessionOpened(); void connectClient(); private: QTcpServer* tcpServer_; }; <file_sep>#pragma once #include <QMainWindow> #include <QGraphicsView> #include <QPushButton> #include <QLineEdit> #include <QLabel> #include <QGridLayout> #include <QMessageBox> #include <QStatusBar> #include "Input/controller.h" #include "Game/gamecore.h" #include "Game/landscape.h" #include "Game/tank.h" #include "Network/connectserverdialog.h" #include "Network/networkclient.h" #include "Network/networkserver.h" class Window : public QMainWindow { Q_OBJECT public: explicit Window(QWidget* _parent = 0); bool initNetwork(); private slots: void connected(); void disconnected(); void gameOver(const QString& _string); private: QWidget* parent_; Network *network_; const unsigned int width_ = 800; const unsigned int height_ = 600; }; <file_sep>#pragma once #include "shell.h" /** @brief Class describes a shell with doubled radius */ class BigShell : public Shell { public: BigShell(QPointF _position, TankDirection _direction, const double _angle = 0); ~BigShell(); /** @brief Creates explosion with bigger radius */ Explosion* blast(); }; <file_sep>#include "networkclient.h" Client::Client(QObject* _parent) : Network(_parent) { tcpSocket_ = new QTcpSocket(this); QNetworkConfigurationManager manager; if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) { networkSession_ = new QNetworkSession(manager.defaultConfiguration(), this); networkSession_->opened(); } connect(tcpSocket_, SIGNAL(readyRead()), this, SLOT(newMessage())); connect(tcpSocket_, SIGNAL(connected()), this, SIGNAL(connected())); connect(tcpSocket_, SIGNAL(disconnected()), this, SIGNAL(disconnected())); } void Client::connectToServer(int _port) { tcpSocket_->abort(); tcpSocket_->connectToHost("localhost", _port); } void Client::decodeMessage(const QString& _message) { if (!_message.size()) { return; } if (_message.at(0) == QChar('L')) { Landscape* landscape = new Landscape(800, 600); QStringList stringList = _message.split(" "); stringList.first().remove(0, 1); int length = stringList.first().toInt(); QVector<QPoint> newSurface(length - 1); for (int i = 0; i < length - 1; ++i) { newSurface[i].rx() = stringList.at(1 + 2*i).toInt(); newSurface[i].ry() = stringList.at(2 + 2*i).toInt(); } landscape->setSurface(newSurface); emit gotLandscape(landscape); } else { Network::decodeMessage(_message); } } <file_sep>#include "killervirus.h" KillerVirus::KillerVirus() { } KillerVirus::~KillerVirus() { } int KillerVirus::getContagiousness() { return 0; } <file_sep>#pragma once #include <QMessageBox> #include <QGraphicsView> #include <QGraphicsScene> #include <QKeyEvent> #include <QTimer> #include "bigshell.h" #include "explosion.h" #include "Network/networkclient.h" #include "Network/networkserver.h" class Tank; class Landscape; class Controller; /** @brief GameCore class controls process of game */ class GameCore : public QGraphicsView { Q_OBJECT public: /** @brief Creates scene according to window size, creates appropriate landscape and places tanks on them */ GameCore(unsigned int _width, unsigned int _height, QWidget* _parent = 0); /** @brief Starts the game, connects input */ void startGame(Network* _network); signals: /** @brief Announces a winner */ void gameOver(const QString& _string); public slots: /** @brief Launches shell and start timer */ void nextStep(bool _isBigGun); void setLandscape(Landscape* _landscape); /** @brief Updates game, checks collisions */ void frame(); void whenGameOver(); private: Network* network_; QGraphicsScene* scene_; QEventLoop* loop_; QTimer* timer_; Landscape* landscape_; Tank* firstTank_; Tank* secondTank_; bool isFirstTankTurn_; Tank* currentTank_; Tank* victim_; Shell* shell_; bool shellLaunched_; bool isServer_; unsigned int windowWidth_; unsigned int windowHeight_; }; <file_sep>#include "networkcontroller.h" #include "Network/networkcore.h" #include "Game/tank.h" #include "Game/gamecore.h" NetworkController::NetworkController(Network* _network, Tank* _tank) : Controller(_network), tank_(_tank) { tank_->setController(this); } void NetworkController::handle(const QString& _message) { if (_message.at(1) == QChar('R')) { emit moveRightPressed(); } else if (_message.at(1) == QChar('L')) { emit moveLeftPressed(); } else if (_message.at(1) == QChar('U')) { emit gunUpPressed(); } else if (_message.at(1) == QChar('D')) { emit gunDownPressed(); } else if (_message.at(1) == QChar('S')) { emit shootPressed(); } else if (_message.at(1) == QChar('C')) { emit changeGunPressed(); } } <file_sep>#pragma once #include "controller.h" /** @brief Handles keyboard input */ class KeyboardController : public Controller { public: explicit KeyboardController(QObject* _parent); protected: bool eventFilter(QObject* object, QEvent* event) Q_DECL_OVERRIDE; }; <file_sep>#pragma once #include <QObject> #include <QWidget> #include <QtWidgets> #include <QtNetwork> #include <QDataStream> #include <QTcpSocket> class Tank; class NetworkController; /** @brief Base class for the Client and Server */ class Network : public QObject { Q_OBJECT public: explicit Network(QObject* _parent = 0); /** @brief Sets the ObserverController for a tank and his input */ void observeController(Tank* _tank); /** @brief Initalize NetworkController instance connected with a tank */ void initController(Tank* _tank); signals: void disconnected(); void connected(); protected slots: void sendMessage(const QString& _message); private slots: void newMessage(); protected: virtual void decodeMessage(const QString& _message); NetworkController* networkController_; QTcpSocket* tcpSocket_; QNetworkSession* networkSession_; quint16 blockSize_; }; <file_sep>#include "tank.h" #include "gamecore.h" #include "Input/controller.h" #include "landscape.h" unsigned int Tank::numberOfTanks_ = 0; Tank::Tank(GameCore *_gamecore, Landscape *_land, QObject *_parent): QObject(_parent), gamecore_(_gamecore), land_(_land), currentDirection_(leftDirection), gunAngle_(0), currentGun_(standardGun), controller_(nullptr) { ++numberOfTanks_; numberOfTank_ = numberOfTanks_ % 2 + 1; gunPosition_.rx() = -35; gunPosition_.ry() = 0; if (numberOfTanks_ % 2) { currentVertex_ = land_->getLength() / 4; currentDirection_ = rightDirection; gunPosition_.rx() = 35; } else { currentVertex_ = 3 * land_->getLength() / 4; } position_ = land_->getCoordinates(currentVertex_); setPos(position_.x(), position_.y()); } Tank::~Tank() { --numberOfTanks_; } void Tank::paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget) { if (numberOfTank_ % 2) { _painter->setBrush(QColor(0, 0, 0)); _painter->setPen(QColor(0, 0, 0)); } else { _painter->setBrush(QColor(255, 0, 0)); _painter->setPen(QColor(255, 0, 0)); } _painter->drawRect(-15, -10, 30, 20); _painter->drawLine(QPointF(0, 0), QPointF(gunPosition_.x(), gunPosition_.y())); } QRectF Tank::boundingRect() const { return QRectF(-15, -10, 30, 20); } QPainterPath Tank::shape() const { QPainterPath path; path.addRect(QRectF(boundingRect())); path.moveTo(0, 0); path.lineTo(gunPosition_.x(), gunPosition_.y()); return path; } QPoint Tank::getPosition() const { return position_; } QPointF Tank::getGunPosition() const { QPointF barrelPosition; barrelPosition.rx() = position_.x() + gunPosition_.x(); barrelPosition.ry() = position_.y() + gunPosition_.y(); return barrelPosition; } double Tank::getAngle() const { return gunAngle_; } void Tank::moveLeft() { currentDirection_ = leftDirection; if (currentVertex_ == 0) { return; } --currentVertex_; position_ = land_->getCoordinates(currentVertex_); if (gunPosition_.x() > 0) { gunPosition_.rx() = -gunPosition_.x(); } setPos(position_.x(), position_.y()); gamecore_->viewport()->update(); } void Tank::moveRight() { currentDirection_ = rightDirection; if (currentVertex_ == (land_->getLength() - 1)) { return; } ++currentVertex_; position_ = land_->getCoordinates(currentVertex_); if (gunPosition_.x() < 0) { gunPosition_.rx() = -gunPosition_.x(); } setPos(position_.x(), position_.y()); gamecore_->viewport()->update(); } void Tank::upGun() { if (gunAngle_ >= 90) { return; } gunAngle_ += 5; gunPosition_.rx() = 35*currentDirection_*cos(qDegreesToRadians(gunAngle_)); gunPosition_.ry() = -35*sin(qDegreesToRadians(gunAngle_)); gamecore_->viewport()->update(); } void Tank::downGun() { if (gunAngle_ <= 0) { return; } gunAngle_ -= 5; gunPosition_.rx() = 35*currentDirection_*cos(qDegreesToRadians(gunAngle_)); gunPosition_.ry() = -35*sin(qDegreesToRadians(gunAngle_)); gamecore_->viewport()->update(); } void Tank::switchGun() { if (currentGun_ == standardGun) { currentGun_ = bigGun; } else { currentGun_ = standardGun; } } void Tank::shoot() { gamecore_->nextStep(currentGun_ == bigGun); } Gun Tank::getGun() const { return currentGun_; } TankDirection Tank::getDirection() const { return currentDirection_; } void Tank::setController(Controller* _controller) { if (controller_) { disconnect(controller_); } controller_ = _controller; connect(_controller, SIGNAL(moveRightPressed()), this, SLOT(moveRight())); connect(_controller, SIGNAL(moveLeftPressed()), this, SLOT(moveLeft())); connect(_controller, SIGNAL(gunUpPressed()), this, SLOT(upGun())); connect(_controller, SIGNAL(gunDownPressed()), this, SLOT(downGun())); connect(_controller, SIGNAL(shootPressed()), this, SLOT(shoot())); connect(_controller, SIGNAL(changeGunPressed()), this, SLOT(switchGun())); } Controller *Tank::getController() { return controller_; } <file_sep>#pragma once /** * @brief IVirus class * Interface for the viruses */ class IVirus { public: IVirus(); ~IVirus(); virtual int getContagiousness(); protected: int contagiousness_; }; <file_sep>#include "gamecore.h" GameCore::GameCore(unsigned int _width, unsigned int _height, QWidget* _parent): QGraphicsView(_parent), winnerMessage_(nullptr), scene_(nullptr), timer_(nullptr), landscape_(nullptr), firstTank_(nullptr), secondTank_(nullptr), currentTank_(nullptr), victim_(nullptr), shell_(nullptr), shellLaunched_(false), windowWidth_(_width), windowHeight_(_height) { timer_ = new QTimer(this); connect(timer_, &QTimer::timeout, this, &GameCore::frame); landscape_ = new Landscape(windowWidth_, windowHeight_); firstTank_ = new Tank(this, landscape_); secondTank_ = new Tank(this, landscape_); currentTank_ = firstTank_; victim_ = secondTank_; scene_ = new QGraphicsScene(this); scene_->setSceneRect(0, 0, windowWidth_, windowHeight_); setScene(scene_); scene_->addItem(landscape_); scene_->addItem(firstTank_); scene_->addItem(secondTank_); } GameCore::~GameCore() { if (scene_) { delete scene_; } if (landscape_) { delete landscape_; } if (firstTank_) { delete firstTank_; } if (secondTank_) { delete secondTank_; } if (currentTank_) { delete currentTank_; } if (victim_) { delete victim_; } } void GameCore::keyPressEvent(QKeyEvent *_event) { if (_event->key() == Qt::Key_Space && !shellLaunched_) { currentTank_->shoot(); } if (_event->key() == Qt::Key_G && !shellLaunched_) { currentTank_->switchGun(); } if (_event->key() == Qt::Key_Left && !shellLaunched_) { currentTank_->moveLeft(); } if (_event->key() == Qt::Key_Right && !shellLaunched_) { currentTank_->moveRight(); } if (_event->key() == Qt::Key_Up && !shellLaunched_) { currentTank_->upGun(); } if (_event->key() == Qt::Key_Down && !shellLaunched_) { currentTank_->downGun(); } viewport()->update(); } void GameCore::nextStep(bool _isBigGun) { shellLaunched_ = true; if (_isBigGun) { shell_ = new BigShell(currentTank_->getGunPosition(), currentTank_->getDirection(), currentTank_->getAngle()); } else { shell_ = new Shell(currentTank_->getGunPosition(), currentTank_->getDirection(), currentTank_->getAngle()); } scene_->addItem(shell_); timer_->start(20); } void GameCore::checkWinner(Tank* _winner) { winnerMessage_ = new QMessageBox; if (_winner == firstTank_) { winnerMessage_->setText("First Tank Wins!"); } else if (_winner == secondTank_) { winnerMessage_->setText("Second Tank Wins!"); } winnerMessage_->setIcon(QMessageBox::Warning); winnerMessage_->exec(); close(); } void GameCore::frame() { if (shell_->collidesWithItem(victim_)) { timer_->stop(); delete shell_; shellLaunched_ = false; checkWinner(currentTank_); qDebug("Collide with victim"); } else if (shell_->collidesWithItem(landscape_)) { timer_->stop(); scene_->addItem(shell_->blast()); if (shell_->blast()->collidesWithItem(victim_)) { checkWinner(currentTank_); qDebug("Explode"); } delete shell_; shellLaunched_ = false; std::swap(currentTank_, victim_); qDebug("Collide with surface"); } else if (scene_->sceneRect().contains(shell_->getPosition())) { shell_->frame(); } else { timer_->stop(); delete shell_; shellLaunched_ = false; std::swap(currentTank_, victim_); qDebug("Out of scene"); } viewport()->update(); } <file_sep>#pragma once #include <QPushButton> #include <QLabel> #include <QWidget> #include <QGridLayout> #include "gamecore.h" /** @brief Window class create client and server */ class Window : public QWidget { Q_OBJECT public: Window(QWidget* _parent = 0); private slots: void startSinglePlayer(); private: QPushButton* startButton_; QLabel* label_; QGridLayout* layout_; QWidget* parent_; GameCore* core_; const unsigned int width_ = 800; const unsigned int height_ = 600; }; <file_sep>#include "keyboardcontroller.h" #include <QKeyEvent> #include <QGraphicsView> #include "Game/gamecore.h" KeyboardController::KeyboardController(QObject* _parent) : Controller(_parent) { _parent->installEventFilter(this); } bool KeyboardController::eventFilter(QObject* object, QEvent* event) { if (object == parent()) { if (event->type() == QEvent::KeyPress) { if (pressed_ != Qt::Key_unknown) { return false; } QKeyEvent* keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->isAutoRepeat()) { return false; } if (keyEvent->key() == Qt::Key_Right) { qDebug("Right"); pressed_ = Qt::Key_Right; emit moveRightPressed(); } else if (keyEvent->key() == Qt::Key_Left) { qDebug("Left"); pressed_ = Qt::Key_Left; emit moveLeftPressed(); } else if (keyEvent->key() == Qt::Key_Up) { qDebug("Up"); pressed_ = Qt::Key_Up; emit gunUpPressed(); } else if (keyEvent->key() == Qt::Key_Down) { qDebug("Down"); pressed_ = Qt::Key_Down; emit gunDownPressed(); } else if (keyEvent->key() == Qt::Key_Space) { qDebug("Space"); pressed_ = Qt::Key_Space; emit shootPressed(); } else if (keyEvent->key() == Qt::Key_G) { qDebug("G"); pressed_ = Qt::Key_G; emit changeGunPressed(); } return true; } else if (event->type() == QEvent::KeyRelease) { QKeyEvent* keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->isAutoRepeat()) { return false; } if (pressed_ == keyEvent->key()) { qDebug("Release"); pressed_ = Qt::Key_unknown; } return true; } else { return false; } } QObject::eventFilter(object, event); } <file_sep>#pragma once #include <QObject> class Controller; class Tank; class GameCore; class ObserverController : public QObject { Q_OBJECT public: explicit ObserverController(QObject* _parent, Tank* _tank); signals: void emitInput(const QString& _message); protected slots: void moveRightPressed(); void moveLeftPressed(); void gunUpPressed(); void gunDownPressed(); void shootPressed(); void changeGunPressed(); private: Tank* tank_; }; <file_sep>#pragma once #include <QtCore/QObject> #include <QtTest/QtTest> #include "network.h" class NetworkTest: public QObject { Q_OBJECT public: explicit NetworkTest(QObject *parent = 0) : QObject(parent) {} private slots: void init() { Computer computer1(31); Computer computer2(13); Computer computer3(78); Computer computer4(88); Computer computer5(56); Computer computer6(27); QVector<Computer> computers(numberOfTestingComputers); computers[0] = computer1; computers[1] = computer2; computers[2] = computer3; computers[3] = computer4; computers[4] = computer5; computers[5] = computer6; QVERIFY(computers[0].getProbability() == 31); QVERIFY(computers[1].getProbability() == 13); QVERIFY(computers[2].getProbability() == 78); QVERIFY(computers[3].getProbability() == 88); QVERIFY(computers[4].getProbability() == 56); QVERIFY(computers[5].getProbability() == 27); bool allConnected[numberOfTestingComputers][numberOfTestingComputers] = {{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,1,1,1},{1,1,1,1,1,1}}; bool **all = new bool *[numberOfTestingComputers]; for (int i = 0; i < numberOfTestingComputers; ++i) { all[i] = new bool[numberOfTestingComputers]; for (int j = 0; j < numberOfTestingComputers; ++j) all[i][j] = allConnected[i][j]; } testingWeb = new Network(computers, all); } void pureNetworkSimulation() { for (int i = 0; i < simulationSteps; ++i) { testingWeb->simulationStep(); } QVERIFY(testingWeb->howManyInfected() == 0); } void allInfectedNetworkSimulation() { delete testingWeb; bool allConnected[numberOfTestingComputers][numberOfTestingComputers] = {{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,1,1,1},{1,1,1,1,1,1}}; bool **all = new bool *[numberOfTestingComputers]; for (int i = 0; i < numberOfTestingComputers; ++i) { all[i] = new bool[numberOfTestingComputers]; for (int j = 0; j < numberOfTestingComputers; ++j) all[i][j] = allConnected[i][j]; } QVector<Computer> computers; computers += Computer(true); computers += Computer(true); computers += Computer(true); computers += Computer(true); computers += Computer(true); computers += Computer(true); testingWeb = new Network(computers, all); for (int i = 0; i < simulationSteps; ++i) { testingWeb->simulationStep(); } QVERIFY(testingWeb->howManyInfected() == numberOfTestingComputers); } void deleteTest() { delete testingWeb; QVERIFY(testingWeb->howManyComputers() == 0); } void DisconnectedNetworkSimulation() { delete testingWeb; bool allDisconnected[numberOfTestingComputers][numberOfTestingComputers] = {{1,0,0,0,0,0},{0,1,0,0,0,0},{0,0,1,0,0,0},{0,0,0,1,0,0},{0,0,0,0,1,0},{0,0,0,0,0,1}}; bool **all = new bool *[numberOfTestingComputers]; for (int i = 0; i < numberOfTestingComputers; ++i) { all[i] = new bool[numberOfTestingComputers]; for (int j = 0; j < numberOfTestingComputers; ++j) all[i][j] = allDisconnected[i][j]; } QVector<Computer> computers; computers += Computer(true); computers += Computer(true); computers += Computer(true); computers += Computer(23); computers += Computer(31); computers += Computer(44); testingWeb = new Network(computers, all); for (int i = 0; i < simulationSteps; ++i) { testingWeb->simulationStep(); } QVERIFY(testingWeb->howManyInfected() == 3); } void accessOperator() { Computer computer(56); QVERIFY(computer == (*testingWeb)[4]); } void infecting() { Computer computer(true); testingWeb->setFirstVictim(1); QVERIFY(computer == (*testingWeb)[1]); } void testKillerVirus() { testingWeb->setFirstVictim(4); IVirus* killer = new KillerVirus; testingWeb->setVirus(killer); for (int i = 0; i < simulationSteps; ++i) { testingWeb->simulationStep(); } delete killer; QVERIFY(testingWeb->howManyInfected() == numberOfTestingComputers); } void testGoodVirus() { testingWeb->setFirstVictim(4); IVirus* gentle = new GoodVirus; testingWeb->setVirus(gentle); for (int i = 0; i < simulationSteps; ++i) { testingWeb->simulationStep(); } delete gentle; QVERIFY(testingWeb->howManyInfected() == 1); } void testStandartVirus1() { delete testingWeb; bool allConnected[numberOfTestingComputers][numberOfTestingComputers] = {{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,1,1,1},{1,1,1,1,1,1}}; bool **all = new bool *[numberOfTestingComputers]; for (int i = 0; i < numberOfTestingComputers; ++i) { all[i] = new bool[numberOfTestingComputers]; for (int j = 0; j < numberOfTestingComputers; ++j) all[i][j] = allConnected[i][j]; } QVector<Computer> computers; computers += Computer(100); computers += Computer(100); computers += Computer(100); computers += Computer(100); computers += Computer(100); computers += Computer(100); testingWeb = new Network(computers, all); testingWeb->setFirstVictim(5); for (int i = 0; i < simulationSteps; ++i) { testingWeb->simulationStep(); } QVERIFY(testingWeb->howManyInfected() == numberOfTestingComputers); } void testStandartVirus2() { delete testingWeb; bool allConnected[numberOfTestingComputers][numberOfTestingComputers] = {{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,1,1,1},{1,1,1,1,1,1}}; bool **all = new bool *[numberOfTestingComputers]; for (int i = 0; i < numberOfTestingComputers; ++i) { all[i] = new bool[numberOfTestingComputers]; for (int j = 0; j < numberOfTestingComputers; ++j) all[i][j] = allConnected[i][j]; } QVector<Computer> computers; computers += Computer(0); computers += Computer(0); computers += Computer(0); computers += Computer(0); computers += Computer(0); computers += Computer(0); testingWeb = new Network(computers, all); testingWeb->setFirstVictim(0); for (int i = 0; i < simulationSteps; ++i) { testingWeb->simulationStep(); } QVERIFY(testingWeb->howManyInfected() == 1); } private: Network *testingWeb; int numberOfTestingComputers = 6; int simulationSteps = 1000; }; <file_sep>#pragma once #include <QGraphicsItem> #include <QTime> #include <QPainter> #include <QtGlobal> /** @brief Describes landscape */ class Landscape : public QGraphicsItem { public: /** @brief Generates landscape according to scene size */ Landscape(unsigned int _sceneWidth, unsigned int _sceneHeight); ~Landscape(); /** @brief Function for drawing */ void paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget = 0); /** @brief Functons for detecting collisions */ QRectF boundingRect() const; QPainterPath shape() const; QPoint getCoordinates(unsigned int _index); /** @brief Returns number of possible for movement flexures in surface */ unsigned int getLength(); private: QVector<QPoint> surface_; /// Path for painting and collisions QPainterPath path_; unsigned int numOfFlexures_; }; <file_sep>#pragma once #include <QGraphicsItem> #include <QTime> #include <QPainter> #include <QtGlobal> /** @brief Describes landscape */ class Landscape : public QGraphicsItem { public: /** @brief Generates landscape according to scene size */ Landscape(unsigned int _sceneWidth, unsigned int _sceneHeight); Landscape(const Landscape& _land); ~Landscape(); /** @brief Function for drawing */ void paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget = 0); /** @brief Functons for detecting collisions */ QRectF boundingRect() const; QPainterPath shape() const; QPoint getCoordinates(unsigned int _index); /** @brief Returns number of possible for movement flexures in surface */ unsigned int getLength() const; /** @brief Functions for copy */ QVector<QPoint> getSurface() const; QPainterPath getPath() const; unsigned int getWidth() const; unsigned int getHeight() const; QVector<int> getX() const; QVector<int> getY() const; void setSurface(QVector<QPoint> _surface); private: unsigned int width_; unsigned int height_; QVector<QPoint> surface_; /** @brief Path for painting and collisions */ QPainterPath path_; unsigned int numOfFlexures_; }; <file_sep>#include "computer.h" Computer::Computer(): morbidityPercentage_(0), infection_(false) { } Computer::Computer(int _probabilityOfInfection): infection_(false) { _probabilityOfInfection = _probabilityOfInfection % 101; morbidityPercentage_ = _probabilityOfInfection; } Computer::Computer(bool _infectedOrNot): morbidityPercentage_(0), infection_(_infectedOrNot) { } Computer::Computer(const Computer& _obj) { morbidityPercentage_ = _obj.morbidityPercentage_; infection_ = _obj.infection_; } Computer::~Computer() { } int Computer::getProbability() const { return morbidityPercentage_; } bool Computer::isInfected() const { return infection_; } void Computer::infect() { infection_ = true; morbidityPercentage_ = 0; } Computer &Computer::operator =(const Computer& _obj) { morbidityPercentage_ = _obj.getProbability(); infection_ = _obj.isInfected(); return *this; } bool Computer::operator ==(const Computer& _second) const { return ((morbidityPercentage_ == _second.getProbability()) && (infection_ == _second.isInfected())); } bool Computer::operator !=(const Computer& _second) const { return ((infection_ != _second.isInfected()) || (morbidityPercentage_ != _second.getProbability())); } std::ostream &operator <<(std::ostream& _stream, const Computer& _computer) { if (_computer.isInfected()) { _stream << "Infected Computer"; } else { _stream << "Pure Computer, with " << _computer.getProbability() << "% probability of infect"; } return _stream; } <file_sep>#include "goodvirus.h" GoodVirus::GoodVirus() { } GoodVirus::~GoodVirus() { } int GoodVirus::getContagiousness() { return 100; } <file_sep>#include "standartvirus.h" StandartVirus::StandartVirus() { } StandartVirus::~StandartVirus() { } int StandartVirus::getContagiousness() { int cube = qrand() % 100; return cube; } <file_sep>#include "explosion.h" Explosion::Explosion(QPointF _position, double _radius): radius_(_radius) { setPos(_position); } Explosion::~Explosion() { } void Explosion::paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget) { _painter->setBrush(QColor(128, 0, 128)); _painter->setPen(QColor(64, 0, 128)); _painter->drawEllipse(QPointF(0, 0) , radius_, radius_); } QRectF Explosion::boundingRect() const { return QRectF(QPointF(-radius_, radius_), QPointF(radius_, -radius_)); } QPainterPath Explosion::shape() const { QPainterPath path; path.addEllipse(QPointF(0, 0) , radius_, radius_); return path; } <file_sep>#pragma once #include <iostream> /** * @brief The Computer class * Imitate computer in network */ class Computer { public: /// @brief Create uninfected computer with 0 morbidity Computer(); Computer(int _probabilityOfInfection); /// @brief Infected Computers has 0 morbidity Computer(bool _infectedOrNot); /// @brief Copy constructor Computer(const Computer& _obj); ~Computer(); int getProbability() const; bool isInfected() const; void infect(); Computer &operator =(const Computer& _obj); bool operator ==(const Computer& _second) const; bool operator !=(const Computer& _second) const; friend std::ostream &operator <<(std::ostream& _stream, const Computer& _computer); private: int morbidityPercentage_; bool infection_; }; <file_sep>#include "gamecore.h" #include "tank.h" #include "landscape.h" #include "Input/keyboardcontroller.h" GameCore::GameCore(unsigned int _width, unsigned int _height, QWidget* _parent): QGraphicsView(_parent), network_(nullptr), scene_(nullptr), loop_(new QEventLoop(this)), timer_(nullptr), landscape_(nullptr), firstTank_(nullptr), secondTank_(nullptr), isFirstTankTurn_(false), currentTank_(nullptr), victim_(nullptr), shell_(nullptr), shellLaunched_(false), isServer_(false), windowWidth_(_width), windowHeight_(_height) { timer_ = new QTimer(this); connect(timer_, &QTimer::timeout, this, &GameCore::frame); connect(this, SIGNAL(gameOver(QString)), this, SLOT(whenGameOver())); scene_ = new QGraphicsScene(this); scene_->setSceneRect(0, 0, windowWidth_, windowHeight_); } void GameCore::setLandscape(Landscape* _landscape) { Client* client = static_cast<Client *>(network_); disconnect(client, SIGNAL(gotLandscape(Landscape*)), this, SLOT(setLandscape(Landscape*))); landscape_ = _landscape; loop_->exit(); } void GameCore::startGame(Network *_network) { network_ = _network; setScene(scene_); KeyboardController* controller = new KeyboardController(this); if (dynamic_cast<Server *>(_network)) { isServer_ = true; Server* server = static_cast<Server *>(_network); landscape_ = new Landscape(windowWidth_, windowHeight_); server->sendLandscape(landscape_); firstTank_ = new Tank(this, landscape_, this); secondTank_ = new Tank(this, landscape_, this); isFirstTankTurn_ = true; currentTank_ = firstTank_; victim_ = secondTank_; } else { Client* client = static_cast<Client *>(_network); connect(client, SIGNAL(gotLandscape(Landscape *)), this, SLOT(setLandscape(Landscape*))); loop_->exec(); secondTank_ = new Tank(this, landscape_, this); firstTank_ = new Tank(this, landscape_, this); isFirstTankTurn_ = false; currentTank_ = secondTank_; victim_ = firstTank_; } scene_->addItem(landscape_); scene_->addItem(firstTank_); scene_->addItem(secondTank_); firstTank_->setController(controller); _network->initController(secondTank_); network_->observeController(firstTank_); if (isFirstTankTurn_) { secondTank_->getController()->blockSignals(true); } else { firstTank_->getController()->blockSignals(true); } } void GameCore::nextStep(bool _isBigGun) { shellLaunched_ = true; if (_isBigGun) { shell_ = new BigShell(currentTank_->getGunPosition(), currentTank_->getDirection(), currentTank_->getAngle()); } else { shell_ = new Shell(currentTank_->getGunPosition(), currentTank_->getDirection(), currentTank_->getAngle()); } scene_->addItem(shell_); firstTank_->getController()->blockSignals(true); secondTank_->getController()->blockSignals(true); if (isFirstTankTurn_) { isFirstTankTurn_ = false; } else { isFirstTankTurn_ = true; } timer_->start(20); } void GameCore::frame() { if (shell_->collidesWithItem(victim_)) { timer_->stop(); delete shell_; shellLaunched_ = false; if (isFirstTankTurn_ ^ isServer_) { emit gameOver("First Tank Wins!"); } else { emit gameOver("Second Tank Wins!"); } qDebug("Collide with victim"); } else if (shell_->collidesWithItem(landscape_)) { timer_->stop(); scene_->addItem(shell_->blast()); if (shell_->blast()->collidesWithItem(victim_)) { if (isFirstTankTurn_ ^ isServer_) { emit gameOver("First Tank Wins!"); } else { emit gameOver("Second Tank Wins!"); } qDebug("Explode"); } delete shell_; shellLaunched_ = false; if (isFirstTankTurn_) { firstTank_->getController()->blockSignals(false); } else { secondTank_->getController()->blockSignals(false); } std::swap(currentTank_, victim_); qDebug("Collide with surface"); } else if (scene_->sceneRect().contains(shell_->getPosition())) { shell_->frame(); } else { timer_->stop(); delete shell_; shellLaunched_ = false; if (isFirstTankTurn_) { firstTank_->getController()->blockSignals(false); } else { secondTank_->getController()->blockSignals(false); } std::swap(currentTank_, victim_); qDebug("Out of scene"); } viewport()->update(); } void GameCore::whenGameOver() { deleteLater(); } <file_sep>#include "controller.h" Controller::Controller(QObject* _parent) : QObject(_parent), pressed_(Qt::Key_unknown) { } <file_sep>#include "observercontroller.h" #include "controller.h" #include "Game/tank.h" #include "Game/gamecore.h" ObserverController::ObserverController(QObject* _parent, Tank* _tank) : QObject(_parent), tank_(_tank) { Controller* controller = _tank->getController(); connect(controller, SIGNAL(gunDownPressed()), this, SLOT(gunDownPressed())); connect(controller, SIGNAL(gunUpPressed()), this, SLOT(gunUpPressed())); connect(controller, SIGNAL(moveRightPressed()), this, SLOT(moveRightPressed())); connect(controller, SIGNAL(moveLeftPressed()), this, SLOT(moveLeftPressed())); connect(controller, SIGNAL(changeGunPressed()), this, SLOT(changeGunPressed())); connect(controller, SIGNAL(shootPressed()), this, SLOT(shootPressed())); } void ObserverController::moveRightPressed() { emit emitInput(QString("KR")); } void ObserverController::moveLeftPressed() { emit emitInput(QString("KL")); } void ObserverController::gunUpPressed() { emit emitInput(QString("KU")); } void ObserverController::gunDownPressed() { emit emitInput(QString("KD")); } void ObserverController::shootPressed() { emit emitInput(QString("KS")); } void ObserverController::changeGunPressed() { emit emitInput(QString("KC")); } <file_sep>#pragma once #include <QGraphicsItem> #include <QPainter> /** @brief Explosion describes an explosion */ class Explosion : public QGraphicsItem { public: Explosion(QPointF _position, double _radius); ~Explosion(); /** @brief Function for drawing */ void paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget = 0); /** @brief Functions for detecting collisions */ QRectF boundingRect() const; QPainterPath shape() const; protected: double radius_; }; <file_sep>#include "landscape.h" Landscape::Landscape(unsigned int _sceneWidth, unsigned int _sceneHeight): width_(_sceneWidth), height_(_sceneHeight) { qsrand(QTime::currentTime().msec()); surface_ = {QPoint(0, height_ / 2)}; int cursor = 0; int heightOffset = height_ / 2; while (cursor < width_) { int sign = qrand() % 2; int increase = qrand() % 10; if (sign && (heightOffset < ((3*height_) / 4))) { heightOffset += increase; cursor += 5; } else if (heightOffset > height_ / 4) { heightOffset -= increase; cursor += 5; } surface_.append(QPoint(cursor, heightOffset)); } numOfFlexures_ = surface_.length(); surface_.append(QPoint(width_, height_)); surface_.append(QPoint(0, height_)); surface_.append(QPoint(0, height_ / 2)); path_.moveTo(0, height_ / 2); for (unsigned int i = 1; i < numOfFlexures_ + 3; ++i) { path_.lineTo(surface_[i]); } } Landscape::Landscape(const Landscape& _land) { if (_land.getLength() < 1) { return; } width_ = _land.getWidth(); height_ = _land.getHeight(); surface_ = _land.getSurface(); path_ = _land.getPath(); numOfFlexures_ = _land.getLength(); } Landscape::~Landscape() { surface_.clear(); } QRectF Landscape::boundingRect() const { return QRectF(QPoint(0, 0), QPoint(800, 600)); } QPainterPath Landscape::shape() const { return path_; } QPoint Landscape::getCoordinates(unsigned int _index) { return surface_[_index]; } unsigned int Landscape::getLength() const { return numOfFlexures_; } QVector<QPoint> Landscape::getSurface() const { return surface_; } QPainterPath Landscape::getPath() const { return path_; } unsigned int Landscape::getWidth() const { return width_; } unsigned int Landscape::getHeight() const { return height_; } QVector<int> Landscape::getX() const { QVector<int> xCoordinates(numOfFlexures_ + 3); for (int i = 0; i < numOfFlexures_ + 3; ++i) { xCoordinates[i] = surface_[i].x(); } return xCoordinates; } QVector<int> Landscape::getY() const { QVector<int> yCoordinates(numOfFlexures_ + 3); for (int i = 0; i < numOfFlexures_ + 3; ++i) { yCoordinates[i] = surface_[i].y(); } return yCoordinates; } void Landscape::setSurface(QVector<QPoint> _surface) { surface_ = _surface; numOfFlexures_ = surface_.length() - 3; path_ = QPainterPath(); path_.moveTo(0, height_ / 2); for (unsigned int i = 1; i < numOfFlexures_ + 3; ++i) { path_.lineTo(surface_[i]); } } void Landscape::paint(QPainter* _painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget) { _painter->setBrush(Qt::green); _painter->setPen(Qt::green); _painter->drawPath(path_); } <file_sep>#include "networkserver.h" Server::Server(QObject *_parent) : Network(_parent), tcpServer_(nullptr) { } bool Server::init() { QNetworkConfigurationManager manager; if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) { networkSession_ = new QNetworkSession(manager.defaultConfiguration(), this); connect(networkSession_, SIGNAL(opened()), this, SLOT(sessionOpened())); networkSession_->open(); } else { sessionOpened(); } if (!tcpServer_) { return false; } connect(tcpServer_, SIGNAL(newConnection()), this, SLOT(connectClient())); return true; } QString Server::getPort() const { if (tcpServer_ && tcpServer_->isListening()) { return QString::number(tcpServer_->serverPort()); } else { return QString(); } } void Server::sendLandscape(Landscape *_landscape) { QVector<int> fieldX = _landscape->getX(); QVector<int> fieldY = _landscape->getY(); int length = _landscape->getLength() + 3; QString message = "L"; message += QString::number(length); for (int i = 0; i < length; ++i) { message += " " + QString::number(fieldX[i]); message += " " + QString::number(fieldY[i]); } sendMessage(message); return; } void Server::sessionOpened() { tcpServer_ = new QTcpServer(this); if (!tcpServer_->listen()) { if (tcpServer_) { delete tcpServer_; } } else { tcpServer_->setMaxPendingConnections(1); } } void Server::connectClient() { if (!(tcpSocket_ && tcpSocket_->state() != QAbstractSocket::UnconnectedState)) { tcpSocket_ = tcpServer_->nextPendingConnection(); connect(tcpSocket_, SIGNAL(readyRead()), this, SLOT(newMessage())); connect(tcpSocket_, SIGNAL(disconnected()), this, SIGNAL(disconnected())); emit connected(); } }
983adc8a9157de8310b9a1354f13aada524a2c3c
[ "C++" ]
49
C++
GArGuTZ/Homework
8b1a9195e6be0beef7ae256fc9c476559fc028a1
3c8f0c21b389738660cd76862da33036534df935
refs/heads/master
<repo_name>Grandez/YATA<file_sep>/YATAManualTech/0601-database.Rmd # Base de datos ## Creacion ctc_db.sql Crea la Base de datos ctc_users.sql Crea el usuario CTC_TABLES CARGA LAS TABLAS NORMALES cc_tables_session las de datos de session para evitar que se borren <file_sep>/YATAWeb/ui/modMainServer.R vars <- reactiveValues(lstData = NULL ,fila = 1 ,clicks = 0 ,numOpers = 0 ,buy = 0 ,sell = 0 ,trading = NULL ,posicion=NULL ,estado=0 # 0 = Inactivo ,mode = 0 ,dfd = NULL # Datos ,dfi = NULL # Datos con indicadores ,dfc = NULL # Datos vistos ,dfp = NULL ,dft = NULL ,sessions=NULL ) # layoutTickers = TBLTickers$new("Tickers") advanceSimulation <- function(input, output, session) { res = nextTicker(case, portfolio) vars$fila = case$current if (case$current > case$getNumTickers()) { vars$fila = vars$fila - 1 vars$estado = 0 return (OP_EXECUTED) } vars$dfc = case$getCurrentData(asClass=T)$df vars$dfp = portfolio$updatePosition(case)$df updateEstado(input, output, session) if (res == OP_EXECUTED) { vars$dft = portfolio$getTrading()$df vars$numOpers = vars$numOpers + 1 if (case$oper$units > 0) vars$buy = vars$buy + 1 if (case$oper$units < 0) vars$sell = vars$sell + 1 } if (res != OP_PROPOSED) { #shinyjs::show("btnStop") if (case$config$mode != MODE_MANUAL) { if (vars$fila <= case$getNumTickers()) { session$sendCustomMessage("handler1", vars$fila) } else { #createSummary() # shinyjs::hide("btnStop") } } } if (res == OP_PROPOSED) { showModal(dlgOper(input, output, session, case$oper)) } Sys.sleep(case$config$delay) res } nextCycle <- function(input, output, session, fila) { action = caso$model$calculateAction(portfolio, caso) if (action[1] == 0) return(OP_NONE) caso$oper = caso$model$calculateOperation(portfolio, caso, action) if (is.null(caso$oper)) return(OP_NONE) if (caso$mode == MODE_AUTOMATIC) { vars$trading = cartera$flowTrade(caso$oper) if (caso$oper$units > 0) vars$buy = vars$buy + 1 if (caso$oper$units < 0) vars$sell = vars$sell + 1 return (OP_EXECUTED) } # callModule(modDlgVerify, "dlgVerify") shinyjs::addClass("lblOperCapital", "shiny-bound-input") shinyjs::removeClass("lblOperCapital", "shiny-bound-output") output$lblOperCapital = renderText("0") showModal(dlgOper(input, output, session, caso$oper)) OP_PROPOSED } updateEstado <- function(input, output, session) { # Update page output$lblMoneda = renderText(portfolio$getActive()$name) output$lblPosFiat = renderText(format(portfolio$getActive(CURRENCY)$position, nsmall=0)) output$lblPosMoneda = renderText(format(portfolio$getActive()$position, nsmall=6)) output$lblPosTotal = renderText(format(portfolio$getBalance(), nsmall=0)) output$lblPosDate = renderText(format(case$tickers$df[vars$fila,case$tickers$DATE], "%d/%m/%Y")) output$lblResMov = renderText(case$current) output$lblTrend = renderText(case$trend * (nrow(case$tickers$df))) res = 0 if(case$config$initial != 0) res = ((portfolio$getBalance() / case$config$initial) - 1) * 100 output$lblEstado = renderText(sprintf("%.2f%%", res)) .updateHTMLEstado(res) output$lblResOper = renderText(vars$numOpers) output$lblResC = renderText(vars$buy) output$lblResV = renderText(vars$sell) } modMain <- function(input, output, session, parent, changed) { #J updateEstado(input, output, session) #J session$sendCustomMessage("hndlButtons", paste(case$config$mode, vars$estado, sep=",")) #J #J plots = case$model$getIndicatorsName() #J updateCheckboxGroupInput(session, "chkPlots1", choices=plots, selected=plots) #J #J output$lblResInicio = renderText({case$config$initial}) ################################################################################ # Dialogo de validar operacion ################################################################################ vars$clicks = 0 ## vars$pos = portfolio$getPosition() observeEvent(input$btnOperESC, { removeModal(); advanceSimulation(input, output, session) }) observeEvent(input$btnOperOK, { removeModal() portfolio$flowTrade(caso$oper) vars$opers = vars$oper + 1 if (caso$oper$units > 0) vars$buy = vars$buy + 1 if (caso$oper$units < 0) vars$sell = vars$sell + 1 vars$dft = portfolio$trading()$df advanceSimulation(input, output, session) }) ################################################################################ # Observers para la simulacion ################################################################################ observeEvent(input$btnSimulate, { vars$clicks = vars$clicks + 1 vars$estado = switch(vars$estado + 1, 1,2,1) session$sendCustomMessage("hndlButtons", paste(case$config$mode, vars$estado, sep=",")) if (vars$estado == 1) advanceSimulation(input, output, session) } ) observeEvent(input$btnSave, { saveSession(input, output, session)}) observeEvent(input$btnNext, { if (vars$estado == 1) advanceSimulation(input, output, session)}) observeEvent(input$btnStop, { shinyjs::toggle("btnStop") vars$estado = 0 vars$fila = 0 session$sendCustomMessage("hndlButtons", paste(case$config$mode, vars$estado, sep=",")) }) observeEvent(vars$dfc, { output$tblBodyData = DT::renderDataTable({.prepareTable(vars$dfc, case$getCurrentData(asClass=T)) }) output$tblBodyPos = DT::renderDataTable({.prepareTable(vars$dfp, portfolio$getPositionHistory()) }) output$tblBodyTrade = DT::renderDataTable({.prepareTableTrading(vars$dft, portfolio$getTrading()) }) }) # trigger <- reactivePoll(1000, session, checkFunc=function() {vars$fila}, valueFunc=function() {caso$dfi}) tblOptions = list(searching = FALSE, rownames = F) #output$tblData = DT::renderDataTable({ caso$dfi[1:vars$fila,]},options = lstOptions) # output$tblBodyData = DT::renderDataTable({.prepareTable(vars$dfc, case$getCurrentData(asClass=T)) }) # output$tblBodyPos = DT::renderDataTable({browser(); .prepareTable(vars$dfp, portfolio$getPositionHistory()) }) # output$tblBodyTrade = DT::renderDataTable({browser(); .prepareTable(vars$dft, portfolio$getTrading()) }) output$plotMain <- renderPlotly({ df = case$tickers$df plots = plotData(vars$clicks, case$tickers, case$model, T, input$chkPlots1) if (is.null(plots)) return (NULL) shapes = list() shapes = list.append( shapes ,vline(as.Date(df[vars$fila, DF_DATE])) # ,zone(vars$df[vars$fila, "Date"], df[nrow(df),"Date"]) ) trading = portfolio$getTrading() if (!is.null(trading$df)) { for (idx in 1:nrow(trading$df)) { colour=ifelse(trading$df[idx,trading$TYPE] == OP_BUY, "green", "red") shapes = list.append(shapes, vline(as.Date(trading$df[idx,DF_DATE]),color=colour)) } } plots[[1]] = plots[[1]] %>% layout(xaxis = axis, shapes=shapes) plots[[2]] = plots[[2]] %>% layout(shapes=shapes) sp = subplot(hide_legend(plots[[1]]), hide_legend(plots[[2]]), nrows = 2, shareX=T, heights=c(0.75,0.25)) sp$elementId = NULL sp }) # output$plotMain <- renderPlotly({ # vars$df = case$data$getData() # # vars$clicksn # # # if (vars$clicks == 0) return(NULL) # if (is.null(vars$df)) return(NULL) # # p1 <- plot_ly(vars$df, x = ~Date, y = ~Price, type = 'scatter', mode = 'lines') # p1$elementId = NULL # # p2 <- plot_ly(vars$df, x = ~Date, y = ~Volume, type = 'bar') # p2$elementId = NULL # # plots = list(p1, p2) # # plots = case$model$plotIndicators (plots, case$data, input$chkPlots1) # # shapes = list() # shapes = list.append( shapes # ,vline(vars$df[vars$fila, "Date"]) # # ,zone(vars$df[vars$fila, "Date"], df[nrow(df),"Date"]) # ) # # plots[[1]] = plots[[1]] %>% layout(xaxis = axis, shapes=shapes) # plots[[2]] = plots[[2]] %>% layout(shapes=shapes) # # sp = subplot(hide_legend(plots[[1]]), hide_legend(plots[[2]]), nrows = 2, shareX=T, heights=c(0.75,0.25)) # sp$elementId = NULL # sp # }) } changeButtonLabel = function(estado) { if (case$config$mode != MODE_MANUAL) { return (switch(estado + 1, "Simulate", "Pause", "Continue")) } return("Next") } # .prepareTableTrading = function(df, data) { # df = data$df # if (is.null(df)) return(NULL) # # # Prepara datos # df[,DF_DATE] = as.Date(df[,DF_DATE]) # # dt = datatable( df[,-c(1,2)] # # ,callback = JS("createdRow( row, data, dataIndex) { # # $(row).addClass((data['Uds'] < 0 ? 'tradingSell' : 'tradingBuy')) # # }") # ) # # dt = dt %>% formatRound(data$getDecimals(), digits = case$config$dec) # dt = dt %>% formatRound(data$getCoins(), digits = 0) # dt # } .updateHTMLEstado = function(res) { if (res == 0) { jqui_remove_class("sim-lblEstado", c("rojo","verde")) # jqui_hide("#sim-resDown","blind") # jqui_hide("#sim-resUp","blind") return() } if (res > 0) { jqui_switch_class('#sim-lblEstado', "rojo", "verde") # jqui_hide ("#sim-resDown","blind") # jqui_show ("#sim-resUp","blind") return() } jqui_switch_class('#sim-lblEstado', "verde", "rojo") # jqui_hide("#sim-resUp","blind") # jqui_show("#sim-resDown","blind") } <file_sep>/YATAAnalytics/R/correl.R library(dplyr) library(XLConnect) library(reshape2) library(Hmisc) XLConnect::xlcFreeMemory() gc() wb = loadWorkbook("d:/prj/R/YATA/YATAData/in/currencies.xlsx") shn = getSheets(wb) shn = shn[which(shn != "$Index")] shn = shn[which(shn != "BTC")] shn = shn[which(shn != "USDT")] tmp = readWorksheet(wb, "BTC") tmp = tmp %>% arrange(Date) %>% filter(as.Date(Date) > as.Date("2016-12-31")) df = tmp[,c("Date","Close")] colnames(df) = c("Date", "BTC") for (sh in shn) { cat(sh, "\n") tmp = readWorksheet(wb, sh) tmp = tmp %>% arrange(Date) %>% filter(Date > "2016-12-31") tmp = tmp[,c("Date","Close")] colnames(tmp) = c("Date", sh) df = full_join(df,tmp, by="Date") } dfl = melt(df, id="Date") #ggplot(data=dfl,aes(x=Date, y=value, colour=variable)) + geom_line() #rcorr(as.matrix(df[,2:ncol(df)])) # Ahora sin BTC shn = shn[which(shn != "BTC")] tmp = readWorksheet(wb, "ADA") tmp = tmp %>% arrange(Date) %>% filter(as.Date(Date) > as.Date("2016-12-31")) df = tmp[,c("Date","Close")] colnames(df) = c("Date", "BTC") for (sh in shn) { cat(sh, "\n") tmp = readWorksheet(wb, sh) tmp = tmp %>% arrange(Date) %>% filter(Date > "2016-12-31") tmp = tmp[,c("Date","Close")] colnames(tmp) = c("Date", sh) df = full_join(df,tmp, by="Date") } dfl = melt(df, id="Date") ggplot(data=dfl,aes(x=Date, y=value, colour=variable)) + geom_line() #rcorr(as.matrix(df[,2:ncol(df)])) <file_sep>/YATACore/R/PKG_IO_CSV.R library(XLConnect) .CSVWriteData <- function(data, container, component) { fName = filePath(YATAENV$dirOut, name=component, ext="csv") write.table(data,fName,row.names=F,sep=";",dec=",") } .CSVAppendData <- function(data, container, component) { fName = filePath(YATAENV$dirOut, name=component, ext="csv") write.table(data, fName, sep=";", dec=",",row.names=F, col.names = F, append=T) } # .makeDir <- function(...) { do.call(file.path,c(DIRS["root"], ...)) } <file_sep>/YATACore/R/TBL_Portfolio.R TBLPortfolio = R6::R6Class("TBLPortfolio", inherit=YATATable, public = list( # Column names CLEARING = "ID_CLEARING" ,CTC = "CURRENCY" ,ACTIVE = "ACTIVE" ,POSITION = "POS" ,AVAILABLE = "AVAILABLE" ,LAST_OPER = "LAST_OP" ,LAST_VALUE = "LAST_VALUE" ,LAST_TMS = "LAST_TMS" ,initialize = function() { self$name="Portfolio"; self$table = "PORTFOLIO"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) } ,getCTCSymbols = function(all = F) { tmp = self$dfa if (!all) tmp = self$dfa[self$dfa$ACTIVE == T,] tmp[,self$CTC] } ,getClearingPosition = function(clearing=NULL) { qry1 = paste("SELECT", self$CTC, ", SUM(", self$POSITION, ") AS ", self$POSITION , ", SUM(", self$AVAILABLE, ") AS ", self$AVAILABLE , ", MAX(", self$LAST_TMS, ") AS ", self$LAST_TMS) qry1 = paste(qry1, "FROM ", self$table) qry2 = paste(qry1, "WHERE", self$CLEARING, " = ?") qry3 = paste( "GROUP BY ", self$CTC) qry = qry1 parms = NULL if (!is.null(clearing)) { qry = qry2 parms = list(clearing) } qry = paste(qry, qry3) df = executeQuery(qry, parms) if (!is.null(df)) { df[,self$POSITION] = as.fiat(df[,self$POSITION]) df[,self$AVAILABLE] = as.fiat(df[,self$AVAILABLE]) df[,self$LAST_TMS] = as.dated(df[,self$LAST_TMS]) } df } ,getAvailable = function(currency,clearing=NULL) { tmp = private$getPos(currency, clearing) res = as.numeric(tmp[1,self$AVAILABLE]) as.ctc(res) } ,updatePosition = function(idOper, clearing, currency, amount, date, executed) { pos = self$getClearingPosition(clearing) if (!is.null(pos)) { pos = pos %>% filter(CURRENCY == currency) if (nrow(pos) == 0) pos = NULL } if (is.null(pos)) { fields = c( self$CLEARING, self$CTC, self$ACTIVE, self$POSITION ,self$AVAILABLE, self$LAST_OPER, self$LAST_VALUE, self$LAST_TMS) values = list(clearing, currency, 1, amount, amount, idOper, amount, date) names(values) = fields self$insert(values) } else { newVal = pos[1, self$POSITION] + amount available = pos[1, self$AVAILABLE] if (executed) available = available + amount fields = c(self$POSITION, self$AVAILABLE, self$LAST_OPER, self$LAST_VALUE, self$LAST_TMS) values = list(newVal, available, idOper, amount, date) names(values) = fields keys = list(clearing, currency) names(keys) = c(self$CLEARING, self$CTC) self$update(values, keys) } } ) ,private = list ( getClearingPos = function(clearing) { } ,getPos = function(currency, clearing) { browser() tmp = self$df %>% filter(self$df$CURRENCY == currency) if (!is.null(clearing)) tmp = tmp %>% filter(tmp$ID_CLEARING == clearing) tmp = tmp %>% group_by(CURRENCY=tmp$CURRENCY) %>% summarise(POS=sum(tmp$POS), AVAILABLE=sum(tmp$AVAILABLE), LAST_TMS=max(LAST_TMS)) if (nrow(tmp) == 0) { tmp = data.frame("CURRENCY"=character(), "POS"=numeric(),"AVAILABLE"=numeric(),"LAST_TMS"=as.Date(character())) cols = colnames(tmp) tmp = rbind(tmp, list(currency, 0.0, 0.0, Sys.Date())) colnames(tmp) = cols } tmp } ,addRecord = function(clearing, currency, amount, date, executed, conn) { sql = paste("INSERT INTO", self$table, "(") sql = paste(sql, self$CLEARING, ",", self$CTC, self$ACTIVE, ",", self$POSITION, ",") sql = paste(sql, self$AVAILABLE, ",", self$LAST_OPER, ",", self$LAST_VALUE, ",", self$LAST_TMS, ")") sql = paste(sql, " VALUES (?, ?, ?, ?, ?, ?, ?, ?)") parms = list(clearing, currency, 1, amount, amount, date, amount, date) executeUpdate(sql, parms, conn) } ,updateRecord = function(clearing, currency, amount, available, date, executed, conn) { parms = NULL sql = paste("UPDATE", self$table, "SET") sql = paste(sql, self$POSITION, "= ?") sql = paste(sql, ",", self$AVAILABLE, " = ?") sql = paste(sql, ",", self$LAST_OPER, " = ?") sql = paste(sql, ",", self$LAST_VALUE, " = ?") sql = paste(sql, ",", self$LAST_TMS, " = ?") sql = paste(sql, ") WHERE ", self$CLEARING, " = ? AND", self$CTC, " = ?") parms = list(amount, available, date, amount, date, clearing, currency) executeUpdate(sql, parms, conn) } ) ) <file_sep>/YATACore/R/TBL_Profile.R TBLProfile = R6::R6Class("TBLProfile", inherit=YATATable, public = list( # Column names ID = "ID" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,FIAT = "FIAT" ,CTC = "CTC" ,MODEL = "MODEL" ,PROFILE = "PROFILE" ,SCOPE = "SCOPE" ,initialize = function() {self$name="Profile"; self$table = "PROFILES"; super$refresh()} ,getFiat = function() {if (self$nrow() == 0) return (NA); self$df[1,self$FIAT] } ,getCTC = function() {if (self$nrow() == 0) return (NA); self$df[1,self$CTC] } ,getModel = function() {if (self$nrow() == 0) return (NA); self$df[1,self$MODEL] } ,getProfile = function() {if (self$nrow() == 0) return (NA); self$df[1,self$PROFILE] } ,getScope = function() {if (self$nrow() == 0) return (SCOPE_DAY); self$df[1,self$SCOPE] } ) ,private = list ( ) ) <file_sep>/YATABatch/R/YATABatch.R detach("package:YATA", unload=T) library(R6) library(dplyr) library(rlist) library(tibble) library(XLConnect) library(lubridate) library(mondate) library(zoo) library(YATA) options( DT.options = list(dom = "t",rownames = FALSE) ,java.parameters = "-Xmx2048m" ) file.sources = list.files("R", pattern="(YATABatch).+\\.R$", full.names=TRUE, ignore.case=F) sapply(file.sources,source) MIN_PERCENTAGE=0.75 # Minimo rango de datos que se deben cumplir summFileName = paste("batch", strftime(Sys.time(),format="%Y%m%d"), strftime(Sys.time(),format="%H%M%S"), sep="_") #nCases = 0 # Used to detect first case or not #' Prueba #' #' @import YATACore #' YATABatch <- function(ids=NULL) { createEnvironment() dbCases = createDBCases() dfCases = prepareCases(ids, dbCases) cat(sprintf("%d casos preparados\n", nrow(dfCases))) nCases = .executeCases(dfCases, dbCases) cat(sprintf("%d casos ejecutados\n", nCases)) } .executeCases <- function(dfCases, dbCases) { nCases = 0 for (iCase in 1:nrow(dfCases)) { xlcFreeMemory() gc() case = as.list(dfCases[iCase,]) tbTickers = TBLTickers$new(dfCases[iCase, "Symbol"]) tbTickers$filterByDate(case[["Start"]], case[["End"]]) # Verificar rango de datos if ((tbTickers$nrow() / (case[["Period"]] * 30)) < MIN_PERCENTAGE) next case = .createCase(dfCases[iCase,], tbTickers, dbCases) nCases = nCases + 1 cat(sprintf("Executing case %6d (%06d) ", nCases, iCase)) tBeg = proc.time() portfolio = YATA::executeSimulation(case) tEnd = proc.time() elapsed = tEnd["elapsed"] - tBeg["elapsed"] .addSummary(iCase, elapsed, dfCases[iCase,], case, portfolio) cat(sprintf(" - %3.0f\n", elapsed)) } nCases } .addSummary <- function(index, elapsed, record, case, portfolio) { modelName = record[1,"Model"] idTest = paste(modelName, round(as.numeric(Sys.time())), sep="_") lPrfx = list(date=Sys.Date(), id=idTest, elapsed=round(elapsed, 2)) lCase = list(record[1,]) lParms = case$model$getParameters() lThres = case$model$getThresholds() lPos = list(portfolio$getPosition()[3:5]) rec = portfolio$getActive()$getLastTrading() lPM = as.list(rec[1, grep("^PM", colnames(rec))]) num = lPos[[1]][1] if (length(lPM) > 0) { # Hay operaciones? num = num + (lPos[[1]][2] * lPM[2]) } else { lPM=list(PMM=0,PMC=0) } den = lCase[[1]]["Capital"] res = round(((num /den) - 1) * 100, 2) angle = round(case$tickers$getTrendAngle(),0) lista = list.append(lPrfx, lCase, lParms, Trend=angle, lPos, lPM, Res=res[1,1]) reg = as.data.frame(lista) if (index > 1) { appendSummary(reg, NULL, summFileName) } else { writeSummary(reg, NULL, summFileName) } } .loadCurrenciesList = function(from, to) { tIdx = DBCTC$getTable(TCTC_INDEX) df = tIdx$df %>% filter(eval(parse(text=tIdx$SYMBOL)) >= from) df = df %>% filter(eval(parse(text=tIdx$SYMBOL)) <= to) df %>% arrange(tIdx$SYMBOL) } .createCase = function(rCase, tbTickers, dbCases) { tbCases = dbCases$getTable(TCASES_CASES) profile = YATAProfile$new() profile$name = "Batch" profile$profile = rCase[1,"Profile"] profile$scope = rCase[1,"Scope"] profile$capital = rCase[1,"Capital"] config = YATAConfig$new() config$symbol = rCase[1,"Symbol"] config$from = rCase[1,"Start"] config$to = rCase[1,"End"] model = loadModel(DBModels, rCase[1,"Model"]) prmNames = grep(paste0("^",tbCases$GRP_PARMS),colnames(rCase), value=T) if (length(prmNames) > 0) { vars = as.vector(rCase[1, prmNames]) names(vars) = prmNames model$setParametersA(vars, tbCases$GRP_PARMS) } thrNames = grep(paste0("^",tbCases$GRP_THRESHOLDS),colnames(rCase), value=T) if (length(thrNames) > 0) { vars = as.vector(rCase[1, thrNames]) names(vars) = thrNames model$setThresholdsA(vars, tbCases$GRP_THRESHOLDS) } rCase = YATACase$new() rCase$tickers = tbTickers rCase$config = config rCase$model = model rCase$profile = profile rCase }<file_sep>/YATALoader/R/loader.R if("YATACore" %in% (.packages())) detach(name="package:YATACore", unload=T, character.only = T, force = T) if("YATAProviders" %in% (.packages())) detach(name="package:YATAProviders", unload=T, character.only = T, force = T) # Common library("dplyr") library("lubridate") library("YATACore") library("YATAProviders") #' @export #' @param pairs Intenta recuperar todas las combinaciones #' Por defecto solo las activas #' @param provider Indica el proveedor, por defecto todos retrieveSessions = function(all.pairs = F, provider=NULL) { providers = provider if (is.null(providers)) { TProviders = TBLProviders$new() providers = TProviders$df[, TProviders$SYMBOL] for (provider in providers) { if (provider == "POL") .getSessionByProvider(provider, all.pairs) } } } #' @export groupSessions = function() { loadWeeks() loadMonths() } .getSessionByProvider = function(provider, all.pairs) { TPairs = .getPairs(provider, all.pairs) .loadSessions(provider, TPairs) groupSessions() } .getPairs = function(provider, all.pairs) { TPairs = TBLPairs$new() pairs = TPairs$getByClearing(provider) if (all.pairs) { TFiat = TBLFiat$new() TCTC = TBLCTC$new() pairsAll = merge(TFiat$df[,TFiat$SYMBOL],TCTC$df[,TCTC$SYMBOL],all=TRUE) colnames(pairsAll) = c("BASE", "COUNTER") pairsAll$CLEARING = provider pairs = merge(pairs, pairsAll, by=c("CLEARING", "BASE", "COUNTER"), all.x=T) } TPairs$df = pairs TPairs } .loadSessions = function(provider, TPairs) { reg = 0 while (reg < nrow(TPairs$df)) { reg = reg + 1 base = TPairs$df[reg, TPairs$BASE] counter = TPairs$df[reg, TPairs$COUNTER] tms = TPairs$df[reg, TPairs$LAST_UPD] cat(sprintf("%s - Retrieving %s/%s\n", format(Sys.time(), "%X"), base, counter)) YATACore::beginTrx(T) maxTMS = tms tms = tms + 1 for (per in c("2H", "4H", "D")) { if (per == "2H") table = "POL_TICKERSH2" if (per == "4H") table = "POL_TICKERSH4" if (per == "D") table = "POL_TICKERSD1" df = YATAProviders::getHistorical(base=base,counter=counter,from=tms,period=per) if (!is.null(df) && nrow(df) > 0) { tmpTMS = max(df$TMS) if (tmpTMS > maxTMS) maxTMS = tmpTMS YATACore::writeTable(table, df, FALSE) } } #JGG Pendiente de ver el alor de TMS cuando es nuevo if (is.na(tms)) { names = c(TPairs$CLEARING, TPairs$BASE, TPairs$COUNTER, TPairs$LAST_UPD) values = list(provider, base, counter, maxTMS) names(values) = names TPairs$insert(values, isolated=FALSE) } else { values = list(maxTMS) names(values) = c(TPairs$LAST_UPD) names = c(TPairs$CLEARING, TPairs$BASE, TPairs$COUNTER) keys = list(provider, base, counter) names(keys) = names TPairs$update(values, keys, isolated=FALSE) } YATACore::commitTrx(T) Sys.sleep(05) } } #' @export adjustTimestamp = function() { YATACore::openConnection(global = T) dfPairs = YATACore::loadTable("PAIRS") # for (per in c("2H", "4H", "D")) { # if (per == "2H") table = "POL_TICKERSH2" # if (per == "4H") table = "POL_TICKERSH4" # if (per == "D") table = "POL_TICKERSD1" qry = c( "SELECT A.BASE, A.COUNTER, LEAST(A.LAST, B.TMS) AS TMS" , "FROM PAIRS AS A " , "JOIN (SELECT BASE, CTC, MAX(TMS) AS TMS FROM " # , table ,"POL_TICKERSD1" ,"GROUP BY BASE, CTC) AS B " ,"ON A.BASE = B.BASE AND A.COUNTER = B.CTC") query = "" for (cc in qry) query = paste(query, cc) df = YATACore::executeQuery(query) if (nrow(df) > 0) { for (idx in 1:nrow(df)) { cat(paste(idx, df[idx, "BASE"], df[idx, "COUNTER"], "\n")) qry = "UPDATE PAIRS SET LAST = ? WHERE BASE = ? AND COUNTER = ?" YATACore::executeUpdate(qry, list(df[idx, "TMS"], df[idx, "BASE"], df[idx, "COUNTER"])) } } # } YATACore::closeConnection() } # Para cada par de datos en D1 # 1.- Obtenemos el domingo anterior o igual a hoy (D2) # 2.- Obtenemos los pares de D1 # 3.- Obtenemos el maximo de W1 por par (D1) #' @export loadWeeks = function() { today = today() nDays = wday(today) - 1 maxDay = today - days(nDays) TDay = TBLSession$new("POL", "D1") TWeek = TBLSession$new("POL", "W1") TWork = TBLSession$new("POL", "D1") TDay$getPairs() TDay$df$TMS = maxDay TWeek$getPairs() TWeek$df$TMS = TWeek$df$TMS + days(1) dfPairs = merge(x=TDay$df, y=TWeek$df, by=c(TDay$BASE, TDay$COUNTER), all.x=T, all.y=F) reg = 0 while (reg < nrow(dfPairs)) { reg = reg + 1 base = dfPairs[reg, TDay$BASE] counter = dfPairs[reg, TDay$COUNTER] from = dfPairs[reg, paste0(TDay$TMS, ".y")] to = dfPairs[reg, paste0(TDay$TMS, ".x")] cat(sprintf("Grouping weeks for %s-%s\n", base, counter)) dfw = TWork$getSessionDataInterval(base, counter,from, to) if (nrow(dfw) == 0) next df = dfw %>% group_by(BASE,COUNTER,YEAR=year(TMS),WEEK=isoweek(TMS)) %>% summarise(OPEN = first(OPEN), CLOSE = last(CLOSE), LOW = min(LOW), HIGH = max(HIGH), VOLUME = mean(VOLUME), AVERAGE = mean(AVERAGE)) df$TMS = as.POSIXct.Date(as.Date(paste(df$YEAR,df$WEEK,7,sep="-"),"%Y-%U-%u")) df$TMS = update(df$TMS, hours=0, minutes=0, seconds=0) df = df[, -which(names(df) %in% c("YEAR", "WEEK"))] YATACore::beginTrx(T) YATACore::writeTable("SESSION_POL_W1", df, isolated=F) YATACore::commitTrx(T) } } #' @export loadMonths = function() { today = today() day(today) = 1 today = today - months(1) day(today) = days_in_month(today) TDay = TBLSession$new("POL", "D1") TMonth = TBLSession$new("POL", "M1") TWork = TBLSession$new("POL", "D1") TDay$getPairs() TDay$df$TMS = today TMonth$getPairs() TMonth$df$TMS = TMonth$df$TMS + days(1) dfPairs = merge(x=TDay$df, y=TMonth$df, by=c(TDay$BASE, TDay$COUNTER), all.x=T, all.y=F) reg = 0 while (reg < nrow(dfPairs)) { reg = reg + 1 base = dfPairs[reg, TDay$BASE] counter = dfPairs[reg, TDay$COUNTER] from = dfPairs[reg, paste0(TDay$TMS, ".y")] to = dfPairs[reg, paste0(TDay$TMS, ".x")] cat(sprintf("Grouping months for %s-%s\n", base, counter)) dfw = TWork$getSessionDataInterval(base, counter,from, to) if (nrow(dfw) == 0) next df = dfw %>% group_by(BASE,COUNTER,YEAR=year(TMS),MONTH=month(TMS)) %>% summarise(OPEN = first(OPEN), CLOSE = last(CLOSE), LOW = min(LOW), HIGH = max(HIGH), VOLUME = mean(VOLUME), AVERAGE = mean(AVERAGE), TMS=max(TMS)) df$TMS = update(df$TMS, hours=0, minutes=0, seconds=0) df = df[, -which(names(df) %in% c("YEAR", "MONTH"))] YATACore::beginTrx(T) YATACore::writeTable("SESSION_POL_M1", df, isolated=F) YATACore::commitTrx(T) } } # Calcula la media ponderada por segmentos # como suma de grupo * numero de grupo wma = function(x) { if (length(x) < 3) return ((sum(x) / length(x))) if (length(x) > 2) g = 2 if (length(x) > 4) g = 3 if (length(x) > 7) g = 4 ss = split(x, cut(x, g)) y = x for (i in 2:length(ss)) { for (j in i:length(ss)) { y = c(y, ss[[j]]) } } return (sum(y) / length(y)) } .getData = function(table, base, counter, tms) { beg = .getBegin(group, table) sql = paste0("SELECT * FROM ", table, " WHERE CTC = ? AND EXC = ? AND TMS > ? ORDER BY TMS") .SQLDataFrame(sql, list(group[1, "CTC"],group[1, "EXC"], beg)) } .getBegin = function(group, table) { dfm = .SQLDataFrame(paste0("SELECT MAX(TMS) FROM ", table, " WHERE CTC = ? AND EXC = ?"), list(group[1, "CTC"],group[1, "EXC"])) # beg = dfm[1,1] # if (is.na(beg)) beg = as.POSIXct(strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S"),tz="UTC") beg } .selectColumns = function(df) { ungroup(df) %>% select(BASE, COUNTER, TMS, OPEN, CLOSE, HIGH, LOW, VOLUME, AVERAGE) } <file_sep>/YATAModels/R/Model.R library(R6) if ("YATACore" %in% (.packages())) detach("package:YATACore", unload=T) if (!require("pacman")) install.packages("pacman") # Common pacman::p_load("R6") pacman::p_load("dplyr") pacman::p_load("YATACore") #' @export loadModel <- function(idModel) { SQLConn = YATACore::openConnection() dfm = YATACore::getModel(as.integer(idModel)) model = YATAModel$new(dfm[1,"ID_MODEL"]) model$name = dfm[1,"NAME"] model$desc = dfm[1,"DESCR"] model$scope = dfm[1,"FLG_SCOPE"] model$parent = dfm[1,"ID_PARENT"] model } #' @export loadIndicators = function(model, scopes) { parents = c(model$id) parent = model$parent # Carga los padres en orden inverso while (parent != 0) { # Root Parent dfm = YATACore::getModel(parent) if (AND(dfm[1, "FLG_SCOPE"], model$scope)) { parents = c(dfm[1, "ID_MODEL"], parents) } parent = dfm[1, "ID_PARENT"] } for (mod in parents) { dfLst = YATACore::getModelIndicators(mod) reg = 1 while (reg <= nrow(dfLst)) { dfInd = YATACore::getIndicator(dfLst[reg, "ID_IND"]) # Para corto, mdio, largo for (term in c(TERM_SHORT, TERM_MEDIUM, TERM_LONG)) { if (bitwAnd(term, dfLst[reg, "FLG_TERM"])) { # Para cada grafico for (i in 1:length(TARGETS)) { idx = bitwShiftL(1, i - 1) if (bitwAnd(idx, dfLst[reg, "FLG_DAT"]) > 0) { ind = eval(parse(text=paste0("IND_",dfInd[1,"NAME"],"$new()"))) ind$id = dfInd[1, "ID_IND"] ind$parent = dfInd[1, "ID_PARENT"] ind$target = TARGETS[i] ind$xAxis = XAXIS[i] ind$idPlot = i .addIndicatorParameters(ind, scopes[i], term) model$addIndicator(ind, term) } } } } reg = reg + 1 } } YATACore::closeConnection(SQLConn) model } .addIndicatorParameters <- function(ind, scope, term) { lstInd = ind$id parent = ind$parent while (parent != 0) { dfTmp = YATACore::getIndicator(parent) lstInd = c(dfTmp[1,"ID_IND"],lstInd) parent = dfTmp[1,"ID_PARENT"] } for (i in lstInd) { parms = YATACore::getIndicatorParameters(i, scope, term) ind$addParameters(parms) } } <file_sep>/YATAManualUser/03-indicators.Rmd # Indicators Indicators are at heart of the trading strategy. They make it unique and profitable. They can be single computations or a long series of analyses. Many technically focused trading platforms like TradeStation, Metatrader, and Interactive Brokers handle all of the data management and let the user select from a list of common and customizable indicators. These platforms typically emphasize visualization rather than computation. We are handling our own data management because we want to compute indicators over many symbols and assess them numerically rather than visually. Computing indicators efficiently over batches of symbols in R requires a lot of familiarity with rollapply(). We will give many examples of common indicators implemented this way to make sure you are comfortable using it. Additionally, we will demonstrate how to change indicators outside of the rollapply() function by including function declarations and parameters at the head of documents. ## Indicator Types Indicators have broad classifications related to how they are best visualized and what kinds of rule sets tend to work well with them. We discuss these in this section. ```{r child = 'indicators/overlays.Rmd'} ``` ### Oscillators Oscillators are also best characterized by their scale. Oscillators typically oscillate around zero. Common examples are the MACD, Stochastic Oscillator, and RSI. These are typically plotted below the price history in charts because they do not share scale with it. Rule sets typically concentrate around the indicator’s interaction with the zero line or other components of itself. Here’s an example: If the MACD rises above zero, buy the stock at market price. ### Accumulators Accumulators depend on the value of itself in past periods to calculate future values. This is different from most indicators that depend only on price history, not indicator history. They have the advantage of being windowlength independent in that the user does not specify any n periods in the past to be computed. This is an advantage purely on the level of robustness and mathematical elegance. They are very often volume-oriented. Examples are On-Balance Volume, Negative Volume Index, and the Accumulation/Distribution Line. Rule sets typically concentrate on the relationship between the accumulator and an average or maximum of itself. Here’s an example: If the Negative Volume Index crosses above a moving average of itself, buy the stock at market price. ### Pattern/Binary/Ternary Pattern indicators are classic technical indicators like the head-and-shoulders. They involve detecting some pattern in the data and triggering a trading signal if found. When we are detecting these patterns with computers, these indicators are often called binary or ternary because they have two or three possible values, -1 (short), 0 (neutral), and 1 (long). Rule sets for these indicators are simple because they are essentially built in to the indicator. Practical rule sets including these indicators often combine or index pattern indicators along with other indicators. ### Machine Learning/Nonvisual/Black Box When utilizing machine-learning methods to generate stock signals, the outputs are often multidimensional. These multidimensional outputs easily interact with rule sets optimized to handle them but are most often not worth visualizing. Not surprisingly, these strategies tend to be the most proprietary and have the highest information latency when used correctly. <file_sep>/YATAProviders/R/PKGMain.R if (!require("pacman")) install.packages("pacman") pacman::p_load("zoo") pacman::p_load("PoloniexR") lastError = NULL #' @export getLastError = function() { lastError } #' @export getTickers = function() { POL.GetTickers() } #' @export getHistorical = function(base, counter, from, to=NULL, period=NULL) { .POLGetHistorical(base, counter, from, to, period) } <file_sep>/YATAManualTech/0500-tech_decissions.Rmd # Technical decisions En este capitulo se especifican las decisiones tecnicas y de arquitectura que se han tomado. El objetivo es no tener que replantearlas y conocer el por que de las mismas ## Excel Connector Existen bastantes paquetes para interactuar con Excel desde R, pero la mayoria utilizan ODBC o el protocolo OOD de Windows. Esto implicaa que se asume que el sistema se esta ejecutando sobre una arquitectura Windows, lo cual no es correcto puesto que es una aplicacion Shiny. Para evitar esta limitacion se ha optado por utilizar el paquete XLConnect que, aunque se basa en Java -lo cual da problemas de rendimiento y de memoria- no necesita que Excel exista. Como efecto colateral es necesario resaltar que **Se suelen producir problemas de heap por que no se realiza una correcta limpieza de la maquina virtual** Para evitar en la medida de lo posible este problema: 1 - Se realiza frecuentemente limpieza de memoria mediante: gc() y XL... 2 - En las opciones globales se indica: options(java.parameters = "-Xmx2048m") <file_sep>/YATAConfig/SQL/ctc_tables.sql USE CTC; -- SET FOREIGN_KEY_CHECKS = 0 ; -- ------------------------------------------------------------------- -- ------------------------------------------------------------------- -- TABLAS DE CONFIGURACION Y GENERALES -- PREFIJO: CFG -- ------------------------------------------------------------------- -- ------------------------------------------------------------------- -- ------------------------------------------------------------------- -- Tabla de configuracion de sistema -- Cuando no hay acceso a la base de datos se corresponde con el -- fichero de propiedades -- ------------------------------------------------------------------- -- Tabla de Parametros DROP TABLE IF EXISTS PARMS CASCADE; CREATE TABLE PARMS ( NAME VARCHAR (32) NOT NULL -- Parametro ,TYPE INTEGER NOT NULL -- Tipo de parametro ,VALUE VARCHAR (64) NOT NULL ,PRIMARY KEY ( NAME ) ); -- Tabla de Textos DROP TABLE IF EXISTS MESSAGES; CREATE TABLE MESSAGES ( CODE VARCHAR (64) NOT NULL ,LANG CHAR(2) NOT NULL ,REGION CHAR(2) NOT NULL ,MSG VARCHAR(255) ,PRIMARY KEY ( CODE ) ); -- Tablas de Codigos DROP TABLE IF EXISTS CODE_GROUPS CASCADE; CREATE TABLE CODE_GROUPS ( ID INTEGER NOT NULL -- Id del Grupo ,NAME VARCHAR(32) NOT NULL -- Nombre ,DESCR VARCHAR(255) ,PRIMARY KEY ( ID ) ); DROP TABLE IF EXISTS CODES CASCADE; CREATE TABLE CODES ( ID_GROUP INTEGER NOT NULL -- Id del Grupo ,ID INTEGER NOT NULL -- Valores del codigo ,NAME VARCHAR(32) NOT NULL -- Nombre ,DESCR VARCHAR(255) ,PRIMARY KEY ( ID_GROUP, NAME ) ); -- Tabla de Parametros DROP TABLE IF EXISTS PROFILES CASCADE; CREATE TABLE PROFILES ( ID INTEGER NOT NULL -- Tipo de parametro ,NAME VARCHAR (32) NOT NULL -- Parametro ,ACTIVE INTEGER NOT NULL -- Tipo de parametro ,FIAT VARCHAR(8) ,CTC VARCHAR(8) ,MODEL INTEGER ,PROFILE INTEGER ,SCOPE INTEGER ,PRIMARY KEY ( ID ) ); -- Tabla de monedas finales (FIAT) DROP TABLE IF EXISTS CURRENCIES_FIAT CASCADE; CREATE TABLE CURRENCIES_FIAT ( SYMBOL VARCHAR(8) NOT NULL -- To Currency ,NAME VARCHAR(64) NOT NULL -- From currency ,DECIMALS INTEGER NOT NULL ,ACTIVE TINYINT NOT NULL ,PRIMARY KEY ( SYMBOL ) ); -- Tabla de monedas DROP TABLE IF EXISTS CURRENCIES_CTC CASCADE; CREATE TABLE CURRENCIES_CTC ( PRTY INTEGER NOT NULL DEFAULT 999 ,SYMBOL VARCHAR(8) NOT NULL -- To Currency ,NAME VARCHAR(64) NOT NULL -- From currency ,DECIMALS INTEGER NOT NULL ,ACTIVE TINYINT NOT NULL ,FEE DOUBLE DEFAULT 0.0 ,PRIMARY KEY ( SYMBOL ) ); -- Contiene los pares cotizados por clearing -- Y la ultima fecha de actualizacion DROP TABLE IF EXISTS CURRENCIES_CLEARING CASCADE; CREATE TABLE CURRENCIES_CLEARING ( CLEARING VARCHAR(8) NOT NULL -- Clearing Symbol ,BASE VARCHAR(8) NOT NULL -- From currency ,COUNTER VARCHAR(8) NOT NULL -- To Currency ,LAST_UPD TIMESTAMP ,PRIMARY KEY ( CLEARING, BASE, COUNTER ) ); -- Tabla de Camaras DROP TABLE IF EXISTS CLEARINGS CASCADE; CREATE TABLE CLEARINGS ( ID_CLEARING VARCHAR(08) NOT NULL -- Clearing Symbol ,NAME VARCHAR(32) NOT NULL -- Clearing Name ,ACTIVE TINYINT NOT NULL DEFAULT 1 -- 0 Compra / 1 Venta ,MAKER TINYINT NOT NULL DEFAULT 0 -- Fees ,TAKER TINYINT NOT NULL DEFAULT 0 ,PRIMARY KEY ( ID_CLEARING ) ); -- Tabla de Proveedores DROP TABLE IF EXISTS PROVIDERS CASCADE; CREATE TABLE PROVIDERS ( SYMBOL VARCHAR (8) NOT NULL -- To Currency ,NAME VARCHAR (32) NOT NULL -- From currency ,ACTIVE TINYINT DEFAULT 1 ,PRIMARY KEY ( SYMBOL ) ); -- Tabla de Cuentas/Camara DROP TABLE IF EXISTS ACCOUNTS CASCADE; CREATE TABLE ACCOUNTS ( ID_CLEARING VARCHAR(8) NOT NULL -- To Currency ,CURRENCY VARCHAR(8) NOT NULL -- From currency ,BALANCE DOUBLE NOT NULL -- From currency ,CC VARCHAR(512) ,PRIMARY KEY ( ID_CLEARING, CURRENCY ) ); -- Tabla de Portfolio DROP TABLE IF EXISTS PORTFOLIO CASCADE; CREATE TABLE PORTFOLIO ( ID_CLEARING VARCHAR(8) NOT NULL -- To Currency ,CURRENCY VARCHAR(8) NOT NULL -- From currency ,ACTIVE TINYINT NOT NULL DEFAULT 1 -- 0 Compra / 1 Venta ,POS DOUBLE NOT NULL -- Posicion total ,AVAILABLE DOUBLE NOT NULL -- Posicion considerando si esa ejecutado o no ,LAST_OP BIGINT ,LAST_VALUE DOUBLE ,LAST_TMS TIMESTAMP ,PRIMARY KEY ( ID_CLEARING, CURRENCY ) ); DROP TABLE IF EXISTS OPERATIONS; CREATE TABLE OPERATIONS ( ID_OPER BIGINT NOT NULL ,TYPE TINYINT NOT NULL ,CLEARING VARCHAR(8) NOT NULL -- Clearing House ,BASE VARCHAR(8) NOT NULL -- From currency ,COUNTER VARCHAR(8) NOT NULL -- To currency ,AMOUNT DOUBLE NOT NULL ,IN_PROPOSAL DOUBLE NOT NULL -- Stop price ,IN_EXECUTED DOUBLE -- Real price ,IN_REASON INTEGER -- Si cero o negativo, esta en tabla, si no es un codigo ,OUT_PROPOSAL DOUBLE ,OUT_EXECUTED DOUBLE -- Real price ,OUT_REASON INTEGER -- Si cero o negativo, esta en tabla, si no es un codigo ,OPLIMIT DOUBLE -- Limit ,OPSTOP DOUBLE -- Limit ,PRICE TINYINT -- Considerar para la toma de precios medios ,TMS_IN TIMESTAMP ,TMS_OUT TIMESTAMP ,TMS_LAST TIMESTAMP ,PRIMARY KEY ( ID_OPER ) ,UNIQUE KEY (CLEARING, BASE, COUNTER, TMS_IN) ); DROP TABLE IF EXISTS FLOWS CASCADE; CREATE TABLE FLOWS ( ID_OPER BIGINT NOT NULL ,ID_FLOW BIGINT NOT NULL ,TYPE TINYINT NOT NULL ,CLEARING VARCHAR(8) NOT NULL -- Clearing House ,BASE VARCHAR(8) NOT NULL -- From currency ,CURRENCY VARCHAR(8) NOT NULL -- From currency ,PROPOSAL DOUBLE NOT NULL -- Stop price ,EXECUTED DOUBLE -- Real price ,MAXLIMIT DOUBLE -- Limit ,FEE_BLOCK DOUBLE -- FEE blockchain ,FEE_EXCH DOUBLE -- FEE Exchange ,TMS_PROPOSAL TIMESTAMP ,TMS_EXECUTED TIMESTAMP ,TMS_LIMIT TIMESTAMP ,TMS_CANCEL TIMESTAMP ,REFERENCE BIGINT ,PRIMARY KEY ( ID_FLOW ) ,UNIQUE KEY ( ID_OPER, ID_FLOW ) ,UNIQUE KEY (CLEARING, BASE, CURRENCY, TMS_PROPOSAL) ); -- Tabla de Agrupaciones de modelos DROP TABLE IF EXISTS IND_GROUPS CASCADE; CREATE TABLE IND_GROUPS ( ID_GROUP INTEGER NOT NULL -- Id CTC ,NAME VARCHAR (32) NOT NULL -- From currency ,ACTIVE TINYINT NOT NULL DEFAULT 1 ,PRIMARY KEY ( ID_GROUP ) ); -- Tabla de Agrupaciones de modelos DROP TABLE IF EXISTS IND_INDS CASCADE; CREATE TABLE IND_INDS ( ID_GROUP INTEGER NOT NULL -- Id CTC ,ID_IND INTEGER NOT NULL -- Id CTC ,ID_PARENT INTEGER NOT NULL -- Id CTC ,ACTIVE TINYINT NOT NULL DEFAULT 1 ,NAME VARCHAR (32) NOT NULL -- From currency ,DESCR VARCHAR(255) NOT NULL -- From currency ,PRIMARY KEY ( ID_GROUP, ID_IND ) -- ,FOREIGN KEY ( ID_GROUP ) REFERENCES IND_GROUPS ( ID_GROUP ) ON DELETE CASCADE ); -- Tabla de Agrupaciones de modelos DROP TABLE IF EXISTS IND_PARMS CASCADE; CREATE TABLE IND_PARMS ( ID_IND INTEGER NOT NULL -- Id CTC ,FLG_SCOPE INTEGER NOT NULL -- Intradia, dia, etc ,FLG_TERM INTEGER NOT NULL DEFAULT 15 -- Ambito: 1 - Corto, 2 - Medio - 3 - Largo ,NAME VARCHAR (32) NOT NULL ,TYPE INTEGER NOT NULL ,VALUE VARCHAR (64) NOT NULL ,DESCR VARCHAR(255) ,PRIMARY KEY ( ID_IND, FLG_SCOPE, FLG_TERM, NAME ) -- ,FOREIGN KEY ( ID_GROUP, ID_IND ) REFERENCES IND_INDS ( ID_GROUP, ID_IND ) ON DELETE CASCADE ); -- Tabla de Agrupaciones de modelos DROP TABLE IF EXISTS MODELS CASCADE; CREATE TABLE MODELS ( ID_MODEL INTEGER NOT NULL -- Id del Modelo ,ID_PARENT INTEGER NOT NULL -- Padre del modelo para agraupar ,FLG_SCOPE INTEGER NOT NULL -- Scope al que aplica el Modelo. 255 = Todos ,ACTIVE TINYINT NOT NULL DEFAULT 1 ,NAME VARCHAR (32) NOT NULL -- From currency ,DESCR VARCHAR(255) ,PRIMARY KEY ( ID_MODEL ) -- ,FOREIGN KEY ( ID_GROUP ) REFERENCES IND_GROUPS ( ID_GROUP ) ON DELETE CASCADE ); -- Tabla de Agrupaciones de modelos DROP TABLE IF EXISTS MODEL_INDICATORS CASCADE; CREATE TABLE MODEL_INDICATORS ( ID_MODEL INTEGER NOT NULL -- ID del Modelo ,ID_IND INTEGER NOT NULL -- Indicador ,FLG_TERM INTEGER NOT NULL DEFAULT 15 -- Ambito: 1 - Corto, 2 - Medio - 3 - Largo ,FLG_DAT INTEGER NOT NULL DEFAULT 255 -- Id del plot (1, 2, 3) Por binario ,PRIMARY KEY ( ID_MODEL, ID_IND, FLG_TERM ) ); COMMIT;<file_sep>/YATAWeb/widgets/rightSideBar.R #' AdminLTE2 dashboard right sidebar #' #' This creates a right sidebar. #' #' @param ... slot for rightSidebarTabContent. Not compatible with .items. #' @param background background color: "dark" or "light". #' @param width Sidebar width in pixels. Numeric value expected. 230 by default. #' @param .items Pass element here if you do not want to embed them in panels. Not compatible with ... #' #' @author <NAME>, \email{<EMAIL>} #' #' @note Until a maximum of 5 rightSidebarTabContent inside! AdminLTE 2 does not #' support more panels. #' #' @examples #' if (interactive()) { #' library(shiny) #' library(shinydashboard) #' shinyApp( #' ui = dashboardPagePlus( #' header = dashboardHeaderPlus( #' enable_rightsidebar = TRUE, #' rightSidebarIcon = "gears" #' ), #' sidebar = dashboardSidebar(), #' body = dashboardBody(), #' rightsidebar = rightSidebar( #' background = "dark", #' rightSidebarTabContent( #' id = 1, #' icon = "desktop", #' title = "Tab 1", #' active = TRUE, #' sliderInput( #' "obs", #' "Number of observations:", #' min = 0, max = 1000, value = 500 #' ) #' ), #' rightSidebarTabContent( #' id = 2, #' title = "Tab 2", #' textInput("caption", "Caption", "Data Summary") #' ), #' rightSidebarTabContent( #' id = 3, #' title = "Tab 3", #' icon = "paint-brush", #' numericInput("obs", "Observations:", 10, min = 1, max = 100) #' ) #' ), #' title = "Right Sidebar" #' ), #' server = function(input, output) { } #' ) #' } #' @export rightSidebar <- function(..., background = "dark", width = 230, .items = NULL) { panels <- list(...) sidebarTag <- shiny::tags$div( id = "controlbar", shiny::tags$aside( class = paste0("control-sidebar control-sidebar-", background), style = paste0("width: ", width, "px;"), # automatically create the tab menu if (length(panels) > 0) rightSidebarTabList(rigthSidebarPanel(...)), if (length(panels) > 0) rigthSidebarPanel(...) else rigthSidebarPanel(.items) ), # Add the sidebar background. This div must be placed # immediately after the control sidebar shiny::tags$div(class = "control-sidebar-bg", style = paste0("width: ", width, "px;")) ) shiny::tagList( shiny::singleton( shiny::tags$head( # Will be usefull to fix issue #4 on github # shiny::includeScript( # system.file(file.path("js", "rightSidebar.js"), package = "shinydashboardPlus") # ), # custom css to correctly handle the width of the rightSidebar shiny::tags$style( shiny::HTML( paste0( ".control-sidebar-bg, .control-sidebar { top: 0; right: ", -width, "px; width: ", width, "px; -webkit-transition: right 0.3s ease-in-out; -o-transition: right 0.3s ease-in-out; transition: right 0.3s ease-in-out; } " ) ) ) ) ), sidebarTag ) } #' AdminLTE2 right sidebar tab list #' #' This creates a right sidebar tab list. #' #' @param ... slot that takes all rightSidebarTabContent as input to automatically #' generate the same number of items in the tab menu with corresponding icons, #' ids, ... #' rightSidebarTabList <- function(...) { tabItems <- list(...) tabItems <- tabItems[[1]]$children len <- length(tabItems) if (len > 0) { # generate tab items based on panel items tabItemList <- lapply(1:len, FUN = function(i) { item <- tabItems[[i]] id <- item$attribs$id id <- gsub(x = id, pattern = "control-sidebar-", replacement = "") id <- gsub(x = id, pattern = "-tab", replacement = "") active <- sum(grep(x = item$attribs$class, pattern = "active")) == 1 icon <- item$attribs$icon rightSidebarTabItem(id = id, icon = icon, active = active) }) # put everything inside the container shiny::tags$ul( class = "nav nav-tabs nav-justified control-sidebar-tabs", tabItemList ) } } #' AdminLTE2 right sidebar tab item #' #' This creates a right sidebar tab item to be inserted in a rightSidebarTabList. #' #' @param id unique item id. #' @param icon tab icon. #' @param active Whether the tab item is active or not. #' rightSidebarTabItem <- function(id, icon, active) { stopifnot(!is.null(id)) shiny::tags$li( class = if (isTRUE(active)) "active" else NULL, shiny::tags$a( href = paste0("#control-sidebar-", id, "-tab"), `data-toggle` = "tab", shiny::tags$i(class = paste0("fa fa-", icon)) ) ) } #' AdminLTE2 wrapper for tab content #' #' This creates a wrapper that will contain rightSidebarTabContent. #' #' @param ... slot for rightSidebarTabContent. #' rigthSidebarPanel <- function(...) { shiny::tags$div( class = "controlbar tab-content", ... ) } #' AdminLTE2 tab content #' #' This creates a wrapper that will contain rightSidebarTabContent. #' #' @param ... any element such as sliderInput, ... #' @param id should be unique. #' @param title content title. #' @param active whether the tab content is active or not. FALSE by default. #' @param icon tab icon. #' #' @export rightSidebarTabContent <- function(..., id, title = NULL, active = FALSE, icon = "database") { stopifnot(!is.null(id)) shiny::tags$div( class = if (isTRUE(active)) "tab-pane active" else "tab-pane", id = paste0("control-sidebar-", id, "-tab"), icon = icon, shiny::tags$h3(class = "control-sidebar-heading", title), ... ) } #' @title AdminLTE2 right sidebar menu #' #' @description Create a nice right sidebar menu. #' #' @param ... Slot for rightsidebarMenuItem. #' #' @author <NAME>, \email{<EMAIL>} #' #' @examples #' if (interactive()) { #' library(shiny) #' library(shinydashboard) #' shinyApp( #' ui = dashboardPagePlus( #' header = dashboardHeaderPlus( #' enable_rightsidebar = TRUE, #' rightSidebarIcon = "gears" #' ), #' sidebar = dashboardSidebar(), #' body = dashboardBody(), #' rightsidebar = rightSidebar( #' background = "dark", #' rightSidebarTabContent( #' id = 1, #' icon = "desktop", #' title = "Tab 1", #' active = TRUE, #' rightSidebarMenu( #' rightSidebarMenuItem( #' icon = menuIcon( #' name = "birthday-cake", #' color = "red" #' ), #' info = menuInfo( #' title = "Langdon's Birthday", #' description = "Will be 23 on April 24th" #' ) #' ), #' rightSidebarMenuItem( #' icon = menuIcon( #' name = "user", #' color = "yellow" #' ), #' info = menuInfo( #' title = "Frodo Updated His Profile", #' description = "New phone +1(800)555-1234" #' ) #' ) #' ) #' ), #' rightSidebarTabContent( #' id = 2, #' title = "Tab 2", #' textInput("caption", "Caption", "Data Summary") #' ), #' rightSidebarTabContent( #' id = 3, #' icon = "paint-brush", #' title = "Tab 3", #' numericInput("obs", "Observations:", 10, min = 1, max = 100) #' ) #' ), #' title = "Right Sidebar" #' ), #' server = function(input, output) { } #' ) #' } #' #' @export rightSidebarMenu <- function(...) { shiny::tags$ul( class = "control-sidebar-menu", ... ) } #' @title AdminLTE2 right sidebar menu item #' #' @description Item to insert in a rightsidebarMenu. #' #' @param icon Slot for menuIcon. #' @param info Slot for menuInfo. #' #' @author <NAME>, \email{<EMAIL>} #' #' @export rightSidebarMenuItem <- function(icon, info) { shiny::tags$li( shiny::tags$a( href = "javascript:void(0)", icon, info ) ) } #' @title AdminLTE2 menu icon item #' #' @description Create a nice menu icon to insert in a rightsidebarMenuItem. #' #' @param name Icon name. #' @param color background color: see here for a list of valid colors #' \url{https://adminlte.io/themes/AdminLTE/pages/UI/general.html}. #' #' @author <NAME>, \email{<EMAIL>} #' #' @export menuIcon <- function(name, color) { stopifnot(!is.null(name)) stopifnot(!is.null(color)) menuIconCl <- paste0("menu-icon", " fa fa-", name, " bg-", color) shiny::tags$i(class = menuIconCl) } #' @title AdminLTE2 menu info item #' #' @description Create a nice menu info to insert in a rightsidebarMenuItem. #' #' @param title Menu title. #' @param description Extra informations. #' #' @author <NAME>, \email{<EMAIL>} #' #' @export menuInfo <- function(title = NULL, description = NULL) { shiny::tags$div( class = "menu-info", shiny::tags$h4(class = "control-sidebar-subheading", title), shiny::tags$p(description) ) }<file_sep>/YATABatch/R/YATABatchModel.R DB_CASES = "Cases" TCASES_CASES = "Cases" TBLCases2 <- R6Class("TBLCases", inherit=YATATable, public = list( ID = "idTest" ,NAME = "Name" ,SUMMARY = "Summary" ,DETAIL = "Detail" ,INFO = "Info" ,PROFILE = "Profile" ,SCOPE = "Scope" ,CAPITAL = "Capital" ,OTRO = "Otro" ,FROM = "From" ,TO = "To" ,START = "Start" ,PERIOD = "Period" ,INTERVAL = "Interval" ,MODEL = "Model" ,END = "End" ,SYM_NAME = "SymName" ,SYM_SYM = "Symbol" ,LBL_PARMS = "lblParms" ,LBL_THRES = "lblThres" ,GRP_PARMS = "Parm" ,GRP_THRESHOLDS = "Thre" ,refresh = function() { super$refresh("loadCases", self$name) } ,filterByID = function(ids) { self$df = self$dfa %>% filter(self$dfa$idTest %in% ids) } ,getGroups = function() { private$groups } ,getGroupFields = function(group) { idx = match(group, private$groups) if (is.na(idx)) return(c()) paste0(private$groups[idx],seq(private$numGroups[idx])) } ,getGroupSize = function(group) { r = match(group, private$groups) if (is.na(r)) return(NA) private$numGroups[r] } ,initialize = function(tbName="NoName") { self$name = tbName private$groups = c(self$GRP_PARMS, self$GRP_THRESHOLDS) private$numGroups = c(5,5) self$refresh() } ) ,private = list( fields = c() ,groups = c() ,numGroups=c() ) ) createDBCases <- function() { DBCases = YATADB$new(DB_CASES) tCase = TBLCases2$new(TCASES_CASES) DBCases$addTables(c(tCase)) } <file_sep>/YATACore/R/indicators2/IND_Overlays.R #' # Overlays are best characterized by their scale. #' # Overlays typically have the same or similar scale to the #' # underlying asset and are meant to be laid over to chart of price history #' #' #Common examples are the simple #' #moving average, Bollinger Bands, and volume-weighted average price #' #' # Single mobile average #' #' @export #' SMA <- function(data, ind, columns, n=7) { #' res = rollapply(data$df[,data$PRICE],n,mean,fill=NA, align="right") #' df = as.data.frame(res) #' colnames(df) = columns #' df #' } #' BBands <- function(data, ind, columns, n, sd) { #' xt=.getXTS(data) #' res = TTR::BBands(xt,n, "SMA", sd) #' .setDF(res, columns) #' } #' ALMA <- function(data, ind, columns, n, offset, sigma) { #' xt=.getXTS(data) #' res = TTR::ALMA(xt,n,offset,sigma) #' .setDF(res, columns) #' } #' EMA <- function(data, ind, columns, n, wilder=FALSE) { #' xt=.getXTS(data) #' res = TTR::EMA(xt,n,wilder) #' .setDF(res, columns) #' } #' DEMA <- function(data, ind, columns, n, v, wilder=FALSE) { #' xt=.getXTS(data) #' res = TTR::DEMA(xt,n,v,wilder) #' } #' #' .getXTS <- function(data) { #' df = data$getData() #' xts::xts(df[,data$PRICE], order.by = df[,data$DATE]) #' } #' #' .setDF <- function(res, columns) { #' df = as.data.frame(res) #' colnames(df) = columns #' df #' } <file_sep>/YATAModels/inst/rmd/Model_ALMA.Rmd --- title: "Arnaud Legoux Moving Average (ALMA)" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Arnaud Legoux Moving Average (ALMA) [comment]: # (This actually is the most platform independent comment) Media Móvil Ponderada con retraso regulado usando una curva de distribución normal (o Gaussiana) como función de ponderación de coeficientes. Esta Media Móvil utiliza una curva de distribución Normal (Gaussiana) que puede ser puesta por el parámetro Offset de 0 a 1. Este parámetro permite regular la suavidad y la alta sensibilidad de la Media Móvil. Sigma es otro parámetro que es responsable de la forma de los coeficientes de la curva. ## Formula $$\frac{1}{NORM} = \sum_{i=1}^{n}p(i){e}\frac{(i-offset)^2}{\sigma^2}$$ ## Parametros __n__ The Window Size is nothing but the look back period and this forms the basis of your ALMA settings. You can use the ALMA window size to any value that you like, although it is best to stick with the well followed parameters such as 200, 100, 50, 20, 30 and so on based on the time frame of your choosing. __offset__ The offset value is used to tweak the ALMA to be more inclined towards responsiveness or smoothness. The offset can be set in decimals between 0 and 1. A setting of 0.99 makes the ALMA extremely responsive, while a value of 0.01 makes it very smooth. __sigma__ The sigma setting is a parameter used for the filter. A setting of 6 makes the filter rather large while a smaller sigma setting makes it more focused. According to Mr. Legoux, a sigma value of 6 is said to offer good performance. <file_sep>/YATAClient/YATAClient/src/main/java/com/jgg/yata/client/pojos/Market.java package com.jgg.yata.client.pojos; public class Market { private String from; private String to; private float open; private float high; private float low; private float close; private float volume; private float bid; private float ask; private long bidOrders; private long askOrders; private long dt; public String getKey() { return from + "-" + to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public float getOpen() { return open; } public void setOpen(float open) { this.open = open; } public float getHigh() { return high; } public void setHigh(float high) { this.high = high; } public float getLow() { return low; } public void setLow(float low) { this.low = low; } public float getClose() { return close; } public void setClose(float close) { this.close = close; } public float getVolume() { return volume; } public void setVolume(float volume) { this.volume = volume; } public float getBid() { return bid; } public void setBid(float bid) { this.bid = bid; } public float getAsk() { return ask; } public void setAsk(float ask) { this.ask = ask; } public long getBidOrders() { return bidOrders; } public void setBidOrders(long bidOrders) { this.bidOrders = bidOrders; } public long getAskOrders() { return askOrders; } public void setAskOrders(long askOrders) { this.askOrders = askOrders; } public long getDt() { return dt; } public void setDt(long dt) { this.dt = dt; } public String toCSV() { StringBuilder sb = new StringBuilder(); sb.append(dt); sb.append(";"); sb.append(from); sb.append(";"); sb.append(to); sb.append(";"); sb.append(open); sb.append(";"); sb.append(high); sb.append(";"); sb.append(low); sb.append(";"); sb.append(close); sb.append(";"); sb.append(volume); sb.append(";"); sb.append(bid); sb.append(";"); sb.append(ask); sb.append(";"); sb.append(bidOrders); sb.append(";"); sb.append(askOrders); return (sb.toString()); } } <file_sep>/YATAModels/inst/rmd/Model_ZLEMA.Rmd --- title: "Double-Exponential Moving Average (DEMA)" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Zero Lag Exponential Moving Average (ZLEMA) This indicator was created by <NAME> and <NAME>.[1] As is the case with the double exponential moving average (DEMA) and the triple exponential moving average (TEMA) and as indicated by the name, the aim is to eliminate the inherent lag associated to all trend following indicators which average a price over time. The formula for a given N-Day period and for a given data series is: $$ \begin{aligned} Lag = (Window − 1) / 2 \\ EmaData = Data + ( Data − Data ( Lagdaysago)) \\ ZLEMA = EMA(EmaData, Period) \\ \end{aligned} $$ Function used in system is: $$ ZLEMA(data, window = 10, ratio = NULL, ...) $$ ## Parametros __window__ The Window Size is nothing but the look back period. __ratio__ A smoothing/decay ratio. ratio overrides wilder in EMA, and provides additional smoothing in VMA. <file_sep>/YATAModels/R/IND_BBandS.R IND_BBandS <- R6Class("IND_BBandS", inherit=IND_MA, public = list( name="Bollinger Bands Simple" ,symbol="BBS" ,initialize = function() { super$initialize() } ,calculate = function(TTickers, date) { window = self$getParameter("window") sd = self$getParameter("sd") maType = self$getParameter("matype", "EMA") xt = private$getXTS(TTickers, pref=window) if (nrow(xt) < window) return (NULL) bb = TTR::BBands(xt[,TTickers$PRICE], n=window, maType=maType, sd=sd) private$data = as.data.frame(bb[(window + 1):nrow(bb),]) private$setDataTypes("ctc", c("dn", "mavg", "up")) private$setDataTypes("percentage", "pctB") private$setColNames() } ,plot = function(p, TTickers) { if (nrow(private$data) == 0) return(p) cols = c("dn", "mavg", "up") texts = c(self$symbol, "Down", "Average", "Up") YATACore::plotLines(p, TTickers$df[,self$xAxis], private$data[,private$setColNames(cols)], hoverText=texts) } ) ) <file_sep>/YATAModels/R/IND_ZLEMA.R source("R/IND_MA.R") IND_ZLEMA <- R6Class("IND_ZLEMA", inherit=IND_MA, public = list( name="Zero Lag Exponential Moving Average" ,symbol="ZLEMA" ,initialize = function() { super$initialize(list(window=7)) ind1 = YATAIndicator$new( self$name, self$symbol, type=IND_LINE, blocks=3 ,parms=list(window=7)) private$addIndicators(ind1) } # ,calculate <- function(data, ind, columns, n, offset, sigma) { ,calculate = function(data, ind) { if (ind$name != self$name) return (super$calculate(data, ind)) xt=private$getXTS(data) n = private$parameters[["window"]] res1 = TTR::ZLEMA(xt[,data$PRICE] ,n) res2 = TTR::ZLEMA(xt[,data$VOLUME],n) list(list(private$setDF(res1, ind$columns)), list(private$setDF(res2, paste0(ind$columns, "_v")))) } ) ) <file_sep>/YATAModels/R/FACT_Target.R # Emula un factor o una enumeracion FTARGET <- R6::R6Class("FTARGET", public = list( value = 0 ,name = "None" ,select = TRUE # Para el combo, acepta cambiar el target ,size = 6 ,NONE = 0 ,OPEN = 1 ,CLOSE = 2 ,HIGH = 3 ,LOW = 4 ,VOLUME = 5 ,MACD = 6 ,names = c("Open", "Close", "High", "Low", "Volume", "MACD") ,initialize = function(tgt = 0) { self$value = as.integer(tgt) } ,print = function() { cat(self$value) } ,setValue = function (val) { nVal = as.integer(val) self$value = nVal self$name = self$names[nVal] } ,getName = function(id = 0) { if (id == 0) id = self$value self$names[id] } ,getCombo = function(none = F) { start = ifelse(none, 0, 1) nm = self$names if (none) nm = c("None", nm) values = seq(start, self$size) names(values) = nm values } ) ) <file_sep>/YATAWeb/ui/partials/modTrading/dlgOperation.R dlgOper <- function() { ns <- session$ns modalDialog(actionButton(ns("closeModalBtn"), "Close Modal")) }<file_sep>/YATAWeb/widgets/YATAWidgetsCode.R comboClearings = function(cash=F) { TClearing = TBLClearing$new() names = TClearing$df[,TClearing$NAME] values = TClearing$df[,TClearing$ID] if (cash) { names = c("Cash", names) values = c("Cash", values) } names(values) = names values } comboBases = function(clearing = NULL) { TFiat = TBLFiat$new() data = TFiat$df if (!is.null(clearing)) { TPairs = TBLPairs$new() bases = TPairs$getBases(clearing) data = data %>% filter(df$SYMBOL %in% bases) } names = data[, TFiat$NAME] values = data[,TFiat$SYMBOL] names(values) = names values } comboCounters = function() { TCTC = TBLCTC$new() names = TCTC$df[, TCTC$NAME] values = TCTC$df[,TCTC$SYMBOL] names(values) = names values[1:50] } comboModels = function(temporary=F) { TMod = TBLModels$new() mods = TMod$getCombo() if (temporary) { nm = names(mods) mods = c(0, mods) names(mods) = c("Work", nm) } mods } comboIndGroups = function() { YATAENV$indGroups$getCombo() } comboIndNames = function(group) { if (group == "") return (NULL) YATAENV$indNames$getCombo(as.integer(group)) } #JGG Esto no recuerdo la pantalla (Sera del inicio) comboBases2 = function(camera) { TPortfolio = TBLPortfolio$new() pos = TPortfolio$getClearingPosition(camera) TCTC = TBLCurrencies$new() data = TCTC$df %>% subset(TCTC$df$SYMBOL %in% pos[,TPortfolio$CTC]) names = data[, TCTC$NAME] values = data[,TCTC$ID] names(values) = names values } comboCurrencies = function() { TCTC = TBLCurrencies$new() names = TCTC$df$NAME values = TCTC$df$SYMBOL names(values) = names values } DTPrepare = function(df) { tmp = df; # Remove auxiliar column: PRICE p=which(colnames(tmp) == "Price") if (length(p) > 0) tmp = tmp[,-p[1]] tblHead = .DTMakeHead(tmp) dt = DT::datatable(tmp, rownames = FALSE, escape=FALSE, selection = list(mode="single", target="row")) dt = .DTFormatColumns(tmp, dt) dt } .DTMakeHead <- function(data) { dfh = data.frame(head=character(), beg=integer(), len=integer(), stringsAsFactors = F) pat = "^[A-Z0-9]+_" w = str_extract(colnames(data), pat) prfx = unique(w) for (p in prfx) { if (!is.na(p)) { r = which(w == p) l = list(head=p, beg=r[1], len=length(r)) dfh = rbind(dfh, as.data.frame(l, stringAsFactors= F)) } } l = list(head="Data", beg=dfh[1,"beg"] - 1, len=dfh[1,"beg"]) dfh = rbind(as.data.frame(l, stringAsFactors= F), dfh) dfh$head = gsub('.{1}$', '', dfh$head) head2 = gsub(pat, "", colnames(data)) htmltools::withTags(table( class = 'display', thead( tr( lapply(1:nrow(dfh), function(x) { print(x) ; th(colspan=dfh[x,"len"], dfh[x, "head"])}) ), tr( lapply(head2, th) ) ) )) } .DTFormatColumns <- function(tmp, dt, decFiat=2) { ctcCol = c() lngCol = c() prcCol = c() datedCol = c() datetCol = c() fiatCol = c() numberCol = c() for (col in colnames(tmp)) { if ("fiat" %in% class(tmp[,col])) fiatCol = c(fiatCol, col) if ("ctc" %in% class(tmp[,col])) ctcCol = c(ctcCol, col) if ("long" %in% class(tmp[,col])) lngCol = c(lngCol, col) if ("number" %in% class(tmp[,col])) numberCol = c(numberCol, col) if ("percentage" %in% class(tmp[,col])) prcCol = c(prcCol, col) if ("dated" %in% class(tmp[,col])) datedCol = c(datedCol, col) if ("datet" %in% class(tmp[,col])) datetCol = c(datetCol, col) } if (length(ctcCol) > 0) dt = dt %>% formatRound(ctcCol, digits = 8) if (length(lngCol) > 0) dt = dt %>% formatRound(lngCol, digits = 0) if (length(prcCol) > 0) dt = dt %>% formatRound(prcCol, digits = 2) if (length(fiatCol) > 0) dt = dt %>% formatRound(fiatCol, digits = decFiat) if (length(numberCol) > 0) dt = dt %>% formatRound(numberCol, digits = 3) if (length(datedCol) > 0) dt = dt %>% formatDate (datedCol, "toLocaleDateString") dt }<file_sep>/YATAManualTech/0900-mermaid.Rmd # Mermaid ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## R Markdown This is an R Markdown document. ```{r, echo=FALSE} library(DiagrammeR) mermaid(" graph LR A-->B ") ``` ```{r, echo=FALSE} library(DiagrammeR) mermaid(" classDiagram Class01 <|-- AveryLongClass : Cool Class03 *-- Class04 Class05 o-- Class06 Class07 .. Class08 Class09 --> C2 : Where am i? Class09 --* C3 Class09 --|> Class07 Class07 : equals() Class07 : Object[] elementData Class01 : size() Class01 : int chimp Class01 : int gorilla Class08 <--> C2: Cool label ") ``` Acaba el proceso<file_sep>/YATACore/R/TBL_Providers.R TBLProviders = R6::R6Class("TBLProviders", inherit=YATATable, public = list( SYMBOL = "SYMBOL" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,LAST_UPD = "LAST_UPD" ,initialize = function() { self$name="Providers"; self$table = "Providers"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) self$df$ACTIVE = as.logical(self$df$ACTIVE) } ) ,private = list ( ) ) <file_sep>/YATAConfig/SQL/ctc_work.sql USE CTC; DROP TABLE IF EXISTS CURRENCIES_CTC CASCADE; CREATE TABLE CURRENCIES_CTC ( PRTY INTEGER NOT NULL DEFAULT 999 ,SYMBOL VARCHAR(8) NOT NULL -- To Currency ,NAME VARCHAR(64) NOT NULL -- From currency ,DECIMALS INTEGER NOT NULL ,ACTIVE TINYINT NOT NULL ,FEE DOUBLE DEFAULT 0.0 ,PRIMARY KEY ( SYMBOL ) ); COMMIT; <file_sep>/YATAModels/inst/rmd/Model_DEMA.Rmd --- title: "Double-Exponential Moving Average (DEMA)" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Double-Exponential Moving Average (DEMA) Calculates an exponentially-weighted mean, giving more weight to recent observations The Exponential Moving Average is a staple of technical analysis and is used in countless technical indicators. In a Simple Moving Average, each value in the time period carries equal weight, and values outside of the time period are not included in the average. However, the Exponential Moving Average is a cumulative calculation, including all data. Past values have a diminishing contribution to the average, while more recent values have a greater contribution. This method allows the moving average to be more responsive to changes in the data. The EMA result is initialized with the n-period sample average at period n. The exponential decay is applied from that point forward. ## Formula $$DEMA = (1 + v) * EMA(x,n) - EMA(EMA(x,n),n) * v$$ ## Parametros __v__ The 'volume factor' (a number in [0,1]) __n__ The Window Size is nothing but the look back period and this forms the basis of your ALMA settings. __wilder__ Set the value of K <file_sep>/YATACore/R/R6_YATADB.R # Clase base de los ficheros YATADB <- R6Class("YATADB", public = list( name = "Database" ,active = NULL ,getDefault = function() { self$getTable(self$active) } ,getTable = function(name) { pos = which(private$.tableNames == name)[1] if (is.na(pos)) return(NA) private$.tables[[pos]] } ,getTables = function() { private$.tableNames } ,addTables = function(tables) { for (t in tables) { if (is.na(self$getTable(t$name))) { private$.tableNames = c(private$.tableNames, t$name) private$.tables = c(private$.tables, t) self$active = t$name } } invisible(self) } ,print = function() { cat(self$name, "\n") } ,initialize = function(name) { self$name = name } ) ,private = list(.tableNames = c(), .tables = c() ) ) <file_sep>/YATAWeb/ui.R YATAPage("YATA!",id="mainbar", selected=PNL_TST ,theme = "yata/yata.css" #,theme=shinytheme("slate") ,useShinyjs(debug=T) #,tabPanel("Test", value=PNL_TST, modTestInput(PNL_TST)) ,tabPanel("On Line", value=PNL_OL, modOnLineInput(PNL_OL)) ,tabPanel("Portfolio", value=PNL_PRF, modPortfolioInput(PNL_PRF)) ,tabPanel("Analysis", value=PNL_ANA, modAnalysisInput(PNL_ANA)) ,tabPanel("Simulation", value=PNL_SIM, modSimmInput(PNL_SIM)) ,tabPanel("Trading", value=PNL_TRAD, modTradingInput(PNL_TRAD)) # ,tabPanel("Configuration", value=PNL_CONF, modConfigInput(PNL_CONF)) # ,navbarMenu("Ayuda" # ,tabPanel("Manual", value=PNL_MAN_USR, modManUserUI(PNL_MAN_USR)) # ,tabPanel("Tecnico", value=PNL_MAN_TECH, modManTechUI(PNL_MAN_TECH)) # ) ) <file_sep>/YATACore/R/TBL_Models.R TBLModels = R6::R6Class("TBLModels", inherit=YATATable, public = list( # Column names ID = "ID_MODEL" ,PARENT = "ID_PARENT" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,SCOPE = "FLG_SCOPE" ,DESCR = "DESCR" ,initialize = function() { self$name="Models"; self$table = "MODELS"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) self$df$ACTIVE = as.logical(self$df$ACTIVE) } ,getCombo = function(item=NULL) { setNames(self$dfa[, self$ID], self$dfa[,self$NAME]) } ) ,private = list ( ) ) <file_sep>/YATAConfig/SQL/ctc_tables_session.sql USE CTC; -- Tabla general de SESSION DROP TABLE IF EXISTS SESSION_BASE CASCADE; CREATE TABLE SESSION_BASE ( BASE VARCHAR(10) NOT NULL -- Moneda base ,COUNTER VARCHAR(10) NOT NULL -- Moneda evaluada ,TMS TIMESTAMP NOT NULL ,OPEN DOUBLE NOT NULL ,CLOSE DOUBLE NOT NULL ,HIGH DOUBLE NOT NULL ,LOW DOUBLE NOT NULL ,VOLUME DOUBLE NOT NULL ,QUOTEVOLUME DOUBLE NOT NULL ,AVERAGE DOUBLE NOT NULL ,PRIMARY KEY ( TMS, BASE, COUNTER ) ); -- Cada tabla se llama SESSIONin - i Intervalo - n Periodos -- SESSION mensuales DROP TABLE IF EXISTS SESSION_POL_M1 CASCADE; CREATE TABLE SESSION_POL_M1 LIKE SESSION_BASE; -- SESSION Semanales DROP TABLE IF EXISTS SESSION_POL_W1 CASCADE; CREATE TABLE SESSION_POL_W1 LIKE SESSION_BASE; -- SESSION Diarios DROP TABLE IF EXISTS SESSION_POL_D1 CASCADE; CREATE TABLE SESSION_POL_D1 LIKE SESSION_BASE; -- SESSION Horarios -- En funcion de las horas que da poloniex DROP TABLE IF EXISTS SESSION_POL_H2 CASCADE; CREATE TABLE SESSION_POL_H2 LIKE SESSION_BASE; DROP TABLE IF EXISTS SESSION_POL_H4 CASCADE; CREATE TABLE SESSION_POL_H4 LIKE SESSION_BASE; DROP TABLE IF EXISTS SESSION_POL_H8 CASCADE; CREATE TABLE SESSION_POL_H8 LIKE SESSION_BASE; COMMIT;<file_sep>/YATAModels/inst/rmd/Model_WMA.Rmd --- title: "Double-Exponential Moving Average (DEMA)" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Weigthed Moving Average (WMA) A weighted average is an average that has multiplying factors to give different weights to data at different positions in the sample window. Mathematically, the moving average is the convolution of the datum points with a fixed weighting function. One application is removing pixelisation from a digital graphical image.[citation needed] In technical analysis of financial data, a weighted moving average (WMA) has the specific meaning of weights that decrease in arithmetical progression.[4] In an n-day WMA the latest day has weight n, the second latest n − 1, etc., down to one. $$ \begin{aligned} WMA_M = \frac{np_M + (n−1) p_{M−1} + ⋯ + 2p_{(M−n+2)} + p_{(M−n+1)}} {n + ( n − 1 ) + ⋯ + 2 + 1} \end{aligned} $$ The denominator is a triangle number equal to $\frac{n(n+1)}{2}$. In the more general case the denominator will always be the sum of the individual weights. When calculating the WMA across successive values, the difference between the numerators of $WMA_{M+1}$ and ${WMA_M}$ is $np_{M+1} − p_M − ⋅⋅⋅ − p_{M−n+1}$. If we denote the sum $p_M + ⋅⋅⋅ + p_{M−n+1}$ by $Total_M$, then $$ \begin{aligned} Total_{M + 1} &= Total_M + p_{M + 1} − p_{M−n+1} \\ Numerator_{M+1} &= Numerator_M + np_{M+1} − Total_M \\ WMA_{M+1} &= \frac{Numerator_{M+1}}{n + (n − 1) + ⋯ + 2 + 1} \end{aligned} $$ $$ ZLEMA(data, window = 10, ratio = NULL, ...) $$ ## Parametros __window__ The Window Size is nothing but the look back period. __ratio__ A smoothing/decay ratio. ratio overrides wilder in EMA, and provides additional smoothing in VMA. <file_sep>/YATAConfig/SQL/ctc_dat_profiles.sql USE CTC; DELETE FROM PROFILES; INSERT INTO PROFILES (ID, NAME, ACTIVE, FIAT, CTC, MODEL, PROFILE, SCOPE) VALUES ( 1, "Defecto", 1, "USD", "ETH", 11, 2, 256); COMMIT; <file_sep>/YATAConfig/SQL/ctc_users.sql -- Usuarios CREATE USER 'CTC'@'localhost' IDENTIFIED BY 'ctc'; GRANT ALL PRIVILEGES ON CTC.* TO 'CTC'@'localhost' WITH GRANT OPTION;<file_sep>/YATAConfig/SQL/ctc_dat_fiat.sql USE CTC; DELETE FROM CURRENCIES_FIAT; INSERT INTO CURRENCIES_FIAT (ACTIVE, DECIMALS, SYMBOL, NAME) VALUES ( 1, 0, "EUR" , "Euro" ); INSERT INTO CURRENCIES_FIAT (ACTIVE, DECIMALS, SYMBOL, NAME) VALUES ( 1, 0, "USD" , "US Dollar" ); INSERT INTO CURRENCIES_FIAT (ACTIVE, DECIMALS, SYMBOL, NAME) VALUES ( 1, 0, "USDT" , "USD T" ); INSERT INTO CURRENCIES_FIAT (ACTIVE, DECIMALS, SYMBOL, NAME) VALUES ( 1, 0, "USDC" , "USD C" ); INSERT INTO CURRENCIES_FIAT (ACTIVE, DECIMALS, SYMBOL, NAME) VALUES ( 1, 6, "BTC" , "Bitcoin" ); INSERT INTO CURRENCIES_FIAT (ACTIVE, DECIMALS, SYMBOL, NAME) VALUES ( 1, 6, "ETH" , "Ethereum" ); COMMIT;<file_sep>/YATAWeb/IND_SMA.md --- title: "Simple Moving Average (EMA)" output: html_document --- Los promedios móviles se utilizan para suavizar los datos en una matriz para ayudar a eliminar el ruido e identificar tendencias. La media móvil simple es, literalmente, la forma más simple de una media móvil. Cada valor de salida es el promedio de los n valores anteriores. En una media móvil simple, cada valor en el período de tiempo tiene el mismo peso, y los valores fuera del período de tiempo no se incluyen en el promedio. Esto hace que sea menos sensible a los cambios recientes en los datos, lo que puede ser útil para filtrar esos cambios. $$ \begin{aligned} SMA = \frac{\sum_1^nprice}{n} \end{aligned} $$ | Parametro | Descripcion | | ------------- | ------------- | | __threshold__ | Porcentaje que se debe superar en el cruce del oscilador para que se considere | | __n__ | The Window Size is nothing but the look back period and this forms the basis of your ALMA settings. | <file_sep>/YATACore/R/TBL_Currencies_Pairs.R TBLPairs = R6::R6Class("TBLPairs", inherit=YATATable, public = list( CLEARING = "CLEARING" ,BASE = "BASE" ,COUNTER = "COUNTER" ,LAST_UPD = "LAST_UPD" ,initialize = function() { self$name="Pairs"; self$table = "CURRENCIES_CLEARING"; super$refresh() } ,getByClearing = function(clearing) { self$df %>% filter(self$df$CLEARING == clearing) } ,getBases = function(clearing) { df = self$getByClearing(clearing) unique(df$BASE) } ) ,private = list ( ) ) <file_sep>/YATAWeb/ui/modConfigServer.R modConfig <- function(input, output, session, parent) { ns <- session$ns vars <- reactiveValues( loaded = F # Tabla de tickers, se inicializa para que exista en init ,tickers = NULL # TBLTickers$new("Tickers") # Tabla de tickers ,changed = FALSE ,parms = NULL ,thres = NULL ,clicks = 0 ,dateChanged = FALSE # Evita el bucle ajustando fechas ) ################################################################################################### ### PRIVATE CODE ################################################################################################### loader <- function() { lista = list.dirs(path = "www/themes", full.names = FALSE, recursive = FALSE) updateSelectInput(session, "theme", choices=lista) vars$loaded = TRUE } if (!vars$loaded) loader() ######################################################################################## ### OBSERVERS ######################################################################################## observeEvent(input$theme, { # output$cssTheme <- renderUI({ tags$head(tags$link(rel = "stylesheet", type = "text/css", # href = paste0(input$theme, "/bootstap.min.css"))) # }) }) # Lo devuelve cada vez que entra aqui return(reactive({vars$changed})) } <file_sep>/YATAModels/inst/rmd/Model_EVWMA.Rmd --- title: "Double-Exponential Moving Average (DEMA)" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Elastic Volume Weighted Moving Average (EVWMA) The elastic volume weighted moving average is a technical indicator used, like all moving averages, to determine the nature of the market and to generate signals. It can also be used as a trigger line. EVWMA has the specificity that it is both symbol-independent and time-frame independent. This is made by introducing what is called the volume period, i.e. the simple moving average of the volume multiplied by a coefficient. EVWMA can be viewed as an approximation of the average price paid per share. EVWMA interpretation is similar to all moving averages types. When prices jump up crossing their EVWMA from below, this is a sign for an up-trend, and a buy signal is generated; when they go down crossing their EVWMA from above, this a sign for a down-trend, and a sell signal is generated. Divergence between the EVWMA and the prices is a strong signal for either an overbought or an oversold market which forecasts a near end of the trend. The elastic volume weighted moving average function you can get here is named 'elastic_volume_wma', and it takes 2 parameters as arguments. The first one is the time period of the simple moving average of the volume; the second is the coefficient by which this SMA will be multiplied to get the volume period. In addition to the mean, we may also be interested in the variance and in the standard deviation to evaluate the statistical significance of a deviation from the mean. EWMVar can be computed easily along with the moving average. The starting values are: $$ \begin{aligned} EMA_1 = x_1$ \\ EMVar_1 = 0 \\ \end{aligned} $$ And we then compute the subsequent values using:[14] $$ \begin{aligned} δ = x_i − EMA_{i − 1} \\ EMA_i = EMA_{i−1} + α ⋅ δ \\ EMVar_i = ( 1 − α ) ⋅ ( EMVar_{i−1} + α ⋅ δ^2 ) \\ \end{aligned} $$ From this, the exponentially weighted moving standard deviation can be computed as $EWSD_i = \sqrt{EMVar_i}$ We can then use the standard score to normalize data with respect to the moving average and variance. This algorithm is based on Welford's algorithm for computing the variance. Function used in system is: $$ ZLEMA(data, window = 10, ratio = NULL, ...) $$ ## Parametros __window__ The Window Size is nothing but the look back period. __ratio__ A smoothing/decay ratio. ratio overrides wilder in EMA, and provides additional smoothing in VMA. <file_sep>/YATAModels/inst/rmd/IND_SMA.Rmd Los promedios móviles se utilizan para suavizar los datos en una matriz para ayudar a eliminar el ruido e identificar tendencias. La media móvil simple es, literalmente, la forma más simple de una media móvil. Cada valor de salida es el promedio de los n valores anteriores. En una media móvil simple, cada valor en el período de tiempo tiene el mismo peso, y los valores fuera del período de tiempo no se incluyen en el promedio. Esto hace que sea menos sensible a los cambios recientes en los datos, lo que puede ser útil para filtrar esos cambios. $$ \begin{aligned} SMA = \frac{\sum_1^n target}{window} \end{aligned} $$ * __threshold__ : Porcentaje que se debe superar en el cruce del oscilador para que se considere | * __n__ : The Window Size is nothing but the look back period and this forms the basis of your ALMA settings. | <file_sep>/YATACore/R/PKG_Tools.R library(stringr) YATACOUNT = 1 #' @export getYATAID = function() { YATACOUNT = YATACOUNT + 1 base = as.numeric(Sys.time()) * 1000 base + (YATACOUNT %% 1000) } #' @export AND = function(a, b) { (bitwAnd(a, b) > 0) } EQU = function(a, b) { (bitwAnd(a, b) == b) } #' @export as.column = function(name) { return(eval(parse(text=name))) } #' @export setDataType <- function(type, value) { l = list() for (i in 1:length(type)) { if (type[i] == TYPE_STR) l = c(l, value[i]) if (type[i] == TYPE_DEC) l = c(l, as.numeric(value[i])) if (type[i] == TYPE_INT) l = c(l, as.integer(value[i])) if (type[i] == TYPE_LONG) l = c(l, as.integer(value[i])) } if (length(l) == 1) return (l[[1]]) l } getDataType <- function(value) { type = TYPE_STR if ("integer" %in% class(value)) type = TYPE_INT if ("numeric" %in% class(value)) type = TYPE_DEC type } #' @export linearTrend = function(data) { lm(data ~ c(1:nrow(data)))$coefficients[2] } #' @export angleTrend = function(data) { atan(linearTrend(data) * nrow(data)) * 180 / pi } #' @export calculateTrendAngle = function(data, window) { browser() rollapply(data, window, angleTrend, fill=0, align="right") } as.date = function (item) { as.Date(item, tz="CET") } #' @export filePath <- function(..., name=NULL,ext=NULL) { args=list(...)[[1]] if (length(args>0)) txt=args[1] i=1 while (i < length(args)) { txt = paste(txt,args[i],sep="/") i = i +1 } if (!is.null(name)) txt=paste(txt,name,sep="/") if (!is.null(ext)) txt=paste(txt,ext ,sep=".") txt } .translateText <- function(text,case) { res = str_match(text, "#.+#") if (is.na(res[1,1])) return(text) toks =unlist(strsplit(res[1,1],",")) toks = unique(unlist(lapply(toks, trimws))) tmp = text for (i in 1:length(toks)) { tmp = .replaceText(tmp, toks[1], case) } tmp } .replaceText <- function(text, tok, case) { word = switch( gsub("#","",tok) ,"MODEL" = case$model$symbolBase ,"SYM" = case$config$symbol ) gsub(tok,word,text) } <file_sep>/YATAModels/R/IND_Oscillator.R library(R6) IND_Oscillator <- R6Class("IND_Oscillator", inherit=IND__BASE, public = list( name="Mobile Average" ,symbolBase="MA" ,symbol="MA" ,initialize = function() { super$initialize() } ,calculateAction = function(case, portfolio) { lInd = self$getIndicators() ind = lInd[[self$symbol]] dfi = as.data.frame(ind$result[[1]]) dft = case$tickers$df fila = case$current pCurrent = dft[fila, DF_PRICE] pInd = dfi[fila, 1] if (is.na(pInd) || pInd == 0 || pCurrent == pInd) return (c(0,100,100)) var = pCurrent / pInd if (var == 1) return (c(0,100,100)) prf = case$profile$profile thres = ifelse(var > 1,private$thresholds[["sell"]],private$thresholds[["buy"]]) action = applyThreshold(prf, var, thres) action } ,calculateOperation = function(portfolio, case, action) { reg = case$tickers$df[case$current,] cap = portfolio$saldo() pos = portfolio$getActive()$position sym = case$config$symbol # Por temas de redondeo, el capital puede ser menor de 0 if (action[1] > 0 && cap > 1) return (YATAOperation$new(sym, reg[1,DF_DATE], cap, reg[1,DF_PRICE])) if (action[1] < 0 && pos > 0) return (YATAOperation$new(sym, reg[1,DF_DATE], pos * -1, reg[1,DF_PRICE])) NULL } ) ,private = list( ) ) <file_sep>/YATAModels/R/$index.R list_modelos <- data.frame(name=c( "Basico" ,"Medias moviles") ,source=c( "modelo_0.0" ,"modelo_1.0") )<file_sep>/YATAManualUser/indicators/overlays.Rmd ### Overlays Overlays are best characterized by their scale. Overlays typically have the same or similar scale to the underlying asset and are meant to be laid over to chart of price history. Common examples are the simple moving average, Bollinger Bands, and volume-weighted average price. Overlays are commonly computed as the average of something added to a deviation of some form, or the price of the asset added to a curve of some form. Rule sets often concentrate on the prices interaction with the overlay or the overlay’s interaction with components of itself. Here’s an example: If price rises above the simple moving average, buy the stock at market price. <file_sep>/YATAWeb/ui/modAnalysisUI.R # files.trading = list.files("ui/partials/modAnalysis", pattern="*UI.R$", full.names=TRUE) # sapply(files.trading,source) # Al ffinal siempre es la misma pagina modAnalysisInput <- function(id) { ns = NS(id) useShinyjs() plotItems = list("None" = 0, "Price" = 1, "Volume" = 2, "MACD" = 3) plotTypes = list("None" = 0, "Linear" = 1, "Log" = 2, "Candle" = 4, "Bar" = 8) panelLeft = tagList( textInput(ns("txtPrfName"), label = "Nombre", value = "Javier") ,selectInput(ns("rdoPProfile"), label=NULL, selected = PRF_MODERATE , choices=c("Conservador", "Moderado", "Atrevido", "Arriesgado")) ,numericInput(ns("txtPrfImpInitial"), label = "Capital", value=10000, min=1000, step=500) ,hr() ,selectInput(ns("cboProvider"), label = "Provider", choices = NULL, selected=NULL) ,selectInput(ns("cboBases"), label = "Base", choices = NULL, selected=NULL) ,selectInput(ns("cboMonedas"), label = "Moneda", choices = NULL, selected=NULL) ,dateInput(ns("dtFrom"),"Desde", value = "2012-02-29", format = "dd/mm/yy", startview = "year") ,dateInput(ns("dtTo"),NULL, value = "2012-02-29", format = "dd/mm/yy", startview = "year") ,hr() ,selectInput(ns("cboScope"), label="Scope", selected=2,choices=c("Intraday"=1,"Day"=2,"Week"=3,"Month"=4)) ,selectInput(ns("cboModels"), label="Modelo", choices=NULL, selected=NULL) ,hr() ,bsButton(ns("btnSave"), label = "Guardar", style="success", size="large") ) panelMain = tagList(#box( width=NULL, solidHeader = T,status = "primary" menuTab(id=ns("tabs"), names=c("Largo", "Intermedio", "Corto"), values=c(1,2,3), selected=2) ,fluidRow(boxPlus(id=ns("boxHeader") ,title=textOutput(ns("lblHeader")) , closable = FALSE ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,enable_label = TRUE ,width = 12 ,plotlyOutput(ns("plot"), width="98%",height="500px") )) ,fluidRow( column(width=6, DT::dataTableOutput(ns("tblData"))) ,column(width=3, DT::dataTableOutput(ns("tblDataUp"))) ,column(width=3, DT::dataTableOutput(ns("tblDataDown"))) ) # tabsetPanel(id=ns("tabs"), type="pills" # ,tabPanel("Largo", value = "4", # column(12, id=ns("pnlLong") # # ,fluidRow(plotlyOutput(ns("plotLong"), width="100%",height="500px")) # ,fluidRow(DT::dataTableOutput(ns("tblLong"))) # ) # ) # ,tabPanel("Intermedio", value="2" # ,column(12, id=ns("pnlMedium") # # ,fluidRow(plotlyOutput(ns("plotMedium"), width="100%",height="500px")) # ,fluidRow(DT::dataTableOutput(ns("tblMedium"))) # ) # ) # ,tabPanel("Corto", value="1" # ,column(12, id=ns("pnlShort") # # ,fluidRow(plotlyOutput(ns("plotShort"), width="100%",height="500px")) # ,fluidRow(DT::dataTableOutput(ns("tblShort"))) # ) # ) # ) # ,column(2 # ,dateInput("dtCurrent", "Date:", value = "2012-02-29", format = "dd/mm/yy", startview = "year") # ,box( width=NULL, title = "Position", solidHeader = T, status = "primary" # ,withTags({ table(class = "boxTable", # tr(td("Euro"), td(colspan="2", class="lblData", textOutput(ns("lblPosFiat")))) # ,tr(td(textOutput(ns("lblMoneda"))), td(colspan="2", class="lblData", textOutput(ns("lblPosMoneda")))) # ,tr(td("Total"), td(colspan="2", class="lblData", textOutput(ns("lblPosTotal")))) # ,tr(td("Estado"), td( img(id=ns("resDown"), icon("triangle-bottom", class = "rojo", lib="glyphicon")) # ,img(id=ns("resUp"), icon("triangle-top", class = "verde", lib="glyphicon"))) # ,td( class="lblData", textOutput(ns("lblEstado")))) # ,tr(td("Tickers"),td(colspan="2", class="lblData", textOutput(ns("lblResMov")))) # ,tr(td("Opers"), td( class="lblData", textOutput(ns("lblResC"))) # ,td( class="lblData", textOutput(ns("lblResV")))) # ,tr(td("Date"), td(colspan="2", class="lblData", textOutput(ns("lblPosDate")))) # ,tr(td("Trend"), td(colspan="2", class="lblData", textOutput(ns("lblTrend")))) # # ) # # })) # ) ) # panelTool = box(width=NULL # , title = p("Toolbox",actionButton( ns("SBLClose"), "",icon = icon("remove"), class = "btn-xs")) # ) # # panelLeft = getPanelLeft(id) # # #source("ui/partials/panelRight.R") panelRight = tagList( wellPanel(h3("Plot sources") ,selectInput(ns("cboPlot1"), label = "Primary", choices = plotItems, selected = 1) ,selectInput(ns("cboPlot2"), label = "Secondary", choices = plotItems, selected = 2) ,selectInput(ns("cboPlot3"), label = "Terciary", choices = plotItems, selected = 0) ) ,wellPanel(h3("Plot types") ,selectInput(ns("cboType1"), label = "Primary", choices = plotTypes, selected = 1) ,selectInput(ns("cboType2"), label = "Secondary", choices = plotTypes, selected = 2) ,selectInput(ns("cboType3"), label = "Terciary", choices = plotTypes, selected = 0) ) # ,radioButtons(ns("rdoPlot"), label="Graph",selected = PLOT_LINEAR # , choices = list( "Linear" = PLOT_LINEAR # ,"Log" = PLOT_LOG # ,"Candles" = PLOT_CANDLE) # )) # ,wellPanel(checkboxGroupInput(ns("chkIndicators"), label = NULL) # ,checkboxInput(ns("chkShowInd"), label=LBL.SHOW_IND, value = TRUE) # ,wellPanel(radioButtons(ns("rdoProcess"), label="Mode",selected = MODE_AUTOMATIC # ,choices = list( "Automatic" = MODE_AUTOMATIC # ,"Inquiry" = MODE_INQUIRY # ,"Manual" = MODE_MANUAL))) # ) # # tagList(fluidRow( #hidden(column(id=ns("pnlLeft"), panelLeft, width=2)) # column(id=ns("pnlMain"), panelMain, width=12) # ,hidden(column(id=ns("pnlRight"), panelRight, width=2)) # # )) # makePage(id, left=panelLeft, main=panelMain, right=panelRight) }<file_sep>/YATAWeb/ui/partials/modTrading/modOpenServer.R modOpen <- function(input, output, session, id) { useShinyjs() vars <- reactiveValues( loaded = F ,oper = NULL ) myModal <- function(session) { ns <- session$ns modalDialog( textInput(ns("modalTextInput"), "Show Me What You Got!", "Get Schwifty!"), actionButton(ns("closeModalBtn"), "Close Modal") ) } ####################################################################### # Private Code ####################################################################### renderTable = function() { op = vars$oper df = op$getOpenPending() df2 = df[,c(op$CLEARING, op$BASE, op$COUNTER, op$AMOUNT, op$IN_PROPOSAL, op$TMS_LAST)] output$tblOpen = DT::renderDataTable({ DTPrepare(df2) }) } ####################################################################### # Server Code ####################################################################### if (!vars$loaded) { vars$oper = TBLOperation$new() renderTable() vars$loaded = T } observeEvent(input$tblOpen_rows_selected, { # showModal(myModal(session)) showModal(modalDialog( title = "Important message", "This is an important message!", easyClose = TRUE )) }) observeEvent(input$tblButton, { browser() }) }<file_sep>/YATAWeb/R/plots.R axis <- list( autotick = TRUE, ticks = "outside", tick0 = 0, dtick = 0.25, ticklen = 5, tickwidth = 2, tickcolor = toRGB("blue") ) vline <- function(x = 0, color = "red") { list( type = "line" ,y0 = 0 ,y1 = 1 ,yref = "paper" ,x0 = x ,x1 = x ,line = list(color = color) ) } zone = function(x0, x1) { list( type = "rect" ,fillcolor = "blue" ,line = list(color = "blue") ,opacity = 0.2 ,x0 = x0 ,x1 = x1 ,xref = "x" ,yref = "paper" ,y0 = 0 ,y1 = 1 ) } #' @description #' Genera el plot general de una criptomoneda #' @param vars Conjunto de vriables reactivas, entre ella tickers #' @param model Modelo a aplicar renderPlotSession = function(tickers, sources, types) { if (is.null(tickers) || is.null(tickers$df)) return (NULL) heights = list(c(1.0), c(0.6, 0.4), c(0.5, 0.25, 0.25), c(0.4, 0.2, 0.2, 0.2)) DT::renderDataTable({ renderTable() }) items = length(sources) plots = list() df = tickers$df idx = 0 while (idx < items) { idx = idx + 1 p = plot_ly() if (!is.null(sources[idx]) && !is.na(sources[idx])) { p = YATACore::plotBase(p, types[idx], x=df[,tickers$DATE] , y=df[,sources[idx]] , open = df[,tickers$OPEN] , close = df[,tickers$CLOSE] , high = df[,tickers$HIGH] , low = df[,tickers$LOW] , hoverText = tickers$symbol) if (!is.null(p)) plots = list.append(plots, plotly_build(hide_legend(p))) } } rows = items - sum(is.na(sources)) sp = subplot( plots, nrows = rows, shareX=T, heights=heights[[rows]]) %>% config(displayModeBar=F) sp$elementId = NULL sp } renderPlot2 = function(vars, model, term, input, showInd) { print("Entra en renderPlot") if (is.null(vars$tickers)) return (NULL) # if (term == 4) { # browser() # } if (showInd) showInd = input$chkShowInd type=PLOT_LINEAR if (term == TERM_LONG) type = PLOT_CANDLE plots = plotData(vars$clicks, term, vars$tickers, case$model, showInd, type ) if (is.null(plots)) return (NULL) sp = subplot( hide_legend(plots[[1]]) ,hide_legend(plots[[2]]) ,hide_legend(plots[[3]]) ,nrows = 3 ,shareX=T ,heights=c(0.5,0.25, 0.25)) %>% config(displayModeBar=F) sp$elementId = NULL sp } plotData = function(flag, term, data, model, showIndicators, type=PLOT_LINEAR) { FUN=function(x) { if (x[1] == x[2]) return (0) if (x[2] == 0) return (0) vv = x[1]/x[2]; if ( vv > 1.03) rr = 1 else { if (vv < .97) rr = -1 else rr = 0 } rr } if (is.null(data)) return (NULL) tickers = data$getTickers(term) if (is.null(tickers) || is.null(tickers$df)) return (NULL) df = tickers$df if (nrow(df) == 0) return(NULL) if (type == PLOT_LINEAR) { p1 <- plot_ly(df, x = df[,tickers$DATE], y = df[,tickers$PRICE], type = 'scatter', mode = 'lines') p1 <- layout(p1, xaxis = axis) } if (type == PLOT_LOG) { p1 <- plot_ly(df, x = df[,tickers$DATE], y = df[,tickers$PRICE], type = 'scatter', mode = 'lines') p1 <- layout(p1, xaxis = axis, yaxis = list(type = "log")) } if (type == PLOT_CANDLE) { p1 <- plot_ly(df, type="candlestick",x=df[,tickers$DATE] ,open=df[,tickers$OPEN] ,close=df[,tickers$CLOSE] ,high=df[,tickers$HIGH] ,low=df[,tickers$LOW]) p1 <- layout(p1, xaxis = list(rangeslider = list(visible = F))) } p1$elementId <- NULL # Evitar aviso del widget ID cc = rollapply(df[,tickers$VOLUME],2,FUN, fill=0,align="right") p2 <- plot_ly(df, x = df[,tickers$DATE], y = df[,tickers$VOLUME], type = 'bar', marker=list(color=cc)) p2$elementId = NULL p3 = plot_ly(df) plots = list(p1, p2, p3) if (showIndicators) { plots = model$plotIndicators (term, plots, data, indicators) } #if (showIndicators) plots = model$plotIndicators (term, plots, tickers, indicators) plots # # # # plots = case$model$plotIndicatorsSecundary(case$data, plots, input$chkPlots2) # # shapes = list() # shapes = list.append( shapes # ,vline(vars$df[vars$fila, "Date"]) # # ,zone(vars$df[vars$fila, "Date"], df[nrow(df),"Date"]) # ) # # plots[[1]] = plots[[1]] %>% layout(xaxis = axis, shapes=shapes) # plots[[2]] = plots[[2]] %>% layout(shapes=shapes) # } basicTheme <- function() { t0 = theme( panel.background = element_blank() ,axis.text.y=element_text(angle=90) ,axis.text.x=element_blank() ,panel.border = element_rect(colour = "black", fill=NA, size=1) ,legend.position="none" ) } basePlot1 <- function(data) { t0 = basicTheme() p1 = ggplot(data,aes(x=date, y=price)) + geom_line() # + #geom_smooth(method="lm") + # ylab("Precio") t1 = t0 # + theme(axis.text.x=element_blank(),legend.position="none") t1 = t1 + theme(axis.title.x=element_blank(), axis.ticks.x = element_blank()) p1 + t1 } basePlot2 <- function(data) { t0 = basicTheme() tmp = data tmp$c = rollapply(df,2,FUN=function(x) { v = x[1]/x[2]; if ( v > 1.03) r = 1 else { if (v < .97) r = -1 else r = 0 } r }, fill=0,align="right") p2 = ggplot(data,aes(date, volume/1000,fill=c)) + geom_bar(stat="identity") + ylab("Volumen (Miles)") #+ #scale_x_date(date_breaks = "1 week", date_labels = "%d/%m/%Y") + #scale_fill_continuous(low="red", high="green") t2 = t0 + theme(axis.text.x=element_text(angle=45, hjust=1)) p2 + t2 } basicPlot <- function(data) { p1 = ggplot(data,aes(x=date, y=price)) + geom_line() + geom_smooth(method="lm") + ylab("Precio") p2 = ggplot(data,aes(date, volume/1000,fill=Volume)) + geom_bar(stat="identity") + ylab("Volumen (Miles)") + scale_x_date(date_breaks = "1 week", date_labels = "%d/%m/%Y") + scale_fill_continuous(low="red", high="green") t0 = theme( panel.background = element_blank() ,axis.text.y=element_text(angle=90) ,panel.border = element_rect(colour = "black", fill=NA, size=1) ) t1 = t0 + theme(axis.title.x=element_blank(),axis.ticks.x = element_blank()) t2 = t0 + theme(axis.text.x=element_text(angle=45, hjust=1)) p1A = p1 + t1 p2A = p2 + t2 grid.arrange(p1A,p2A,heights=c(6,4)) }<file_sep>/YATACore/R/TBL_Session.R TBLSession = R6::R6Class("TBLSession", inherit=YATATable, public = list( provider = NULL ,base = NULL ,counter = NULL ,BASE = "BASE" ,COUNTER = "COUNTER" ,TMS = "TMS" ,OPEN = "OPEN" ,CLOSE = "CLOSE" ,HIGH = "HIGH" ,LOW = "LOW" ,VOLUME = "VOLUME" ,AVERAGE = "AVERAGE" ,initialize = function(period, provider="POL") { super$initialize(F, paste("Poloniex", period), paste("SESSION", provider, period, sep="_")) } ,getDateColumn = function() { self$TMS } ,getTargetColByName = function(name) { ucols = toupper(colnames(self$dfa)) which(ucols == toupper(name)) } ,getPairs = function() { qry = paste("select BASE, COUNTER, MAX(TMS) AS TMS FROM", self$table, " GROUP BY BASE, COUNTER") self$df = YATACore::executeQuery(qry) self$df } ,getSessionDataInterval = function(base, counter, from, to) { self$base = base self$counter = counter qry = paste("SELECT * FROM", self$table, " WHERE BASE = ? AND COUNTER = ? AND TMS BETWEEN ? AND ?") self$dfa = YATACore::executeQuery(qry, parms = list(base, counter, from - months(1), to)) self$dfa = self$dfa %>% subset(select = -c(BASE, COUNTER)) self$df = self$dfa %>% filter(self$dfa$TMS >= from) private$adjustTypes() } # ,refresh = function() { # if (is.null(self$dfa)) { # self$dfa = loadSessions(self$symbol, self$table, self$fiat) # self$dfa$Change = rollapplyr(self$dfa[,self$VALUE], 2, FUN = calculateChange, fill = 0) # self$dfa = private$adjustTypes(self$dfa) # } # self$df = self$dfa # if (nrow(self$df) > 0) self$df[,self$PRICE] = self$df[,self$VALUE] # # invisible(self) # } # ,reverse = function() { # tmp = self$df[seq(dim(self$df)[1],1),] # private$adjustTypes(tmp) # } # ,getRange = function(rng=0) { # beg = self$dfa[1,self$DATE] # start = beg # last = self$dfa[nrow(self$dfa), self$DATE] # current = Sys.Date() # year(start) = year(current) # month(start) = 1 # if (month(current) < 6) {year(start) = year(start) - 1 ; month(start) = 6} # # if (start <= beg) start = beg # # if (rng > 0 && nrow(self$dfa) > rng) { # # start = as.Date(self$dfa[nrow(self$dfa) - rng, self$DATE]) # # } # c(beg, last, start) # } # ,filterByDate = function(from, to) { private$makeDF(self$dfa %>% filter(Date >= from, Date <= to)) } # ,filterByRows = function(from, to=0) { if (to == 0) to = nrow(self$dfa) # if (from < 0) from = to + from + 1 # if (from <= 0) from = 1 # private$makeDF(self$dfa[from:to,]) # } # ,getTrend = function() { lm(self$df[,self$PRICE] ~ c(1:nrow(self$df)))$coefficients[2] } # ,getTrendAngle = function() { atan(self$getTrend() * nrow(self$df)) * 180 / pi } # ,getData = function() { self$df } # ,getBaseData = function() { self$df[,self$DATE, self$PRICE] } # ,getCurrentData = function(regs) { # tmp = self$clone() # tmp$filterByRows(1,regs) # tmp # } # ,getCurrentTicker = function(reg) { self$df[reg,] } ) ,private = list( adjustTypes = function() { self$df[,self$TMS] = as.datet(self$df[,self$TMS]) self$df[,self$OPEN] = as.fiat (self$df[,self$OPEN]) self$df[,self$CLOSE] = as.fiat (self$df[,self$CLOSE]) self$df[,self$HIGH] = as.fiat (self$df[,self$HIGH]) self$df[,self$LOW] = as.fiat (self$df[,self$LOW]) self$df[,self$VOLUME] = as.long (self$df[,self$VOLUME]) df } # ,calculateVariation = function() { # for (col in colnames(self$df)) { # if ("numeric" %in% class(self$df[,col])) { # self$df[,col] = rollapplyr(self$df[,col], 2, calculateChange, fill = 0) # self$df[,col] = as.percentage(self$df[,col]) # } # } # } ) ) <file_sep>/YATAWeb/ui/modManuals.R modManUserUI <- function(id) { # Create a namespace function using the provided id ns <- NS(id) tagList( #includeHTML("www/user/index.html") htmlOutput(ns("manual")) ) } modManUser <- function(input, output, session, parent) { ns <- session$ns changed = reactiveVal(FALSE) # output$manual <- renderUI({tags$iframe(seamless="seamless",class="manual", src="www/user/index.html")}) output$manual <- renderUI({tags$iframe(seamless="seamless" ,class="manual" , style="position: absolute; width: 100%; height: 100%; border: none" ,src="man/user/index.html")}) return(reactiveVal({TRUE})) } modManTechUI <- function(id) { # Create a namespace function using the provided id ns <- NS(id) tagList( #includeHTML("www/user/index.html") htmlOutput(ns("manual")) ) } modManTech <- function(input, output, session, parent) { ns <- session$ns changed = reactiveVal(FALSE) # output$manual <- renderUI({tags$iframe(seamless="seamless",class="manual", src="www/user/index.html")}) output$manual <- renderUI({tags$iframe(seamless="seamless" ,class="manual" , style="position: absolute; width: 100%; height: 100%; border: none" ,src="man/tech/index.html")}) return(reactiveVal({TRUE})) }<file_sep>/YATAWeb/ui/modSimmServer.R library(shinyjs) modSimm <- function(input, output, session, parent) { shinyjs::runjs(paste0("YATAPanels('", session$ns(""), "')")) # Control la carga # LOADED = 7 # LOAD_MONEDA = 1 # Carga los tickers # LOAD_MODELO = 2 # Carga el modelo sin indicadores # LOAD_INDICATORS = 4 # Si hay tickers y modelo, carga indicadores # LOAD_ALL = 15 plotItems = list("None" = 0, "Price" = 1, "Volume" = 2, "MACD" = 3) vars <- reactiveValues( loaded = F ,tab = 2 ,provider = "POL" ,base = "USDT" ,counter = "BTC" # ,scope = 0 ,sessions = list() ,session = NULL # Current ,plots = c(2,5,0, 0) ,plotTypes = c(3,4,0, 0) ,dtTo = Sys.Date() ,dtFrom = Sys.Date() - months(3) ,dlgShow = FALSE ,model = NULL ,modWork = NULL ,targets = FTARGET$new() ) ######################################################################################## ### PRIVATE CODE ######################################################################################## loadPage = function() { fTarget = FTARGET$new() updateSelectInput(session, "cboProvider", choices=comboClearings(), selected="POL") updateSelectInput(session, "cboBases", choices=comboBases(NULL), selected="USDT") updateSelectInput(session, "cboModel", choices=comboModels(TRUE)) updateSelectInput(session, "cboMonedas", choices=comboCounters(), selected="BTC") updateSelectInput(session, "cboTarget", choices=fTarget$getCombo(T)) updateDateInput(session, "dtFrom", value = Sys.Date() - months(3)) updateDateInput(session, "dtTo", value = Sys.Date()) vars$modWork = YATAModels::YATAModel$new() vars$model = vars$modWork # Ajustar el dia a 1 para evitar errores en la resta de meses vars$dtFrom = Sys.Date() day(vars$dtFrom) = 1 vars$dtFrom = vars$dtFrom - months(3) per = c("W1", "D1", "H8") vars$sessions = list(TBLSession$new(per[1]),TBLSession$new(per[2]),NULL, TBLSession$new(per[3])) vars$loaded = T vars$tab = 2 vars$session = vars$sessions[[vars$tab]] updateData() renderInfo() } updateData = function(calculate = F) { # lapply(vars$sessions, function(x) { # eval(x)$getSessionDataInterval(vars$base, vars$counter, input$dtFrom, input$dtTo)}) vars$session = vars$sessions[[vars$tab]] vars$session$getSessionDataInterval(vars$base, vars$counter, vars$dtFrom, vars$dtTo) output$lblHeader = renderText(paste(vars$session$base, vars$session$counter, sep="/")) if (calculate) {case$model$calculateIndicators(vars$tickers, force=T)} } renderInfo = function() { renderPlots() renderData() } renderPlots = function () { heights = list(c(500), c(300, 200), c(250, 125, 125), c(200, 100, 100, 100)) plots = which(vars$plots > 0) nPlots = length(plots) height = heights[[nPlots]] iHeight = 1 # Falla si reutilizo la variable if (vars$plots[1] > 0) { p1 = renderPlot(plots[1], height[iHeight]) if (nPlots > 1) p1 = p1 %>% layout(xaxis=list(visible=FALSE)) output$plot1 = renderPlotly({p1}) shinyjs::show("plot1") iHeight = iHeight + 1 } else { shinyjs::hide("plot1") } if (vars$plots[2] > 0) { p2 = renderPlot(plots[2], height[iHeight]) if (nPlots > 2) p2 = p2 %>% layout(xaxis=list(visible=FALSE)) output$plot2 = renderPlotly({p2}) shinyjs::show("plot2") iHeight = iHeight + 1 } else { shinyjs::hide("plot2") } if (vars$plots[3] > 0) { p3 = renderPlot(plots[3], height[iHeight]) if (nPlots > 3) p3 = p3 %>% layout(xaxis=list(visible=FALSE)) output$plot3 = renderPlotly({p3}) shinyjs::show("plot3") iHeight = iHeight + 1 } else { shinyjs::hide("plot3") } if (vars$plots[4] > 0) { p4 = renderPlot(plots[4], height[iHeight]) output$plot4 = renderPlotly({p4}) shinyjs::show("plot4") } else { shinyjs::hide("plot4") } } renderPlot = function(idx, height) { m <- list(l = 1,r = 1,b = 1,t = 1,pad = 1) data = vars$session colName = vars$targets$getName(as.integer(vars$plots[idx])) col = data$getTargetColByName(colName) yData = data$df[,col] xData = data$df[,data$TMS] p = plot_ly() p = YATACore::plotBase(p, as.integer(vars$plotTypes[[idx]]) , x=xData , y=yData , open = data$df[,data$OPEN] , close = data$df[,data$CLOSE] , high = data$df[,data$HIGH] , low = data$df[,data$LOW] , hover = data$counter) if (!is.null(p)) { p = p %>% layout(yaxis = list(title=colName)) p = plotIndicators(p, colName, xData) p = p %>% layout(autosize = T, width = "1400px", height = height, margin = m, showlegend=F) #plots = list.append(plots, plotly_build(p)) #hide_legend(p))) } p } renderData = function() { data = vars$session$df inds = vars$model$getIndicators(vars$tab) iInd = 0 while (iInd < length(inds)) { browser() iInd = iInd + 1 ind = inds[[iInd]] data = cbind(data, ind$getData) } data = data[order(data$TMS , decreasing = TRUE ),] table = .prepareTable(data) output$tblSimm = DT::renderDataTable({ table }) } plotIndicators = function(plot, colName, xData) { if (is.null(vars$model)) return (plot) vars$model$plotIndicators(plot=plot, scope=vars$tab, target=colName, xAxis=xData) } createIndicator = function() { parms = vars$dlgInd$getParameters() npar = 1 while (npar <= length(parms)) { p = parms[[npar]] value = eval(parse(text=paste0("input$parm", npar))) vars$dlgInd$addParameter(names(parms)[npar], p) npar = npar + 1 } if (input$cboTarget != "") vars$dlgInd$setTarget(FTARGET$new(input$cboTarget)) } closeDialog = function() { shinyjs::hide(id="modal-panel") shinyjs::hide(id="modal-back") vars$dlgShow = FALSE } ######################################################################################## ### OBSERVERS ######################################################################################## observeEvent(input$tabs, ignoreInit = TRUE, { vars$tab = as.integer(input$tabs) vars$session = vars$sessions[[vars$tab]] renderInfo() }) observeEvent(input$cboModel, ignoreInit = TRUE, { idModel = as.integer(input$cboModel) if (idModel == 0) vars$model = vars$modWork }) observeEvent(c(input$cboPlot1,input$cboPlot1,input$cboPlot1,input$cboPlot1), { vars$plots[1] = input$cboPlot1 vars$plots[2] = input$cboPlot2 vars$plots[3] = input$cboPlot3 vars$plots[4] = input$cboPlot4 }) observeEvent(c(input$cboType1,input$cboType2,input$cboType3, input$cboType4), { vars$plotTypes[1] = input$cboType1 vars$plotTypes[2] = input$cboType2 vars$plotTypes[3] = input$cboType3 vars$plotTypes[4] = input$cboType4 }) # observeEvent(input$cboScope, { # browser() # per = c("W1", "D1", "H8") # if (input$cboScope == 1) per = c("D1", "H8", "H2") # Intraday # if (input$cboScope == 2) per = c("W1", "D1", "H8") # Day # if (input$cboScope == 3) per = c("M1", "W1", "D1") # Week # if (input$cboScope == 4) per = c("M1", "W1", "D1") # Month # vars$sessions = list(TBLSession$new(per[1]),TBLSession$new(per[2]),TBLSession$new(per[3])) # }) observeEvent(input$btnSave, { shinyjs::runjs("YATAToggleSideBar(1, 0)") # if (input$cboMonedas == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MONEDA); return (NULL) } # updateActionButton(session, "tradTitle", label = input$cboMonedas) vars$base = input$cboBases vars$counter = input$cboMonedas vars$scope = input$cboScope updateData() }) ######################################################################################## ### MODAL DIALOG ######################################################################################## observeEvent(input$btnOpenDlg, { shinyjs::show(id="modal-back", anim=TRUE) if (vars$dlgShow == FALSE) { updateSelectInput(session, "cboIndGroups", choices=comboIndGroups()) vars$dlgShow = TRUE } shinyjs::show(id="modal-panel") }) observeEvent(input$btnCloseDlg, { closeDialog() }) observeEvent(input$btnAddDlg, { createIndicator() vars$model$addIndicator(vars$dlgInd, vars$tab) vars$model$calculateIndicators(vars$session, vars$tab) closeDialog() renderInfo() }) observeEvent(input$cboIndGroups, { shinyjs::hide(id="dlgIndBody") l = comboIndNames(input$cboIndGroups) updateSelectInput(session, "cboIndNames", choices=comboIndNames(input$cboIndGroups)) }) observeEvent(input$cboIndNames, { if (input$cboIndNames == "") return (NULL) shinyjs::show(id="dlgIndBody") indName = YATAENV$indNames$getIndNameByID(input$cboIndNames) ind = eval(parse(text=paste0("YATAModels::IND_", indName, "$new()"))) output$indTitle = renderText({ind$name}) updateTextInput(session, "lblIndName", value = ind$name) #txt = Rmd2HTML(ind$getDoc()) #output$indDoc = renderUI(txt, quoted=TRUE) #output$indDoc = renderUI({withMathJax(helpText('and output 2 $$3^2+4^2=5^2$$'))}) output$indDoc = renderUI({withMathJax(helpText(ind$getDoc()))}) tgt = ind$getTarget() if (tgt$select) { updateSelectInput(session, "cboTarget", selected=tgt$value) shinyjs::show("row0") } parms = ind$getParameters() npar = 1 while (npar <= length(parms)) { p = parms[[npar]] eval(parse(text=paste0("output$lblParm", npar, " = renderText({'", names(parms)[npar], "'})"))) updateNumericInput(session, paste0("parm", npar), value=p) shinyjs::show(paste0("row", npar)) npar = npar + 1 } vars$dlgInd = ind }) # updateSelectInput(session, "cboMonedas", choices=cboMonedas_load(),selected=NULL) # updateSelectInput(session, "cboModels" , choices=cboModels_load()) # # observeEvent(input$tabTrading, { if (vars$loaded > 0) updateData(input, EQU(vars$loaded, LOADED)) }) # observeEvent(input$cboMonedas, { print("event moneda"); # if (input$cboMonedas == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MONEDA); return (NULL) } # updateActionButton(session, "tradTitle", label = input$cboMonedas) # # shinyjs::enable("btnSave") # vars$tickers = YATAData$new(case$profile$scope, input$cboMonedas) # rng = vars$tickers$getRange(YATAENV$getRangeInterval()) # vars$pendingDTFrom = T # vars$pendingDTTo = T # updateDateInput(session, "dtFrom", min=rng[1], max=rng[2], value=rng[3]) # updateDateInput(session, "dtTo", min=rng[1], max=rng[2], value=rng[2]) # vars$tickers$filterByDate(rng[3], rng[2]) # vars$loaded = bitwOr(vars$loaded, LOAD_MONEDA) # if (AND(vars$loaded, LOAD_MODELO)) { # case$model = loadIndicators(case$model, vars$tickers$scopes) # vars$loaded = bitwOr(vars$loaded, LOAD_INDICATORS) # } # updateData(input, EQU(vars$loaded, LOADED)) # # vars$dfd = vars$tickers$df # }, ignoreNULL=T, ignoreInit = T) # # # observeEvent(input$cboModels, { print("event Models") # shinyjs::enable("btnSave") # if (input$cboModels == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MODELO); return(NULL) } # case$model = YATAModels::loadModel(input$cboModels) # vars$loaded = bitwOr(vars$loaded, LOAD_MODELO) # if (AND(vars$loaded, LOAD_MONEDA)) { # case$model = loadIndicators(case$model, vars$tickers$scopes) # vars$loaded = bitwOr(vars$loaded, LOAD_INDICATORS) # } # updateData(input, EQU(vars$loaded, LOADED)) # }, ignoreNULL=T, ignoreInit = T) # # # # observeEvent(input$chkShowInd, {if (input$chkShowInd) { # # case$model$setParameters(getNumericGroup(input,vars$parms)) # # #JGG Revisar, no es una lista al uso # # #case$model$setThresholds(getNumericGroup(input,vars$thres)) # # ##case$model$calculateIndicatorsGlobal(vars$tickers) # # }}) # observeEvent(input$dtFrom, {if (vars$pendingDTFrom) { vars$pendingDTFrom = F; return (NULL) } # if (AND(vars$loaded, LOAD_MONEDA)) {print("event dtFrom"); # vars$tickers$filterByDate(input$dtFrom, input$dtTo) # case$model$calculated = FALSE # updateData(input, EQU(vars$loaded,LOADED)) # } # }, ignoreNULL=F, ignoreInit = T) # observeEvent(input$dtTo, { if (vars$pendingDTTo) { vars$pendingDTTo = F; return (NULL) } # if (AND(vars$loaded, LOAD_MONEDA)) { print("event dtTo"); # vars$tickers$filterByDate(input$dtFrom, input$dtTo) # case$model$calculated = FALSE # updateData(input, EQU(vars$loaded,LOADED)) # } # }, ignoreNULL=F, ignoreInit = T) # observeEvent(input$btnSave, { # updateParameter(PARM_CURRENCY, input$cboMoneda) # updateParameter(PARM_MODEL, input$cboModel) # shinyjs::disable("btnSave") # }) # # # First time ################################################################################################### ### PRIVATE CODE ################################################################################################### # adjustToolbox = function(tabId) { # browser() # pnlIds = c("pnlShort", "pnlMedium", "pnlEmpty", "pnlLong") # tbIds = c("tbShort", "tbMedium", "tbEmpty", "tbLong") # print("entra en adjust") # newSize = "col-sm-10" # oldSize = "col-sm-12" # if (vars$toolbox[tabId]) { # newSize = "col-sm-12" # oldSize = "col-sm-10" # } # shinyjs::removeCssClass (id=pnlIds[tabId], oldSize) # shinyjs::toggle(id = tbIds[tabId]) # vars$toolbox[tabId] = !(vars$toolbox[tabId]) # shinyjs::addCssClass (id=pnlIds[tabId], newSize) # } # # # Lo devuelve cada vez que entra aqui # return(reactive({vars$changed})) # } # # # btnLoad_click <- function(input, output, session, vars) { # # if (validate()) return(showModal(dataError())) # # # Create user profile # profile = YATAProfile$new() # profile$name = input$txtPrfName # profile$profile = input$rdoPrfProfile # profile$capital = input$txtPrfImpInitial # profile$scope = input$rdoPrfScope # # # Create configuration for case # config = YATAConfig$new() # config$symbol = input$moneda # config$initial = input$txtPrfImpInitial # config$from = input$dtFrom # config$to = input$dtTo # config$mode = input$rdoProcess # config$delay = input$processDelay # # # Initialize case # case$profile = profile # case$config = config # case$tickers = vars$tickers # case$current = 0 # case$oper = NULL # # case$config$summFileName = setSummaryFileName(case) # case$config$summFileData = setSummaryFileData(case) # # calculateIndicators(case) # # # Create Portofolio # portfolio <<- YATAPortfolio$new() # portfolio$addActive(YATAActive$new(input$moneda)) # portfolio$flowFIAT(config$from, config$initial) # } # cboMonedas_load <- function() { # print("Load Monedas") # tIdx = DBCTC$getTable(TCTC_INDEX) # data = tIdx$df %>% arrange(Name) # setNames(c(0, data[,tIdx$SYMBOL]),c(" ", data[,tIdx$NAME])) # } # cboModels_load <- function() { # print("Load Modelos") # df = YATACore::loadModelsByScope(case$profile$getScope()) # setNames(c(0, df$ID_MODEL), c(" ", df$DESCR)) # } # # updateManual <- function(input, output, session, model) { # fp = paste(YATAENV$modelsMan, model$doc, sep="/") # # if (file.exists(fp)) { # output$modelDoc = renderUI({ # HTML(markdown::markdownToHTML(knit(fp, quiet = TRUE),fragment.only = TRUE)) # }) # } # else { # output$modelDoc = renderUI({"<h2>No hay documentacion</h2>"}) # } # } # # setParmsGroup = function(parms) { # if (length(parms) == 0) return (NULL) # # LL <- vector("list",length(parms)) # nm = names(parms) # for(i in 1:length(vars$parms)){ # LL[[i]] <- list(numericInput(ns(paste0("txt", nm[i])), label = nm[i], value = parms[[i]])) # } # return(LL) # # } # getNumericGroup = function(input, parms) { # # if (length(parms) == 0) return (NULL) # ll <- vector("list",length(parms)) # nm = names(parms) # # for(i in 1:length(parms)) { # # cat(eval(parse(text=paste0("input$txt", nm[i]))), "\n") # ll[[i]][1] = eval(parse(text=paste0("input$txt", nm[i]))) # } # names(ll) = nm # ll # } # # loadTickers = function(scope, moneda) { # pos = which(SCOPES == scope) # YATACore::openConnection() # t1 = NULL # t3 = NULL # if (pos > 1) t1 = TBLTickers$new(SCOPES[pos - 1], moneda) # t2 = TBLTickers$new(SCOPES[pos], moneda) # if (pos < length(SCOPES)) t3 = TBLTickers$new(SCOPES[pos + 1], moneda) # # YATACore::closeConnection() # list(t1,t2,t3) # } # # adjustPanel = function(expand, left, vars) { # shinyjs::removeCssClass (id="pnlMain", paste0("col-sm-", vars$mainSize)) # if (expand) vars$mainSize = vars$mainSize + 2 # if (!expand) vars$mainSize = vars$mainSize - 2 # shinyjs::addCssClass (id="pnlMain", paste0("col-sm-", vars$mainSize)) # if (left) { # shinyjs::toggle(id = "pnlLeft") # shinyjs::toggle(id = "SBLOpen") # } # else { # shinyjs::toggle(id = "pnlRight") # shinyjs::toggle(id = "SBROpen") # } # } if (!vars$loaded) loadPage() } # ui <- tagList( # numericInput("nplot","Number of plots",2), # uiOutput( # 'chartcontainer' # ) # ) # # server <- function(input, output, session) { # output$chartcontainer <- renderUI({ # tagList( # lapply( # seq_len(input$nplot), # function(x){ # htmltools::tags$div( # style="display:block;float:left;width:45%;height:50%;", # tags$h3(paste0("plot #",x)), # #NOTE: inside of renderUI, need to wrap plotly chart with as.tags # htmltools::as.tags(p) # ) # } # ) # ) # }) # }<file_sep>/YATACore/R/PKG_Math.R #' @description Calcula la distancia de un punto a una recta #' @export #' dist <- function(recta, punto) { num = abs((recta[2] * punto[1]) - punto[2] + recta[1]) den = sqrt(recta[2]^2 + 1) num /den } <file_sep>/YATAWeb/ui/modConfigUI.R modConfigInput <- function(id) { # Create a namespace function using the provided id ns <- NS(id) #$('#data2').addClass('form-control'); tagList( # uiOutput(ns("cssTheme")) # ,selectInput(ns("theme"), label = ("Tema"), choices = list("YATA")) ) }<file_sep>/YATAWeb/R/R6OLInfo.R YATAOLInfo <- R6Class("YATAOLInfo", public = list( base = NULL ,showBTC = TRUE ,choices = NULL ,selected = NULL ,rangeValue = NULL ,rangePercentage = NULL ) ) <file_sep>/YATAClient/YATAClient/src/main/java/com/jgg/yata/client/timers/TimerTicker.java package com.jgg.yata.client.timers; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import com.jgg.yata.client.Providers; import com.jgg.yata.client.pojos.Ticker; import com.jgg.yata.client.providers.Provider; import com.jgg.yata.client.providers.ProviderFactory; public class TimerTicker extends TimerTask { int seconds = 1; Provider prov; public TimerTicker (int seconds, Providers provider) { this.seconds = seconds; this.prov = ProviderFactory.getProvider(provider); } public void start() { Timer timer = new Timer(); timer.scheduleAtFixedRate(this, 0, seconds * 1000); } @Override public void run() { try { Map<String, Ticker> map = prov.getTickers(); for(Map.Entry<String, Ticker> entry : map.entrySet()) { System.out.println(entry.getValue().asString()); } } catch (Exception e) { System.err.println(e.getMessage()); System.exit(16); } } } <file_sep>/YATAWSSServer/WSSServer.R # A little example server that Winston made for testing. library(httpuv) cat("Starting server on port 8888...\n") startServer("0.0.0.0", 8888, list( onHeaders = function(req) { # Print connection headers cat(capture.output(str(as.list(req))), sep = "\n") }, onWSOpen = function(ws) { cat("Connection opened.\n") ws$onMessage(function(binary, message) { cat("Server received message:", message, "\n") ws$send(message) }) ws$onClose(function() { cat("Connection closed.\n") }) } ) ) #stopAllServers()<file_sep>/YATACore/R/PKG_DataModel.R library("R6") DB_MODELS = "Models" TMOD_GROUPS = "Groups" TMOD_MODELS = "Models" DB_CURRENCIES = "CTC" TCTC_INDEX = "$Index" TCTC_CURRENCY = "Currency" TBLPosition = R6::R6Class("TBLPosition", inherit=YATATable, public = list( ORDER = DF_ORDER ,DATE = DF_DATE ,FIAT = NULL ,CTC = NULL ,BALANCE = "Balance" ,initialize = function(fiat, ctc) {self$FIAT = fiat; self$CTC = ctc } ,getPosition = function() { self$df[nrow(self$df),] } ,getDecimals = function() { c(self$CTC) } ,getCoins = function() { c(self$FIAT, self$CTC, self$BALANCE) } ,getDates = function() { c(self$DATE) } ,add = function(date, fiat, ctc, balance) { if (is.null(self$df)) { self$df = private$makeRecord(date,fiat,ctc,balance) } else { self$df = rbind(self$df, private$makeRecord(date,fiat,ctc,balance, nrow(self$df))) } invisible(self) } ) ,private = list ( makeRecord = function(date, fiat, ctc, balance, o=0) { rec = as.data.frame(list(o + 1, date, fiat, ctc, balance)) colnames(rec) = c(self$ORDER, self$DATE, self$FIAT, self$CTC, self$BALANCE) rec } ) ) TBLOperation = R6::R6Class("TBLOperation", inherit=YATATable, public = list( ORDER = DF_ORDER ,TYPE = "Type" ,DATE = DF_DATE ,UDS = "Uds" ,PRICE = DF_PRICE ,TOTAL = DF_TOTAL ,PMM = "PMM" ,PMA = "PMA" ,POSITION = "Position" ,refresh = function() { } # No data to load ,initialize = function() { super$initialize("Operation") } ,getDecimals = function() { c(self$UDS, self$PRICE, self$POSITION)} ,getCoins = function() { c(self$TOTAL, self$PMM)} ,getDates = function() { c(self$DATE)} ,getBuy = function(asc=T) { private$getOpers( 1, asc) } ,getSell = function(asc=T) { private$getOpers(-1, asc) } ,getByType = function(type, asClass=F) { if (!asClass) return(self$df[self$df$Type==type,]) tmp = self$clone() tmp$df = tmp$df[Type==type,] tmp } ,getLast = function(asClass=F) { if (!asClass) return(self$df[nrow(self$df),]) tmp = self$clone() tmp$df = tmp$df[nrow(self$df),] tmp } ,add = function(date, uds, price) { if (is.null(self$df)) { # Siempre es una compra self$df = private$makeRecord(date, uds, price, price, price) } else { pmm = private$calcPMM(uds, price) pma = self$df[nrow(self$df),self$PMA] if (uds > 0) pma = private$calcPMA(uds, price) self$df = rbind(self$df, private$makeRecord(date, uds, price, pmm, pma,nrow(self$df))) } nrow(self$df) } ) ,private = list ( makeRecord = function(date, uds, price, pmm, pma, order=0) { type = ifelse(uds > 0, 1 , -1) pos = 0 if (order > 0) pos = sum(self$df[,self$UDS]) rec = as.data.frame(list(order + 1, type, date, uds, price, uds * price, pos + uds, pmm, pma)) colnames(rec) = c(self$ORDER, self$TYPE, self$DATE, self$UDS, self$PRICE, self$TOTAL, self$POSITION, self$PMM, self$PMA) rec } ,calcPMM = function(uds, price) { last = nrow(self$df) if (last == 0) return (price) den = self$df[last, self$POSITION] + uds if (den == 0) return (0) return ((self$df[last, self$PMM] + (uds * price)) / den) } ,calcPMA = function(uds, price) { last = nrow(self$df) return ((self$df[last, self$PMA] + (uds * price)) / (self$df[last, self$POSITION] + uds)) } ,getOpers = function(type=1, asc=T) { df = self$df[df$Type == type,] if (!asc) df = df %>% arrange(desc(eval(self$asVar(self$DATE)))) df } ) ) TBLIND = R6::R6Class("TBLIND", public = list( ORDER = "Order" ,DATE = "Date" ,PRICE = "Price" ,vOLUME = "Volume" ,VAR = "Var" ,TREND = "Trend" ,lines = list() ,dfi = NULL ,add = function(ind, data) { if (ind$type == IND_LINE) { self$lines = c(self$lines, enquote(data)) names(self$lines) = c(names(self$lines), ind$columns) } if (ind$type == IND_OVERLAY) { # Data frame colnames(data) = ind$columns if (is.null(self$dfi)) { self$dfi = data; return (invisible(self)) } self$dfi = cbind(self$dfi, data) } invisible(self) } ,filterByDate = function(from, to) { self$dfi = self$dfi %>% filter(Date >= from, Date <= to) self$dfi$Order = rep(1:nrow(self$dfi)) } ) ) TBLModGroup = R6::R6Class("TBLModGroup", inherit=YATATable, public = list( ID = "IdGroup" ,ACTIVE = "Active" ,NAME = "Name" ,refresh = function() { super$refresh("loadModelGroups") } ,filter = function(active=T) { if (active) self$df = self$df[self$df$Active==T,] invisible(self) } ) ) TBLModMod = R6::R6Class("TBLModMod", inherit=YATATable, public = list( ID = "IdModel" ,MODEL = "Model" ,GROUP = "Group" ,ACTIVE = "Active" ,SOURCE = "Source" ,CLASS = "Class" ,DESC = "Description" ,refresh = function() { super$refresh("loadModelModels") } ,filter = function(idGroup=NULL, active=T, model=NULL) { self$df = self$dfa if (!is.null(idGroup)) self$df = self$df %>% filter(Group == idGroup) if (!active) self$df = self$df %>% filter(Active == T) if (!is.null(model)) self$df = self$df %>% filter(Model == model) invisible(self) } ) ) # # Tabla de monedas # TBLIndex = R6::R6Class("TBLIndex", inherit=YATATable, public = list( NAME = "Name" ,SYMBOL = "Symbol" ,DECIMAL = "Decimals" ,ACTIVE = "Active" ,refresh = function() { super$refresh("loadCTCIndex") } ,filter = function(active=T) { if (active) self$df = self$dfa[self$dfa$Active==T,] invisible(self) } ,select = function(key) {self$df[self$df$Symbol == key,]} ,setRange = function(from = NULL, to = NULL) { if (!is.null(from)) self$df = self$df %>% filter(self$df$Symbol >= from) if (!is.null(to)) self$df = self$df %>% filter(self$df$Symbol <= to ) invisible(self) } ,initialize = function(tbName) { super$initialize(tbName) self$refresh() self$filter() } ) ) ######################################################################## ### FUNCTIONS ######################################################################## #' @export createDBModels <- function() { # DBModels = YATADB$new(DB_MODELS) # tGrp = TBLModGroup$new(TMOD_GROUPS) # tMod = TBLModMod$new(TMOD_MODELS) # DBModels$addTables(c(tGrp, tMod)) } #' @export createDBCurrencies <- function() { # DBCurrencies = YATADB$new(DB_CURRENCIES) # # tIdx = TBLIndex$new(TCTC_INDEX) # DBCurrencies$addTables(c(tIdx)) } <file_sep>/YATACore/R/indicators.R # Crea el df de indicadores con los datos comunes indBase <- function(data, modelo) { d = data[,c("orden","Date",modelo$col.precio,"Volume")] colnames(d) <- c("orden", "fecha", "precio", "volumen") d$fecha = as.Date(d$fecha) d$pmm = 0 d$oper = 0 v0 <- rollapply(d$precio, 2 , function(x) return (((x[2] / x[1]) - 1) * 100) , fill=NA, align="right") cbind(d, v0) } <file_sep>/YATAWeb/ui/modCurrencyUI.R modCurrencyUI <- function(id) { ns <- NS(id) useShinyjs() # panelLeft = column(id = ns("left"), width=2, style="display: none" # ,radioButtons(ns("swSource"),"Source" , selected = 1, choices = list("Price" = 0, "Volume" = 1)) # ,bsButton(ns("btnConfig"), "Moneda", icon = icon("check"), style = "primary") # ) plotType = list("Linear" = PLOT_LINE, "Log" = PLOT_LOG, "Candlestick" = PLOT_CANDLE, "Bar"=PLOT_BAR) plotData = list("Price" = 1, "Volume" = 2, "Choice 3" = 3) panelMain = boxPlus(width=NULL, closable = F, collapsible = TRUE ,title = textOutput(ns("txtMainPlot")) ,status = "info" ,solidHeader = FALSE # ,enable_dropdown = TRUE # ,dropdown_icon = "wrench" # ,dropdown_menu = dropdownItemList( # wellPanel("Primary", # selectInput(ns("cbo11"), label = NULL, choices = plotData, selected = 1) # ,selectInput(ns("cbo12"), label = NULL, choices = plotType, selected = PLOT_LINE) # ) # ,wellPanel("Secondary", # selectInput(ns("cbo21"), label = NULL, choices = plotData, selected = 2) # ,selectInput(ns("cbo22"), label = NULL, choices = plotType, selected = PLOT_BAR) # ) # ,bsButton(ns("btnPlots"), style="success", label = "Update") # ) ,fluidRow(plotlyOutput(ns("plotCTC"), width="100%",height="500px")) ,fluidRow( column(width=6, DT::dataTableOutput(ns("tblCTC"))) ,column(width=6, fluidRow( DT::dataTableOutput(ns("tblPos")) ,DT::dataTableOutput(ns("tblFlow")) ) ) ) ) tagList( fluidRow(panelMain)) }<file_sep>/YATACore/R/PKG_Layouts.R DB_CURRENCIES = "Currencies" TBL_INDEX = "$Index" TBL_CURRENCY = "Currency" IDX_NAME="Name" IDX_SYMBOL="Symbol" IDX_DECIMAL="Decimals" IDX_ACTIVE="Active" DF_CTC_INDEX=c(IDX_NAME,IDX_SYMBOL,IDX_DECIMAL,IDX_ACTIVE) CTC_DATE="Date" CTC_OPEN="Open" CTC_HIGH="High" CTC_LOW="Low" CTC_CLOSE="Close" CTC_VOLUME="Volume" CTC_CAP="MarketCap" DF_CTC_CTC=c(CTC_DATE,CTC_OPEN,CTC_HIGH,CTC_LOW,CTC_CLOSE,CTC_VOLUME,CTC_CAP) # Dataframe for position POS_ORDER="orden" POS_DATE="date" POS_EUR="EUR" POS_CURRENCY="Moneda" POS_BALANCE="Balance" DF_POSITION=c(POS_ORDER,POS_DATE,POS_EUR,POS_CURRENCY,POS_BALANCE) # Dataframe de Operacion OP_ORDER="orden" OP_DATE="date" OP_UDS="uds" OP_PRICE="price" OP_TOTAL="total" OP_PMM="pmm" OP_POS="position" DF_OPERATION=c(OP_ORDER,OP_DATE,OP_UDS,OP_PRICE,OP_TOTAL,OP_PMM,OP_POS) # Cases DB_CASES = "Cases" TBL_CASES = "Cases" CASE_ID = "idTest" CASE_NAME = "Name" CASE_SUMMARY = "Summary" CASE_DETAIL = "Detail" CASE_INFO = "Info" CASE_PROFILE = "Profile" CASE_SCOPE = "Scope" CASE_CAPITAL = "Capital" CASE_OTRO = "Otro" CASE_FROM = "From" CASE_TO = "To" CASE_START = "Start" CASE_PERIOD = "Period" CASE_INTERVAL = "Interval" CASE_MODEL = "Model" CASE_VERSION = "Version" CASE_GRP_PARMS = "Parm" CASE_GRP_THRESHOLDS = "Thre" CASE_END = "End" CASE_SYM_NAME = "SymName" CASE_SYM_SYM = "Symbol" DF_CASES=c( CASE_ID,CASE_NAME,CASE_SUMMARY,CASE_DETAIL,CASE_INFO ,CASE_PROFILE,CASE_SCOPE,CASE_CAPITAL,CASE_OTRO ,CASE_FROM,CASE_TO,CASE_START,CASE_PERIOD,CASE_INTERVAL ,CASE_MODEL,CASE_VERSION ) # Dataframe with indicatos DFI_ORDER = "orden" DFI_DATE = "date" DFI_PRICE = "price" DFI_VOLUME = "volume" ######################################################################## ### FUNCTIONS ######################################################################## .generateLayouts <- function() { index = YATATable$new(TBL_INDEX, DF_CTC_INDEX) currency = YATATable$new(TBL_CURRENCY, DF_CTC_CTC) DBCurrencies = YATADB$new(DB_CURRENCIES) DBCurrencies$addTables(c(index, currency)) } .generateDBCases <- function() { DBCases = YATADB$new(DB_CASES) DBCases$addTables(c(YATATable$new(TBL_CASES, DF_CASES , groups=c(CASE_GRP_PARMS, CASE_GRP_THRESHOLDS) , numGroups=c(5,5))) ) } <file_sep>/YATAConfig/SQL/ctc_dat_parms.sql USE CTC; DELETE FROM PARMS; INSERT INTO PARMS ( NAME, TYPE, VALUE ) VALUES ("provider", 1 , "POLONIEX" ); INSERT INTO PARMS ( NAME, TYPE, VALUE ) VALUES ("range", 11 , "30" ); COMMIT; <file_sep>/YATACore/R/IND_Blackbox.R #When utilizing machine-learning methods to generate stock signals, the outputs are often multidimensional. # These multidimensional outputs easily interact with rule sets optimized to handle them but are most often # not worth visualizing. Not surprisingly, these strategies tend to be the most proprietary and have the highest # information latency when used correctly<file_sep>/YATACore/R/TBL_Clearing.R TBLClearing = R6::R6Class("TBLClearing", inherit=YATATable, public = list( # Column names ID = "ID_CLEARING" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,MAKER = "MAKER" ,TAKER = "TAKER" ,initialize = function() { self$name="Clearing"; self$table = "CLEARINGS"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) self$df$ACTIVE = as.logical(self$df$ACTIVE) } ,getCombo = function(item=NULL) { setNames(self$dfa[, self$ID], self$dfa[,self$NAME]) } ,setClearing = function(clearing) { self$df = self$dfa[self$dfa$ID_CLEARING == clearing,] } ,getFeeMaker = function() { as.numeric(paste0("0.", self$df[1, self$MAKER])) } ,getFeeTaker = function() { as.numeric(paste0("0.", self$df[1, self$TAKER])) } ,getName = function() { as.chracter(self$df[1, self$NAME]) } ) ,private = list ( ) ) <file_sep>/YATACore/R/TBL_INDGroups.R TBLIndGroups = R6::R6Class("TBLIndGroups", inherit=YATATable, public = list( # Column names ID = "ID_GROUP" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,initialize = function() { self$name="Groups"; self$table = "IND_GROUPS"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) self$df$ACTIVE = as.logical(self$df$ACTIVE) } ,getCombo = function() { setNames(self$dfa[, self$ID], self$dfa[,self$NAME]) } ) ,private = list ( ) ) <file_sep>/YATAWeb/R/tools.R #' @description Returns data for a combobox #' @param table Can be a YATATAble Class definition or an instance #' @param basedOn When not NULL and table base can be grouped, this parameter set the group makeCombo = function(table, basedOn=NULL) { if ("R6ClassGenerator" %in% class(table)) { t = table$new() } else { t = table } t$getCombo(basedOn) } Rmd2HTML = function(text) { # t = withMathJax(markdown::markdownToHTML(text=text, fragment.only=T)) #fname = paste0("IND_", self$symbol, ".Rmd") # f = system.file("rmd", "IND_SMA.Rmd", package = "YATAModels") # HTML(markdown::markdownToHTML(knit(f, quiet = TRUE))) HTML(markdown::markdownToHTML("test.md")) # if (file.exists(f)) { # txt = knit(text=read_file(f), quiet = TRUE) # } # HTML(markdown::markdownToHTML(knit('RMarkdownFile.rmd', quiet = TRUE))) #Encoding(t) = "UTF-8" #HTML(t) } makeList = function(values, names) { l = as.list(values) names(l) = names l } .prepareTable = function(df) { tmp = df; # Remove auxiliar column: PRICE p=which(colnames(tmp) == "Price") if (length(p) > 0) tmp = tmp[,-p[1]] #tblHead = .makeHead(tmp) tmp = .convertDates(tmp) #dt = datatable(tmp, container = tblHead, rownames = FALSE) dt = datatable(tmp, rownames = FALSE) .formatColumns(tmp, dt) } .makeHead <- function(data) { dfh = data.frame(head=character(), beg=integer(), len=integer(), stringsAsFactors = F) pat = "^[A-Z0-9]+_" w = str_extract(colnames(data), pat) prfx = unique(w) for (p in prfx) { if (!is.na(p)) { r = which(w == p) l = list(head=p, beg=r[1], len=length(r)) dfh = rbind(dfh, as.data.frame(l, stringAsFactors= F)) } } l = list(head="Data", beg=dfh[1,"beg"] - 1, len=dfh[1,"beg"]) dfh = rbind(as.data.frame(l, stringAsFactors= F), dfh) dfh$head = gsub('.{1}$', '', dfh$head) head2 = gsub(pat, "", colnames(data)) # htmltools::withTags(table( # class = 'display', # thead( # tr( # lapply(1:nrow(dfh), function(x) { print(x) ; th(colspan=dfh[x,"len"], dfh[x, "head"])}) # ), # tr( # lapply(head2, th) # ) # ) # )) } .convertDates = function(tmp) { datedCol = c() datetCol = c() for (col in colnames(tmp)) { if ("dated" %in% class(tmp[,col])) datedCol = c(datedCol, col) if ("datet" %in% class(tmp[,col])) datetCol = c(datetCol, col) } if (length(datedCol) > 0) { for (col in datedCol) tmp[,col] = as.Date(tmp[,col]) } if (length(datetCol) > 0) { for (col in datetCol) tmp[,col] = as.Date(tmp[,col]) } tmp } .formatColumns <- function(tmp, dt, decFiat=2) { ctcCol = c() lngCol = c() prcCol = c() datedCol = c() datetCol = c() fiatCol = c() numberCol = c() for (col in colnames(tmp)) { if ("fiat" %in% class(tmp[,col])) fiatCol = c(fiatCol, col) if ("ctc" %in% class(tmp[,col])) ctcCol = c(ctcCol, col) if ("long" %in% class(tmp[,col])) lngCol = c(lngCol, col) if ("number" %in% class(tmp[,col])) numberCol = c(numberCol, col) if ("percentage" %in% class(tmp[,col])) prcCol = c(prcCol, col) } if (length(ctcCol) > 0) dt = dt %>% formatRound(ctcCol, digits = 8) if (length(lngCol) > 0) dt = dt %>% formatRound(lngCol, digits = 0) if (length(prcCol) > 0) dt = dt %>% formatRound(prcCol, digits = 2) if (length(fiatCol) > 0) dt = dt %>% formatRound(fiatCol, digits = decFiat) if (length(numberCol) > 0) dt = dt %>% formatRound(numberCol, digits = 3) dt }<file_sep>/YATAClient/YATAClient/src/main/java/com/jgg/yata/client/providers/ProviderFactory.java package com.jgg.yata.client.providers; import com.jgg.yata.client.Providers; public class ProviderFactory { public static Provider getProvider(Providers provider) { switch (provider) { case POLONIEX: return (Provider) new ProviderPoloniex(); case BITTREX: return (Provider) new BittexProvider(); default: return null; } } } <file_sep>/YATACore/R/TBL_Currencies_FIAT.R TBLFiat = R6::R6Class("TBLFiat", inherit=YATATable, public = list( SYMBOL = "SYMBOL" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,DECIMALS = "DECIMALS" ,initialize = function() { self$name="Currencies"; self$table = "CURRENCIES_FIAT"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) self$df$ACTIVE = as.logical(self$df$ACTIVE) } ,getDecimals = function(symbol) { self$df[self$df$SYMBOL == symbol, "DECIMALS"] } ) ,private = list ( ) ) <file_sep>/YATAConfig/SQL/ctc_dat_all.sql source ctc_dat_codes.sql source ctc_dat_parms.sql source ctc_dat_providers.sql source ctc_dat_ctc.sql source ctc_dat_fiat.sql source ctc_dat_pairs.sql source ctc_dat_pairs.sql source ctc_dat_portfolio.sql source ctc_dat_profiles.sql source ctc_dat_ind.sql source ctc_dat_ind_parms.sql source ctc_dat_messages.sql<file_sep>/YATACore/R/PKG_Main.R library(R.utils) library(lubridate) library(XLConnect) library(stringr) library(zoo) library(RMariaDB) library(YATAProviders) library(rlist) library(dplyr) YATAVARS <- R6::R6Class("YATAVARS" ,public = list( SQLConn = list() ,lastErr = NULL ,tmpConn = NULL ,msg = NULL ,addConn = function (SQLConn = NULL) { if (is.null(SQLConn)) SQLConn = openConnection() self$SQLConn = c(SQLConn, self$SQLConn) SQLConn } ,getConn = function() { tmp = NULL if (length(self$SQLConn) > 0) tmp = self$SQLConn[[1]] tmp } ,removeConn = function(disc = T) { if (length(self$SQLConn) == 0) return (NULL) tmp = self$SQLConn[[1]] if (disc) closeConnection(tmp) self$SQLConn = self$SQLConn[-1] } ) ) coreVars = YATAVARS$new() #' Create the global object YATAENV #' #' @note This function should be called before any process #' #' @param cases If TRUE also create the object DBCases #' @export createEnvironment <- function() { # if (!exists("YATAENV")) { YATAENV <<- YATAEnvironment$new() # DBCTC <<- createDBCurrencies() # DBModels <<- createDBModels() # } } #' @export cleanEnvironment = function() { tmp = coreVars$getConn() while (!is.null(tmp)) { closeConnection(tmp) tmp = coreVars$getConn() } } #' @export getMessage = function(code, ...) { # Lazy Loading if (is.null(coreVars$msg)) coreVars$msg = TBLMessages$new() coreVars$msg$getMessage(code) } #' Clase de configuracion general #' #' @export #' ################################### AQUI ################################################ executeSimulation <- function(case=NULL) { if (is.null(case)) stop(MSG_NO_CASE()) xlcFreeMemory() gc() portfolio = YATAPortfolio$new() a=YATAActive$new(case$config$symbol) portfolio$addActive(a) portfolio$flowFIAT(case$config$from, case$profile$capital) calculateIndicators(case) while (case$hasNext()) { nextTicker(case, portfolio) portfolio$updatePosition(case) } portfolio } #' @export nextTicker <- function(case, portfolio) { case$current = case$current + 1 action = case$model$calculateAction(case, portfolio) if (action[1] == 0) return(OP_NONE) case$oper = case$model$calculateOperation(portfolio, case, action) if (is.null(case$oper)) return(OP_NONE) if (case$config$mode == MODE_AUTOMATIC) { portfolio$flowTrade(case$oper) return (OP_EXECUTED) } return (OP_PROPOSED) } #' @export calculateIndicators <- function(case) { model = case$model tIndex = DBCTC$getTable(TCTC_INDEX) case$config$dec = tIndex$select(case$config$symbol)[1,tIndex$DECIMAL] case$trend = case$tickers$getTrend() model$calculateIndicatorsGlobal(case$tickers) } <file_sep>/YATACore/R/PKG_Common.R # Aplica el threshold si procede # threshold esta en 0-100 (pasar a porc) # Si DARED no se mira applyThreshold = function(prf, var, threshold) { tipo = ifelse(var > 1, -1, 1) if (prf == PRF_DARED) return(c(tipo,0,0)) if (var > 1) var = var - 1 if (var < 1) var = 1 - var if (var < threshold) return (c(0,0,0)) tipo = tipo * cut(var / threshold, breaks=c(0.9,1.5,2,3,4,+Inf ), labels=FALSE) return (c(tipo,0,0)) } SplineSmooth <- function(formula, data, weights, span = 0.5, ...) { pred <- smooth.spline(data$x, data$y, df = length(data$y)*span,...)$y # print(pred[1:10]) model <- list(x = data$x, pred = pred) class(model) <- "my_smooth" model } predictdf.my_smooth <- function(model, xseq, se, level) { data.frame(x = model$x, y = model$pred) } calculateChange <- function(x) { if (x[1] == 0) return (0) return ((x[2] / x[1]) - 1) } <file_sep>/YATACore/R/R6_YATAEnvironment.R #' Global Environment data for YATA System #' #' @title YATAEnv #' #' @docType class #' @description Class to manage global configuration. #' Todos los atributos son publicos y tienen un valor por defecto #' Se pueden cambiar de manera global mediante \code{YATAENV$attribute <- ...} #' #' #' @export YATAEnvironment <- R6Class("YATAEnvironment", public = list( provider = "POL" # proveedor de datos ,period = "D1" # Periodo en uso ,currency="USDT" ,base = NULL ,dirRoot="D:/R/YATA" ,dirOut=NULL ,dirData=NULL ,dataSourceDir=NULL ,dataSourceDBName = "currencies" ,dataSourceDBType = IO_SQL ,modelsDBDir = NULL ,modelsDBName = "Models" ,modelsDBType = IO_SQL ,modelPrefix = "IND_" ,modelBase = "YATAModels" ,modelsDir = NULL ,modelsMan = NULL ,outputType = IO_CSV ,templateSummaryFile="sprintf('sum_%s_%s',#SYM#, #MODEL#)" ,templateSummaryData="sprintf('det_%s_%s',#SYM#, #MODEL#)" ,parms = NULL ,profile = NULL ,fiat = NULL ,indGroups = NULL ,indNames = NULL ,lastErr = NULL ,initialize = function(root=NULL) { if (!is.null(root)) self$dirRoot = root self$dirData = private$envFilePath(self$dirRoot, "YATAData") self$modelsDBDir = private$envFilePath(self$dirData, "in") self$modelsDir = private$envFilePath(self$dirRoot, "YATAModels/R") self$modelsMan = private$envFilePath(self$dirRoot, "YATAModels/doc") self$dataSourceDir = private$envFilePath(self$dirData, "in") self$dirOut = private$envFilePath(self$dirData, "out") # self$parms = loadParameters() self$fiat = TBLFiat$new() self$indGroups = TBLIndGroups$new() self$indNames = TBLIndNames$new() } ################################################################################ ### WRAPPERS FOR PARAMETERS ############################################################################### ,loadProfile = function() { df = getProfile() if (nrow > 0) { self$CURRENCY = df[1,"CURRENCY"] } } ,getParameter = function(parm, def=NA) { if (is.null(self$parms)) return (def) rec = self$parms[self$parms$NAME == parm,] if (nrow(rec) == 0) return (def) setDataType(rec[1,"TYPE"], rec[1,"VALUE"]) } ,getProvider = function() { if (is.null(self$provider)) { provider = self$getParameter(PARM_PROVIDER) if (is.na(provider)) stop(MSG_NO_PROVIDER(provider)) self$provider = YATAProvider$new(provider) } self$provider } ,getRangeInterval = function() { self$getParameter(PARM_RANGE, 0) } # Wrappers ,getProviderPrefix = function() { provider = self$getProvider() provider$prefix } ) ,private=list( envFilePath = function(..., name=NULL,ext=NULL) { txt="" if (length(list(...)) > 0) { args=as.character(list(...)) txt=args[1] i=1 while (i < length(args)) { i = i + 1 txt = paste(txt,args[i],sep="/") } } if (!is.null(name)) txt=paste(txt,name,sep="/") if (!is.null(ext)) txt=paste(txt,ext ,sep=".") gsub("\\/", "/",gsub("//", "/",txt)) } ) ) <file_sep>/YATACore/R/R6_YATATickers.R # Tickers no es una tabla YATATickers = R6::R6Class("YATATickers", public = list(provider = NULL ,TMS = "TMS" ,BASE = "BASE" ,COUNTER = "COUNTER" ,HIGH = "HIGH" ,LOW = "LOW" ,LAST = "LAST" ,VOLUME = "VOLUME" ,ASK = "ASK" ,BID = "BID" ,CHANGE = "CHANGE" ,VAR = "VAR" ,SESSION = "SESSION" ,CLOSE = "CLOSE" ,points = 0 ,inError = FALSE ,lastError = "" ,df = NULL #######################################################33 ,refresh = function() { # Por logica de programa se llama tras initialize if (private$first) { private$first = FALSE } else { curr = private$getLastTickers() if (is.null(curr)) return (NULL) private$dfTickers = rbind(private$dfTickers, curr) private$calculateAll(curr) private$dfLast = curr } } ,initialize = function() { dfSes = getLastSessions() cols = c(self$TMS, self$BASE, self$COUNTER, self$CLOSE, self$VOLUME) private$dfSession = dfSes[ ,cols] dfAct = private$getLastTickers() if (!is.null(dfAct)) { private$dfTickers = dfAct private$dfFirst = dfAct private$dfLast = dfAct private$calculateAll(private$dfFirst) private$bases = unique(private$dfFirst$BASE) } self$setBase(private$bases[1]) } ,getBases = function() { private$bases } ,getCounters = function() {unique(self$df$COUNTER) } ,setBase = function(base) { private$base = base self$df = private$dfTickers %>% filter(BASE == private$base) } ,getTickers = function(reverse = T) { private$getDF(private$dfTickers, reverse) } ,getVarFirst = function(reverse = T) { private$getDF(private$dfVarFirst, reverse) } ,getVarLast = function(reverse = T) { private$getDF(private$dfVarLast, reverse) } ,getVarSession = function(reverse = T) { private$getDF(private$dfVarSession, reverse) } ,getLast = function() { private$dfLast %>% filter(BASE == private$base) } ,getRange = function() { private$dfTickers %>% filter(BASE == private$base) } ,setPoints = function(points) { self$points = points } ,print = function() { print(private$base) } ) ,private = list(first = TRUE ,dfSession = NULL ,dfFirst = NULL ,dfLast = NULL ,dfTickers = NULL ,dfVarLast = NULL ,dfVarFirst = NULL ,dfVarSession = NULL ,bases = NULL ,base = NULL ,getDF = function(df, reverse) { tmp = df %>% filter(BASE == private$base) # column 1 es TMS if (reverse) tmp = tmp[seq(dim(tmp)[1],1),] tmp } ,getLastTickers = function() { tmp = YATAProviders::getTickers() # Control de error if ("character" %in% class(tmp)) { self$inError = TRUE self$lastError = tmp return (NULL) } tmp$CHANGE = tmp$CHANGE * 100 # A veces hay discrepancias entre la sesion y los tickers # solo tratamos aquellos datos de los que tenemos cierre cols = c(self$BASE, self$COUNTER) dfm = merge(tmp, private$dfSession[, cols]) dfm = private$calcVarTickers(dfm) private$adjustTypes(dfm) } ,calculateAll = function(curr) { # Variacion respecto al ultimo ticker dfvar = private$calculateVar(curr, private$dfLast) private$dfVarLast = rbind(private$dfVarLast, dfvar) # Variacion respecto al inicio de sesion dfvar = private$calculateVar(curr, private$dfFirst) private$dfVarFirst = rbind(private$dfVarFirst, dfvar) # Variacion respecto al cierre anterior cols = c(self$TMS, self$BASE, self$COUNTER, self$LAST, self$VOLUME) dfX = curr[,cols] tmp = private$calculateVar(dfX, private$dfSession) private$dfVarSession = rbind(private$dfVarSession, tmp) } ,calculateVar = function(curr, prev) { last = curr # Merge para que no haya problemas de dimensiones cols = c(self$BASE, self$COUNTER) tmp = merge(last, prev, by=cols) colsT = colnames(tmp) colsX = colsT[grepl(".x", colsT)] for (col in colsX) { colbase = substr(col, 1, nchar(col) - 2) cols = c(paste0(colbase, ".x"), paste0(colbase, ".y"), colbase) if (is.numeric(tmp[,cols[1]])) tmp[,cols[3]] = ((tmp[,cols[1]] / tmp[,cols[2]]) - 1) * 100 } tmp = replace(tmp, is.na(tmp), 0) colnames(tmp) = sub("TMS.x", "TMS", colnames(tmp)) colsDot = grepl(".[xy]", colnames(tmp)) tmp[, !colsDot] } ,calcVarTickers = function(act) { cols = c(self$BASE, self$COUNTER, self$LAST) dfa = act if (is.null(private$dfFirst)) { dfa$VAR = 0.0 dfa$SESSION = 0.0 } else { dfa$VAR = private$calcVarField(dfa[,cols], private$dfLast[,cols]) dfa$SESSION = private$calcVarField(dfa[,cols], private$dfFirst[,cols]) } dfs = private$dfSession[,c("BASE", "COUNTER", "CLOSE")] dft = dfa[,cols] dfm = merge(dfa, dfs) dfm$CLOSE = ((dfm[,"LAST"] / dfm[,"CLOSE"]) - 1) * 100 dfa$CLOSE = dfm$CLOSE dfa } ,calcVarField = function(dfx, dfy) { cols = c(self$BASE, self$COUNTER) dfm = merge(dfx, dfy, by=cols) dfm$VAR = ((dfm[,"LAST.x"] / dfm[,"LAST.y"]) - 1) * 100 dfm$VAR } ,adjustTypes = function(tmp) { tmp[,self$TMS] = as.datet(tmp[,self$TMS]) tmp[,self$HIGH] = as.fiat(tmp[,self$HIGH]) tmp[,self$LOW] = as.fiat(tmp[,self$LOW]) tmp[,self$LAST] = as.fiat(tmp[,self$LAST]) tmp[,self$ASK] = as.fiat(tmp[,self$ASK]) tmp[,self$BID] = as.fiat(tmp[,self$BID]) tmp[,self$CHANGE] = as.percentage(tmp[,self$CHANGE]) tmp[,self$VAR] = as.percentage(tmp[,self$VAR]) tmp[,self$SESSION] = as.percentage(tmp[,self$SESSION]) tmp[,self$CLOSE] = as.percentage(tmp[,self$CLOSE]) tmp[,self$VOLUME] = as.long(tmp[,self$VOLUME]) tmp } ) ) <file_sep>/YATACore/R/PKG_CTES.R # Execution mode MODE_AUTOMATIC = 0 MODE_INQUIRY = 1 MODE_MANUAL = 2 # Status of operation OP_PENDING = 0 OP_EXECUTED = 1 OP_PROPOSED = 2 OP_BUY = 1 OP_SELL = -1 OP_NONE = 0 # Risk profiles PRF_DARED = 5 # Ignora todo PRF_BOLD = 4 # Considera thresholds y alguna cosa PRF_MODERATE = 3 # Considera todo PRF_CONSERVATIVE = 2 PRF_SAVER = 1 # Tipos de indicadores IND_POINT = 1 IND_LINE = 2 IND_LINE_MULT = 3 IND_OVERLAY = 11 IND_OSCILLATOR = 12 IND_aCCUMULATOR = 13 IND_PATTERN = 14 IND_MACHINE = 15 IND_BLACKBOX = 16 PLOT_FUNC = vector() PLOT_FUNC[IND_POINT] = "plotPoint" PLOT_FUNC[IND_LINE] = "plotLine" PLOT_FUNC[IND_LINE_MULT] = "plotLines" PLOT_FUNC[IND_OVERLAY] = "plotLine" # Fuentes de datos SRC_XLS="XLS" SRC_DB="MySQL" # Modes for I/O IO_XLS="XLS" IO_CSV="CSV" IO_SQL="SQL" # Default FIAT currency CURRENCY = "EUR" # Common names for columns DF_PRICE = "Price" DF_DATE = "Date" DF_ORDER = "Order" DF_TOTAL = "Total" DF_TYPE = "Type" # Messages MSG_METHOD_READ_ONLY = function(txt) {cat(sprintf("%s is read only", txt))} MSG_BAD_CLASS = function(txt) {cat(sprintf("Object is not a %s", txt))} MSG_NO_NAME = function(txt) {cat(sprintf("%s must have a name", txt))} MSG_MISSING = function(txt) {cat(sprint("%s must be specified\n", txt))} MSG_NO_MODELS = function() {cat("There is not active models")} MSG_NO_ACTIVES = function() {cat("No hay activos en la cartera\n")} MSG_BAD_ARGS = function() {cat("Argumentos del metodo erroneos")} MSG_NO_CASE = function() {cat("No se puede ejectuar la simulacion sin un caso")} MSG_NO_PROVIDER = function(txt) {cat(sprint("There is not information about provider %s\n", txt))} <file_sep>/YATACore/R/TBL_Flows.R TBLFlow = R6::R6Class("TBLFlow", inherit=YATATable, public = list( # Column names ID_OPER = "ID_OPER" ,ID_FLOW = "ID_FLOW" ,TYPE = "TYPE" ,CLEARING = "CLEARING" ,BASE = "BASE" ,CURRENCY = "CURRENCY" ,PROPOSAL = "PROPOSAL" ,EXECUTED = "EXECUTED" ,MAXLIMIT = "MAXLIMIT" ,FEE_BLOCK = "FEE_BLOCK" ,FEE_EXCH = "FEE_EXCH" ,TMS_PROPOSAL = "TMS_PROPOSAL" ,TMS_EXECUTED = "TMS_EXECUTED" ,TMS_LIMIT = "TMS_LIMIT" ,TMS_CANCEL = "TMS_CANCEL" ,REFERENCE = "REFERENCE" ,initialize = function() { self$name="Flows"; self$table = "FLOWS"; } ) ,private = list ( ) ) <file_sep>/YATATest/R/YATATest.R detach("package:YATA", unload=T) library(R6) library(dplyr) library(rlist) library(XLConnect) library(lubridate) library(mondate) library(zoo) library(YATA) ENV=YATAEnv$new() # options(java.parameters = "-Xmx1024m") # files.config = list.files("D:/prj/R/YATA/YATAConfig/R", pattern="*.R$", full.names=TRUE, ignore.case=F) # sapply(files.config,source,.GlobalEnv) # # files.layout = list.files("D:/prj/R/YATA/YATAData/R", pattern="*.R$", full.names=TRUE, ignore.case=F) # sapply(files.layout,source) # ,.GlobalEnv) # XLS_CASES="d:/prj/R/YATA/YATAData/in/cases.xlsx" MIN_PERCENTAGE=0.75 # Minimo rango de datos que se deben cumplir dfSumm = NULL #' Prueba #' #' @import YATACore #' YATABatch <- function(ids=NULL) { createEnvironment(cases=T) cases = .prepareCases(ids) cat(sprintf("%d casos preparados\n", nrow(cases))) nCases = .executeCases(cases) cat(sprintf("%d casos ejecutados\n", nCases)) tNow=Sys.time() summFileName = paste("batch", strftime(tNow,format="%Y%m%d"), strftime(tNow,format="%H%M%S"), sep="_") writeSummary(dfSumm, NULL, summFileName) # sh = .loadCases(1) # prf = .makeProfile(sh) # print(sh) } .prepareCases <- function(ids) { dfTotal = NULL TBCases = DBCases$getTable(TBL_CASES) dfCases = loadCases(DBCases$name, TBCases$name) if (!is.null(ids)) { #idLst=eval(parse(text=paste("rep(",ids,")",sep=""))) dfCases = dfCases %>% filter(eval(parse(text=CASE_ID)) %in% ids) } for (iCase in 1:nrow(dfCases)) { dfIndex = loadCurrencies(dfCases[iCase,CASE_FROM], dfCases[iCase,CASE_TO]) for (iCurrency in 1:nrow(dfIndex)) { df = .makeIntervals(dfIndex[iCurrency,IDX_SYMBOL], TBCases, as.list(dfCases[iCase,])) df[,IDX_NAME] = dfIndex[iCurrency, IDX_NAME] df[,IDX_SYMBOL] = dfIndex[iCurrency, IDX_SYMBOL] df[,CASE_ID] = dfCases[iCase, CASE_ID] df[,CASE_CAPITAL] = dfCases[iCase, CASE_CAPITAL] df[,CASE_MODEL] = dfCases[iCase, CASE_MODEL] df[,CASE_VERSION] = dfCases[iCase, CASE_VERSION] if (is.null(dfTotal)) { dfTotal = df } else { dfTotal = rbind(dfTotal, df) } } } dfTotal } .executeCases <- function(cases) { nCases = 0 for (iCase in 1:nrow(cases)) { xlcFreeMemory() gc() record = cases[iCase,] profile = .createProfile(record) config = .createConfig(record) model = .createModel(record) data = .createData(record) if (!is.null(data)) { nCases = nCases + 1 cat(sprintf("Executing case %6d (%06d) ", nCases, iCase)) tBeg = proc.time() case = YATACase$new(profile, data, model, config) portfolio = YATA::executeSimulation(case) tEnd = proc.time() elapsed = tEnd["elapsed"] - tBeg["elapsed"] .addSummary(iCase, elapsed, record, case, portfolio) cat(sprintf(" - %3.0f\n", elapsed)) } } nCases } .addSummary <- function(index, elapsed, record, case, portfolio) { idTest = paste(record[1,CASE_MODEL], as.numeric(Sys.Date()), sep="_") model = record[1,CASE_MODEL] if (!is.na(record[1,CASE_VERSION])) model = paste(model, record[1,CASE_VERSION], sep='.') lPrfx = list(date=Sys.Date(), orden=index, id=idTest, elapsed=elapsed) lCase = list(record[1,]) lPos = list(portfolio$position()) lista = list.append(lPrfx, lCase, Trend=case$trend,lPos) summRec = as.data.frame(lista) if (is.null(dfSumm)) { dfSumm <<- summRec } else { dfSumm <<- rbind(dfSumm, summRec) } } .makeIntervals <- function(symbol, TBCases, ...) { prms = list(...)[[1]] data = loadData(symbol) beg=as.Date(ifelse(is.na(prms[[CASE_START]]), data[1,CTC_DATE], as.character(prms[[CASE_START]]))) last= as.Date(as.character(data[nrow(data),CTC_DATE])) prf = .expandNumber(prms[[CASE_PROFILE]]) per = .expandNumber(prms[[CASE_PERIOD]]) start = .expandMonth(beg,last,prms[[CASE_INTERVAL]]) end = as.mondate(start) + per end = as.Date(end) cols = list(prf, start, per, end) colNames = c(CASE_PROFILE, CASE_START, CASE_PERIOD, CASE_END) parms = TBCases$getGroupFields(CASE_GRP_PARMS) for (parm in parms) { if (is.na(prms[[parm]])) break; prm = .expandNumber(prms[[parm]]) cols = list.append(cols, prm) colNames = c(colNames, parm) } gr = expand.grid(cols) df = data.frame(gr) colnames(df) <- colNames df } .expandNumber <- function(num) { toks=strsplit(as.character(num), ":")[[1]] if (length(toks) == 1) toks = c(toks, toks) seq(from=toks[1],to=toks[2]) } .expandMonth <- function(beg, end, interval) { if (interval == 0) return(beg) seq(from=beg, to=end, by=paste(interval, "months")) } .createProfile <- function(record) { profile = YATAProfile$new() profile$name = "Batch" profile$profile = record[1,CASE_PROFILE] profile$scope=record[1,CASE_SCOPE] profile$saldo=record[1,CASE_CAPITAL] profile } .createConfig <- function(record) { config = YATAConfig$new() config$symbol = record[1,CASE_SYM_SYM] config$from = record[1,CASE_START] config$to = record[1,CASE_END] config$initial = record[1,CASE_CAPITAL] config } .createData <- function(record) { data = YATAData$new() data$name = record[1,CASE_SYM_NAME] data$symbol = record[1,CASE_SYM_SYM] data$start = record[1,CASE_START] data$end = record[1,CASE_END] df = loadData(data$symbol) tgt = df %>% filter(Date >= data$start, Date <= data$end) # Verificar rango de datos if ((nrow(tgt) / (record[1,CASE_PERIOD] * 30)) < MIN_PERCENTAGE) return (NULL) data$dfa = df data } .createModel <- function(record) { name=record[1,CASE_MODEL] if (!is.na(record[1,CASE_VERSION])) name = paste(name,record[1,CASE_VERSION],sep=".") model = loadModel(name) model$setParameters(as.vector(record[1, grep(CASE_GRP_PARMS, colnames(record))])) model # base=eval(parse(.makeDir(DIRS["models"],"Model_Base.R"))) # file=.makeDir(DIRS["models"], paste(paste("Model_",name,sep=""),"R",sep=".")) # mod=eval(parse(file)) # model = eval(parse(text=paste(MODEL_PREFIX, name, "$new()", sep=""))) # model } <file_sep>/YATACore/R/R6_YATACase.R # Caso # Contiene: # - Una configuracion inicial # - Un modelo # - Una posible operacion pendiente (o ejecutada) # - los datos de trabajo # YATACase <- R6Class("YATACase", public = list( profile = NULL # Investor attributes ,tickers = NULL # Data ,model = NULL # Modelo activo ,config = NULL # Configuration ,oper = NULL # Orden a procesar/procesada ,current = 0 # Registro actual ,trend = 0.0 # Tangente de la linea ,date = Sys.Date() # Execution date ,hasNext = function() { (self$current < self$getNumTickers()) } ,getNumTickers = function() { nrow(self$tickers$df) } ,getCurrentTicker = function() { self$tickers$df[self$current,] } ,getCurrentData = function(asClass=F) { if (!asClass) return (self$tickers$df[1,self$current]) tmp = self$tickers$clone() tmp$filterByRows(1,self$current) tmp } ) ) <file_sep>/YATAWeb/ui/modPortfolioServer.R modPortfolio <- function(input, output, session) { shinyjs::runjs(paste0("YATAPanels('", session$ns(""), "')")) vars <- reactiveValues( loaded = F ,tab = "General" ,plot = 2 ,TPortfolio = NULL ,TSession = NULL ,nDays = 60 ,symbols = NULL ,tickers = list() ,vars = list() ,last = NULL ,plots = c() # Index de los graficos ,tabs=c("general") ) plotTypes = list("Linear" = 1, "Log" = 2, "Bar" = 3, "Candle" = 4) ######################################################################################## ### PRIVATE CODE ######################################################################################## # panelMain <- function(pref) { # ns = NS(pref) # useShinyjs() # panelMain = tagList(fluidRow( # checkboxGroupInput(ns("variable2"), "Variables to show:", # c("Cylinders2" = "cyl", # "Transmission2" = "am", # "Gears2" = "gear")) # ) # ,fluidRow(plotlyOutput(ns("plotPortfolio"), width="100%",height="500px")) # ,fluidRow(DT::dataTableOutput(ns("tblPortfolio"))) # ,fluidRow(actionButton(ns("BotonXXX"), "BotonXXX")) # ) # panelMain # } # # panelLeft <- function(ctc) { # tagList( # tags$div(id=session$ns("left-ctc") # ,radioButtons(session$ns(paste0(ctc, "-swPlt1S")), "Primary" , selected = 1, choices = list("Price" = 1, "Volume" = 2)) # ,radioButtons(session$ns(paste0(ctc, "-swPlt2S")), "Secondary", selected = 2, choices = list("Price" = 1, "Volume" = 2)) # ,radioButtons(session$ns(paste0(ctc, "-swPlt3S")), "Terciary" , selected = 4, choices = list("None" = 4, "Variation" = 3, "Volume" = 2)) # ,selectInput(session$ns(paste0(ctc, "-swPlt1T")), "Tipo Primary", selected = 1, choices = plotTypes) # ,selectInput(session$ns(paste0(ctc, "-swPlt2T")), "Tipo Primary", selected = 3, choices = plotTypes) # ,selectInput(session$ns(paste0(ctc, "-swPlt3T")), "Tipo Primary", selected = 1, choices = plotTypes) # ,hr() # ,bsButton(session$ns(paste0(ctc, "-btnConfig")), "JGGMoneda", icon = icon("check"), style = "primary") # ) # ) # } addClearings = function() { TClearing = TBLClearing$new() names = c("General", TClearing$df[,TClearing$NAME]) values = c("General", TClearing$df[,TClearing$ID]) updateMenuTab(session, "tabs", choiceNames=names, choiceValues=values) # apply(TClearing$df, 1, function(x) { # appendTab(inputId = "tabs", tabPanel(x[TClearing$NAME], value=x[TClearing$ID]))} # ) } loader = function() { browser() addClearings() vars$TPortfolio = TBLPortfolio$new() vars$symbols = vars$TPortfolio$getCTCSymbols() # updateRadioGroupButtons(session, "clearings", choices=TClearing$getCombo(), status="success") # browser() for (sym in vars$symbols) { tmp = TBLSession$new(sym, TBL_DAY, YATAENV$currency) tmp$filterByRows(vars$nDays * -1) tmpVar = TBLSession$new(source=tmp) tlast = tmp$filterByRows(nrow(tmp$df),nrow(tmp$df)) pos <- which(names(tlast)==tmpVar$DATE) tlast = data.frame(tlast[1:pos],Counter=tmp$symbol,tlast[(pos+1):ncol(tlast)]) vars$last = rbind(vars$last, tlast) vars$tickers = list.append(vars$tickers, tmp) vars$vars = list.append(vars$vars, tmpVar) } names(vars$tickers) = vars$symbols names(vars$vars) = vars$symbols renderPlot() output$tblSessions = DT::renderDataTable({ renderTable() }) } renderPlot = function() { titles = c("Prices (linear mode)", "Prices (log mode)", "Volume (Linear mode)", "Volume (Log mode)") output$txtMainPlot = renderPrint({ cat(titles[vars$plot]) }) p = renderSessions() if (!is.null(p)) { # Caso no hay datos p %>% layout (legend = list(orientation = 'h', xanchor="center", x=0.5)) output$plotSessions = renderPlotly({ p }) } } renderSessions = function() { if (input$swValue == 0) lData = vars$tickers else lData = vars$vars if (is.null(lData) || length(lData) == 0) return (NULL) tsample = lData[[1]] value = ifelse (input$swSource == 0, tsample$PRICE, tsample$VOLUME) p <- plot_ly(source="X") for (idx in 1:length(lData)) { ticker = lData[[idx]] df = ticker$df if (nrow(df) == 0) { browser() } x = df[,ticker$DATE] y = df[,value] if (input$swPlot == 1) p = YATACore::plotLine (p, x, y, hoverText=ticker$symbol) if (input$swPlot == 2) p = YATACore::plotLog (p, x, y, hoverText=ticker$symbol) if (input$swPlot == 3) p = YATACore::plotBar (p, x, y, hoverText=ticker$symbol) if (input$swPlot == 4 && input$swSource == 0) { p = YATACore::plotCandle (p, x, df[,ticker$OPEN], df[,ticker$CLOSE], df[,ticker$HIGH],df[,ticker$LOW], hoverText=ticker$symbol) } } p # ax <- list(title = "",zeroline = FALSE,showline = FALSE,showticklabels = FALSE,showgrid = FALSE) # m <- list(l = 2,r = 2,b = 2,t = 2,pad = 1) # if (main) vars$plots = isolate(c()) # # p <- plot_ly(source=ifelse(main, "X", type)) # # index = 1 # for (ticker in vars$tickers) { # df = ticker$df # if (nrow(df) > 1) { # if (main) vars$plots = isolate(c(vars$plots, index)) # if (type == 1) p = YATACore::plotLine (p, df[,ticker$DATE], df[,ticker$PRICE], hoverText=ticker$symbol) # if (type == 2) p = YATACore::plotLog (p, df[,ticker$DATE], df[,ticker$PRICE], hoverText=ticker$symbol) # if (type == 3) p = YATACore::plotLine (p, df[,ticker$DATE], df[,ticker$VOLUME], hoverText=ticker$symbol) # if (type == 4) p = YATACore::plotLog (p, df[,ticker$DATE], df[,ticker$VOLUME], hoverText=ticker$symbol) # } # index = index + 1 # } # # # Quitar ejes # if (!main) p = p %>% layout(xaxis= ax, yaxis = ax, showlegend=F, margin=m) # p } makeTableSession = function(df) { # Remove auxiliar column: PRICE p=which(colnames(df) == "Price") if (length(p) > 0) tmp = df[,-p[1]] tblHead = .makeHead(df) dt = datatable(df, container = tblHead, rownames = FALSE) dt = .formatColumns(df, dt) dt } renderTable = function() { makeTableSession(vars$last) } renderData = function() { browser() clearing = vars$tab if(vars$tab == "General") clearing = NULL df = vars$TPortfolio$getClearingPosition(clearing) } ######################################################################################## ### OBSERVERS ######################################################################################## observeEvent(input$btnConfig, { browser() print("Update") }) observeEvent(input$tabs, { browser() vars$tab = input$tabs renderData() lbar = paste0(session$ns(""), "left-") if (input$tabs != "General") { # htmlwidgets::JS("iconNavJS(0)") shinyjs::runjs(paste0("toggleSideBar('", lbar, "ctc', '", lbar, "main')")) callModule(modCurrency, input$tabs, input$tabs) } else { #htmlwidgets::JS("iconNavJS(1)") shinyjs::runjs(paste0("toggleSideBar('", lbar, "main', '", lbar, "ctc')")) } }) # observeEvent(event_data("plotly_click", source = "1"), { vars$plot = 1; plotDefault() }) # observeEvent(event_data("plotly_click", source = "2"), { vars$plot = 2; plotDefault() }) # observeEvent(event_data("plotly_click", source = "3"), { vars$plot = 3; plotDefault() }) # observeEvent(event_data("plotly_click", source = "4"), { vars$plot = 4; plotDefault() }) observeEvent(event_data("plotly_click", source = "X"), { d = event_data("plotly_click", source = "X") ctc = vars$symbols[d$curveNumber + 1] if (ctc %in% vars$tabs) { updateTabsetPanel(session, "tabs", selected = ctc) } else { ns = session$ns("") vars$tabs = c(vars$tabs, ctc) appendTab(inputId = "tabs", select = TRUE, tabPanel(HTML(paste('<i class="fa fa-close" onclick=\"alert(\'HALA\')\"></i>',ctc)) ,id=paste0(session$ns(""), ctc), value=ctc ,modCurrencyUI(paste0(session$ns(""), ctc))) ) insertUI(selector = "#prf-left", immediate = TRUE, ui=panelLeft(ctc)) } }) ################################################################# ### PRIVATE FUNCTIONS ### ################################################################# ################################################################# ### SERVER CODE ### ################################################################# if (is.null(vars$TPortfolio)) loader() observeEvent(input$btnConfig, { output$plotSessions = renderPlotly({renderSessions()}) }) } <file_sep>/YATACore/R/R6_YATALayout.R Model_Base <- R6Class("Model_Base", public = list( name="Modelo abstracto" ,symbolBase="NONE" ,symbol="NONE" ,colPrice="Close" ,indicators=NULL ,entry = "caso$dfi[caso$curr, 'lmcd'] > 2" # Cuando entramos en la moneda ,initial = 0.5 ,prob ="lmcd" ,createPrimaryIndicators = function(data) {stop("This class is virtual") } ,createSecondaryIndicators = function(data) {stop("This class is virtual") } ,invertir = function(curr) {stop("This class is virtual") } ,entrada = function(cartera) {stop("This class is virtual") } ,calculateAction = function(cartera, caso, reg) { stop("This class is virtual") } ,calculateOperation = function(cartera, caso, reg, action) { stop("This class is virtual") } ,createIndicatorsSecondary = function(data) { data } ,createIndicatorsTerciary = function(data) { data } ,plotIndicatorsSecondary = function(plots) { plots } ,plotIndicatorsTerciary = function(plots) { plots } ,getRmdDoc = function() { stop("This class is virtual") } ,print = function() { cat(self$name) } ,createIndicatorsPrimary = function(data) { d = data[,c("Date", self$colPrice, "Volume")] colnames(d) <- c("date", "price", "volume") d$date = as.Date(d$date) d$pmm = 0 d$oper = 0 v0 <- rollapply(d$price, 2 , function(x) return (((x[2] / x[1]) - 1) * 100) , fill=NA, align="right") cbind(d, v0) } ,plotIndicatorsPrimary = function(plots) { plots[1][[1]] = plots[1][[1]] + geom_smooth(method="lm", na.rm=T) return (plots) } ) ,private = list( getParameters = function(reg) { parms = list() names = c() idx=5 # Los parametros empiezan en la 5 while (idx <= ncol(reg)) { if (!is.na(reg[1,idx])) { parms[length(parms) + 1] = reg[1,idx] names=c(names, reg[1,idx-1]) idx = idx + 2 # Nombre/valor } else { names(parms) = names return (parms) } } NULL } ) ) <file_sep>/YATACore/R/IND_Overlays.R # Overlays are best characterized by their scale. # Overlays typically have the same or similar scale to the # underlying asset and are meant to be laid over to chart of price history #Common examples are the simple #moving average, Bollinger Bands, and volume-weighted average price # Single mobile average #' @export SMA <- function(data,interval=7) { res = rollapply(data$df[,data$PRICE],interval,mean,fill=NA, align="right") as.data.frame(res) } #' @description Calculate the best spline line for the data #' @param data Values to spline #' @param ind Not used #' @param columns Not used SPLINE <- function(data=NULL, ind=NULL, columns=NULL) { res1 = supsmu(data$df[,data$ORDER], data$df[,data$PRICE]) res2 = supsmu(data$df[,data$ORDER], data$df[,data$VOLUME]) list(list(res1[["y"]]), list(res2[["y"]])) } <file_sep>/YATACore/R/IND_Lines.R TREND <- function(data=NULL, ind=NULL, columns=NULL) { modLM = lm(Price ~ Order, data=data$df) pred = predict(modLM, data$df) list(list(pred)) } <file_sep>/README.md # YATA # Yet Another Algorithm for Trading ## Colaboradores son bienvenidos ## Collaborators are welcome Un sistema para analizar y evaluar la fiabilidad de los indicadores tecnicos y realizar algotrading sobre cryptomonedas <file_sep>/YATAClient/YATAClient/src/main/java/com/jgg/yata/client/timers/TimerMarket.java package com.jgg.yata.client.timers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import com.jgg.yata.client.Providers; import com.jgg.yata.client.pojos.Market; import com.jgg.yata.client.providers.Provider; import com.jgg.yata.client.providers.ProviderFactory; public class TimerMarket extends TimerTask { int interval = 1; Provider prov; public TimerMarket (int interval, Providers provider) { this.interval = interval; this.prov = ProviderFactory.getProvider(provider); } public void start() { Timer timer = new Timer(); this.run(); if (interval > 0) timer.scheduleAtFixedRate(this, interval, interval * 60000); } @Override public void run() { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss"); System.err.println("Started at " + dateFormat.format(new Date())); try { Map<String, Market> map = prov.getMarkets(); for(Map.Entry<String, Market> entry : map.entrySet()) { System.out.println(entry.getValue().toCSV()); } } catch (Exception e) { System.err.println(e.getMessage()); System.exit(16); } } } <file_sep>/YATAWeb/ui/partials/modTrading/modSellUI.R modSellInput <- function(id) { ns = NS(id) useShinyjs() tableOper = {tags$table(class = "box-table", tags$tr(tags$td("Camara", class="tblLabel"), tags$td(class="tblRow", colspan="6", selectInput(ns("cboCamera"), label=NULL, choices=c("")) ) ) ,tags$tr(tags$td("Base", class="tblLabel"), tags$td(class="tblRow", colspan="6", selectInput(ns("cboBase"), label=NULL, choices=c("")) ) ) ,tags$tr(tags$td("Moneda", class="tblLabel") ,tags$td(class="tblRow", colspan="6", selectInput(ns("cboCTC"), label=NULL, choices=c("No curencies"="None")) ) ) ,tags$tr( tags$td("Saldo", class="tblLabel") ,tags$td(class="tblRow",colspan="6",verbatimTextOutput(ns("lblSaldo"))) ) ,tags$tr( tags$td("Amount", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtAmount"), label = NULL, value = 0)) ) ,tags$tr( tags$td("Camera Fee", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtFeeCam"), label = NULL, value = 0)) ) ,tags$tr( tags$td("Blockchain Fee", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtFeeCTC"), label = NULL, value = 0)) ) ,tags$tr( tags$td("Other Fee", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtFeeOTH"), label = NULL, value = 0)) ) ,tags$tr( tags$td("Max Limiit", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtLimit"), label = NULL, value = 0)) ) ,tags$tr( tags$td("Stop", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtStop"), label = NULL, value = 0)) ) ,tags$tr( tags$td() ,tags$td( colspan="6", bsButton(ns("btnOK"), "Transfer", icon = icon("check"), style = "success") , bsButton(ns("btnXCancel"), "Cancel", icon = icon("remove"), style = "danger") ) ) ,tags$tr( tags$td() ,tags$td( colspan="6", htmlOutput(ns("lblStatus"))) ) ) } tableFun = { tags$table(class = "boxTable" ,tags$tr( tags$td("Motivo", class="tblLabel") ,tags$td(class="tblRow", colspan="6",verbatimTextOutput("value")) ) # ,tags$tr( tags$td("Exchange Fee"), tags$td(textOutput(ns("lblFeeExch"))) ) # ,tags$tr( tags$td("Block Fee"), tags$td(textOutput(ns("lblBlockExch"))) ) # ,tags$tr( tags$td("Effective"), tags$td(textOutput(ns("lblCTCAmount"))) ) # ,tags$tr( tags$td("Total"), tags$td(textOutput(ns("lblTotal"))) ) # ,tags$tr( tags$td("Comment"), tags$td(textAreaInput(ns("txtCommentTotal"), label=NULL, rows=5))) # ,tags$tr( tags$td(bsButton(ns("btnOK"), "Make", icon = icon("check"), style = "primary")) # ,tags$td(bsButton(ns("btnCancel"), "Cancel", icon = icon("check"), style = "danger")) # ) # ) ) } fluidRow( column(width=2) ,column(width=4, h3("Operativo"), tableOper) ,column(width=4, h3("Functional"), tableFun) ) }<file_sep>/YATAManualTech/prueba.R library(plantuml) library(YATA) case = YATACase$new() x=as.plantuml(case) plot(x) <file_sep>/YATAModels/R/IND_VWMA.R source("R/IND_MA.R") IND_VWMA <- R6Class("IND_VWMA", inherit=IND_MA, public = list( name="Media movil simple" ,symbol="SMA" ) ) <file_sep>/YATAModels/inst/rmd/Model_EMA.Rmd --- title: "Exponential moving average (EMA)" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Exponential moving average (EMA) Calculates an exponentially-weighted mean, giving more weight to recent observations The Exponential Moving Average is a staple of technical analysis and is used in countless technical indicators. In a Simple Moving Average, each value in the time period carries equal weight, and values outside of the time period are not included in the average. However, the Exponential Moving Average is a cumulative calculation, including all data. Past values have a diminishing contribution to the average, while more recent values have a greater contribution. This method allows the moving average to be more responsive to changes in the data. The EMA result is initialized with the n-period sample average at period n. The exponential decay is applied from that point forward. ## Formula $$ \begin{aligned} wilder=T \implies K = \frac{2}{(n+1)} \\ wilder=F \implies K = \frac{1}{n} \\ EMA = EMA_{[-1]} + K (v(i) - EMA_[-1]) \end{aligned} $$ ## Parametros __n__ The Window Size is nothing but the look back period and this forms the basis of your ALMA settings. __wilder__ Set the value of K <file_sep>/YATATest/test.R ctc <- fromJSON("https://poloniex.com/public?command=returnCurrencies", simplifyDataFrame = FALSE) rows=names(ctc) ll = lapply(ctc,t) df = as.data.frame(ll[[1]]) for (i in 2:length(ll)) df = rbind(df, ll[[i]]) <file_sep>/YATAModels/R/FACT_Scope.R # Emula un factor o una enumeracion FSCOPE <- R6::R6Class("FSCOPE", public = list( value = 0 ,size = 4 ,NONE = 0 ,LONG = 1 ,MEDIUM = 2 ,SHORT = 4 ,ALL = 7 ,names = c("Long", "Medium", "", "Short") ,initialize = function(scope = 0) { self$value = scope } ,getCombo = function() { values = c(1,2,4) names(values) = self$names values } ) ) <file_sep>/YATAWeb/ui/modPortfolioUI.R modPortfolioInput <- function(id) { ns <- NS(id) useShinyjs() panelLeft = column(id = ns("left"), width=2, style="display: none" ,tags$div(id=ns("left-main") ,radioButtons(ns("swSource"),"Source" , selected = 1, choices = list("Price" = 0, "Volume" = 1)) ,radioButtons(ns("swValue"), "Data" , selected = 1, choices = list("Value" = 0, "Variation" = 1)) ,radioButtons(ns("swPlot"), "Plot type", selected = 1, choices = list("Linear" = 1, "Log" = 2, "Bar" = 3, "Candle" = 4)) ,radioButtons(ns("swShow"), "Show" , selected = 2, choices = list("Active" = 1, "Portfolio" = 2, "All" = 3)) ,radioButtons(ns("swWindow"),"Interval" , selected = 2, choices = list("Week" = 1, "fothnight" = 2, "Month" = 3, "Quarter"= 4)) ,bsButton(ns("btnConfig"), "Update", icon = icon("check"), style = "primary") ) ) panelMain = column(id = ns("main"), width=12 ,boxPlus(width=12, closable = FALSE,status = "primary",solidHeader = FALSE,collapsible = TRUE ,menuTab(ns("tabs"), c("General")) # ,tabsetPanel(id=ns("tabs") # ,tabPanel( id=ns("General"), "General" # ,fluidRow(plotlyOutput(ns("plotSessions"), width="100%",height="500px")) # ,fluidRow(column(width=6, DT::dataTableOutput(ns("tblSessions")))) # ) # ) ) ) panelRight = column(id = ns("right"), width=2, style="display: none" , checkboxGroupInput(ns("chkCTC"), "Currencies to plot:") ,fluidRow( column(width=6, bsButton(ns("btnNone"), "Ninguno", icon = icon("trash"), class="btn-block", style = "warning")) ,column(width=6, bsButton(ns("btnAll"), "Todos", icon = icon("edit"), class="btn-block", style = "success")) ) ,fluidRow(column(width=12,bsButton(ns("btnPlot"), "Update", icon = icon("check"), class="btn-block", style = "primary"))) ) tagList( fluidRow(panelLeft, panelMain, panelRight)) } <file_sep>/YATAWeb/ui/modIndicatorsServer.R library(shinyjs) modIndicators <- function(input, output, session, parent) { ns <- session$ns useShinyjs() # Control la carga LOADED = 7 LOAD_MONEDA = 1 # Carga los tickers LOAD_MODELO = 2 # Carga el modelo sin indicadores LOAD_INDICATORS = 4 # Si hay tickers y modelo, carga indicadores LOAD_ALL = 15 vars <- reactiveValues( dfd = NULL # Datos ,loaded = 0 # 1 - Moneda, 2 - Modelo, 4 - Otro # Tabla de tickers, se inicializa para que exista en init ,tickers = NULL # TBLTickers$new("Tickers") # Tabla de tickers ,changed = FALSE ,parms = NULL ,thres = NULL ,clicks = 0 ,mainSize = 12 ,pendingDTFrom = F ,pendingDTTo = F ,toolbox = c(F,F,F,F) ) updateSelectInput(session, "cboMonedas", choices=cboMonedas_load(),selected=NULL) updateSelectInput(session, "cboModels" , choices=cboModels_load()) observeEvent(input$SBLOpen, { print("event SBLOpen"); adjustPanel(F, T, vars); }) observeEvent(input$SBROpen, { print("event SBROpen"); adjustPanel(F, F, vars); }) observeEvent(input$SBLClose, { print("event SBLClose");adjustPanel(T, T, vars); }) observeEvent(input$SBRClose, { print("event SBRClose");adjustPanel(T, F, vars); }) observeEvent(input$btnToolbox, { print("event btnToolBolx");adjustToolbox(as.integer(input$tabTrading))}) observeEvent(input$tabTrading, { if (vars$loaded > 0) updateData(input, EQU(vars$loaded, LOADED)) }) observeEvent(input$cboMonedas, { print("event moneda"); if (input$cboMonedas == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MONEDA); return (NULL) } updateActionButton(session, "tradTitle", label = input$cboMonedas) shinyjs::enable("btnSave") vars$tickers = YATAData$new(case$profile$scope, input$cboMonedas) rng = vars$tickers$getRange(YATAENV$getRangeInterval()) vars$pendingDTFrom = T vars$pendingDTTo = T updateDateInput(session, "dtFrom", min=rng[1], max=rng[2], value=rng[3]) updateDateInput(session, "dtTo", min=rng[1], max=rng[2], value=rng[2]) vars$tickers$filterByDate(rng[3], rng[2]) vars$loaded = bitwOr(vars$loaded, LOAD_MONEDA) if (AND(vars$loaded, LOAD_MODELO)) { case$model = loadIndicators(case$model, vars$tickers$scopes) vars$loaded = bitwOr(vars$loaded, LOAD_INDICATORS) } updateData(input, EQU(vars$loaded, LOADED)) # vars$dfd = vars$tickers$df }, ignoreNULL=T, ignoreInit = T) observeEvent(input$cboModels, { print("event Models") shinyjs::enable("btnSave") if (input$cboModels == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MODELO); return(NULL) } case$model = YATAModels::loadModel(input$cboModels) vars$loaded = bitwOr(vars$loaded, LOAD_MODELO) if (AND(vars$loaded, LOAD_MONEDA)) { case$model = loadIndicators(case$model, vars$tickers$scopes) vars$loaded = bitwOr(vars$loaded, LOAD_INDICATORS) } updateData(input, EQU(vars$loaded, LOADED)) }, ignoreNULL=T, ignoreInit = T) # observeEvent(input$chkShowInd, {if (input$chkShowInd) { # case$model$setParameters(getNumericGroup(input,vars$parms)) # #JGG Revisar, no es una lista al uso # #case$model$setThresholds(getNumericGroup(input,vars$thres)) # ##case$model$calculateIndicatorsGlobal(vars$tickers) # }}) observeEvent(input$dtFrom, {if (vars$pendingDTFrom) { vars$pendingDTFrom = F; return (NULL) } if (AND(vars$loaded, LOAD_MONEDA)) {print("event dtFrom"); vars$tickers$filterByDate(input$dtFrom, input$dtTo) case$model$calculated = FALSE updateData(input, EQU(vars$loaded,LOADED)) } }, ignoreNULL=F, ignoreInit = T) observeEvent(input$dtTo, { if (vars$pendingDTTo) { vars$pendingDTTo = F; return (NULL) } if (AND(vars$loaded, LOAD_MONEDA)) { print("event dtTo"); vars$tickers$filterByDate(input$dtFrom, input$dtTo) case$model$calculated = FALSE updateData(input, EQU(vars$loaded,LOADED)) } }, ignoreNULL=F, ignoreInit = T) observeEvent(input$btnSave, { updateParameter(PARM_CURRENCY, input$cboMoneda) updateParameter(PARM_MODEL, input$cboModel) shinyjs::disable("btnSave") }) # First time if (vars$loaded == 0) { if (!is.na(case$profile$getCTC())) updateSelectInput(session, "cboMonedas", selected = case$profile$getCTC()) if (!is.na(case$profile$getModel())) updateSelectInput(session, "cboModels", selected = case$profile$getModel()) } ################################################################################################### ### PRIVATE CODE ################################################################################################### updateData <- function(input, calculate) { print("Update Data") panel = as.integer(input$tabTrading) if (calculate) {case$model$calculateIndicators(vars$tickers, force=T)} plot = renderPlot(vars, case$model, panel, input, calculate) tbl = DT::renderDataTable({ makeTable(panel, vars, case$model) }) if (panel == TERM_SHORT) { output$plotShort = renderPlotly({plot}); output$tblShort = tbl } if (panel == TERM_MEDIUM) { output$plotMedium = renderPlotly({plot}); output$tblMedium = tbl } if (panel == TERM_LONG) { output$plotLong = renderPlotly({plot}); output$tblLong = tbl } } makeTable = function(panel, vars, model) { df = vars$tickers$getTickers(panel)$df if (!is.null(case$model) && EQU(vars$loaded, LOADED)) { for (ind in case$model$getIndicators(panel)) { cols = ind$getData() if (!is.null(cols)) df = cbind(df,cols) } } .prepareTable(df) } adjustToolbox = function(tabId) { browser() pnlIds = c("pnlShort", "pnlMedium", "pnlEmpty", "pnlLong") tbIds = c("tbShort", "tbMedium", "tbEmpty", "tbLong") print("entra en adjust") newSize = "col-sm-10" oldSize = "col-sm-12" if (vars$toolbox[tabId]) { newSize = "col-sm-12" oldSize = "col-sm-10" } shinyjs::removeCssClass (id=pnlIds[tabId], oldSize) shinyjs::toggle(id = tbIds[tabId]) vars$toolbox[tabId] = !(vars$toolbox[tabId]) shinyjs::addCssClass (id=pnlIds[tabId], newSize) } # Lo devuelve cada vez que entra aqui return(reactive({vars$changed})) } btnLoad_click <- function(input, output, session, vars) { # if (validate()) return(showModal(dataError())) # Create user profile profile = YATAProfile$new() profile$name = input$txtPrfName profile$profile = input$rdoPrfProfile profile$capital = input$txtPrfImpInitial profile$scope = input$rdoPrfScope # Create configuration for case config = YATAConfig$new() config$symbol = input$moneda config$initial = input$txtPrfImpInitial config$from = input$dtFrom config$to = input$dtTo config$mode = input$rdoProcess config$delay = input$processDelay # Initialize case case$profile = profile case$config = config case$tickers = vars$tickers case$current = 0 case$oper = NULL case$config$summFileName = setSummaryFileName(case) case$config$summFileData = setSummaryFileData(case) calculateIndicators(case) # Create Portofolio portfolio <<- YATAPortfolio$new() portfolio$addActive(YATAActive$new(input$moneda)) portfolio$flowFIAT(config$from, config$initial) } cboMonedas_load <- function() { print("Load Monedas") tIdx = DBCTC$getTable(TCTC_INDEX) data = tIdx$df %>% arrange(Name) setNames(c(0, data[,tIdx$SYMBOL]),c(" ", data[,tIdx$NAME])) } cboModels_load <- function() { print("Load Modelos") df = YATACore::loadModelsByScope(case$profile$getScope()) setNames(c(0, df$ID_MODEL), c(" ", df$DESCR)) } updateManual <- function(input, output, session, model) { fp = paste(YATAENV$modelsMan, model$doc, sep="/") if (file.exists(fp)) { output$modelDoc = renderUI({ HTML(markdown::markdownToHTML(knit(fp, quiet = TRUE),fragment.only = TRUE)) }) } else { output$modelDoc = renderUI({"<h2>No hay documentacion</h2>"}) } } setParmsGroup = function(parms) { if (length(parms) == 0) return (NULL) LL <- vector("list",length(parms)) nm = names(parms) for(i in 1:length(vars$parms)){ LL[[i]] <- list(numericInput(ns(paste0("txt", nm[i])), label = nm[i], value = parms[[i]])) } return(LL) } getNumericGroup = function(input, parms) { if (length(parms) == 0) return (NULL) ll <- vector("list",length(parms)) nm = names(parms) for(i in 1:length(parms)) { # cat(eval(parse(text=paste0("input$txt", nm[i]))), "\n") ll[[i]][1] = eval(parse(text=paste0("input$txt", nm[i]))) } names(ll) = nm ll } loadTickers = function(scope, moneda) { pos = which(SCOPES == scope) YATACore::openConnection() t1 = NULL t3 = NULL if (pos > 1) t1 = TBLTickers$new(SCOPES[pos - 1], moneda) t2 = TBLTickers$new(SCOPES[pos], moneda) if (pos < length(SCOPES)) t3 = TBLTickers$new(SCOPES[pos + 1], moneda) YATACore::closeConnection() list(t1,t2,t3) } adjustPanel = function(expand, left, vars) { shinyjs::removeCssClass (id="pnlMain", paste0("col-sm-", vars$mainSize)) if (expand) vars$mainSize = vars$mainSize + 2 if (!expand) vars$mainSize = vars$mainSize - 2 shinyjs::addCssClass (id="pnlMain", paste0("col-sm-", vars$mainSize)) if (left) { shinyjs::toggle(id = "pnlLeft") shinyjs::toggle(id = "SBLOpen") } else { shinyjs::toggle(id = "pnlRight") shinyjs::toggle(id = "SBROpen") } } <file_sep>/YATACore/R/R6_YATAPortfolio.R YATAPortfolio <- R6Class("YATAPortfolio", public = list( initialize = function(currency="EUR", active = NULL) { if (!is.null(active) && !("YATAActive" %in% c(class(active)))) { stop(MSG_BAD_CLASS("YATAActive")) } self$addActive(YATAActive$new(currency)) private$position = TBLPosition$new(currency, active$name) } ,getActive = function(moneda=NULL) { if (is.null(moneda)) moneda = private$moneda if (!(moneda %in% names(private$activos))) return (NULL) return (private$activos[[moneda]]) } ,addActive = function(active = NULL) { if (is.null(active)) stop(MSG_BAD_CLASS("NULL")) if (!("YATAActive" %in% c(class(active)))) stop(MSG_BAD_CLASS("YATAActive")) #if (active$idName %in% names(private$activos)) return (invisible(self)) nm <- names(private$activos) if(is.null(nm)) { nm = active$name } else { nm = c(nm, active$name) } private$activos <- c(private$activos, active) names(private$activos) = nm # El activo por defecto es el ultimo private$moneda = active$name private$position$CTC = active$name invisible(self) } ,flowFIAT = function(fecha = NULL, uds = NULL) { private$flowCapital(fecha, uds) } ,flowTrade = function(oper=NULL) { if (is.null(oper)) return(oper) if (oper$status == OP_EXECUTED) return(oper) active = self$getActive() if (is.null(active)) self$addActive(Active$new(oper$currency)) oper$order = active$addFlow(oper$operDate, oper$units, oper$price) private$flowCapital(oper$operDate, oper$amount) oper$status = OP_EXECUTED active$getOperations() } ,updatePosition = function(case) { if (case$current == 0) return (NULL) reg = case$getCurrentTicker() aa = self$getActive() # Monedas ee = self$getActive(case$config$currency) # Euros pp = aa$position * reg[1,DF_PRICE] bb = ee$balance + pp private$position$add(reg[1,DF_DATE], ee$balance, aa$position, bb) self$getPositionHistory() } ,getPosition = function (value) { if (!missing(value)) stop(MSG_METHOD_READ_ONLY("Position")) private$position$getPosition() } ,getPositionHistory = function (value) { if (!missing(value)) stop(MSG_METHOD_READ_ONLY("Position")) private$position } ,saldo = function (value) { if (!missing(value)) stop(MSG_METHOD_READ_ONLY("Saldo")) self$getActive(CURRENCY)$position } ,getBalance = function (value) { if (!missing(value)) stop(MSG_METHOD_READ_ONLY("Balance")) if (is.null(private$activos)) return(0) sum(sapply(private$activos, function(x) { x$balance })) } ,getTrading = function(currency = NULL) { self$getActive(currency)$getOperations() } ,operNum = function(moneda) { private$activos[[moneda]]$operNum() } ,print = function() { if (length(private$activos) == 0) return(MSG_NO_ACTIVES()) for (a in private$activos) { cat(a$print()) } } ) ,private = list(moneda = NULL, activos = list() ,position = NULL ,flowCapital = function(fecha, uds) { private$activos[[CURRENCY]]$addFlow(fecha, uds, 1) } ) ) <file_sep>/YATAWeb/widgets/YATAWrappers.R showLeftBar = function() { .toggleSideBar(TRUE, TRUE) } HideLeftBar = function() { .toggleSideBar(FALSE, TRUE) } showRighttBar = function() { .toggleSideBar(TRUE, FALSE) } HideRightBar = function() { .toggleSideBar(FALSE, FALSE) } iconBarShow = function(side) { shinyjs::showElement(selector=paste0("#YATAIconNav-", side)) } iconBarHide = function(side) { shinyjs::hideElement(selector=paste0("#YATAIconNav-", side)) } toggleLeftBar = function() { toggleSideBar(T) } toggleRightBar = function() { toggleSideBar(F) } toggleSideBar = function(left) { selector = ifelse(left, "#YATALeftSide", "#YATARightSide") shinyjs::toggle(selector=selector, anim=T) shinyjs::runjs(paste0("YATAToggleSideBar(", left, ")")) } updateIconsRightBar = function() { } updateIconsLefttBar = function() { } makePage = function(id, left=NULL, main=NULL, right=NULL, modal=NULL) { ns <- NS(id) useShinyjs() divLeft = NULL divMain = NULL divRight = NULL divModal = NULL if (!is.null(left)) divLeft = div(id = ns("left"), left) if (!is.null(main)) divMain = div(id = ns("main"), class="YATAMainPanel", main) if (!is.null(right)) divRight = div(id = ns("right"), right) if (!is.null(modal)) { divContainer = div(id=ns("container"), class="YATAContainer") #divModal = div(id=ns("modal-back"),class="YATAModalBack") divModal = div(id=ns("modal-panel"), class="YATAModalPanel", wellPanel(modal)) divContainer = tagAppendChild(divContainer, hidden(divModal)) # divContainer = tagAppendChild(divContainer, hidden(div(id=ns("modal-panel"), class="YATAModalPanel", wellPanel(modal)))) divContainer = tagAppendChild(divContainer, divMain) divMain = divContainer } tagList(divLeft, divMain, divRight) } ################################################################# ### PAGE MENU ################################################################# menuTab = function(idMenu, choices=NULL, selected=NULL, names=NULL, values=NULL) { sel = selected mnu = NULL if (!is.null(choices)) { if (class(choices) == "list") choices = unlist(choices) if (is.null(sel)) sel = choices[1] mnu = radioGroupButtons(idMenu, choices = choices, label = NULL, selected = sel, direction="horizontal", size="lg", justified = TRUE, status = "menu") } else { mnu = radioGroupButtons(idMenu, choiceNames = names, choiceValues = values, label = NULL, selected = selected, direction="horizontal", size="lg", justified = FALSE, status = "menu") } tagList(mnu, hr(class="hr-menu")) } updateMenuTab = function(session, idMenu, label=NULL, choices=NULL, selected=NULL, status="menu", size="normal",choiceNames=NULL, choiceValues=NULL) { updateRadioGroupButtons(session, idMenu, label=label, choices=choices, selected= selected , choiceNames = choiceNames, choiceValues = choiceValues , status = status, size = size) } ################################################################# ### Iconos de las barras ################################################################# YATAIconNav = function (left=TRUE, icons) { lib = "font-awesome" suffix = ifelse(left, "left", "right") class = paste0("nav navbar-icon-", suffix) icons = .getIcons(icons) jscall = paste0("YATAToggleSideBar((0 == ", ifelse(left, 0, 1), "), ") iconTagOn <- tags$span(id=paste0("YATAIconNav-", suffix, "-on") , class="navbar-icon" , style="display: inline-block;", tags$i(class = icons[[1]], onclick=htmlwidgets::JS(paste0(jscall, "(0 == 0))")))) iconTagOff <- tags$span(id=paste0("YATAIconNav-", suffix, "-off") , class="navbar-icon" , style="display: none;", tags$i(class = icons[[2]], onclick=htmlwidgets::JS(paste0(jscall, "(0 == 1))")))) container = tags$div(id=paste0("YATANav-", suffix), style=paste0("float: ", suffix, ";"), class="navbar-nav shinyjs-show") container = tagAppendChild(container, iconTagOn) container = tagAppendChild(container, iconTagOff) container } .getIcons = function(icons) { #lib = "font-awesome" lib = "glyphicon" # Poner como lista de caracteres names = icons if (is.null(names)) names ="menu-hamburger" if (class(icons) == "list") names = unlist(icons) # Obtener la libreria si hay pos = which(names(names) == "lib") if (length(pos) > 0) { lib = names[pos] names = names[-pos] } # Crear dos items (1 = On, 2 = Off) if (length(names) == 1) names = c(names, names) iconOn = .mountIcon(names[1], lib) iconOff = .mountIcon(names[2], lib) list(iconOn, iconOff) } .mountIcon <- function(name, lib) { prefixes <- list(`font-awesome` = "fa", glyphicon = "glyphicon") prefix <- prefixes[[lib]] iconClass = "" prefix_class <- prefix if (prefix_class == "fa" && name %in% font_awesome_brands) { prefix_class <- "fab" } paste0(prefix_class, " ", prefix, "-", name) } <file_sep>/YATACore/R/IND_Points.R MAXMIN <- function(data, extreme=T) { df = data$df[,data$PRICE] Mm = rollapply(df,3,FUN=.detect_max_min,fill=0,align="center") # Tratamiento de infinitos if (sum(Mm == Inf) > 0) Mm <- process_inf(df,Mm,which(Mm == Inf), "left") if (sum(Mm == -Inf) > 0) Mm <- process_inf(df,Mm,which(Mm == -Inf), "right") list(Mm) } # Los maximos son para un rango dado, aquellos por encima del mayor de los minimos # Lo minimos a la inversa # Si dos de lostres puntos son iguales, devuelve +/- Inf para procesarlos despues .detect_max_min <- function(x) { if (x[2] > x[1] && x[2] > x[3]) return( x[2]) if (x[2] < x[1] && x[2] < x[3]) return(-x[2]) if (x[2] == x[1]) { if (x[2] > x[3]) return(+Inf) if (x[2] < x[3]) return(-Inf) } if (x[2] == x[3]) { if (x[2] > x[1]) return(+Inf) if (x[2] < x[1]) return(-Inf) } return(0) } # Detecta los maximos y minimos relativos # En caso de alineacion, se marca el especificado en align process_inf <- function(data, Mm, rows, align) { beg = rows[1] end = rows[2] left = data[beg - 1,1] i = 2 while ( i <= length(rows)) { if (i < length(rows) && (rows[i] - rows[i - 1]) == 1) { end = rows[i] } else { Mm[beg:end] = 0 if (rows[i] < length(Mm)) { right = data[end + 1,1] val = 0 if (left < data[beg,1] && data[beg,1] > right) val = data[beg,1] if (left > data[beg,1] && data[beg,1] < right) val = data[beg,1] * -1 if (val != 0) { if (align == "left") { Mm[beg] = val } else { Mm[end] = val } } } beg=rows[i] } i = i + 1 } Mm } MaxMin2 <- function(data) { data$Mm = rollapply(c(data$precio, data$Mm),4,function(x, y) {detect_max_min(x)} ,fill=0,align="right",by.column=T) data } <file_sep>/YATAProviders/R/poloniex.R pol.api = NULL .POLGetHistorical = function(base, counter, from, to, period) { end = as.POSIXct(Sys.time()) if (!is.null(to)) end = to if (is.null(pol.api)) pol.api = PoloniexR::PoloniexPublicAPI() data = PoloniexR::ReturnChartData( theObject = pol.api ,pair = paste(base, counter, sep="_") ,from=from + 1 ,to=end ,period=period) if (is.null(data)) return (NULL) # El tipo devuelve todo como factores cols = colnames(data) for (col in cols) { if (is.factor(data[,col])) data[,col] = as.numeric(levels(data[,col])) } df = as.data.frame(data) df$TMS = zoo::index(data) df$BASE = base df$COUNTER = counter row.names(df) = NULL df } POL.GetTickers = function() { df = tryCatch({ if (is.null(pol.api)) pol.api = PoloniexR::PoloniexPublicAPI() data = PoloniexR::ReturnTicker(pol.api) # El tipo devuelve todo como factores cols = colnames(data) for (col in cols) { if (is.factor(data[,col])) data[,col] = as.numeric(as.vector(data[,col])) } df = as.data.frame(data) l = strsplit(row.names(data), "_") m = sapply(l, c) df$Base = m[1,] df$CTC = m[2,] df$TMS = Sys.time() # Remover inactivos (not trading and last = 0) df = df %>% filter (last > 0, isFrozen == 0) # Seleccionar las columnas con nombre df = df[,c("TMS", "Base", "CTC", "last", "lowestAsk","highestBid","percentChange","baseVolume", "high24hr","low24hr")] colnames(df) = c("TMS","BASE", "COUNTER", "LAST", "ASK", "BID","CHANGE","VOLUME", "HIGH","LOW") rownames(df) = NULL df } ,error=function(e) { e$message }) df } <file_sep>/YATAWeb/ui/partials/modTrading/modSellServer.R modSell <- function(input, output, session, id, type) { useShinyjs() vars <- reactiveValues( loaded = F ) ####################################################################### # Private Code ####################################################################### loadPage = function() { browser() updateSelectInput(session, "cboCamera", choices=comboClearings(FALSE)) updateSelectInput(session, "cboCamera", choices=comboClearings(FALSE)) } ####################################################################### # Server Code ####################################################################### if (!vars$loaded) loadPage() observeEvent(input$cboCamera, { browser() if (nchar(input$cboCamera) == 0) return (NULL) updateSelectInput(session, "cboBase", choices=comboBases(input$cboCamera)) }) }<file_sep>/YATAWeb/locale/messages_ES.R # Spanish texts LBL.DARED = "Arriesgado" LBL.BOLD = "Audaz" LBL.MODERATE = "Moderado" # Considera todo LBL.CONSERVATIVE = "Conservador" LBL.SAVER = "Ahorrador" LBL.ALL_MODULES = "Todos" LBL.SHOW_IND = "Mostrar indicadores"<file_sep>/YATABatch/R/YATAInternals.R .makeIntervals <- function(symbol, TBCases, ...) { prms = list(...)[[1]] data = loadSymbolData(symbol) beg=as.Date(ifelse(is.na(prms[[CASE_START]]), data[1,CTC_DATE], as.character(prms[[CASE_START]]))) last= as.Date(as.character(data[nrow(data),CTC_DATE])) prf = .expandNumber(prms[[CASE_PROFILE]]) per = .expandNumber(prms[[CASE_PERIOD]]) start = .expandMonth(beg,last,prms[[CASE_INTERVAL]]) cols = list(prf, start, per) colNames = c(CASE_PROFILE, CASE_START, CASE_PERIOD) parms = TBCases$getGroupFields(CASE_GRP_PARMS) for (parm in parms) { if (is.na(prms[[parm]])) break; prm = .expandNumber(prms[[parm]]) cols = list.append(cols, prm) colNames = c(colNames, parm) } gr = expand.grid(cols) df = data.frame(gr) colnames(df) = colNames # El calculo de la fecha fin se debe hacer cuando ya esta expandido colEnd = as.mondate(eval(TBCases$fieldExpr(CASE_START))) + eval(TBCases$fieldExpr(CASE_PERIOD)) df = add_column(df, End = as.Date(colEnd), .after = CASE_START) df } .expandNumber <- function(num) { toks=strsplit(as.character(num), ";")[[1]] toks = as.integer(toks) if (length(toks) == 1) toks = c(toks, toks) if (length(toks) < 3) toks = c(toks, 1) seq(from=toks[1],to=toks[2], by=toks[3]) } .expandMonth <- function(beg, end, interval) { if (interval == 0) return(beg) seq(from=beg, to=end, by=paste(interval, "months")) } .createProfile <- function(record) { profile = YATAProfile$new() profile$name = "Batch" profile$profile = record[1,CASE_PROFILE] profile$scope=record[1,CASE_SCOPE] profile$saldo=record[1,CASE_CAPITAL] profile } .createConfig <- function(record) { config = YATAConfig$new() config$symbol = record[1,CASE_SYM_SYM] config$from = record[1,CASE_START] config$to = record[1,CASE_END] config$initial = record[1,CASE_CAPITAL] config } .createData <- function(record) { data = YATAData$new() data$name = record[1,CASE_SYM_NAME] data$symbol = record[1,CASE_SYM_SYM] data$start = record[1,CASE_START] data$end = record[1,CASE_END] df = loadSymbolData(data$symbol) tgt = df %>% filter(Date >= data$start, Date <= data$end) # Verificar rango de datos if ((nrow(tgt) / (record[1,CASE_PERIOD] * 30)) < MIN_PERCENTAGE) return (NULL) data$dfa = df data } .createModel <- function(record) { name=record[1,CASE_MODEL] if (!is.na(record[1,CASE_VERSION])) name = paste(name,record[1,CASE_VERSION],sep=".") model = loadModel(name) model$setParameters(as.vector(record[1, grep(CASE_GRP_PARMS, colnames(record))])) model # base=eval(parse(.makeDir(DIRS["models"],"Model_Base.R"))) # file=.makeDir(DIRS["models"], paste(paste("Model_",name,sep=""),"R",sep=".")) # mod=eval(parse(file)) # model = eval(parse(text=paste(MODEL_PREFIX, name, "$new()", sep=""))) # model } <file_sep>/YATAWeb/ui/partials/modTrading/modXFerServer.R modXFer <- function(input, output, session, id) { ns <- session$ns useShinyjs() vars <- reactiveValues( loaded = F ,opers = YATAOperation$new() ) ####################################################################### # Private Code ####################################################################### loadSources = function(cash=TRUE) { choices = comboClearings(TRUE) updateSelectInput(session, "cboFrom", choices=choices) updateSelectInput(session, "cboTo" , choices=choices) } validateForm = function() { res = FALSE if (input$cboFrom == input$cboTo) return (getMessage("SAME.CLEARING")) if (input$txtAmount <= 0) return (getMessage("INVALID.AMOUNT")) NULL } cleanForm = function() { updateNumericInput(session, "txtAmount", value=0) } ####################################################################### # Server Code ####################################################################### if (!vars$loaded) { loadSources() vars$loaded = T } observeEvent(input$cboFrom, { vars$source = input$cboFrom loadCboCurrency() }) observeEvent(input$cboCurrencies, { vars$ctc = input$cboCurrencies loadSaldo() }) observeEvent(input$btnCancel, { cleanFormXfer() }) observeEvent(input$btnOK, { msg = validateForm() if (!is.null(msg)) { output$lblStatus <- renderText(paste("<span class='msgErr'>", msg, "</span>")) return (NULL) } vars$opers$transfer(input$cboXferFrom, input$cboXferTo, input$cboXferCurrencies, input$txtXferAmount) output$lblStatus = renderText(paste("<span class='msgOK'>", getMessage("OK.OPER"), "</span>")) }) } <file_sep>/YATAModels/R/IND_Slope.R IND_Slope <- R6Class("IND_Slope", inherit=IND__Base, public = list( name="Slope" ,symbol="SLOPE" ,initialize = function() { super$initialize() } ,calculate = function(TTickers, date) { ##JGG Falta ajustar los periodos si no es un dia ###################################################################### # 1.- Obtener el valor de i para los datos # (Cf / Ci) = (1 + i) ^ n # 2.- Si (Cf / ci ) < 1 Es un interes negativo, hacemos el inverso # 3.- Calculamos la variacion para el caso n = 180 (v) # 4.- La tangente es el log en base 2 de v # 5.- Si el interes era negativo, la pendiente es negativa ###################################################################### xt = private$getXTS(TTickers, pref=0) n = nrow(xt) Ci = xt[1,TTickers$PRICE] v0 = (xt[n,TTickers$PRICE] / Ci) v = v0 - 1 if (v0 < 1) v = (1 / v0) - 1 i = (2 ^ (v / n)) - 1 # interes original v = (1 + i) ^ 180 # 180 (PI) es un valor fijo slope = log2(v) rad = atan(slope) alpha = 180 * rad / pi if (v0 < 1) alpha = alpha * -1 alpha } ) ) <file_sep>/YATAWeb/ui/modMainUI.R modMainInput <- function(id) { ns <- NS(id) useShinyjs() tagList( useShinyjs() ,box( fluidRow( column(10 # ,box(width=NULL, plotlyOutput(ns("plotMain"))) ,tabBox( # title = "First tabBox", # The id lets us use input$tabset1 on the server to find the current tab id = "tabset1", width = NULL, tabPanel("Largo", plotlyOutput(ns("plotMain"))), tabPanel("Intermedio", "Tab content 2"), tabPanel("Corto", "Tab content 2") ) ) ,column(2, box( width=NULL, title = "Position", solidHeader = T, status = "primary" ,withTags({ table(class = "boxTable", tr(td("Euro"), td(colspan="2", class="lblData", textOutput(ns("lblPosFiat")))) ,tr(td(textOutput(ns("lblMoneda"))), td(colspan="2", class="lblData", textOutput(ns("lblPosMoneda")))) ,tr(td("Total"), td(colspan="2", class="lblData", textOutput(ns("lblPosTotal")))) ,tr(td("Estado"), td( img(id=ns("resDown"), icon("triangle-bottom", class = "rojo", lib="glyphicon")) ,img(id=ns("resUp"), icon("triangle-top", class = "verde", lib="glyphicon"))) ,td( class="lblData", textOutput(ns("lblEstado")))) ,tr(td("Tickers"),td(colspan="2", class="lblData", textOutput(ns("lblResMov")))) ,tr(td("Opers"), td( class="lblData", textOutput(ns("lblResC"))) ,td( class="lblData", textOutput(ns("lblResV")))) ,tr(td("Date"), td(colspan="2", class="lblData", textOutput(ns("lblPosDate")))) ,tr(td("Trend"), td(colspan="2", class="lblData", textOutput(ns("lblTrend")))) ) })) , box( width=NULL, title = "Indicators", solidHeader = T, status = "primary" ,checkboxGroupInput(ns("chkPlots1"), label = NULL) ,checkboxGroupInput(ns("chkPlots2"), label = NULL) ,checkboxGroupInput(ns("chkPlots3"), label = NULL) ) )) ,width=NULL, collapsible = T, title = "Plot", solidHeader = T, status="primary") ,fluidRow( id="rowButtons" ,column(1, bsButton(ns("btnSimulate"), style="success", label = "Simulate" )) ,column(1, bsButton(ns("btnStop"), style="danger", label = "Stop" )) ,column(1, bsButton(ns("btnNext"), style="warning", label = "Next" )) ,column(1, bsButton(ns("btnOper"), style="info", label = "Operar" )) ,column(1, bsButton(ns("btnExport"), style="dark", label = "Excel" )) ) ,fluidRow(column(5, box(width=NULL, title = "Tickers", solidHeader = T, status = "primary", collapsible = T, DT::dataTableOutput(ns("tblBodyData")))) ,column(3, box(width=NULL, title = "Position", solidHeader = T, status = "primary", collapsible = T, DT::dataTableOutput(ns("tblBodyPos")))) ,column(4, box(width=NULL, title = "Trading", solidHeader = T, status = "primary", collapsible = T, DT::dataTableOutput(ns("tblBodyTrade")))) ) # ,checkboxInput(ns("heading"), "Has heading"), # selectInput(ns("quote"), "Quote", c( # "None" = "", # "Double quote" = "\"", # "Single quote" = "'" # )) ) }<file_sep>/YATAConfig/SQL/ctc_dat_messages.sql USE CTC; DELETE FROM MESSAGES; INSERT INTO MESSAGES (CODE, LANG, REGION, MSG) VALUES ( "OK.XFER" ,"XX", "XX" , "Trasnferencia realizada" ); INSERT INTO MESSAGES (CODE, LANG, REGION, MSG) VALUES ( "OK.OPER" ,"XX", "XX" , "Operacion Realizada: %s" ); INSERT INTO MESSAGES (CODE, LANG, REGION, MSG) VALUES ( "SAME.CLEARING" ,"XX", "XX" , "Origen y destino no pueden ser iguales" ); INSERT INTO MESSAGES (CODE, LANG, REGION, MSG) VALUES ( "INVALID.AMOUNT" ,"XX", "XX" , "El importe es erroneo" ); COMMIT; <file_sep>/YATAWeb/server.R vars <- reactiveValues(lstData = NULL ,fila = 1 ,clicks = 0 ,numOpers = 0 ,buy = 0 ,sell = 0 ,trading = NULL ,posicion=NULL ,estado=0 # 0 = Inactivo ,mode = 0 ,dfd = NULL # Datos ,dfi = NULL # Datos con indicadores ,dfc = NULL # Datos vistos ,dfp = NULL ,dft = NULL ,sessions=NULL ) server <- function(input, output, session) { # No lo captura en el modulo # onclick("trad-tradSBOpen", function() { # shinyjs::addCssClass(id="trad-tradMain", "col-sm-10") # shinyjs::removeCssClass(id="trad-tradMain", "col-sm-12") # shinyjs::show(id = "trad-tradSB") # }, add=TRUE) # # onclick("trad-tradSBClose", function() { # shinyjs::hide(id = "trad-tradSB") # shinyjs::addCssClass(id="trad-tradMain", "col-sm-12") # shinyjs::removeCssClass(id="trad-tradMain", "col-sm-10") # }, add=TRUE) # files.code = list.files("ui", pattern="*Code.R$", full.names=TRUE, ignore.case=F) # sapply(files.code,source,local=T) # files.server = list.files("ui", pattern="*Server.R$", full.names=TRUE, ignore.case=F) # sapply(files.server,source,local=T) observeEvent(input$show, { browser() showModal(dataModal()) }) observeEvent(input$mainbar,{ updateTextInput(session, "nsPreffix", label=NULL, value=input$mainbar); if (input$mainbar == PNL_TST) callModule(modTest, PNL_TST) if (input$mainbar == PNL_OL) callModule(modOnLine, PNL_OL) if (input$mainbar == PNL_PRF) callModule(modPortfolio, PNL_PRF) if (input$mainbar == PNL_TRAD) callModule(modTrading, PNL_TRAD) if (input$mainbar == PNL_ANA) callModule(modAnalysis, PNL_ANA) if (input$mainbar == PNL_CONF) callModule(modConfig, PNL_CONF) if (input$mainbar == PNL_SIM) callModule(modSimm, PNL_SIM) # if (input$mainbar == PNL_SIMM) callModule(modMain, PNL_SIMM, changed) if (input$mainbar == PNL_HELP) callModule(modManual, PNL_HELP) if (input$mainbar == PNL_SYS) callModule(modSystem, PNL_SYS) if (input$mainbar == PNL_IND) callModule(modIndicators, PNL_IND) }) observeEvent(input$YATALeftBar, { browser(); shinyjs::hide("leftbar")}) observeEvent(input$YATARightBar, { browser(); shinyjs::hide("leftbar")}) observeEvent(input$btnjs, { browser(); shinyjs::hide("leftbar")}) observeEvent(input$btnLeft, { browser(); print("Para")}) observeEvent(input$btnRight, { browser(); print("Para")}) #callModule(modOnLine, "online") #changed = callModule(modConfig, "config", parent=session) # callModule(modMain, "main", parent=session, changed) # observeEvent(changed(),{ # browser() # # Se llama cada vez que se cambian datos en Config # # browser() # # msg <- sprintf("Changed es %s", changed()) # # cat(msg, "\n") # callModule(modMain, "main", parent=session, changed) # # }) #source("ui/modMainServer.R") #output$texto = renderText({ txt() }) # browser() # vars1 = vars # vars2 = callModule(modGlobals, "globals") # df <- callModule(linkedScatter, "scatters", reactive(mpg), # left = reactive(c("cty", "hwy")), # right = reactive(c("drv", "hwy")) # ) # observeEvent(input$navbar, { browser() }, ignoreInit = T) # # output$plot <- renderPlot({ # plot(cars, type=input$plotType) # }) # # output$summary <- renderPrint({ # summary(cars) # }) # # output$table <- DT::renderDataTable({ # DT::datatable(cars) # }) } <file_sep>/YATACore/R/TBL_Tickers.R # Implementa la tabla de cambios: last, ask, bid, etc. TBLTickers = R6::R6Class("TBLTickers", inherit=YATATable, public = list( symbol = NULL ,TMS = "TMS" ,BASE = "EXC" ,CTC = "CTC" ,HIGH = "High" ,LOW = "Low" ,LAST = "Last" ,VOLUME = "Volume" ,ASK = "Ask" ,BID = "Bid" ,CHANGE = "Change" ,base = NULL ,refresh = function() { if (is.null(private$bases)) { private$firstTime() return (invisible(self)) } tmp = private$getTickers() if (nrow(tmp) == 0) return (invisible(self)) private$makeLast(tmp) # Append data for graph for (base in private$bases) { df = tmp %>% filter(EXC == base) private$dfList[[which(private$bases == base)]] = rbind(private$dfList[[which(private$bases == base)]], df) } invisible(self) } ,getData = function() { self$df } ,getBases = function() { private$bases } ,getLast = function() { private$dfLast[[which(private$bases == self$base)]] } ,setBase = function(base) { self$base = base; self$df = private$dfList[[which(private$bases == base)]] } ,initialize = function() { browser() self$name = "Tickers" super$initialize(refresh=FALSE); private$firstTime() } ) ,private = list( bases = NULL ,dfFirst = NULL ,dfLast = list() ,dfList = list() ,dfSession = NULL ,firstTime = function() { private$dfFirst = private$getTickers() if (nrow(private$dfFirst) == 0) return (invisible(self)) private$bases = unique(private$dfFirst$EXC) dfSes = getLastSessions() private$dfSession = dfSes[,c("CTC", "EXC", "CLOSE")] private$dfSession = plyr::join( private$dfSession ,private$dfFirst[,c("CTC", "EXC", "Last")] ,by = c("CTC", "EXC")) colnames(private$dfSession) = c("CTC", "EXC", "Close", "Session") for (base in private$bases) { df = private$dfFirst %>% filter(EXC == base) private$dfList = list.append(private$dfList, df) } private$makeLast(private$dfFirst) } ,makeLast = function(last) { last = plyr::join(last, private$dfSession, by = c("CTC", "EXC")) last = private$adjustTypes(last) last[,"Close"] = as.fiat(last[,"Close"]) last[,"Session"] = as.fiat(last[,"Session"]) columns = c("TMS", "EXC", "CTC", "Last", "Ask", "Bid", "High", "Low", "Volume", "Change", "Session", "Close") last = last[,columns] private$dfLast = list() for (base in private$bases) { df = last %>% filter(EXC == base) private$dfLast = list.append(private$dfLast, df) } } ,getTickers = function() { tmp = YATAProviders::getTickers() private$adjustTypes(tmp) } # ,calculateChange = function(last) { # tmp = join( private$dfSession, last[,c("EXC","CTC", "Last")],by = c("CTC", "EXC")) # tmp$Session = (tmp[,4] / tmp[,3]) - 1 # tmp[,3:4] = NULL # tmp = replace(tmp, is.na(tmp), 0) # df = merge(last, tmp, by = c("CTC", "EXC")) # df # } # ,calculateChangeDay = function(last) { # browser() # tmp = join( private$dfSession[,c("EXC","CTC", "Close")] # ,last[,c("EXC","CTC", "Last")] # ,by = c("CTC", "EXC")) # tmp$Session = (tmp[,4] / tmp[,3]) - 1 # tmp[,3:4] = NULL # tmp = replace(tmp, is.na(tmp), 0) # df = merge(last, tmp, by = c("CTC", "EXC")) # df # # # } ,adjustTypes = function(tmp) { tmp[,self$TMS] = as.datet(tmp[,self$TMS]) tmp[,self$HIGH] = as.fiat(tmp[,self$HIGH]) tmp[,self$LOW] = as.fiat(tmp[,self$LOW]) tmp[,self$LAST] = as.fiat(tmp[,self$LAST]) tmp[,self$ASK] = as.fiat(tmp[,self$ASK]) tmp[,self$BID] = as.fiat(tmp[,self$BID]) tmp[,self$CHANGE] = as.percentage(tmp[,self$CHANGE]) tmp[,self$VOLUME] = as.long(tmp[,self$VOLUME]) tmp } ) ) <file_sep>/YATACore/R/PKG_CTES_DB.R # Tables TBL_CURRENCIES = "Currencies" TBL_DAY = "TICKERSD1" TBL_IND_GROUPS = "IND_GROUPS" TBL_IND = "IND_INDS" # Scope of Tickers SCOPE_NONE = 0 SCOPE_ALL = 65535 SCOPE_REAL = 1 SCOPE_MIN05 = 2 SCOPE_MIN15 = 4 SCOPE_HOUR01 = 8 SCOPE_HOUR02 = 16 SCOPE_HOUR04 = 32 SCOPE_HOUR08 = 64 SCOPE_DAY = 256 SCOPE_WEEK = 512 SCOPE_MONTH = 1024 SCOPES = c(SCOPE_REAL ,SCOPE_MIN05 , SCOPE_MIN15, SCOPE_HOUR01, SCOPE_HOUR02, SCOPE_HOUR04 ,SCOPE_HOUR08, SCOPE_DAY, SCOPE_WEEK, SCOPE_MONTH) TERM_LONG = 1 TERM_MEDIUM = 2 TERM_SHORT = 4 TERM_ALL = 15 # Target for formulas TGT_OPEN = 1 TGT_CLOSE = 2 TGT_LOW = 4 TGT_HIGH = 8 TGT_TICKER = 16 TGT_VOLUME = 32 # Data Types TYPE_STR = 1 TYPE_DEC = 10 TYPE_INT = 11 TYPE_LONG = 12 TARGETS = c("Price", "Volume", "Other") XAXIS = c("Date", "Date", "Date") # Parameters PARM_CURRENCY = "currency" PARM_MODEL = "model" PARM_RANGE = "range" PARM_PROVIDER = "provider" <file_sep>/YATAWeb/ui/partials/modTrading/modXFerUI.R modXFerInput <- function(id) { ns = NS(id) useShinyjs() table = {tags$table(class = "box-table", tags$tr(tags$td("Origen", class="tblLabel"), tags$td(class="tblRow", colspan="6", selectInput(ns("cboFrom"), label=NULL, choices=c("Cash"="Cash")) ) ) ,tags$tr(tags$td("Destino", class="tblLabel"), tags$td(class="tblRow", colspan="6", selectInput(ns("cboTo"), label=NULL, choices=c("Cash"="Cash")) ) ) ,tags$tr(tags$td("Moneda", class="tblLabel") ,tags$td(class="tblRow", colspan="6", selectInput(ns("cboXferCurrencies"), label=NULL, choices=c("No curencies"="None")) ) ) ,tags$tr( tags$td("Saldo", class="tblLabel") ,tags$td(class="tblRow",colspan="6",verbatimTextOutput(ns("lblXferSaldo"))) ) ,tags$tr( tags$td("Amount", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtAmount"), label = NULL, value = 0)) ) ,tags$tr( tags$td("Fee", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtXferFee"), label = NULL, value = 0)) ) ,tags$tr(tags$td("Total", class="tblLabel") ,tags$td(class="tblRow",colspan="6",numericInput(ns("txtXferFee"), label = NULL, value = 0)) ) ,tags$tr( tags$td() ,tags$td("Amount", class="tblLabel") ,tags$td(class="tblRow",verbatimTextOutput(ns("lblXferAmount"))) ,tags$td("Efectivo", class="tblLabel") ,tags$td(class="tblRow",verbatimTextOutput(ns("lblXferEfectivo"))) ,tags$td("Fee", class="tblLabel") ,tags$td(class="tblRow",verbatimTextOutput(ns("lblXferFee"))) ) ,tags$tr( tags$td() ,tags$td( colspan="6", bsButton(ns("btnOK"), "Transfer", icon = icon("check"), style = "success") , bsButton(ns("btnXCancel"), "Cancel", icon = icon("remove"), style = "danger") ) ) ,tags$tr( tags$td() ,tags$td( colspan="6", htmlOutput(ns("lblStatus"))) ) ) } tagList(fluidRow(column(width=4) ,column(width=6, table))) } <file_sep>/YATACore/R/TBL_IndNames.R TBLIndNames = R6::R6Class("TBLIndNames", inherit=YATATable, public = list( # Column names ID_GRP = "ID_GROUP" ,ID = "ID_IND" ,PARENT = "ID_PARENT" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,DESCR = "DESCR" ,initialize = function() { self$name="Indicators"; self$table = "IND_INDS"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) self$dfa = self$dfa[self$dfa$ACTIVE == TRUE,] self$df = self$dfa self$df$ACTIVE = as.logical(self$df$ACTIVE) } ,getCombo = function(group) { self$df = self$dfa %>% filter( self$dfa$ID_GROUP == group) setNames(self$df[, self$ID], self$df[,self$NAME]) } ,getIndNameByID = function(id) { id = as.integer(id) tmp = self$dfa[self$dfa$ID_IND == id,] tmp[1,self$NAME] } ) ,private = list ( ) ) <file_sep>/YATAModels/R/IND_OBV.R IND_OBV <- R6Class("IND_OBV", inherit=IND__Base, public = list( name="On-Balance Volume" ,symbol="OBV" ,initialize = function() { super$initialize() } ,calculate = function(TTickers, date) { threshold = self$getParameter("threshold") if (!(threshold < 1 )) threshold = threshold / 100 xt = private$getXTS(TTickers, pref=prev) calcVar = function(x) { res = x[2] / x[1] if (res > (1.0 + threshold)) return (+1) if (res < (1.0 - threshold)) return (-1) return (0) } var = rollapply(private$data[,TTIckers$PRICE], 2, calcVar, fill=0, align="right") prevVol = rbind(private$data[1,TTIckers$VOLUME], private$data[1:nrow(private$data)-1,TTIckers$VOLUME]) prevVol = prevVol * var private$data = private$data[,TTIckers$VOLUME] + prevVol applySign = function(x) { if (sign(x[2]) == sign(x[1])) return (0) if (sign(x[1]) == -1) return (+1) return (-1) } nFast = self$getParameter("nfast") nSlow = self$getParameter("nslow") nSig = self$getParameter("nsig") maType = self$getParameter("matype", "EMA") prev = max(nFast, nSlow, nSig) xt = private$getXTS(TTickers, pref=prev) if (nrow(xt) < prev) return (NULL) tryCatch({ macd = TTR::MACD(xt[,TTickers$PRICE], nFast, nSlow, nSig, maType=maType) private$data = as.data.frame(macd[(prev + 1):nrow(macd),]) private$setDataTypes("number", c("macd", "signal")) private$calcVariation("macd") private$data[,"act"] = rollapply(private$data[,"var"], 2, applySign, fill=0, align="right") private$setColNames() } ,error = function(e) { return (NULL) } ) } # Dibuja sus graficos ,plot = function(p, TTickers) { if (!is.null(private$data)) { p = YATACore::plotBar (p, TTickers$df[,self$xAxis], private$data[,private$setColNames("macd")],hoverText=self$symbol) p = YATACore::plotLine(p, TTickers$df[,self$xAxis], private$data[,private$setColNames("signal")],hoverText=c(self$symbol, "Signal")) } p } ) ) <file_sep>/YATAConfig/SQL/ctc_dat_portfolio.sql USE CTC; DELETE FROM PROVIDERS; INSERT INTO PROVIDERS ( ID, NAME) VALUES ( "POL", "Poloniex" ); DELETE FROM CLEARINGS; -- INSERT INTO CLEARINGS (ID_CLEARING, NAME) VALUES ( "ING", "ING"); INSERT INTO CLEARINGS (ID_CLEARING, NAME, MAKER, TAKER) VALUES ( "POL", "Poloniex", 8, 20); -- INSERT INTO CLEARINGS (ID_CLEARING, NAME) VALUES ( "COINBASE", "Coin Base"); DELETE FROM ACCOUNTS; -- INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("ING" , "EUR", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("POL" , "USDC", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("POL" , "USDT", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("POL" , "BTC", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("POL" , "ETH", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); -- INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("COINBASE" , "USDT", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); -- INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("COINBASE" , "BTC", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); -- INSERT INTO ACCOUNTS (ID_CLEARING, CURRENCY, BALANCE, CC) VALUES ("COINBASE" , "ETH", 0.0, "XXXX-XXXX-XX-XXXXXXXX"); -- DELETE FROM PORTFOLIO; -- INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "ING", "EUR", 10000, 1, 0, 10000, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "USD", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "BTC", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "ETH", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "LTC", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "USDT", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "USDC", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "ETC", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "RDD", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); INSERT INTO PORTFOLIO (ID_CLEARING, CURRENCY, POS, AVAILABLE, ACTIVE, LAST_OP, LAST_VALUE, LAST_TMS) VALUES ( "POL", "STRAT", 0.0, 0.0, 1, 0, 0, "1980-01-01 00:00:00"); COMMIT; <file_sep>/YATAAnalytics/R/loadCase.R library(XLConnect) library(plotly) case="batch_20181027_142527" XLConnect::xlcFreeMemory() gc() df = read.csv(paste0("d:/prj/R/YATA/YATAData/out/",case,".csv"),sep=";",dec=",") # # plot_ly(df, x = ~Trend, y = ~Res, z = ~Period) %>% add_markers() # plot_ly(df, x = ~Trend, y = ~Res, color = ~Period) %>% add_markers() table(sign(df$Res)) tbl=NULL for (w in unique(df$window)) { #tbl = rbind(tbl,table(sign(df[df$window == w,"Res"]))) table(sign(df[df$window == w,"Res"])) } # TUSD Vale 1.11 respecto al USDT, pero contra el dólar no tiene esa diferencia, # no es que haya subido el TUSD tanto respecto al dólar, sino que el Tether ha caído, # de ahí esa diferencia de precio respecto el TUSD. <file_sep>/YATAConfig/SQL/ctc_db.sql DROP DATABASE IF EXISTS CTC; CREATE DATABASE CTC CHARACTER SET utf8 COLLATE utf8_general_ci; <file_sep>/YATAWeb/ui/modSimmUI.R # files.trading = list.files("ui/partials/modAnalysis", pattern="*UI.R$", full.names=TRUE) # sapply(files.trading,source) # Al ffinal siempre es la misma pagina modSimmInput <- function(id) { ns = NS(id) useShinyjs() tgts = FTARGET$new() panelLeft = tagList( textInput(ns("txtPrfName"), label = "Nombre", value = "Javier") ,selectInput(ns("rdoPProfile"), label=NULL, selected = PRF_MODERATE , choices=c("Conservador", "Moderado", "Atrevido", "Arriesgado")) ,numericInput(ns("txtPrfImpInitial"), label = "Capital", value=10000, min=1000, step=500) ,hr() ,selectInput(ns("cboProvider"), label = "Provider", choices = NULL, selected=NULL) ,selectInput(ns("cboBases"), label = "Base", choices = NULL, selected=NULL) ,selectInput(ns("cboMonedas"), label = "Moneda", choices = NULL, selected=NULL) ,dateInput(ns("dtFrom"),"Desde", value = "2012-02-29", format = "dd/mm/yy", startview = "year") ,dateInput(ns("dtTo"),NULL, value = "2012-02-29", format = "dd/mm/yy", startview = "year") ,hr() ,selectInput(ns("cboScope"), label="Scope", selected=2,choices=c("Intraday"=1,"Day"=2,"Week"=3,"Month"=4)) ,hr() ,bsButton(ns("btnSave"), label = "Guardar", style="success", size="large") ) panelMain = tagList( #fluidRow( # fluidRow( class="YATAInline", width="100%" # ,column(width=7, # menuTab(id=ns("tabs"), names=c("Largo", "Intermedio", "Corto"), values=c(1,2,4), selected=2) # )) # ) fluidRow(boxPlus(id=ns("boxHeader") ,title=textOutput(ns("lblHeader")) , closable = FALSE ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,enable_label = TRUE ,width = 12 # ,plotlyOutput(ns("plot"), height="500px", inline=TRUE) ,hidden(plotlyOutput(ns("plot1"), width="100%", height="auto", inline=T)) ,hidden(plotlyOutput(ns("plot2"), width="100%", height="auto", inline=T)) ,hidden(plotlyOutput(ns("plot3"), width="100%", height="auto", inline=T)) ,hidden(plotlyOutput(ns("plot4"), width="100%", height="auto", inline=T)) ,fluidRow( selectInput(ns("cboModel"), label=NULL, choices=NULL, selected=NULL) ,bsButton(ns("btnModel"), label = "Modelo", style="success", size="large") ,sliderInput(ns("sldRange"), label = NULL, min = 0, max = 100, value = c(40, 60)) ,bsButton(ns("btnOpenDlg"), label = "Indicador", style="success", size="large") ) )) ,fluidRow( column(width=6, DT::dataTableOutput(ns("tblSimm"))) # ,column(width=3, DT::dataTableOutput(ns("tblDataUp"))) # ,column(width=3, DT::dataTableOutput(ns("tblDataDown"))) ) # tabsetPanel(id=ns("tabs"), type="pills" # ,tabPanel("Largo", value = "4", # column(12, id=ns("pnlLong") # # ,fluidRow(plotlyOutput(ns("plotLong"), width="100%",height="500px")) # ,fluidRow(DT::dataTableOutput(ns("tblLong"))) # ) # ) # ,tabPanel("Intermedio", value="2" # ,column(12, id=ns("pnlMedium") # # ,fluidRow(plotlyOutput(ns("plotMedium"), width="100%",height="500px")) # ,fluidRow(DT::dataTableOutput(ns("tblMedium"))) # ) # ) # ,tabPanel("Corto", value="1" # ,column(12, id=ns("pnlShort") # # ,fluidRow(plotlyOutput(ns("plotShort"), width="100%",height="500px")) # ,fluidRow(DT::dataTableOutput(ns("tblShort"))) # ) # ) # ) # ,column(2 # ,dateInput("dtCurrent", "Date:", value = "2012-02-29", format = "dd/mm/yy", startview = "year") # ,box( width=NULL, title = "Position", solidHeader = T, status = "primary" # ,withTags({ table(class = "boxTable", # tr(td("Euro"), td(colspan="2", class="lblData", textOutput(ns("lblPosFiat")))) # ,tr(td(textOutput(ns("lblMoneda"))), td(colspan="2", class="lblData", textOutput(ns("lblPosMoneda")))) # ,tr(td("Total"), td(colspan="2", class="lblData", textOutput(ns("lblPosTotal")))) # ,tr(td("Estado"), td( img(id=ns("resDown"), icon("triangle-bottom", class = "rojo", lib="glyphicon")) # ,img(id=ns("resUp"), icon("triangle-top", class = "verde", lib="glyphicon"))) # ,td( class="lblData", textOutput(ns("lblEstado")))) # ,tr(td("Tickers"),td(colspan="2", class="lblData", textOutput(ns("lblResMov")))) # ,tr(td("Opers"), td( class="lblData", textOutput(ns("lblResC"))) # ,td( class="lblData", textOutput(ns("lblResV")))) # ,tr(td("Date"), td(colspan="2", class="lblData", textOutput(ns("lblPosDate")))) # ,tr(td("Trend"), td(colspan="2", class="lblData", textOutput(ns("lblTrend")))) # # ) # # })) # ) ) # panelTool = box(width=NULL # , title = p("Toolbox",actionButton( ns("SBLClose"), "",icon = icon("remove"), class = "btn-xs")) # ) # # panelLeft = getPanelLeft(id) # # #source("ui/partials/panelRight.R") panelRight = tagList( boxPlus(id=ns("boxPlots") ,title="Plot" ,closable = FALSE ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,enable_label = TRUE ,width = 6 ,wellPanel(h3("Plot sources") ,selectInput(ns("cboPlot1"), label = "Primary", choices = tgts$getCombo(), selected = 2) ,selectInput(ns("cboPlot2"), label = "Secondary", choices = tgts$getCombo(), selected = 0) ,selectInput(ns("cboPlot3"), label = "Terciary", choices = tgts$getCombo(), selected = 0) ,selectInput(ns("cboPlot4"), label = "Terciary", choices = tgts$getCombo(), selected = 0) ) ,wellPanel(h3("Plot types") ,selectInput(ns("cboType1"), label = "Primary", choices = PLOT$getCombo(), selected = 3) ,selectInput(ns("cboType2"), label = "Secondary", choices = PLOT$getCombo(), selected = 4) ,selectInput(ns("cboType3"), label = "Terciary", choices = PLOT$getCombo(), selected = 0) ,selectInput(ns("cboType4"), label = "Terciary", choices = PLOT$getCombo(), selected = 0) ) ) # ,radioButtons(ns("rdoPlot"), label="Graph",selected = PLOT_LINEAR # , choices = list( "Linear" = PLOT_LINEAR # ,"Log" = PLOT_LOG # ,"Candles" = PLOT_CANDLE) # )) # ,wellPanel(checkboxGroupInput(ns("chkIndicators"), label = NULL) # ,checkboxInput(ns("chkShowInd"), label=LBL.SHOW_IND, value = TRUE) # ,wellPanel(radioButtons(ns("rdoProcess"), label="Mode",selected = MODE_AUTOMATIC # ,choices = list( "Automatic" = MODE_AUTOMATIC # ,"Inquiry" = MODE_INQUIRY # ,"Manual" = MODE_MANUAL))) # ) # # tagList(fluidRow( #hidden(column(id=ns("pnlLeft"), panelLeft, width=2)) # column(id=ns("pnlMain"), panelMain, width=12) # ,hidden(column(id=ns("pnlRight"), panelRight, width=2)) # # )) # panelModal = fluidRow(column(width=3) ,column(width=6, boxPlus(id=ns("boxDlg") ,title="Cosa modal" ,closable = TRUE ,status = "primary" ,solidHeader = TRUE ,collapsible = FALSE ,enable_label = TRUE ,width = 12 ,fluidRow( column(width=1), column(width=2, h3("Group")) ,column(width=6, selectInput(ns("cboIndGroups"), label = NULL, choices = NULL)) ) ,fluidRow( column(width=1), column(width=2, h3("Indicator")) ,column(width=6,selectInput(ns("cboIndNames"), label = NULL, choices = NULL)) ) ,hidden(div(id=ns("dlgIndBody") ,fluidRow(column(width=1), column(width=6, h3(textOutput(ns("indTitle"))))) ,fluidRow(column(width=1), column(width=8, uiOutput(ns("indDoc"))) ) ,fluidRow(column(width=1), column(width=2, h3("Nombre")) , column(width=6, textInput(ns("lblIndName"), label=NULL))) ,hidden(fluidRow(id=ns("row0"), column(width=1), column(width=2, h3("Apply To")) , column(width=6, selectInput(ns("cboTarget"), label = NULL , choices = c(""))))) ,hidden(fluidRow(id=ns("row1"), column(width=1), column(width=2, h3(textOutput(ns("lblParm1")))) , column(width=6, numericInput(ns("parm1"), label = NULL, value=0)))) ,hidden(fluidRow(id=ns("row2"), column(width=1), column(width=2, h3(textOutput(ns("lblParm2")))) , column(width=6, numericInput(ns("parm2"), label = NULL, value=0)))) ,hidden(fluidRow(id=ns("row3"), column(width=1), column(width=2, h3(textOutput(ns("lblParm3")))) , column(width=6, numericInput(ns("parm3"), label = NULL, value=0)))) ,hidden(fluidRow(id=ns("row4"), column(width=1), column(width=2, h3(textOutput(ns("lblParm4")))) , column(width=6, numericInput(ns("parm4"), label = NULL, value=0)))) ,hidden(fluidRow(id=ns("row5"), column(width=1), column(width=2, h3(textOutput(ns("lblParm5")))) , column(width=6, numericInput(ns("parm5"), label = NULL, value=0)))) ,hidden(fluidRow(id=ns("row6"), column(width=1), column(width=2, h3(textOutput(ns("lblParm6")))) , column(width=6, numericInput(ns("parm6"), label = NULL, value=0)))) )) ,fluidRow( column(width=4) ,column(width=6, bsButton(ns("btnAddDlg"), "Add", icon = icon("check"), style = "success") , bsButton(ns("btnCloseDlg"), "Cancel", icon = icon("remove"), style = "danger")) ) )) ) # dataModal <- function(failed = FALSE) { # modalDialog( # textInput("dataset", "Choose data set", # placeholder = 'Try "mtcars" or "abc"' # ), # span('(Try the name of a valid data object like "mtcars", ', # 'then a name of a non-existent object like "abc")'), # if (failed) # div(tags$b("Invalid name of data object", style = "color: red;")), # # footer = tagList( # modalButton("Cancel"), # actionButton("ok", "OK") # ) # ) # } makePage(id, left=panelLeft, main=panelMain, right=panelRight, modal=panelModal) }<file_sep>/YATAWeb/ui/dlgModal.R dataModal <- function(failed = FALSE) { modalDialog( textInput("dataset", "Choose data set", placeholder = 'Try "mtcars" or "abc"' ), span('(Try the name of a valid data object like "mtcars", ', 'then a name of a non-existent object like "abc")'), if (failed) div(tags$b("Invalid name of data object", style = "color: red;")), footer = tagList( modalButton("Cancel"), actionButton("ok", "OK") ) ) } <file_sep>/YATACore/R/TBL_Currencies_CTC.R TBLCTC = R6::R6Class("TBLCTC", inherit=YATATable, public = list( PRTY = "PRTY" ,SYMBOL = "SYMBOL" ,NAME = "NAME" ,ACTIVE = "ACTIVE" ,DECIMALS = "DECIMALS" ,initialize = function() { self$name="Currencies"; self$table = "CURRENCIES_CTC"; super$refresh() self$dfa$ACTIVE = as.logical(self$dfa$ACTIVE) self$df$ACTIVE = as.logical(self$df$ACTIVE) } ) ,private = list ( ) ) <file_sep>/YATABatch/R/YATABatchInternals.R # Clase base de los ficheros prepareCases <- function(ids, dbCases) { dfTotal = NULL tbCases = dbCases$getTable(TCASES_CASES) tbIndex = DBCTC$getTable(TCTC_INDEX) if (!is.null(ids)) { tbCases$filterByID(ids) } for (iCase in 1:nrow(tbCases$df)) { tbIndex$setRange(tbCases$df[iCase,tbCases$FROM], tbCases$df[iCase,tbCases$TO]) for (iCurrency in 1:nrow(tbIndex$df)) { df = .makeIntervals(tbIndex$df[iCurrency, tbIndex$SYMBOL], tbCases, iCase) df[,"Name"] = tbIndex$df[iCurrency, tbIndex$NAME] df[,"Symbol"] = tbIndex$df[iCurrency, tbIndex$SYMBOL] df[,"idTest"] = tbCases$df[iCase, tbCases$ID] df[,"Capital"] = tbCases$df[iCase, tbCases$CAPITAL] df[,"Model"] = tbCases$df[iCase, tbCases$MODEL] if (is.null(dfTotal)) { dfTotal = df } else { dfTotal = rbind(dfTotal, df) } } } dfTotal } .makeIntervals <- function(symbol, tbCases, idx) { # ...) { # prms = list(...)[[1]] tbTickers = TBLTickers$new(symbol) beg = as.date(tbTickers$getField("FIRST", tbTickers$DATE)) last = as.date(tbTickers$getField("LAST", tbTickers$DATE)) if(!is.na(tbCases$df[idx,tbCases$START])) beg=as.date(tbCases$df[idx,tbCases$START]) prf = .expandNumber(tbCases$df[idx,tbCases$PROFILE]) per = .expandNumber(tbCases$df[idx,tbCases$PERIOD]) start = .expandMonth (beg,last,tbCases$df[idx,tbCases$INTERVAL]) cols = list(prf, start, per) colNames = c(tbCases$PROFILE, tbCases$START, tbCases$PERIOD) if(!is.na(tbCases$df[idx,tbCases$LBL_PARMS])) { parms = tbCases$getGroupFields(tbCases$GRP_PARMS) pNames = strsplit(tbCases$df[idx,tbCases$LBL_PARMS], ";")[[1]] iPrm = 1 for (nPrm in pNames) { prm = .expandNumber(tbCases$df[idx, parms[[iPrm]]]) cols = list.append(cols, prm) colNames = c(colNames, paste0(tbCases$GRP_PARMS,nPrm)) iPrm = iPrm + 1 } } if(!is.na(tbCases$df[idx,tbCases$LBL_THRES])) { thres = tbCases$getGroupFields(tbCases$GRP_THRES) pThres = strsplit(tbCases$df[idx,tbCases$LBL_THRES], ";")[[1]] iThr = 1 for (nThr in pThres) { thr = .expandNumber(tbCases$df[idx, thres[[iThr]]]) cols = list.append(cols, thr) colNames = c(colNames, paste0(tbCases$GRP_THRES,nThr)) iThr = iThr + 1 } } gr = expand.grid(cols) df = data.frame(gr) colnames(df) = colNames # El calculo de la fecha fin se debe hacer cuando ya esta expandido colEnd = as.mondate(eval(tbCases$asExpr(tbCases$START))) + eval(tbCases$asExpr(tbCases$PERIOD)) df = add_column(df, End = as.date(colEnd), .after = tbCases$START) df } .expandNumber <- function(num) { toks=strsplit(as.character(num), ";")[[1]] toks = as.numeric(toks) if (length(toks) == 1) toks = c(toks, toks) if (length(toks) < 3) toks = c(toks, 1) seq(from=toks[1],to=toks[2], by=toks[3]) } .expandMonth <- function(beg, end, interval) { if (interval == 0) return(beg) seq(from=beg, to=end, by=paste(interval, "months")) } <file_sep>/YATAConfig/SQL/ctc_dat_codes.sql USE CTC; DELETE FROM CODE_GROUPS; DELETE FROM CODES; INSERT INTO CODE_GROUPS ( ID, NAME, DESCR) VALUES ( 1, "TERM", "Short, Medium and Long"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 1, 1, "Short" , "Ambito corto"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 1, 2, "Medium" , "Ambito normal"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 1, 4, "Long" , "Ambito largo"); INSERT INTO CODE_GROUPS ( ID, NAME, DESCR) VALUES ( 2, "SCOPE" , "Alcance de los Tickers"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 1, "Real" , "Minuto o tiempo real"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 2, "5 Min." , "5 Minutos"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 4, "15 Min." , "Cuartos"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 8, "1 Hour" , "1 Hora"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 16, "2 Hours" , "2 Horas"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 32, "4 Hours" , "Media Jornada"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 64, "8 Hour" , "Jornada Laboral"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 256, "Day" , "Diario" ); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 512, "Weekly" , "Semanal"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 1024, "Monthly" , "Mensual"); INSERT INTO CODE_GROUPS ( ID, NAME, DESCR) VALUES ( 5, "TARGET" , "Dato operativo del indicator"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 5, 1, "Open" , "Open"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 2, "Close" , "Close"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 4, "Low" , "Low"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 8, "High" , "High"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 16, "Ticker" , "Open/Close - High/Low"); INSERT INTO CODES (ID_GROUP, ID, NAME, DESCR) VALUES ( 2, 32, "Volume" , "Volumen"); COMMIT;<file_sep>/YATAManualTech/9999-TODO.Rmd # TO DO En esta seccion estan las cosas que se deberian implementar, mejorar, etc. Cuando alguna de ellas se realice, normalment pasara al apartado de decisiones ## Tablas de Datos La clase base deberia incoprorar metodos para inserta y actualizar datos Para el Update por ejemplo update(list(campos), list(where)) ## Tablas HTML Se deberia hacer un widget para el control de las tablas HTML del tipo etiqueta, widget<file_sep>/YATACore/R/IND_Oscillators.R # Oscillators are also best characterized by their scale. # Oscillators typically oscillate around zero. # Common examples are the MACD, Stochastic Oscillator, and RSI. # These are typically plotted below the price history in charts because they do not share scale with it.<file_sep>/YATACore/R/R6_YATADBTable.R # Clase base de los ficheros y tablas # Emula una tabla YATATable <- R6Class("YATATable", public = list( name = "friendlyName" ,table = "tableName" ,df = NULL # Selected data ,dfa = NULL # All data ,metadata = NULL ,initialize = function(refresh=TRUE, name = NULL, table = NULL) { if (!is.null(name)) { self$name = name self$table = name } if (!is.null(table)) self$table = table if (refresh) self$refresh() self$metadata = getMetadata(self$table) } ,select = function(key) { stop("This method is virtual") } ,insert = function(values, isolated=T) { sql = paste("INSERT INTO ", self$table, "(") sql = paste(sql, toString(names(values))) sql = paste(sql, ") VALUES (", toString(rep("?", length(values))), ")") executeUpdate(sql, values, isolated=isolated) } ,update = function(values, keys, isolated=T) { sql = paste("UPDATE ", self$table, "SET") upd = gsub(",", " = ?,", paste(toString(names(values)), ",")) upd = substr(upd, 1, nchar(upd) - 1) sql = paste(sql, upd, "WHERE") key = gsub(",", " = ? AND", paste(toString(names(keys)), ",")) key = substr(key, 1, nchar(key) - 3) sql = paste(sql, key) executeUpdate(sql, parms=c(values, keys), isolated=isolated) } ,refresh = function(method = NULL, ...) { if (is.null(self$dfa)) { # dfa tiene todo, no tiene sentido refrescarlo ##JGG mirar con substitute #parms = as.list(...) # Cargar por tabla if (is.null(method)) { method = "loadTable" parms = list(self$table) } self$dfa = do.call(method, parms) self$df = self$dfa } invisible(self) } ,setData = function(df) { self$dfa = df; self$df=df; invisible(self) } ,getRow = function(row) { if (is.numeric(row)) return (self$df[row,]) if (toupper(row) == "FIRST") return (self$df[1,]) if (toupper(row) == "LAST") return (self$df[nrow(self$df),]) stop(MSG_BAD_ARGS()) } ,nrow = function() { nrow(self$df) } ,getColumn = function(colname) { self$df[,colname] } ,getField = function(row, col) { row = self$getRow(row); return (row[1,col]) } ,getColumns = function(colnames) { self$df[,colnames] } ,fieldIndex = function(name) { which(private$fields == name)[1] } ,fieldName = function(index) { private$fields[index] } ,fieldsCount = function() { length(private$fields) } ,asExpr = function(name, df="df") { parse(text=paste0(df,"$",name)) } ,print = function(...) { cat(self$name) } ) ) <file_sep>/YATAModels/R/IND_ALMA.R # Media Móvil Ponderada con retraso regulado usando una curva de distribución normal (o Gaussiana) # como función de ponderación de coeficientes. # Esta Media Móvil utiliza una curva de distribución Normal (Gaussiana) que puede ser puesta # por el parámetro Offset de 0 a 1. # Este parámetro permite regular la suavidad y la alta sensibilidad de la Media Móvil. # Sigma es otro parámetro que es responsable de la forma de los coeficientes de la curva. # Una descripción más detallada de ALMA se puede encontrar en el sitio web del autor. # https://www.mql5.com/go?link=http://www.arnaudlegoux.com/ # Window size: # The Window Size is nothing but the look back period and this forms the basis of your ALMA settings. # You can use the ALMA window size to any value that you like, # although it is best to stick with the well followed parameters # such as 200, 100, 50, 20, 30 and so on based on the time frame of your choosing. # Offset: # The offset value is used to tweak the ALMA to be more inclined towards responsiveness or smoothness. # The offset can be set in decimals between 0 and 1. # A setting of 0.99 makes the ALMA extremely responsive, while a value of 0.01 makes it very smooth. #Sigma: # The sigma setting is a parameter used for the filter. # A setting of 6 makes the filter rather large while a smaller sigma setting makes it more focused. # According to Mr. Legoux, a sigma value of 6 is said to offer good performance. # Formula # 1/NORM SUM(i=1 hasta window) p(i)e elevado (i-offset)2 / sigma 2 #source(paste(YATAENV$modelsDir,"Model_MA.R",sep="/")) source("R/IND_MA.R") IND_ALMA <- R6Class("IND_ALMA", inherit=IND_MA, public = list( name="<NAME>" ,symbol="ALMA" ,initialize = function() { super$initialize(list(window=7,offset=0.5,sigma=6)) ind1 = YATAIndicator$new( self$name, self$symbol, type=IND_LINE, blocks=3 ,parms=list(window=7, offset=0.5, sigma=6)) private$addIndicators(ind1) } # ,calculate <- function(data, ind, columns, n, offset, sigma) { ,calculate = function(data, ind) { if (ind$name != self$symbol) return (super$calculate(data, ind)) xt=private$getXTS(data) n = private$parameters[["window"]] offset = private$parameters[["offset"]] sigma = private$parameters[["sigma" ]] res1 = TTR::ALMA(xt[,data$PRICE] ,n,offset,sigma) res2 = TTR::ALMA(xt[,data$VOLUME],n,offset,sigma) list(list(private$setDF(res1, ind$columns)), list(private$setDF(res2, paste0(ind$columns, "_v")))) } ) ) <file_sep>/YATAWSSClient/WSSClient.R library(websocket) #ws <- WebSocket$new("ws://127.0.0.1:8888/", # headers = list(Cookie = "Xyz"), # accessLogChannels = "all" # enable all websocketpp logging ws <- WebSocket$new("wss://api2.poloniex.com") ws$onOpen(function(event) { cat("Connection opened\n") }) ws$onClose(function(event) { cat("Client disconnected with code ", event$code, " and reason ", event$reason, "\n", sep = "") }) ws$onError(function(event) { cat("Client failed to connect: ", event$message, "\n") }) ws$onMessage(function(event) { cat("RECIBIDO: ", event$data, "\n") }) #ws$send("hello") #ws$send(charToRaw("hello")) #ws$close() # { "command": "subscribe", "channel": "1002" }<file_sep>/YATACore/R/IND_Accumulators.R # Accumulators depend on the value of itself in past periods to calculate future values. # This is different from most indicators that depend only on price history, not indicator history. # They have the advantage of being windowlengthindependent in that the user does not specify any n periods # in the past to be computed. This is an advantage purely on the level of robustness and mathematical elegance. # They are very often volume-oriented. # Examples are On-Balance Volume, Negative Volume Index, and the Accumulation/Distribution Line. # Rule sets typically concentrate on the relationship between the accumulator and an average or # maximum of itself. Here’s an example: If the Negative Volume Index crosses above a moving average of itself, # buy the stock at market price. # LM <- function(data,interval=7) { # res = rollapply(data$df[,data$PRICE],interval,mean,fill=NA, align="right") # as.data.frame(res) # } <file_sep>/YATAWeb/ui/partials/modTrading/modOpenUI.R modOpenInput <- function(id) { ns = NS(id) useShinyjs() fluidRow( column(width=6, DT::dataTableOutput(ns("tblOpen"))) ) }<file_sep>/YATAConfig/R/GlobalConfig.R DIR_MODELS="D:/prj/R/YATA/YATAModels/R" #MODEL_PREFIX="Model_" MODEL_BASE="Model_Base.R" # Cual es el minimo numero de datos a procesar en funcion del periodo deseado # Es decir, si queremos un periodo de 3 meses y solo disponemos de 2 (0.66) procesar o no? MIN_PERCENTAGE=0.8 <file_sep>/YATAWeb/ui/modOnLineUI.R modOnLineInput <- function(id) { ns <- NS(id) useShinyjs() panelLeft = tagList( bsButton(ns("btnCancel"), "Stop subscription", icon = icon("remove"), style = "danger") ,wellPanel(h3("Plot") ,sliderInput(ns("mins"), "Interval", min=0, max=60, step=5, value=15) ,sliderInput(ns("rows"), "Max. Points", min=0, max=500, step=10, value=0) ,radioGroupButtons(ns("field"), label = "Data", choices = list("Last", "Ask", "Bid", "High", "Low", "Volume"), selected = "Last", direction="horizontal", size="xs", justified = FALSE, status = "primary", checkIcon = list(yes = icon("ok", lib = "glyphicon")) ) ,radioGroupButtons(ns("graph"), label = "Plot type", choices = list("Value"=1, "Last Change"=2, "Session Change"=3, "Day Change"=4, "Candle"=5), selected = 1, direction="horizontal", size="xs", justified = FALSE, status = "secondary", checkIcon = list(yes = icon("ok", lib = "glyphicon")) ) ) ,wellPanel(h3("Currencies") ,radioGroupButtons(ns("rdoRange"), label = "Data value", choices=c("Close", "Session", "Last"="Var"), selected="Close" ,direction="horizontal", size="sm",justified = FALSE, status = "primary" ,checkIcon = list(yes = icon("ok", lib = "glyphicon")) ) ,sliderInput(ns("sldRows"), "Max", min=0, max=10, step=1, value=10) ,sliderInput(ns("sldVar"), "Show Variation", min=0, max=100, step=10, value=5) ) ,bsButton(ns("btnConfig"), "Update", icon = icon("check"), style = "success") ) #panelMain = column(id = ns("main"), width=12 panelMain = tagList(fluidRow(boxPlus(id=ns("boxHeader") ,title=textOutput(ns("lblHeader")) , closable = FALSE ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,enable_label = TRUE ,width = 12 ,label_text = textOutput(ns("lblMins"), inline=TRUE) ,menuTab(ns("olMenu"), c("")) ,fluidRow(plotlyOutput(ns("plot"), width="98%",height="500px")) )) ,fluidRow( column(width=6, DT::dataTableOutput(ns("tblData"))) ,column(width=3, DT::dataTableOutput(ns("tblDataUp"))) ,column(width=3, DT::dataTableOutput(ns("tblDataDown"))) ) ) panelRight = tagList( # div(id = ns("right")# , class="shinyjs-hide" switchInput(inputId = ns("swBTC"),label = "Bitcoin", labelWidth = "80px") ,pickerInput(inputId = ns("chkCTC"),label = "Currency" ,multiple = TRUE ,choices = NULL ,options = list( title="Currencies" ,selectedTextFormat = "count" ,`actions-box` = TRUE ,liveSearch = TRUE) ) ,noUiSliderInput(inputId = ns("sldRngVal"),label = "Value Range" ,min = 0, max = 10000, step=1000, value=c(10,10000)) ,noUiSliderInput(inputId = ns("sldRngPrc"),label = "Value Percentage" ,min = -100, max = 100, step=10, value=c(-100,100)) ,fluidRow(column(width=12,bsButton(ns("btnInfo"), "Update", icon = icon("check"), class="btn-block", style = "primary"))) ) # tagList( fluidRow(panelLeft, panelMain, panelRight)) makePage(id, left=panelLeft, main=panelMain, right=panelRight) } <file_sep>/YATAWeb/www/yata/yata.js /* * Muestra/oculta los iconos de los paneles laterales */ function YATAIconBar(side, show) { el = document.getElementById("YATANav-" + side); if (show) { el.classList.add("shinyjs-show"); el.classList.remove("shinyjs-hide"); } else { el.classList.add("shinyjs-hide"); el.classList.remove("shinyjs-show"); } } function YATALang() { var language = window.navigator.userLanguage || window.navigator.language; Shiny.onInputChange('YATALang', language); } /* * Muestra/oculta El panel lateral */ function YATAToggleSideBar(left, show) { var item = "YATAIconNav"; var side = (left) ? "-left" : "-right"; var div = (left) ? "YATALeftSide" : "YATARightSide"; divBase = item + side; if (show) { document.getElementById(divBase + "-on").style.display = "none"; document.getElementById(divBase + "-off").style.display = "inline-block"; } else { document.getElementById(divBase + "-on").style.display = "inline-block"; document.getElementById(divBase + "-off").style.display = "none"; } var element = document.getElementById(div); element.classList.toggle("shinyjs-hide"); element.classList.toggle("shinyjs-show"); } /* * Ajusta los paneles y los iconos */ function YATAShowHide(panel, child) { child.classList.add("shinyjs-show"); child.classList.remove("shinyjs-hide"); p = document.getElementById(panel); childs = p.childNodes; for (var i = 0; i < childs.length; i++) { childs[i].classList.add("shinyjs-hide"); childs[i].classList.remove("shinyjs-show"); } p.appendChild(child); } function YATAPanels(ns) { left = document.getElementById(ns + "left"); right = document.getElementById(ns + "right"); // modal = document.getElementById(ns + "modal"); YATAIconBar("left", 0); YATAIconBar("right", 0); if (left) { YATAShowHide("YATALeftSide", left); YATAIconBar("left", 1); } if (right) { YATAShowHide("YATARightSide", right); YATAIconBar("right", 1); } // if (modal) { // p = document.getElementById("main-container"); // p.appendChild(modal); // } } <file_sep>/YATAConfig/SQL/ctc.sql /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; CREATE TABLE IF NOT EXISTS `currencies_ctc` ( `PRTY` int(11) NOT NULL DEFAULT 999, `SYMBOL` varchar(8) NOT NULL, `NAME` varchar(64) NOT NULL, `DECIMALS` int(11) NOT NULL, `ACTIVE` tinyint(4) NOT NULL, `FEE` double DEFAULT 0, PRIMARY KEY (`SYMBOL`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40000 ALTER TABLE `currencies_ctc` DISABLE KEYS */; INSERT IGNORE INTO `currencies_ctc` (`PRTY`, `SYMBOL`, `NAME`, `DECIMALS`, `ACTIVE`, `FEE`) VALUES (500, '1CR', '1Credit', 6, 1, 0), (501, 'ABY', 'ArtByte', 6, 1, 0), (502, 'AC', 'AsiaCoin', 6, 1, 0), (503, 'ACH', 'AchieveCoin', 6, 1, 0), (504, 'ADN', 'Aiden', 6, 1, 0), (505, 'AEON', 'Aeon', 6, 1, 0), (506, 'AERO', 'CryptoAero', 6, 1, 0), (507, 'AIR', 'AirToken', 6, 1, 0), (768, 'AMP', 'HyperSpace', 6, 1, 0), (508, 'APH', 'Aphelion', 6, 1, 0), (755, 'ARCH', 'ARCHCoin', 6, 1, 0), (778, 'ARDR', 'ARDR', 6, 1, 0), (59, 'AUR', 'AuroraCoin', 6, 1, 0), (510, 'AXIS', 'AxisCoin', 6, 1, 0), (511, 'BALLS', 'SnowBalls', 6, 1, 0), (512, 'BANK', 'BANK', 6, 1, 0), (795, 'BAT', 'Basic Attentio Token', 6, 1, 0), (513, 'BBL', 'BitBlock', 6, 1, 0), (514, 'BBR', 'BoolBerry', 6, 1, 0), (515, 'BCC', 'BitConnect', 6, 1, 0), (4, 'BCH', 'Bitcoin Cash', 6, 1, 0), (801, 'BCHABC', 'Bitcoin Cash ABC', 6, 1, 0), (14, 'BCHSV', 'Bitcoin SV', 6, 1, 0), (42, 'BCN', 'Bytecoin', 6, 1, 0), (762, 'BCY', 'BitCrystals', 6, 1, 0), (517, 'BDC', 'Bollywood Coin', 6, 1, 0), (518, 'BDG', 'BitDegree', 6, 1, 0), (519, 'BELA', 'BELA Coin', 6, 1, 0), (766, 'BITCNY', 'bitCNY', 6, 1, 0), (520, 'BITS', 'Bitstart', 6, 1, 0), (765, 'BITUSD', 'bitUSD', 6, 1, 0), (521, 'BLK', 'Black Coin', 6, 1, 0), (522, 'BLOCK', 'Block Net', 6, 1, 0), (523, 'BLU', 'BlueCoin', 6, 1, 0), (524, 'BNS', 'BonusCoin', 6, 1, 0), (798, 'BNT', 'Bancor', 6, 1, 0), (525, 'BONES', 'Bones Cryptocoin', 6, 1, 0), (526, 'BOST', 'BoostCoin', 6, 1, 0), (1, 'BTC', 'Bitcoin', 6, 1, 0), (528, 'BTCD', 'Bitcoin Dark', 6, 1, 0), (529, 'BTCS', 'Bitcoin Shop', 6, 1, 0), (530, 'BTM', 'Bytom', 6, 1, 0), (45, 'BTS', 'Bitshares', 6, 1, 0), (532, 'BURN', 'BURN Cryptocoin', 6, 1, 0), (533, 'BURST', 'Burst Cryptocoin', 6, 1, 0), (534, 'C2', 'Coin 2.1', 6, 1, 0), (535, 'CACH', 'CacheCoin', 6, 1, 0), (536, 'CAI', 'CAI Token', 6, 1, 0), (537, 'CC', 'CyberCoin', 6, 1, 0), (538, 'CCN', 'CannaCoin', 6, 1, 0), (539, 'CGA', 'Cryptografic Anomaly', 6, 1, 0), (540, 'CHA', 'ChanceCoin', 6, 1, 0), (541, 'CINNI', 'CinniCoin', 6, 1, 0), (542, 'CLAM', 'Clams', 6, 1, 0), (543, 'CNL', 'ConcealCoin', 6, 1, 0), (544, 'CNMT', 'CNMT', 6, 1, 0), (545, 'CNOTE', 'CryptoNote', 6, 1, 0), (546, 'COMM', 'COMM', 6, 1, 0), (547, 'CON', 'PayCon', 6, 1, 0), (548, 'CORG', 'CorgiCoin', 6, 1, 0), (549, 'CRYPT', 'CryptCoin', 6, 1, 0), (550, 'CURE', 'CureCoin', 6, 1, 0), (787, 'CVC', 'Civic', 6, 1, 0), (551, 'CYC', 'Cycling Coin', 6, 1, 0), (772, 'DAO', 'Decentralized Autonomous Organization', 6, 1, 0), (13, 'DASH', 'Dash', 6, 1, 0), (30, 'DCR', 'Decred', 6, 1, 0), (47, 'DGB', 'DigiByte', 6, 1, 0), (553, 'DICE', 'Etheroll', 6, 1, 0), (554, 'DIEM', '<NAME> Coin', 6, 1, 0), (555, 'DIME', 'Dime Coin', 6, 1, 0), (556, 'DIS', 'Distrocoin', 6, 1, 0), (557, 'DNS', 'DNSCrypt', 6, 1, 0), (26, 'DOGE', 'DogeCoin', 6, 1, 0), (560, 'DRKC', 'Dark Cash', 6, 1, 0), (561, 'DRM', 'DreamCoin', 6, 1, 0), (562, 'DSH', 'Dashcoin', 6, 1, 0), (563, 'DVK', 'DvoraKoin', 6, 1, 0), (564, 'EAC', 'EarthCoin', 6, 1, 0), (565, 'EBT', 'Ebittree Coin', 6, 1, 0), (566, 'ECC', 'ECC Coin', 6, 1, 0), (567, 'EFL', 'e-Gulden', 6, 1, 0), (568, 'EMC2', 'Einsteinium', 6, 1, 0), (569, 'EMO', 'Emoticoint', 6, 1, 0), (570, 'ENC', 'EntropyCoin', 6, 1, 0), (6, 'EOS', 'Crypt/EOS', 6, 1, 0), (18, 'ETC', 'Ethereum Classic', 6, 1, 0), (2, 'ETH', 'Ethereum', 6, 1, 0), (571, 'eTOK', 'eTOK', 6, 1, 0), (572, 'EXE', 'ExeCoin', 6, 1, 0), (763, 'EXP', 'Expanse', 6, 1, 0), (573, 'FAC', 'FAC', 6, 1, 0), (574, 'FCN', 'FantomCoin', 6, 1, 0), (66, 'FCT', 'Factom', 6, 1, 0), (575, 'FIBRE', 'FIBRE Cryptocoin', 6, 1, 0), (576, 'FLAP', 'FlappyCoin', 6, 1, 0), (577, 'FLDC', 'FoldingCoin', 6, 1, 0), (753, 'FLO', 'Florin', 6, 1, 0), (578, 'FLT', 'FlutterCoin', 6, 1, 0), (800, 'FOAM', 'FOAM Protocol', 6, 1, 0), (579, 'FOX', 'FoxCoin', 6, 1, 0), (580, 'FRAC', 'FractalCoin', 6, 1, 0), (581, 'FRK', 'Franko', 6, 1, 0), (582, 'FRQ', 'FairQuark', 6, 1, 0), (583, 'FVZ', 'FVZCoin', 6, 1, 0), (584, 'FZ', 'Frozen', 6, 1, 0), (585, 'FZN', 'Fuzon', 6, 1, 0), (592, 'GAME', 'GameCredits', 6, 1, 0), (586, 'GAP', 'GapCoin', 6, 1, 0), (789, 'GAS', 'GAS Neo', 6, 1, 0), (587, 'GDN', 'Global Denomination', 6, 1, 0), (588, 'GEMZ', 'GetGems', 6, 1, 0), (589, 'GEO', 'GeoCoin', 6, 1, 0), (590, 'GIAR', 'GIAR', 6, 1, 0), (591, 'GLB', 'Globe', 6, 1, 0), (593, 'GML', 'Game League Coin', 6, 1, 0), (784, 'GNO', 'Gnosis', 6, 1, 0), (594, 'GNS', 'Gnosis', 6, 1, 0), (73, 'GNT', 'Golem', 6, 1, 0), (595, 'GOLD', 'Crypto-Gold', 6, 1, 0), (596, 'GPC', 'GROUPCoin', 6, 1, 0), (597, 'GPUC', 'GPUCoin', 6, 1, 0), (757, 'GRC', 'GridCoin', 6, 1, 0), (598, 'GRCX', 'Gridcoin Classic', 6, 1, 0), (599, 'GRS', 'GroestlCoin', 6, 1, 0), (600, 'GUE', 'GUE', 6, 1, 0), (601, 'H2O', 'Hidrominer', 6, 1, 0), (602, 'HIRO', 'HIRO', 6, 1, 0), (603, 'HOT', 'HOT', 6, 1, 0), (604, 'HUC', 'HUC', 6, 1, 0), (756, 'HUGE', 'CryptoHuge', 6, 1, 0), (605, 'HVC', 'HVC', 6, 1, 0), (606, 'HYP', 'HYP', 6, 1, 0), (607, 'HZ', 'HZ', 6, 1, 0), (608, 'IFC', 'IFC', 6, 1, 0), (759, 'INDEX', 'INDEX', 6, 1, 0), (758, 'IOC', 'I/O Coin', 6, 1, 0), (609, 'ITC', 'ITC', 6, 1, 0), (610, 'IXC', 'IXC', 6, 1, 0), (611, 'JLH', 'JLH', 6, 1, 0), (612, 'JPC', 'JPC', 6, 1, 0), (613, 'JUG', 'JUG', 6, 1, 0), (614, 'KDC', 'KDC', 6, 1, 0), (615, 'KEY', 'KEY', 6, 1, 0), (794, 'KNC', 'Kyber Network', 6, 1, 0), (773, 'LBC', 'LBRY Credits', 6, 1, 0), (616, 'LC', 'LC', 6, 1, 0), (617, 'LCL', 'LCL', 6, 1, 0), (618, 'LEAF', 'LEAF', 6, 1, 0), (619, 'LGC', 'LGC', 6, 1, 0), (620, 'LOL', 'LOL', 6, 1, 0), (796, 'LOOM', 'LOOM Networks', 6, 1, 0), (621, 'LOVE', 'LOVE', 6, 1, 0), (805, 'LPT', 'Livepeer', 6, 1, 0), (622, 'LQD', 'LQD', 6, 1, 0), (35, 'LSK', 'Lisk', 6, 1, 0), (623, 'LTBC', 'LTBC', 6, 1, 0), (5, 'LTC', 'Litecoin', 6, 1, 0), (625, 'LTCX', 'LTCX', 6, 1, 0), (626, 'MAID', 'MaidSafeCoin', 6, 1, 0), (799, 'MANA', 'Decentraland', 6, 1, 0), (627, 'MAST', 'MAST', 6, 1, 0), (628, 'MAX', 'MAX', 6, 1, 0), (629, 'MCN', 'MCN', 6, 1, 0), (630, 'MEC', 'MEC', 6, 1, 0), (631, 'METH', 'METH', 6, 1, 0), (632, 'MIL', 'MIL', 6, 1, 0), (633, 'MIN', 'MIN', 6, 1, 0), (634, 'MINT', 'MINT', 6, 1, 0), (635, 'MMC', 'MMC', 6, 1, 0), (636, 'MMNXT', 'MMNXT', 6, 1, 0), (637, 'MMXIV', 'MMXIV', 6, 1, 0), (638, 'MNTA', 'MNTA', 6, 1, 0), (639, 'MON', 'MON', 6, 1, 0), (640, 'MRC', 'MRC', 6, 1, 0), (641, 'MRS', 'MRS', 6, 1, 0), (643, 'MTS', 'MTS', 6, 1, 0), (644, 'MUN', 'MUN', 6, 1, 0), (645, 'MYR', 'MYR', 6, 1, 0), (646, 'MZC', 'MZC', 6, 1, 0), (647, 'N5X', 'N5X', 6, 1, 0), (648, 'NAS', 'NAS', 6, 1, 0), (649, 'NAUT', 'NAUT', 6, 1, 0), (650, 'NAV', 'NAV', 6, 1, 0), (651, 'NBT', 'NBT', 6, 1, 0), (652, 'NEOS', 'NEOS', 6, 1, 0), (653, 'NL', 'NL', 6, 1, 0), (654, 'NMC', 'NMC', 6, 1, 0), (803, 'NMR', 'Numerate', 6, 1, 0), (655, 'NOBL', 'NOBL', 6, 1, 0), (656, 'NOTE', 'NOTE', 6, 1, 0), (657, 'NOXT', 'NOXT', 6, 1, 0), (658, 'NRS', 'NRS', 6, 1, 0), (659, 'NSR', 'NSR', 6, 1, 0), (660, 'NTX', 'NTX', 6, 1, 0), (781, 'NXC', 'Nexium', 6, 1, 0), (661, 'NXT', 'NXT Coin', 6, 1, 0), (662, 'NXTI', 'NXTI', 6, 1, 0), (788, 'OMG', 'OmiseGO', 6, 1, 0), (642, 'OMNI', 'OMNI', 6, 1, 0), (663, 'OPAL', 'OPAL', 6, 1, 0), (664, 'PAND', 'PAND', 6, 1, 0), (782, 'PASC', 'Pascal Coin', 6, 1, 0), (665, 'PAWN', 'PAWN', 6, 1, 0), (666, 'PIGGY', 'PIGGY', 6, 1, 0), (667, 'PINK', 'PINK', 6, 1, 0), (668, 'PLX', 'PLX', 6, 1, 0), (669, 'PMC', 'PMC', 6, 1, 0), (804, 'POLY', 'PolyMath', 6, 1, 0), (670, 'POT', 'POT', 6, 1, 0), (671, 'PPC', 'PPC', 6, 1, 0), (672, 'PRC', 'PRC', 6, 1, 0), (673, 'PRT', 'PRT', 6, 1, 0), (674, 'PTS', 'PTS', 6, 1, 0), (675, 'Q2C', 'Q2C', 6, 1, 0), (676, 'QBK', 'QBK', 6, 1, 0), (677, 'QCN', 'QCN', 6, 1, 0), (678, 'QORA', 'QORA', 6, 1, 0), (679, 'QTL', 'QTL', 6, 1, 0), (34, 'QTUM', 'Qtum', 6, 1, 0), (767, 'RADS', 'Radium', 6, 1, 0), (680, 'RBY', 'RBY', 6, 1, 0), (94, 'RDD', 'ReddCoin', 6, 1, 0), (29, 'REP', 'Augur', 6, 1, 0), (682, 'RIC', 'RIC', 6, 1, 0), (683, 'RZR', 'RZR', 6, 1, 0), (775, 'SBD', '<NAME>', 6, 1, 0), (761, 'SC', 'Siacoin', 6, 1, 0), (684, 'SDC', 'SDC', 6, 1, 0), (685, 'SHIBE', 'SHIBE', 6, 1, 0), (686, 'SHOPX', 'SHOPX', 6, 1, 0), (687, 'SILK', 'SILK', 6, 1, 0), (688, 'SJCX', 'SJCX', 6, 1, 0), (689, 'SLR', 'SLR', 6, 1, 0), (690, 'SMC', 'SMC', 6, 1, 0), (67, 'SNT', 'Status', 6, 1, 0), (691, 'SOC', 'SOC', 6, 1, 0), (692, 'SPA', 'SPA', 6, 1, 0), (693, 'SQL', 'SQL', 6, 1, 0), (694, 'SRCC', 'SRCC', 6, 1, 0), (695, 'SRG', 'SRG', 6, 1, 0), (696, 'SSD', 'SSD', 6, 1, 0), (774, 'STEEM', 'Steem', 6, 1, 0), (790, 'STORJ', 'Decentralized Cloud Storage', 6, 1, 0), (697, 'STR', 'STR', 6, 1, 0), (64, 'STRAT', 'Stratis', 6, 1, 0), (698, 'SUM', 'SUM', 6, 1, 0), (699, 'SUN', 'SUN', 6, 1, 0), (700, 'SWARM', 'SWARM', 6, 1, 0), (701, 'SXC', 'SXC', 6, 1, 0), (703, 'SYS', 'SysCoin', 6, 1, 0), (704, 'TAC', 'TalkCoin', 6, 1, 0), (705, 'TOR', 'TORCoin', 6, 1, 0), (706, 'TRUST', 'Crypto Trust Network', 6, 1, 0), (707, 'TWE', 'TWE', 6, 1, 0), (708, 'UIS', 'Unitus', 6, 1, 0), (709, 'ULTC', 'Umbrella-LTC', 6, 1, 0), (710, 'UNITY', 'SuperNET', 6, 1, 0), (711, 'URO', 'UroCoin', 6, 1, 0), (28, 'USDC', 'USD Coin', 6, 1, 0), (712, 'USDE', 'USDe Coin', 6, 1, 0), (713, 'USDT', 'Tether', 6, 1, 0), (714, 'UTC', 'UltraCoin', 6, 1, 0), (715, 'UTIL', 'UTIL', 6, 1, 0), (716, 'UVC', 'UniversityCoin', 6, 1, 0), (717, 'VIA', 'Viacoin', 6, 1, 0), (718, 'VOOT', 'Crypto VOOT', 6, 1, 0), (769, 'VOX', 'Voxels', 6, 1, 0), (719, 'VRC', 'VeriCoin', 6, 1, 0), (720, 'VTC', 'Vertcoin', 6, 1, 0), (721, 'WC', 'WinCoin', 6, 1, 0), (722, 'WDC', 'WorldCoin', 6, 1, 0), (723, 'WIKI', 'WIKI', 6, 1, 0), (724, 'WOLF', 'CryptoWolf', 6, 1, 0), (725, 'X13', 'X13 Coin', 6, 1, 0), (726, 'XAI', 'Sapience AIFX', 6, 1, 0), (727, 'XAP', 'Apollon', 6, 1, 0), (728, 'XBC', 'Bitcoin Plus', 6, 1, 0), (729, 'XC', 'XCurrency', 6, 1, 0), (730, 'XCH', 'ClearingHouse', 6, 1, 0), (731, 'XCN', 'Crypton,ite', 6, 1, 0), (732, 'XCP', 'CounterParty', 6, 1, 0), (733, 'XCR', 'Crypti', 6, 1, 0), (734, 'XDN', 'DigitalNote', 6, 1, 0), (735, 'XDP', 'DogeParty', 6, 1, 0), (19, 'XEM', 'NEM/XEM', 6, 1, 0), (736, 'XHC', 'HonorCoin', 6, 1, 0), (737, 'XLB', 'LibertyCoin', 6, 1, 0), (738, 'XMG', 'Magi', 6, 1, 0), (12, 'XMR', 'Monero', 6, 1, 0), (740, 'XPB', 'PebbleCoin', 6, 1, 0), (741, 'XPM', 'PrimeCoin', 6, 1, 0), (3, 'XRP', 'Ripple', 6, 1, 0), (743, 'XSI', 'StabilityShares', 6, 1, 0), (744, 'XST', 'Stealth', 6, 1, 0), (745, 'XSV', 'SilliconValleyCoin', 6, 1, 0), (746, 'XUSD', 'CoinoUSD', 6, 1, 0), (752, 'XVC', 'VCash', 6, 1, 0), (747, 'XXC', 'Creds XXC', 6, 1, 0), (748, 'YACC', 'YACCoin', 6, 1, 0), (749, 'YANG', 'YangCoin', 6, 1, 0), (750, 'YC', 'YellowCoin', 6, 1, 0), (751, 'YIN', 'YinCoin', 6, 1, 0), (702, 'YNC', 'SYNC', 6, 1, 0), (24, 'ZEC', 'ZCash', 6, 1, 0), (41, 'ZRX', '0x', 6, 1, 0); /*!40000 ALTER TABLE `currencies_ctc` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/YATAWeb/widgets/leftSideBar.R #' Create a dashboard sidebar. #' #' A dashboard sidebar typically contains a \code{\link{sidebarMenu}}, although #' it may also contain a \code{\link{sidebarSearchForm}}, or other Shiny inputs. #' #' @param ... Items to put in the sidebar. #' @param disable If \code{TRUE}, the sidebar will be disabled. #' @param width The width of the sidebar. This must either be a number which #' specifies the width in pixels, or a string that specifies the width in CSS #' units. #' @param collapsed If \code{TRUE}, the sidebar will be collapsed on app startup. #' #' @seealso \code{\link{sidebarMenu}} #' #' @examples #' ## Only run this example in interactive R sessions #' if (interactive()) { #' header <- dashboardHeader() #' #' sidebar <- dashboardSidebar( #' sidebarUserPanel("User Name", #' subtitle = a(href = "#", icon("circle", class = "text-success"), "Online"), #' # Image file should be in www/ subdir #' image = "userimage.png" #' ), #' sidebarSearchForm(label = "Enter a number", "searchText", "searchButton"), #' sidebarMenu( #' # Setting id makes input$tabs give the tabName of currently-selected tab #' id = "tabs", #' menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")), #' menuItem("Widgets", icon = icon("th"), tabName = "widgets", badgeLabel = "new", #' badgeColor = "green"), #' menuItem("Charts", icon = icon("bar-chart-o"), #' menuSubItem("Sub-item 1", tabName = "subitem1"), #' menuSubItem("Sub-item 2", tabName = "subitem2") #' ) #' ) #' ) #' #' body <- dashboardBody( #' tabItems( #' tabItem("dashboard", #' div(p("Dashboard tab content")) #' ), #' tabItem("widgets", #' "Widgets tab content" #' ), #' tabItem("subitem1", #' "Sub-item 1 tab content" #' ), #' tabItem("subitem2", #' "Sub-item 2 tab content" #' ) #' ) #' ) #' #' shinyApp( #' ui = dashboardPage(header, sidebar, body), #' server = function(input, output) { } #' ) #' } #' @export dashboardSidebar <- function(..., disable = FALSE, width = NULL, collapsed = FALSE) { width <- validateCssUnit(width) # Set up custom CSS for custom width custom_css <- NULL if (!is.null(width)) { # This CSS is derived from the sidebar-related instances of '230px' (the # default sidebar width) from inst/AdminLTE/AdminLTE.css. One difference is # that instead making changes to the global settings, we've put them in a # media query (min-width: 768px), so that it won't override other media # queries (like max-width: 767px) that work for narrower screens. custom_css <- tags$head(tags$style(HTML(gsub("_WIDTH_", width, fixed = TRUE, ' .main-sidebar, .left-side { width: _WIDTH_; } @media (min-width: 768px) { .content-wrapper, .right-side, .main-footer { margin-left: _WIDTH_; } .main-sidebar, .left-side { width: _WIDTH_; } } @media (max-width: 767px) { .sidebar-open .content-wrapper, .sidebar-open .right-side, .sidebar-open .main-footer { -webkit-transform: translate(_WIDTH_, 0); -ms-transform: translate(_WIDTH_, 0); -o-transform: translate(_WIDTH_, 0); transform: translate(_WIDTH_, 0); } } @media (max-width: 767px) { .main-sidebar, .left-side { -webkit-transform: translate(-_WIDTH_, 0); -ms-transform: translate(-_WIDTH_, 0); -o-transform: translate(-_WIDTH_, 0); transform: translate(-_WIDTH_, 0); } } @media (min-width: 768px) { .sidebar-collapse .main-sidebar, .sidebar-collapse .left-side { -webkit-transform: translate(-_WIDTH_, 0); -ms-transform: translate(-_WIDTH_, 0); -o-transform: translate(-_WIDTH_, 0); transform: translate(-_WIDTH_, 0); } } ')))) } # If we're restoring a bookmarked app, this holds the value of whether or not the # sidebar was collapsed. If this is not the case, the default is whatever the user # specified in the `collapsed` argument. dataValue <- shiny::restoreInput(id = "sidebarCollapsed", default = collapsed) if (disable) dataValue <- TRUE # this is a workaround to fix #209 dataValueString <- if (dataValue) "true" else "false" # The expanded/collapsed state of the sidebar is actually set by adding a # class to the body (not to the sidebar). However, it makes sense for the # `collapsed` argument to belong in this function. So this information is # just passed through (as the `data-collapsed` attribute) to the # `dashboardPage()` function tags$aside( id = "sidebarCollapsed", class = "main-sidebar", `data-collapsed` = dataValueString, custom_css, tags$section( id = "sidebarItemExpanded", class = "sidebar", `data-disable` = if (disable) 1 else NULL, list(...) ) ) } #' A panel displaying user information in a sidebar #' #' @param name Name of the user. #' @param subtitle Text or HTML to be shown below the name. #' @param image A filename or URL to use for an image of the person. If it is a #' local file, the image should be contained under the www/ subdirectory of #' the application. #' #' @family sidebar items #' #' @seealso \code{\link{dashboardSidebar}} for example usage. #' #' @export sidebarUserPanel <- function(name, subtitle = NULL, image = NULL) { div(class = "user-panel", if (!is.null(image)) { div(class = "pull-left image", img(src = image, class = "img-circle", alt = "User Image") ) }, div(class = "pull-left info", # If no image, move text to the left: by overriding default left:55px style = if (is.null(image)) "left: 4px", p(name), subtitle ) ) } #' Create a search form to place in a sidebar #' #' A search form consists of a text input field and a search button. #' #' @param textId Shiny input ID for the text input box. #' @param buttonId Shiny input ID for the search button (which functions like an #' \code{\link[shiny]{actionButton}}). #' @param label Text label to display inside the search box. #' @param icon An icon tag, created by \code{\link[shiny]{icon}}. #' #' @family sidebar items #' #' @seealso \code{\link{dashboardSidebar}} for example usage. #' #' @export sidebarSearchForm <- function(textId, buttonId, label = "Search...", icon = shiny::icon("search")) { tags$form(class = "sidebar-form", div(class = "input-group", tags$input(id = textId, type = "text", class = "form-control", placeholder = label, style = "margin: 5px;" ), span(class = "input-group-btn", tags$button(id = buttonId, type = "button", class = "btn btn-flat action-button", icon ) ) ) ) } #' Create a dashboard sidebar menu and menu items. #' #' A \code{dashboardSidebar} can contain a \code{sidebarMenu}. A #' \code{sidebarMenu} contains \code{menuItem}s, and they can in turn contain #' \code{menuSubItem}s. #' #' Menu items (and similarly, sub-items) should have a value for either #' \code{href} or \code{tabName}; otherwise the item would do nothing. If it has #' a value for \code{href}, then the item will simply be a link to that value. #' #' If a \code{menuItem} has a non-NULL \code{tabName}, then the \code{menuItem} #' will behave like a tab -- in other words, clicking on the \code{menuItem} #' will bring a corresponding \code{tabItem} to the front, similar to a #' \code{\link[shiny]{tabPanel}}. One important difference between a #' \code{menuItem} and a \code{tabPanel} is that, for a \code{menuItem}, you #' must also supply a corresponding \code{tabItem} with the same value for #' \code{tabName}, whereas for a \code{tabPanel}, no \code{tabName} is needed. #' (This is because the structure of a \code{tabPanel} is such that the tab name #' can be automatically generated.) Sub-items are also able to activate #' \code{tabItem}s. #' #' Menu items (but not sub-items) also may have an optional badge. A badge is a #' colored oval containing text. #' #' @param text Text to show for the menu item. #' @param id For \code{sidebarMenu}, if \code{id} is present, this id will be #' used for a Shiny input value, and it will report which tab is selected. For #' example, if \code{id="tabs"}, then \code{input$tabs} will be the #' \code{tabName} of the currently-selected tab. If you want to be able to #' bookmark and restore the selected tab, an \code{id} is required. #' @param icon An icon tag, created by \code{\link[shiny]{icon}}. If #' \code{NULL}, don't display an icon. #' @param badgeLabel A label for an optional badge. Usually a number or a short #' word like "new". #' @param badgeColor A color for the badge. Valid colors are listed in #' \link{validColors}. #' @param href An link address. Not compatible with \code{tabName}. #' @param tabName The name of a tab that this menu item will activate. Not #' compatible with \code{href}. #' @param newtab If \code{href} is supplied, should the link open in a new #' browser tab? #' @param selected If \code{TRUE}, this \code{menuItem} or \code{menuSubItem} #' will start selected. If no item have \code{selected=TRUE}, then the first #' \code{menuItem} will start selected. #' @param expandedName A unique name given to each \code{menuItem} that serves #' to indicate which one (if any) is currently expanded. (This is only applicable #' to \code{menuItem}s that have children and it is mostly only useful for #' bookmarking state.) #' @param startExpanded Should this \code{menuItem} be expanded on app startup? #' (This is only applicable to \code{menuItem}s that have children, and only #' one of these can be expanded at any given time). #' @param ... For menu items, this may consist of \code{\link{menuSubItem}}s. #' @param .list An optional list containing items to put in the menu Same as the #' \code{...} arguments, but in list format. This can be useful when working #' with programmatically generated items. #' #' @family sidebar items #' #' @seealso \code{\link{dashboardSidebar}} for example usage. For #' dynamically-generated sidebar menus, see \code{\link{renderMenu}} and #' \code{\link{sidebarMenuOutput}}. #' #' @export sidebarMenu <- function(..., id = NULL, .list = NULL) { items <- c(list(...), .list) # Restore a selected tab from bookmarked state. Bookmarking was added in Shiny # 0.14. if (utils::packageVersion("shiny") >= "0.14" && !is.null(id)) { selectedTabName <- shiny::restoreInput(id = id, default = NULL) if (!is.null(selectedTabName)) { # Find the menuItem or menuSubItem with a `tabname` that matches # `selectedTab`. Then set `data-start-selected` to 1 for that tab and 0 # for all others. # Given a menuItem and a logical value for `selected`, set the # data-start-selected attribute to the appropriate value (1 or 0). selectItem <- function(item, selected) { # in the cases that the children of menuItems are NOT menuSubItems if (is.atomic(item) || length(item$children) == 0) { return(item) } if (selected) value <- 1 else value <- NULL # Try to find the child <a data-toggle="tab"> tag and then set # data-start-selected="1". The []<- assignment is to preserve # attributes. item$children[] <- lapply(item$children, function(child) { # Find the appropriate <a> child if (tagMatches(child, name = "a", `data-toggle` = "tab")) { child$attribs[["data-start-selected"]] <- value } child }) item } # Given a menuItem and a tabName (string), return TRUE if the menuItem has # that tabName, FALSE otherwise. itemHasTabName <- function(item, tabName) { # Must be a <li> tag if (!tagMatches(item, name = "li")) { return(FALSE) } # Look for an <a> child with data-value=tabName found <- FALSE lapply(item$children, function(child) { if (tagMatches(child, name = "a", `data-value` = tabName)) { found <<- TRUE } }) found } # Actually do the work of marking selected tabs and unselected ones. items <- lapply(items, function(item) { if (tagMatches(item, name = "li", class = "treeview")) { # Search in menuSubItems item$children[] <- lapply(item$children[], function(subItem) { if (tagMatches(subItem, name = "ul", class = "treeview-menu")) { subItem$children[] <- lapply(subItem$children, function(subSubItem) { selected <- itemHasTabName(subSubItem, selectedTabName) selectItem(subSubItem, selected) }) } subItem }) } else { # Regular menuItems selected <- itemHasTabName(item, selectedTabName) item <- selectItem(item, selected) } item }) } # This is a 0 height div, whose only purpose is to hold the tabName of the currently # selected menuItem in its `data-value` attribute. This is the DOM element that is # bound to tabItemInputBinding in the JS side. items[[length(items) + 1]] <- div(id = id, class = "sidebarMenuSelectedTabItem", `data-value` = selectedTabName %OR% "null") } # Use do.call so that we don't add an extra list layer to the children of the # ul tag. This makes it a little easier to traverse the tree to search for # selected items to restore. do.call(tags$ul, c(class = "sidebar-menu", items)) } #' @rdname sidebarMenu #' @export menuItem <- function(text, ..., icon = NULL, badgeLabel = NULL, badgeColor = "green", tabName = NULL, href = NULL, newtab = TRUE, selected = NULL, expandedName = as.character(gsub("[[:space:]]", "", text)), startExpanded = FALSE) { subItems <- list(...) if (!is.null(icon)) tagAssert(icon, type = "i") if (!is.null(href) + !is.null(tabName) + (length(subItems) > 0) != 1 ) { stop("Must have either href, tabName, or sub-items (contained in ...).") } if (!is.null(badgeLabel) && length(subItems) != 0) { stop("Can't have both badge and subItems") } validateColor(badgeColor) # If there's a tabName, set up the correct href and <a> target isTabItem <- FALSE target <- NULL if (!is.null(tabName)) { validateTabName(tabName) isTabItem <- TRUE href <- paste0("#shiny-tab-", tabName) } else if (is.null(href)) { href <- "#" } else { # If supplied href, set up <a> tag's target if (newtab) target <- "_blank" } # Generate badge if needed if (!is.null(badgeLabel)) { badgeTag <- tags$small( class = paste0("badge pull-right bg-", badgeColor), badgeLabel ) } else { badgeTag <- NULL } # If no subitems, return a pretty simple tag object if (length(subItems) == 0) { return( tags$li( a(href = href, `data-toggle` = if (isTabItem) "tab", `data-value` = if (!is.null(tabName)) tabName, `data-start-selected` = if (isTRUE(selected)) 1 else NULL, target = target, icon, span(text), badgeTag ) ) ) } # If we're restoring a bookmarked app, this holds the value of what menuItem (if any) # was expanded (this has be to stored separately from the selected menuItem, since # these actually independent in AdminLTE). If no menuItem was expanded, `dataExpanded` # is NULL. However, we want to this input to get passed on (and not dropped), so we # do `%OR% ""` to assure this. default <- if (startExpanded) expandedName else "" dataExpanded <- shiny::restoreInput(id = "sidebarItemExpanded", default) %OR% "" # If `dataExpanded` is not the empty string, we need to check that it is eqaul to the # this menuItem's `expandedName`` isExpanded <- nzchar(dataExpanded) && (dataExpanded == expandedName) tags$li(class = "treeview", a(href = href, icon, span(text), shiny::icon("angle-left", class = "pull-right") ), # Use do.call so that we don't add an extra list layer to the children of the # ul tag. This makes it a little easier to traverse the tree to search for # selected items to restore. do.call(tags$ul, c( class = paste0("treeview-menu", if (isExpanded) " menu-open" else ""), style = paste0("display: ", if (isExpanded) "block;" else "none;"), `data-expanded` = expandedName, subItems)) ) } #' @rdname sidebarMenu #' @export menuSubItem <- function(text, tabName = NULL, href = NULL, newtab = TRUE, icon = shiny::icon("angle-double-right"), selected = NULL) { if (!is.null(href) && !is.null(tabName)) { stop("Can't specify both href and tabName") } # If there's a tabName, set up the correct href isTabItem <- FALSE target <- NULL if (!is.null(tabName)) { validateTabName(tabName) isTabItem <- TRUE href <- paste0("#shiny-tab-", tabName) } else if (is.null(href)) { href <- "#" } else { # If supplied href, set up <a> tag's target if (newtab) target <- "_blank" } tags$li( a(href = href, `data-toggle` = if (isTabItem) "tab", `data-value` = if (!is.null(tabName)) tabName, `data-start-selected` = if (isTRUE(selected)) 1 else NULL, target = target, icon, text ) ) } <file_sep>/YATACore/R/R6_YATAData.R YATAData = R6::R6Class("YATAData", public = list( symbol = NULL ,name = "Tickers data" ,scopes = c(SCOPE_HOUR04, SCOPE_DAY, SCOPE_WEEK) ,getDecimals = function() { c(self$OPEN,self$HIGH,self$LOW,self$CLOSE) } ,getCoins = function() { c(self$VOLUME,self$CAP) } ,getDates = function() { c(self$DATE) } ,setPriceColumn = function(col) { self$VALUE = col } ,getTickers = function(idx) { i = idx ; if (i == 4) i = 3; private$adjustDateTypes(private$tickers[[i]], i) } ,getTickersShort = function() { self$getTickers(1) } ,getTickersMedium = function() { self$getTickers(2) } ,getTickersLong = function() { self$getTickers(3) } ,refresh = function() { SQLConn <<- openConnection() for (tick in private$tickers) tick$refresh() closeConnection(SQLConn) invisible(self) } ,getRange = function(rng=0) { private$tickers[[2]]$getRange(rng) } ,filterByDate = function(from, to) { if (from != private$from || to != private$to) { for (t in private$tickers) t$filterByDate(from, to) private$from = from private$to = to } } ,print = function() { print(self$name) } ,initialize = function(scope, symbol, fiat) { self$symbol = symbol private$setTBNames(scope) openConnection() for (idx in 1:length(private$tables)) { if (idx > 1) private$tickers = c(private$tickers, NULL) if (!is.null(private$tables[[idx]])) { private$tickers = c(private$tickers, TBLTickers$new(symbol, private$tables[[idx]], fiat)) } } closeConnection() } ) ,private = list( from = Sys.Date() ,to = Sys.Date() ,tickers = list() ,tables = list() ,adjustDateTypes = function (tickers, i) { if (i == 2 || i == 4) { tickers$df$Date = as.dated(tickers$df$Date) } else { tickers$df$Date = as.datet(tickers$df$Date) } tickers } ,setTBNames = function(scope) { ##JGG TODO Por ahora solo diarios private$tables = c("TICKERSH4", "TICKERSD1", "TICKERSW1") # pos = which(SCOPES == scope) # sc1 = NULL # sc2 = SCOPES[pos] # sc3 = NULL # if (pos > 2) sc1 = SCOPES[pos - 2] # if (pos < length(SCOPES)) sc3 = SCOPES[pos + 1] # for (i in c(sc1,sc2,sc3)) private$tables = c(private$tables, private$mountTBName(i)) # private$tables = c(private$tables, private$tables[3]) } # ,mountTBName = function(scope) { # base = "TICKERS" # if (scope == SCOPE_HOUR) return (paste0(base, "H2")) # if (scope == SCOPE_MIDDAY) return (paste0(base, "H4")) # if (scope == SCOPE_WORKDAY) return (paste0(base, "H8")) # if (scope == SCOPE_DAY) return (paste0(base, "D1")) # if (scope == SCOPE_WEEK) return (paste0(base, "W1")) # paste0(base, "M1") # } ) ) <file_sep>/YATAModels/R/ZIND_AD.R IND_AD <- R6Class("IND_AD", inherit=IND__Base, public = list( name="Accumulation/Distribution" ,symbol="AD" ,initialize = function() { super$initialize() } ,calculate = function(TTickers, date) { threshold = self$getParameter("threshold") if (!(threshold < 1 )) threshold = threshold / 100 xt = private$getXTS(TTickers, pref=prev) private$data = (xt[,TTickers$CLOSE] - xt[,TTickers$OPEN]) * xt[,TTickers$VOLUME] / (xt[,TTickers$HIGH] - xt[,TTickers$LOW]) colnames(private$data) = self$symbol private$setDataTypes("number", self$symbol) private$calcVariation(self$symbol) } # Dibuja sus graficos ,plot = function(p, TTickers) { if (!is.null(private$data)) { p = YATACore::plotLine(p, TTickers$df[,self$xAxis], private$data[,self$symbol],hoverText=self$symbol) } p } ) ) <file_sep>/YATACore/R/FACT_PLOT.R # Plot type FACT_PLOT <- R6::R6Class("FACT_PLOT", public = list( value = 0 ,name = "None" ,select = TRUE # Para el combo, acepta cambiar el target ,size = 5 ,NONE = 0 ,LINE = 1 ,LOG = 2 ,CANDLE = 3 ,BAR = 4 ,POINT = 5 ,names = c("Line", "Log", "Candle", "Bar", "Point") ,initialize = function(tgt = 0) { self$value = as.integer(tgt) } ,print = function() { cat(self$value) } ,setValue = function (val) { nVal = as.integer(val) self$value = nVal self$name = self$names[nVal] } ,getName = function(id = 0) { if (id == 0) id = self$value self$names[id] } ,getCombo = function(none = F) { start = ifelse(none, 0, 1) nm = self$names if (none) nm = c("None", nm) values = seq(start, self$size) names(values) = nm values } ) ) <file_sep>/YATAWeb/widgets/shiny-utils.R #' @include globals.R #' @include map.R NULL #' Make a random number generator repeatable #' #' Given a function that generates random data, returns a wrapped version of #' that function that always uses the same seed when called. The seed to use can #' be passed in explicitly if desired; otherwise, a random number is used. #' #' @param rngfunc The function that is affected by the R session's seed. #' @param seed The seed to set every time the resulting function is called. #' @return A repeatable version of the function that was passed in. #' #' @note When called, the returned function attempts to preserve the R session's #' current seed by snapshotting and restoring #' \code{\link[base]{.Random.seed}}. #' #' @examples #' rnormA <- repeatable(rnorm) #' rnormB <- repeatable(rnorm) #' rnormA(3) # [1] 1.8285879 -0.7468041 -0.4639111 #' rnormA(3) # [1] 1.8285879 -0.7468041 -0.4639111 #' rnormA(5) # [1] 1.8285879 -0.7468041 -0.4639111 -1.6510126 -1.4686924 #' rnormB(5) # [1] -0.7946034 0.2568374 -0.6567597 1.2451387 -0.8375699 #' @export repeatable <- function(rngfunc, seed = stats::runif(1, 0, .Machine$integer.max)) { force(seed) function(...) { # When we exit, restore the seed to its original state if (exists('.Random.seed', where=globalenv())) { currentSeed <- get('.Random.seed', pos=globalenv()) on.exit(assign('.Random.seed', currentSeed, pos=globalenv())) } else { on.exit(rm('.Random.seed', pos=globalenv())) } set.seed(seed) rngfunc(...) } } .globals$ownSeed <- NULL # Evaluate an expression using Shiny's own private stream of # randomness (not affected by set.seed). withPrivateSeed <- function(expr) { # Save the old seed if present. if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) { hasOrigSeed <- TRUE origSeed <- .GlobalEnv$.Random.seed } else { hasOrigSeed <- FALSE } # Swap in the private seed. if (is.null(.globals$ownSeed)) { if (hasOrigSeed) { # Move old seed out of the way if present. rm(.Random.seed, envir = .GlobalEnv, inherits = FALSE) } } else { .GlobalEnv$.Random.seed <- .globals$ownSeed } # On exit, save the modified private seed, and put the old seed back. on.exit({ .globals$ownSeed <- .GlobalEnv$.Random.seed if (hasOrigSeed) { .GlobalEnv$.Random.seed <- origSeed } else { rm(.Random.seed, envir = .GlobalEnv, inherits = FALSE) } # Need to call this to make sure that the value of .Random.seed gets put # into R's internal RNG state. (Issue #1763) httpuv::getRNGState() }) expr } #JGG # Version of runif that runs with private seed # p_runif <- function(...) { # withPrivateSeed(stats::runif(...)) # } # Version of sample that runs with private seed # p_sample <- function(...) { # withPrivateSeed(sample(...)) # } # Return a random integral value in the range [min, max). # If only one argument is passed, then min=0 and max=argument. randomInt <- function(min, max) { if (missing(max)) { max <- min min <- 0 } if (min < 0 || max <= min) stop("Invalid min/max values") min + sample(max-min, 1)-1 } p_randomInt <- function(...) { withPrivateSeed(randomInt(...)) } isWholeNum <- function(x, tol = .Machine$double.eps^0.5) { abs(x - round(x)) < tol } `%OR%` <- function(x, y) { if (is.null(x) || isTRUE(is.na(x))) y else x } `%AND%` <- function(x, y) { if (!is.null(x) && !isTRUE(is.na(x))) if (!is.null(y) && !isTRUE(is.na(y))) return(y) return(NULL) } `%.%` <- function(x, y) { paste(x, y, sep='') } # Given a vector or list, drop all the NULL items in it dropNulls <- function(x) { x[!vapply(x, is.null, FUN.VALUE=logical(1))] } nullOrEmpty <- function(x) { is.null(x) || length(x) == 0 } # Given a vector or list, drop all the NULL items in it dropNullsOrEmpty <- function(x) { x[!vapply(x, nullOrEmpty, FUN.VALUE=logical(1))] } # Given a vector/list, return TRUE if any elements are named, FALSE otherwise. anyNamed <- function(x) { # Zero-length vector if (length(x) == 0) return(FALSE) nms <- names(x) # List with no name attribute if (is.null(nms)) return(FALSE) # List with name attribute; check for any "" any(nzchar(nms)) } # Given a vector/list, return TRUE if any elements are unnamed, FALSE otherwise. anyUnnamed <- function(x) { # Zero-length vector if (length(x) == 0) return(FALSE) nms <- names(x) # List with no name attribute if (is.null(nms)) return(TRUE) # List with name attribute; check for any "" any(!nzchar(nms)) } # Given a vector/list, returns a named vector (the labels will be blank). asNamedVector <- function(x) { if (!is.null(names(x))) return(x) names(x) <- rep.int("", length(x)) x } # Given two named vectors, join them together, and keep only the last element # with a given name in the resulting vector. If b has any elements with the same # name as elements in a, the element in a is dropped. Also, if there are any # duplicated names in a or b, only the last one with that name is kept. mergeVectors <- function(a, b) { if (anyUnnamed(a) || anyUnnamed(b)) { stop("Vectors must be either NULL or have names for all elements") } x <- c(a, b) drop_idx <- duplicated(names(x), fromLast = TRUE) x[!drop_idx] } # Sort a vector by the names of items. If there are multiple items with the # same name, preserve the original order of those items. For empty # vectors/lists/NULL, return the original value. sortByName <- function(x) { if (anyUnnamed(x)) stop("All items must be named") # Special case for empty vectors/lists, and NULL if (length(x) == 0) return(x) x[order(names(x))] } # Wrapper around list2env with a NULL check. In R <3.2.0, if an empty unnamed # list is passed to list2env(), it errors. But an empty named list is OK. For # R >=3.2.0, this wrapper is not necessary. list2env2 <- function(x, ...) { # Ensure that zero-length lists have a name attribute if (length(x) == 0) attr(x, "names") <- character(0) list2env(x, ...) } # Combine dir and (file)name into a file path. If a file already exists with a # name differing only by case, then use it instead. file.path.ci <- function(...) { result <- find.file.ci(...) if (!is.null(result)) return(result) # If not found, return the file path that was given to us. return(file.path(...)) } # Does a particular file exist? Case-insensitive for filename, case-sensitive # for path (on platforms with case-sensitive file system). file.exists.ci <- function(...) { !is.null(find.file.ci(...)) } # Look for a file, case-insensitive for filename, case-sensitive for path (on # platforms with case-sensitive filesystem). If found, return the path to the # file, with the correct case. If not found, return NULL. find.file.ci <- function(...) { default <- file.path(...) if (length(default) > 1) stop("find.file.ci can only check for one file at a time.") if (file.exists(default)) return(default) dir <- dirname(default) name <- basename(default) # If we got here, then we'll check for a directory with the exact case, and a # name with any case. all_files <- list.files(dir, all.files=TRUE, full.names=TRUE, include.dirs=TRUE) match_idx <- tolower(name) == tolower(basename(all_files)) matches <- all_files[match_idx] if (length(matches) == 0) return(NULL) return(matches[1]) } # The function base::dir.exists was added in R 3.2.0, but for backward # compatibility we need to add this function dirExists <- function(paths) { file.exists(paths) & file.info(paths)$isdir } # Removes empty directory (vectorized). This is needed because file.remove() # on Unix will remove empty directories, but on Windows, it will not. On # Windows, you would need to use unlink(recursive=TRUE), which is not very # safe. This function does it safely on Unix and Windows. dirRemove <- function(path) { for (p in path) { if (!dirExists(p)) { stop("Cannot remove non-existent directory ", p, ".") } if (length(dir(p, all.files = TRUE, no.. = TRUE)) != 0) { stop("Cannot remove non-empty directory ", p, ".") } result <- unlink(p, recursive = TRUE) if (result == 1) { stop("Error removing directory ", p, ".") } } } # Attempt to join a path and relative path, and turn the result into a # (normalized) absolute path. The result will only be returned if it is an # existing file/directory and is a descendant of dir. # # Example: # resolve("/Users/jcheng", "shiny") # "/Users/jcheng/shiny" # resolve("/Users/jcheng", "./shiny") # "/Users/jcheng/shiny" # resolve("/Users/jcheng", "shiny/../shiny/") # "/Users/jcheng/shiny" # resolve("/Users/jcheng", ".") # NULL # resolve("/Users/jcheng", "..") # NULL # resolve("/Users/jcheng", "shiny/..") # NULL resolve <- function(dir, relpath) { abs.path <- file.path(dir, relpath) if (!file.exists(abs.path)) return(NULL) abs.path <- normalizePath(abs.path, winslash='/', mustWork=TRUE) dir <- normalizePath(dir, winslash='/', mustWork=TRUE) # trim the possible trailing slash under Windows (#306) if (isWindows()) dir <- sub('/$', '', dir) if (nchar(abs.path) <= nchar(dir) + 1) return(NULL) if (substr(abs.path, 1, nchar(dir)) != dir || substr(abs.path, nchar(dir)+1, nchar(dir)+1) != '/') { return(NULL) } return(abs.path) } isWindows <- function() .Platform$OS.type == 'windows' # This is a wrapper for download.file and has the same interface. # The only difference is that, if the protocol is https, it changes the # download settings, depending on platform. download <- function(url, ...) { # First, check protocol. If http or https, check platform: if (grepl('^https?://', url)) { # Check whether we are running R 3.2 isR32 <- getRversion() >= "3.2" # Windows if (.Platform$OS.type == "windows") { if (isR32) { method <- "wininet" } else { # If we directly use setInternet2, R CMD CHECK gives a Note on Mac/Linux seti2 <- `::`(utils, 'setInternet2') # Check whether we are already using internet2 for internal internet2_start <- seti2(NA) # If not then temporarily set it if (!internet2_start) { # Store initial settings, and restore on exit on.exit(suppressWarnings(seti2(internet2_start))) # Needed for https. Will get warning if setInternet2(FALSE) already run # and internet routines are used. But the warnings don't seem to matter. suppressWarnings(seti2(TRUE)) } method <- "internal" } # download.file will complain about file size with something like: # Warning message: # In download.file(url, ...) : downloaded length 19457 != reported length 200 # because apparently it compares the length with the status code returned (?) # so we supress that suppressWarnings(utils::download.file(url, method = method, ...)) } else { # If non-Windows, check for libcurl/curl/wget/lynx, then call download.file with # appropriate method. if (isR32 && capabilities("libcurl")) { method <- "libcurl" } else if (nzchar(Sys.which("wget")[1])) { method <- "wget" } else if (nzchar(Sys.which("curl")[1])) { method <- "curl" # curl needs to add a -L option to follow redirects. # Save the original options and restore when we exit. orig_extra_options <- getOption("download.file.extra") on.exit(options(download.file.extra = orig_extra_options)) options(download.file.extra = paste("-L", orig_extra_options)) } else if (nzchar(Sys.which("lynx")[1])) { method <- "lynx" } else { stop("no download method found") } utils::download.file(url, method = method, ...) } } else { utils::download.file(url, ...) } } getContentType <- function(file, defaultType = 'application/octet-stream') { subtype <- ifelse(grepl('[.]html?$', file), 'charset=UTF-8', '') mime::guess_type(file, unknown = defaultType, subtype = subtype) } # Create a zero-arg function from a quoted expression and environment # @examples # makeFunction(body=quote(print(3))) makeFunction <- function(args = pairlist(), body, env = parent.frame()) { eval(call("function", args, body), env) } #' Convert an expression to a function #' #' This is to be called from another function, because it will attempt to get #' an unquoted expression from two calls back. #' #' If expr is a quoted expression, then this just converts it to a function. #' If expr is a function, then this simply returns expr (and prints a #' deprecation message). #' If expr was a non-quoted expression from two calls back, then this will #' quote the original expression and convert it to a function. # #' @param expr A quoted or unquoted expression, or a function. #' @param env The desired environment for the function. Defaults to the #' calling environment two steps back. #' @param quoted Is the expression quoted? #' #' @examples #' # Example of a new renderer, similar to renderText #' # This is something that toolkit authors will do #' renderTriple <- function(expr, env=parent.frame(), quoted=FALSE) { #' # Convert expr to a function #' func <- shiny::exprToFunction(expr, env, quoted) #' #' function() { #' value <- func() #' paste(rep(value, 3), collapse=", ") #' } #' } #' #' #' # Example of using the renderer. #' # This is something that app authors will do. #' values <- reactiveValues(A="text") #' #' \dontrun{ #' # Create an output object #' output$tripleA <- renderTriple({ #' values$A #' }) #' } #' #' # At the R console, you can experiment with the renderer using isolate() #' tripleA <- renderTriple({ #' values$A #' }) #' #' isolate(tripleA()) #' # "text, text, text" #' @export exprToFunction <- function(expr, env=parent.frame(), quoted=FALSE) { if (!quoted) { expr <- eval(substitute(substitute(expr)), parent.frame()) } # expr is a quoted expression makeFunction(body=expr, env=env) } #' Install an expression as a function #' #' Installs an expression in the given environment as a function, and registers #' debug hooks so that breakpoints may be set in the function. #' #' This function can replace \code{exprToFunction} as follows: we may use #' \code{func <- exprToFunction(expr)} if we do not want the debug hooks, or #' \code{installExprFunction(expr, "func")} if we do. Both approaches create a #' function named \code{func} in the current environment. #' #' @seealso Wraps \code{\link{exprToFunction}}; see that method's documentation #' for more documentation and examples. #' #' @param expr A quoted or unquoted expression #' @param name The name the function should be given #' @param eval.env The desired environment for the function. Defaults to the #' calling environment two steps back. #' @param quoted Is the expression quoted? #' @param assign.env The environment in which the function should be assigned. #' @param label A label for the object to be shown in the debugger. Defaults to #' the name of the calling function. #' @param wrappedWithLabel,..stacktraceon Advanced use only. For stack manipulation purposes; see #' \code{\link{stacktrace}}. #' @export installExprFunction <- function(expr, name, eval.env = parent.frame(2), quoted = FALSE, assign.env = parent.frame(1), label = deparse(sys.call(-1)[[1]]), wrappedWithLabel = TRUE, ..stacktraceon = FALSE) { if (!quoted) { quoted <- TRUE expr <- eval(substitute(substitute(expr)), parent.frame()) } func <- exprToFunction(expr, eval.env, quoted) if (length(label) > 1) { # Just in case the deparsed code is more complicated than we imagine. If we # have a label with length > 1 it causes warnings in wrapFunctionLabel. label <- paste0(label, collapse = "\n") } if (wrappedWithLabel) { func <- wrapFunctionLabel(func, label, ..stacktraceon = ..stacktraceon) } else { registerDebugHook(name, assign.env, label) } assign(name, func, envir = assign.env) } #' Parse a GET query string from a URL #' #' Returns a named list of key-value pairs. #' #' @param str The query string. It can have a leading \code{"?"} or not. #' @param nested Whether to parse the query string of as a nested list when it #' contains pairs of square brackets \code{[]}. For example, the query #' \samp{a[i1][j1]=x&b[i1][j1]=y&b[i2][j1]=z} will be parsed as \code{list(a = #' list(i1 = list(j1 = 'x')), b = list(i1 = list(j1 = 'y'), i2 = list(j1 = #' 'z')))} when \code{nested = TRUE}, and \code{list(`a[i1][j1]` = 'x', #' `b[i1][j1]` = 'y', `b[i2][j1]` = 'z')} when \code{nested = FALSE}. #' @export #' @examples #' parseQueryString("?foo=1&bar=b%20a%20r") #' #' \dontrun{ #' # Example of usage within a Shiny app #' function(input, output, session) { #' #' output$queryText <- renderText({ #' query <- parseQueryString(session$clientData$url_search) #' #' # Ways of accessing the values #' if (as.numeric(query$foo) == 1) { #' # Do something #' } #' if (query[["bar"]] == "targetstring") { #' # Do something else #' } #' #' # Return a string with key-value pairs #' paste(names(query), query, sep = "=", collapse=", ") #' }) #' } #' } #' parseQueryString <- function(str, nested = FALSE) { if (is.null(str) || nchar(str) == 0) return(list()) # Remove leading ? if (substr(str, 1, 1) == '?') str <- substr(str, 2, nchar(str)) pairs <- strsplit(str, '&', fixed = TRUE)[[1]] # Drop any empty items (if there's leading/trailing/consecutive '&' chars) pairs <- pairs[pairs != ""] pairs <- strsplit(pairs, '=', fixed = TRUE) keys <- vapply(pairs, function(x) x[1], FUN.VALUE = character(1)) values <- vapply(pairs, function(x) x[2], FUN.VALUE = character(1)) # Replace NA with '', so they don't get converted to 'NA' by URLdecode values[is.na(values)] <- '' # Convert "+" to " ", since URLdecode doesn't do it keys <- gsub('+', ' ', keys, fixed = TRUE) values <- gsub('+', ' ', values, fixed = TRUE) keys <- URLdecode(keys) values <- URLdecode(values) res <- stats::setNames(as.list(values), keys) if (!nested) return(res) # Make a nested list from a query of the form ?a[1][1]=x11&a[1][2]=x12&... for (i in grep('\\[.+\\]', keys)) { k <- strsplit(keys[i], '[][]')[[1L]] # split by [ or ] res <- assignNestedList(res, k[k != ''], values[i]) res[[keys[i]]] <- NULL # remove res[['a[1][1]']] } res } # Assign value to the bottom element of the list x using recursive indices idx assignNestedList <- function(x = list(), idx, value) { for (i in seq_along(idx)) { sub <- idx[seq_len(i)] if (is.null(x[[sub]])) x[[sub]] <- list() } x[[idx]] <- value x } # decide what to do in case of errors; it is customizable using the shiny.error # option (e.g. we can set options(shiny.error = recover)) #' @include conditions.R shinyCallingHandlers <- function(expr) { withCallingHandlers(captureStackTraces(expr), error = function(e) { # Don't intercept shiny.silent.error (i.e. validation errors) if (inherits(e, "shiny.silent.error")) return() handle <- getOption('shiny.error') if (is.function(handle)) handle() } ) } #' Print message for deprecated functions in Shiny #' #' To disable these messages, use \code{options(shiny.deprecation.messages=FALSE)}. #' #' @param new Name of replacement function. #' @param msg Message to print. If used, this will override the default message. #' @param old Name of deprecated function. #' @param version The last version of Shiny before the item was deprecated. #' @keywords internal shinyDeprecated <- function(new=NULL, msg=NULL, old=as.character(sys.call(sys.parent()))[1L], version = NULL) { if (getOption("shiny.deprecation.messages") %OR% TRUE == FALSE) return(invisible()) if (is.null(msg)) { msg <- paste(old, "is deprecated.") if (!is.null(new)) { msg <- paste(msg, "Please use", new, "instead.", "To disable this message, run options(shiny.deprecation.messages=FALSE)") } } if (!is.null(version)) { msg <- paste0(msg, " (Last used in version ", version, ")") } # Similar to .Deprecated(), but print a message instead of warning message(msg) } #' Register a function with the debugger (if one is active). #' #' Call this function after exprToFunction to give any active debugger a hook #' to set and clear breakpoints in the function. A debugger may implement #' registerShinyDebugHook to receive callbacks when Shiny functions are #' instantiated at runtime. #' #' @param name Name of the field or object containing the function. #' @param where The reference object or environment containing the function. #' @param label A label to display on the function in the debugger. #' @noRd registerDebugHook <- function(name, where, label) { if (exists("registerShinyDebugHook", mode = "function")) { registerShinyDebugHook <- get("registerShinyDebugHook", mode = "function") params <- new.env(parent = emptyenv()) params$name <- name params$where <- where params$label <- label registerShinyDebugHook(params) } } Callbacks <- R6Class( 'Callbacks', portable = FALSE, class = FALSE, public = list( .nextId = integer(0), .callbacks = 'Map', initialize = function() { # NOTE: we avoid using '.Machine$integer.max' directly # as R 3.3.0's 'radixsort' could segfault when sorting # an integer vector containing this value .nextId <<- as.integer(.Machine$integer.max - 1L) .callbacks <<- Map$new() }, register = function(callback) { if (!is.function(callback)) { stop("callback must be a function") } id <- as.character(.nextId) .nextId <<- .nextId - 1L .callbacks$set(id, callback) return(function() { .callbacks$remove(id) }) }, invoke = function(..., onError=NULL, ..stacktraceon = FALSE) { # Ensure that calls are invoked in the order that they were registered keys <- as.character(sort(as.integer(.callbacks$keys()), decreasing = TRUE)) callbacks <- .callbacks$mget(keys) for (callback in callbacks) { if (is.null(onError)) { if (..stacktraceon) { ..stacktraceon..(callback(...)) } else { callback(...) } } else { tryCatch( captureStackTraces( if (..stacktraceon) ..stacktraceon..(callback(...)) else callback(...) ), error = onError ) } } }, count = function() { .callbacks$size() } ) ) # convert a data frame to JSON as required by DataTables request dataTablesJSON <- function(data, req) { n <- nrow(data) # DataTables requests were sent via POST params <- URLdecode(rawToChar(req$rook.input$read())) q <- parseQueryString(params, nested = TRUE) ci <- q$search[['caseInsensitive']] == 'true' # data may have been replaced/updated in the new table while the Ajax request # from the previous table is still on its way, so it is possible that the old # request asks for more columns than the current data, in which case we should # discard this request and return empty data; the next Ajax request from the # new table will retrieve the correct number of columns of data if (length(q$columns) != ncol(data)) { res <- toJSON(list( draw = as.integer(q$draw), recordsTotal = n, recordsFiltered = 0, data = NULL )) return(httpResponse(200, 'application/json', enc2utf8(res))) } # global searching i <- seq_len(n) if (length(q$search[['value']]) && q$search[['value']] != '') { i0 <- apply(data, 2, function(x) { grep2(q$search[['value']], as.character(x), fixed = q$search[['regex']] == 'false', ignore.case = ci) }) i <- intersect(i, unique(unlist(i0))) } # search by columns if (length(i)) for (j in names(q$columns)) { col <- q$columns[[j]] # if the j-th column is not searchable or the search string is "", skip it if (col[['searchable']] != 'true') next if ((k <- col[['search']][['value']]) == '') next j <- as.integer(j) dj <- data[, j + 1] r <- commaToRange(k) ij <- if (length(r) == 2 && is.numeric(dj)) { which(dj >= r[1] & dj <= r[2]) } else { grep2(k, as.character(dj), fixed = col[['search']][['regex']] == 'false', ignore.case = ci) } i <- intersect(ij, i) if (length(i) == 0) break } if (length(i) != n) data <- data[i, , drop = FALSE] # sorting oList <- list() for (ord in q$order) { k <- ord[['column']] # which column to sort d <- ord[['dir']] # direction asc/desc if (q$columns[[k]][['orderable']] != 'true') next col <- data[, as.integer(k) + 1] oList[[length(oList) + 1]] <- (if (d == 'asc') identity else `-`)( if (is.numeric(col)) col else xtfrm(col) ) } if (length(oList)) { i <- do.call(order, oList) data <- data[i, , drop = FALSE] } # paging if (q$length != '-1') { i <- seq(as.integer(q$start) + 1L, length.out = as.integer(q$length)) i <- i[i <= nrow(data)] fdata <- data[i, , drop = FALSE] # filtered data } else fdata <- data fdata <- unname(as.matrix(fdata)) if (is.character(fdata) && q$escape != 'false') { if (q$escape == 'true') fdata <- htmlEscape(fdata) else { k <- as.integer(strsplit(q$escape, ',')[[1]]) # use seq_len() in case escape = negative indices, e.g. c(-1, -5) for (j in seq_len(ncol(fdata))[k]) fdata[, j] <- htmlEscape(fdata[, j]) } } res <- toJSON(list( draw = as.integer(q$draw), recordsTotal = n, recordsFiltered = nrow(data), data = fdata )) httpResponse(200, 'application/json', enc2utf8(res)) } # when both ignore.case and fixed are TRUE, we use grep(ignore.case = FALSE, # fixed = TRUE) to do lower-case matching of pattern on x grep2 <- function(pattern, x, ignore.case = FALSE, fixed = FALSE, ...) { if (fixed && ignore.case) { pattern <- tolower(pattern) x <- tolower(x) ignore.case <- FALSE } # when the user types in the search box, the regular expression may not be # complete before it is sent to the server, in which case we do not search if (!fixed && inherits(try(grep(pattern, ''), silent = TRUE), 'try-error')) return(seq_along(x)) grep(pattern, x, ignore.case = ignore.case, fixed = fixed, ...) } getExists <- function(x, mode, envir = parent.frame()) { if (exists(x, envir = envir, mode = mode, inherits = FALSE)) get(x, envir = envir, mode = mode, inherits = FALSE) } # convert a string of the form "lower,upper" to c(lower, upper) commaToRange <- function(string) { if (!grepl(',', string)) return() r <- strsplit(string, ',')[[1]] if (length(r) > 2) return() if (length(r) == 1) r <- c(r, '') # lower, r <- as.numeric(r) if (is.na(r[1])) r[1] <- -Inf if (is.na(r[2])) r[2] <- Inf r } # for options passed to DataTables/Selectize/..., the options of the class AsIs # will be evaluated as literal JavaScript code checkAsIs <- function(options) { evalOptions <- if (length(options)) { nms <- names(options) if (length(nms) == 0L || any(nms == '')) stop("'options' must be a named list") i <- unlist(lapply(options, function(x) { is.character(x) && inherits(x, 'AsIs') })) if (any(i)) { # must convert to character, otherwise toJSON() turns it to an array [] options[i] <- lapply(options[i], paste, collapse = '\n') nms[i] # options of these names will be evaluated in JS } } list(options = options, eval = evalOptions) } srcrefFromShinyCall <- function(expr) { srcrefs <- attr(expr, "srcref") num_exprs <- length(srcrefs) if (num_exprs < 1) return(NULL) c(srcrefs[[1]][1], srcrefs[[1]][2], srcrefs[[num_exprs]][3], srcrefs[[num_exprs]][4], srcrefs[[1]][5], srcrefs[[num_exprs]][6]) } # Indicates whether the given querystring should cause the associated request # to be handled in showcase mode. Returns the showcase mode if set, or NULL # if no showcase mode is set. showcaseModeOfQuerystring <- function(querystring) { if (nchar(querystring) > 0) { qs <- parseQueryString(querystring) if (exists("showcase", where = qs)) { return(as.numeric(qs$showcase)) } } return(NULL) } showcaseModeOfReq <- function(req) { showcaseModeOfQuerystring(req$QUERY_STRING) } # Returns (just) the filename containing the given source reference, or an # empty string if the source reference doesn't include file information. srcFileOfRef <- function(srcref) { fileEnv <- attr(srcref, "srcfile") # The 'srcfile' attribute should be a non-null environment containing the # variable 'filename', which gives the full path to the source file. if (!is.null(fileEnv) && is.environment(fileEnv) && exists("filename", where = fileEnv)) basename(fileEnv[["filename"]]) else "" } # Format a number without sci notation, and keep as many digits as possible (do # we really need to go beyond 15 digits?) formatNoSci <- function(x) { if (is.null(x)) return(NULL) format(x, scientific = FALSE, digits = 15) } # Returns a function that calls the given func and caches the result for # subsequent calls, unless the given file's mtime changes. cachedFuncWithFile <- function(dir, file, func, case.sensitive = FALSE) { dir <- normalizePath(dir, mustWork=TRUE) mtime <- NA value <- NULL function(...) { fname <- if (case.sensitive) file.path(dir, file) else file.path.ci(dir, file) now <- file.info(fname)$mtime if (!identical(mtime, now)) { value <<- func(fname, ...) mtime <<- now } value } } # turn column-based data to row-based data (mainly for JSON), e.g. data.frame(x # = 1:10, y = 10:1) ==> list(list(x = 1, y = 10), list(x = 2, y = 9), ...) columnToRowData <- function(data) { do.call( mapply, c( list(FUN = function(...) list(...), SIMPLIFY = FALSE, USE.NAMES = FALSE), as.list(data) ) ) } #' Declare an error safe for the user to see #' #' This should be used when you want to let the user see an error #' message even if the default is to sanitize all errors. If you have an #' error \code{e} and call \code{stop(safeError(e))}, then Shiny will #' ignore the value of \code{getOption("shiny.sanitize.errors")} and always #' display the error in the app itself. #' #' @param error Either an "error" object or a "character" object (string). #' In the latter case, the string will become the message of the error #' returned by \code{safeError}. #' #' @return An "error" object #' #' @details An error generated by \code{safeError} has priority over all #' other Shiny errors. This can be dangerous. For example, if you have set #' \code{options(shiny.sanitize.errors = TRUE)}, then by default all error #' messages are omitted in the app, and replaced by a generic error message. #' However, this does not apply to \code{safeError}: whatever you pass #' through \code{error} will be displayed to the user. So, this should only #' be used when you are sure that your error message does not contain any #' sensitive information. In those situations, \code{safeError} can make #' your users' lives much easier by giving them a hint as to where the #' error occurred. #' #' @seealso \code{\link{shiny-options}} #' #' @examples #' ## Only run examples in interactive R sessions #' if (interactive()) { #' #' # uncomment the desired line to experiment with shiny.sanitize.errors #' # options(shiny.sanitize.errors = TRUE) #' # options(shiny.sanitize.errors = FALSE) #' #' # Define UI #' ui <- fluidPage( #' textInput('number', 'Enter your favorite number from 1 to 10', '5'), #' textOutput('normalError'), #' textOutput('safeError') #' ) #' #' # Server logic #' server <- function(input, output) { #' output$normalError <- renderText({ #' number <- input$number #' if (number %in% 1:10) { #' return(paste('You chose', number, '!')) #' } else { #' stop( #' paste(number, 'is not a number between 1 and 10') #' ) #' } #' }) #' output$safeError <- renderText({ #' number <- input$number #' if (number %in% 1:10) { #' return(paste('You chose', number, '!')) #' } else { #' stop(safeError( #' paste(number, 'is not a number between 1 and 10') #' )) #' } #' }) #' } #' #' # Complete app with UI and server components #' shinyApp(ui, server) #' } #' @export safeError <- function(error) { if (inherits(error, "character")) { error <- simpleError(error) } if (!inherits(error, "error")) { stop("The class of the `error` parameter must be either 'error' or 'character'") } class(error) <- c("shiny.custom.error", class(error)) error } #***********************************************************************# #**** Keep this function internal for now, may chnage in the future ****# #***********************************************************************# # #' Propagate an error through Shiny, but catch it before it throws # #' # #' Throws a type of exception that is caught by observers. When such an # #' exception is triggered, all reactive links are broken. So, essentially, # #' \code{reactiveStop()} behaves just like \code{stop()}, except that # #' instead of ending the session, it is silently swalowed by Shiny. # #' # #' This function should be used when you want to disrupt the reactive # #' links in a reactive chain, but do not want to end the session. For # #' example, this enables you to disallow certain inputs, but get back # #' to business as usual when valid inputs are re-entered. # #' \code{reactiveStop} is also called internally by Shiny to create # #' special errors, such as the ones generated by \code{\link{validate}()}, # #' \code{\link{req}()} and \code{\link{cancelOutput}()}. # #' # #' @param message An optional error message. # #' @param class An optional class to add to the error. # #' @export # #' @examples # #' ## Note: the breaking of the reactive chain that happens in the app # #' ## below (when input$txt = 'bad' and input$allowBad = 'FALSE') is # #' ## easily visualized with `reactlogShow()` # #' # #' ## Only run examples in interactive R sessions # #' if (interactive()) { # #' # #' ui <- fluidPage( # #' textInput('txt', 'Enter some text...'), # #' selectInput('allowBad', 'Allow the string \'bad\'?', # #' c('TRUE', 'FALSE'), selected = 'FALSE') # #' ) # #' # #' server <- function(input, output) { # #' val <- reactive({ # #' if (!(as.logical(input$allowBad))) { # #' if (identical(input$txt, "bad")) { # #' reactiveStop() # #' } # #' } ## ' }) # #' # #' observe({ # #' val() # #' }) # #' } # #' # #' shinyApp(ui, server) # #' } # #' @export reactiveStop <- function(message = "", class = NULL) { stopWithCondition(c("shiny.silent.error", class), message) } #' Validate input values and other conditions #' #' For an output rendering function (e.g. \code{\link{renderPlot}()}), you may #' need to check that certain input values are available and valid before you #' can render the output. \code{validate} gives you a convenient mechanism for #' doing so. #' #' The \code{validate} function takes any number of (unnamed) arguments, each of #' which represents a condition to test. If any of the conditions represent #' failure, then a special type of error is signaled which stops execution. If #' this error is not handled by application-specific code, it is displayed to #' the user by Shiny. #' #' An easy way to provide arguments to \code{validate} is to use the \code{need} #' function, which takes an expression and a string; if the expression is #' considered a failure, then the string will be used as the error message. The #' \code{need} function considers its expression to be a failure if it is any of #' the following: #' #' \itemize{ #' \item{\code{FALSE}} #' \item{\code{NULL}} #' \item{\code{""}} #' \item{An empty atomic vector} #' \item{An atomic vector that contains only missing values} #' \item{A logical vector that contains all \code{FALSE} or missing values} #' \item{An object of class \code{"try-error"}} #' \item{A value that represents an unclicked \code{\link{actionButton}}} #' } #' #' If any of these values happen to be valid, you can explicitly turn them to #' logical values. For example, if you allow \code{NA} but not \code{NULL}, you #' can use the condition \code{!is.null(input$foo)}, because \code{!is.null(NA) #' == TRUE}. #' #' If you need validation logic that differs significantly from \code{need}, you #' can create other validation test functions. A passing test should return #' \code{NULL}. A failing test should return an error message as a #' single-element character vector, or if the failure should happen silently, #' \code{FALSE}. #' #' Because validation failure is signaled as an error, you can use #' \code{validate} in reactive expressions, and validation failures will #' automatically propagate to outputs that use the reactive expression. In #' other words, if reactive expression \code{a} needs \code{input$x}, and two #' outputs use \code{a} (and thus depend indirectly on \code{input$x}), it's #' not necessary for the outputs to validate \code{input$x} explicitly, as long #' as \code{a} does validate it. #' #' @param ... A list of tests. Each test should equal \code{NULL} for success, #' \code{FALSE} for silent failure, or a string for failure with an error #' message. #' @param errorClass A CSS class to apply. The actual CSS string will have #' \code{shiny-output-error-} prepended to this value. #' @export #' @examples #' ## Only run examples in interactive R sessions #' if (interactive()) { #' options(device.ask.default = FALSE) #' #' ui <- fluidPage( #' checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)), #' selectizeInput('in2', 'Select a state', choices = state.name), #' plotOutput('plot') #' ) #' #' server <- function(input, output) { #' output$plot <- renderPlot({ #' validate( #' need(input$in1, 'Check at least one letter!'), #' need(input$in2 != '', 'Please choose a state.') #' ) #' plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', ')) #' }) #' } #' #' shinyApp(ui, server) #' #' } validate <- function(..., errorClass = character(0)) { results <- sapply(list(...), function(x) { # Detect NULL or NA if (is.null(x)) return(NA_character_) else if (identical(x, FALSE)) return("") else if (is.character(x)) return(paste(as.character(x), collapse = "\n")) else stop("Unexpected validation result: ", as.character(x)) }) results <- stats::na.omit(results) if (length(results) == 0) return(invisible()) # There may be empty strings remaining; these are message-less failures that # started as FALSE results <- results[nzchar(results)] reactiveStop(paste(results, collapse="\n"), c(errorClass, "validation")) } #' @param expr An expression to test. The condition will pass if the expression #' meets the conditions spelled out in Details. #' @param message A message to convey to the user if the validation condition is #' not met. If no message is provided, one will be created using \code{label}. #' To fail with no message, use \code{FALSE} for the message. #' @param label A human-readable name for the field that may be missing. This #' parameter is not needed if \code{message} is provided, but must be provided #' otherwise. #' @export #' @rdname validate need <- function(expr, message = paste(label, "must be provided"), label) { force(message) # Fail fast on message/label both being missing if (!isTruthy(expr)) return(message) else return(invisible(NULL)) } #' Check for required values #' #' Ensure that values are available ("truthy"--see Details) before proceeding #' with a calculation or action. If any of the given values is not truthy, the #' operation is stopped by raising a "silent" exception (not logged by Shiny, #' nor displayed in the Shiny app's UI). #' #' The \code{req} function was designed to be used in one of two ways. The first #' is to call it like a statement (ignoring its return value) before attempting #' operations using the required values: #' #' \preformatted{rv <- reactiveValues(state = FALSE) #' r <- reactive({ #' req(input$a, input$b, rv$state) #' # Code that uses input$a, input$b, and/or rv$state... #' })} #' #' In this example, if \code{r()} is called and any of \code{input$a}, #' \code{input$b}, and \code{rv$state} are \code{NULL}, \code{FALSE}, \code{""}, #' etc., then the \code{req} call will trigger an error that propagates all the #' way up to whatever render block or observer is executing. #' #' The second is to use it to wrap an expression that must be truthy: #' #' \preformatted{output$plot <- renderPlot({ #' if (req(input$plotType) == "histogram") { #' hist(dataset()) #' } else if (input$plotType == "scatter") { #' qplot(dataset(), aes(x = x, y = y)) #' } #' })} #' #' In this example, \code{req(input$plotType)} first checks that #' \code{input$plotType} is truthy, and if so, returns it. This is a convenient #' way to check for a value "inline" with its first use. #' #' \strong{Truthy and falsy values} #' #' The terms "truthy" and "falsy" generally indicate whether a value, when #' coerced to a \code{\link[base]{logical}}, is \code{TRUE} or \code{FALSE}. We use #' the term a little loosely here; our usage tries to match the intuitive #' notions of "Is this value missing or available?", or "Has the user provided #' an answer?", or in the case of action buttons, "Has the button been #' clicked?". #' #' For example, a \code{textInput} that has not been filled out by the user has #' a value of \code{""}, so that is considered a falsy value. #' #' To be precise, \code{req} considers a value truthy \emph{unless} it is one #' of: #' #' \itemize{ #' \item{\code{FALSE}} #' \item{\code{NULL}} #' \item{\code{""}} #' \item{An empty atomic vector} #' \item{An atomic vector that contains only missing values} #' \item{A logical vector that contains all \code{FALSE} or missing values} #' \item{An object of class \code{"try-error"}} #' \item{A value that represents an unclicked \code{\link{actionButton}}} #' } #' #' Note in particular that the value \code{0} is considered truthy, even though #' \code{as.logical(0)} is \code{FALSE}. #' #' If the built-in rules for truthiness do not match your requirements, you can #' always work around them. Since \code{FALSE} is falsy, you can simply provide #' the results of your own checks to \code{req}: #' #' \code{req(input$a != 0)} #' #' \strong{Using \code{req(FALSE)}} #' #' You can use \code{req(FALSE)} (i.e. no condition) if you've already performed #' all the checks you needed to by that point and just want to stop the reactive #' chain now. There is no advantange to this, except perhaps ease of readibility #' if you have a complicated condition to check for (or perhaps if you'd like to #' divide your condition into nested \code{if} statements). #' #' \strong{Using \code{cancelOutput = TRUE}} #' #' When \code{req(..., cancelOutput = TRUE)} is used, the "silent" exception is #' also raised, but it is treated slightly differently if one or more outputs are #' currently being evaluated. In those cases, the reactive chain does not proceed #' or update, but the output(s) are left is whatever state they happen to be in #' (whatever was their last valid state). #' #' Note that this is always going to be the case if #' this is used inside an output context (e.g. \code{output$txt <- ...}). It may #' or may not be the case if it is used inside a non-output context (e.g. #' \code{\link{reactive}}, \code{\link{observe}} or \code{\link{observeEvent}}) #' -- depending on whether or not there is an \code{output$...} that is triggered #' as a result of those calls. See the examples below for concrete scenarios. #' #' @param ... Values to check for truthiness. #' @param cancelOutput If \code{TRUE} and an output is being evaluated, stop #' processing as usual but instead of clearing the output, leave it in #' whatever state it happens to be in. #' @param x An expression whose truthiness value we want to determine #' @return The first value that was passed in. #' @export #' @examples #' ## Only run examples in interactive R sessions #' if (interactive()) { #' ui <- fluidPage( #' textInput('data', 'Enter a dataset from the "datasets" package', 'cars'), #' p('(E.g. "cars", "mtcars", "pressure", "faithful")'), hr(), #' tableOutput('tbl') #' ) #' #' server <- function(input, output) { #' output$tbl <- renderTable({ #' #' ## to require that the user types something, use: `req(input$data)` #' ## but better: require that input$data is valid and leave the last #' ## valid table up #' req(exists(input$data, "package:datasets", inherits = FALSE), #' cancelOutput = TRUE) #' #' head(get(input$data, "package:datasets", inherits = FALSE)) #' }) #' } #' #' shinyApp(ui, server) #' } req <- function(..., cancelOutput = FALSE) { dotloop(function(item) { if (!isTruthy(item)) { if (isTRUE(cancelOutput)) { cancelOutput() } else { reactiveStop(class = "validation") } } }, ...) if (!missing(..1)) ..1 else invisible() } #***********************************************************************# #**** Keep this function internal for now, may chnage in the future ****# #***********************************************************************# # #' Cancel processing of the current output # #' # #' Signals an error that Shiny treats specially if an output is currently being # #' evaluated. Execution will stop, but rather than clearing the output (as # #' \code{\link{req}} does) or showing an error message (as \code{\link{stop}} # #' does), the output simply remains unchanged. # #' # #' If \code{cancelOutput} is called in any non-output context (like in an # #' \code{\link{observe}} or \code{\link{observeEvent}}), the effect is the same # #' as \code{\link{req}(FALSE)}. # #' @export # #' @examples # #' ## Only run examples in interactive R sessions # #' if (interactive()) { # #' # #' # uncomment the desired line to experiment with cancelOutput() vs. req() # #' # #' ui <- fluidPage( # #' textInput('txt', 'Enter text'), # #' textOutput('check') # #' ) # #' # #' server <- function(input, output) { # #' output$check <- renderText({ # #' # req(input$txt) # #' if (input$txt == 'hi') return('hi') # #' else if (input$txt == 'bye') return('bye') # #' # else cancelOutput() # #' }) # #' } # #' # #' shinyApp(ui, server) # #' } cancelOutput <- function() { reactiveStop(class = "shiny.output.cancel") } # Execute a function against each element of ..., but only evaluate each element # after the previous element has been passed to fun_. The return value of fun_ # is discarded, and only invisible() is returned from dotloop. # # Can be used to facilitate short-circuit eval on dots. dotloop <- function(fun_, ...) { for (i in 1:(nargs()-1)) { fun_(eval(as.symbol(paste0("..", i)))) } invisible() } #' @export #' @rdname req isTruthy <- function(x) { if (inherits(x, 'try-error')) return(FALSE) if (!is.atomic(x)) return(TRUE) if (is.null(x)) return(FALSE) if (length(x) == 0) return(FALSE) if (all(is.na(x))) return(FALSE) if (is.character(x) && !any(nzchar(stats::na.omit(x)))) return(FALSE) if (inherits(x, 'shinyActionButtonValue') && x == 0) return(FALSE) if (is.logical(x) && !any(stats::na.omit(x))) return(FALSE) return(TRUE) } # add class(es) to the error condition, which will be used as names of CSS # classes, e.g. shiny-output-error shiny-output-error-validation stopWithCondition <- function(class, message) { cond <- structure( list(message = message), class = c(class, 'error', 'condition') ) stop(cond) } #' Collect information about the Shiny Server environment #' #' This function returns the information about the current Shiny Server, such as #' its version, and whether it is the open source edition or professional #' edition. If the app is not served through the Shiny Server, this function #' just returns \code{list(shinyServer = FALSE)}. #' #' This function will only return meaningful data when using Shiny Server #' version 1.2.2 or later. #' @export #' @return A list of the Shiny Server information. #' #JGG # serverInfo <- function() { # .globals$serverInfo # } # .globals$serverInfo <- list(shinyServer = FALSE) # # setServerInfo <- function(...) { # infoOld <- serverInfo() # infoNew <- list(...) # infoOld[names(infoNew)] <- infoNew # .globals$serverInfo <- infoOld # } # assume file is encoded in UTF-8, but warn against BOM checkEncoding <- function(file) { # skip *nix because its locale is normally UTF-8 based (e.g. en_US.UTF-8), and # *nix users have to make a conscious effort to save a file with an encoding # that is not UTF-8; if they choose to do so, we cannot do much about it # except sitting back and seeing them punished after they choose to escape a # world of consistency (falling back to getOption('encoding') will not help # because native.enc is also normally UTF-8 based on *nix) if (!isWindows()) return('UTF-8') size <- file.info(file)[, 'size'] if (is.na(size)) stop('Cannot access the file ', file) # BOM is 3 bytes, so if the file contains BOM, it must be at least 3 bytes if (size < 3L) return('UTF-8') # check if there is a BOM character: this is also skipped on *nix, because R # on *nix simply ignores this meaningless character if present, but it hurts # on Windows if (identical(charToRaw(readChar(file, 3L, TRUE)), charToRaw('\UFEFF'))) { warning('You should not include the Byte Order Mark (BOM) in ', file, '. ', 'Please re-save it in UTF-8 without BOM. See ', 'http://shiny.rstudio.com/articles/unicode.html for more info.') return('UTF-8-BOM') } x <- readChar(file, size, useBytes = TRUE) if (is.na(iconv(x, 'UTF-8', 'UTF-8'))) { warning('The input file ', file, ' does not seem to be encoded in UTF8') } 'UTF-8' } # read a file using UTF-8 and (on Windows) convert to native encoding if possible readUTF8 <- function(file) { enc <- checkEncoding(file) file <- base::file(file, encoding = enc) on.exit(close(file), add = TRUE) x <- enc2utf8(readLines(file, warn = FALSE)) tryNativeEncoding(x) } # if the UTF-8 string can be represented in the native encoding, use native encoding tryNativeEncoding <- function(string) { if (!isWindows()) return(string) string2 <- enc2native(string) if (identical(enc2utf8(string2), string)) string2 else string } # similarly, try to source() a file with UTF-8 sourceUTF8 <- function(file, envir = globalenv()) { lines <- readUTF8(file) enc <- if (any(Encoding(lines) == 'UTF-8')) 'UTF-8' else 'unknown' src <- srcfilecopy(file, lines, isFile = TRUE) # source reference info # oddly, parse(file) does not work when file contains multibyte chars that # **can** be encoded natively on Windows (might be a bug in base R); we # rewrite the source code in a natively encoded temp file and parse it in this # case (the source reference is still pointed to the original file, though) if (isWindows() && enc == 'unknown') { file <- tempfile(); on.exit(unlink(file), add = TRUE) writeLines(lines, file) } exprs <- try(parse(file, keep.source = FALSE, srcfile = src, encoding = enc)) if (inherits(exprs, "try-error")) { diagnoseCode(file) stop("Error sourcing ", file) } # Wrap the exprs in first `{`, then ..stacktraceon..(). It's only really the # ..stacktraceon..() that we care about, but the `{` is needed to make that # possible. exprs <- makeCall(`{`, exprs) # Need to wrap exprs in a list because we want it treated as a single argument exprs <- makeCall(..stacktraceon.., list(exprs)) eval(exprs, envir) } # @param func Name of function, in unquoted form # @param args An evaluated list of unevaluated argument expressions makeCall <- function(func, args) { as.call(c(list(substitute(func)), args)) } # a workaround for https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=16264 srcfilecopy <- function(filename, lines, ...) { if (getRversion() > '3.2.2') return(base::srcfilecopy(filename, lines, ...)) src <- base::srcfilecopy(filename, lines = '', ...) src$lines <- lines src } # write text as UTF-8 writeUTF8 <- function(text, ...) { text <- enc2utf8(text) writeLines(text, ..., useBytes = TRUE) } URLdecode <- function(value) { decodeURIComponent(value) } URLencode <- function(value, reserved = FALSE) { value <- enc2utf8(value) if (reserved) encodeURIComponent(value) else encodeURI(value) } # This function takes a name and function, and it wraps that function in a new # function which calls the original function using the specified name. This can # be helpful for profiling, because the specified name will show up on the stack # trace. wrapFunctionLabel <- function(func, name, ..stacktraceon = FALSE) { if (name == "name" || name == "func" || name == "relabelWrapper") { stop("Invalid name for wrapFunctionLabel: ", name) } assign(name, func, environment()) registerDebugHook(name, environment(), name) relabelWrapper <- eval(substitute( function(...) { # This `f` gets renamed to the value of `name`. Note that it may not # print as the new name, because of source refs stored in the function. if (..stacktraceon) ..stacktraceon..(f(...)) else f(...) }, list(f = as.name(name)) )) relabelWrapper } # This is a very simple mutable object which only stores one value # (which we can set and get). Using this class is sometimes useful # when communicating persistent changes across functions. Mutable <- R6Class("Mutable", private = list( value = NULL ), public = list( set = function(value) { private$value <- value }, get = function() { private$value } ) ) # More convenient way of chaining together promises than then/catch/finally, # without the performance impact of %...>%. promise_chain <- function(promise, ..., catch = NULL, finally = NULL, domain = NULL, replace = FALSE) { do <- function() { p <- Reduce(function(memo, func) { promises::then(memo, func) }, list(...), promise) if (!is.null(catch)) { p <- promises::catch(p, catch) } if (!is.null(finally)) { p <- promises::finally(p, finally) } p } if (!is.null(domain)) { promises::with_promise_domain(domain, do(), replace = replace) } else { do() } } # Like promise_chain, but if `expr` returns a non-promise, then `...`, `catch`, # and `finally` are all executed synchronously hybrid_chain <- function(expr, ..., catch = NULL, finally = NULL, domain = NULL, replace = FALSE) { do <- function() { runFinally <- TRUE tryCatch( { captureStackTraces({ result <- withVisible(force(expr)) if (promises::is.promising(result$value)) { # Purposefully NOT including domain (nor replace), as we're already in # the domain at this point p <- promise_chain(setVisible(result), ..., catch = catch, finally = finally) runFinally <- FALSE p } else { result <- Reduce(function(v, func) { if (".visible" %in% names(formals(func))) { withVisible(func(v$value, .visible = v$visible)) } else { withVisible(func(v$value)) } }, list(...), result) setVisible(result) } }) }, error = function(e) { if (!is.null(catch)) catch(e) else stop(e) }, finally = if (runFinally && !is.null(finally)) finally() ) } if (!is.null(domain)) { promises::with_promise_domain(domain, do(), replace = replace) } else { do() } } # Returns `value` with either `invisible()` applied or not, depending on the # value of `visible`. # # If the `visible` is missing, then `value` should be a list as returned from # `withVisible()`, and that visibility will be applied. setVisible <- function(value, visible) { if (missing(visible)) { visible <- value$visible value <- value$value } if (!visible) { invisible(value) } else { (value) } } createVarPromiseDomain <- function(env, name, value) { force(env) force(name) force(value) promises::new_promise_domain( wrapOnFulfilled = function(onFulfilled) { function(...) { orig <- env[[name]] env[[name]] <- value on.exit(env[[name]] <- orig) onFulfilled(...) } }, wrapOnRejected = function(onRejected) { function(...) { orig <- env[[name]] env[[name]] <- value on.exit(env[[name]] <- orig) onRejected(...) } }, wrapSync = function(expr) { orig <- env[[name]] env[[name]] <- value on.exit(env[[name]] <- orig) force(expr) } ) } getSliderType <- function(min, max, value) { vals <- dropNulls(list(value, min, max)) type <- unique(lapply(vals, function(x) { if (inherits(x, "Date")) "date" else if (inherits(x, "POSIXt")) "datetime" else "number" })) if (length(type) > 1) { stop("Type mismatch for `min`, `max`, and `value`. Each must be Date, POSIXt, or number.") } type[[1]] } # Reads the `shiny.sharedSecret` global option, and returns a function that can # be used to test header values for a match. loadSharedSecret <- function() { normalizeToRaw <- function(value, label = "value") { if (is.null(value)) { raw() } else if (is.character(value)) { charToRaw(paste(value, collapse = "\n")) } else if (is.raw(value)) { value } else { stop("Wrong type for ", label, "; character or raw expected") } } sharedSecret <- normalizeToRaw(getOption("shiny.sharedSecret")) if (is.null(sharedSecret)) { function(x) TRUE } else { # We compare the digest of the two values so that their lengths are equalized function(x) { x <- normalizeToRaw(x) # Constant time comparison to avoid timing attacks constantTimeEquals(sharedSecret, x) } } } # Compares two raw vectors of equal length for equality, in constant time constantTimeEquals <- function(raw1, raw2) { stopifnot(is.raw(raw1)) stopifnot(is.raw(raw2)) if (length(raw1) != length(raw2)) { return(FALSE) } sum(as.integer(xor(raw1, raw2))) == 0 } <file_sep>/YATAWeb/ui/modTradingUI.R files.trading = list.files("ui/partials/modTrading", pattern="*UI.R$", full.names=TRUE) sapply(files.trading,source) modTradingInput <- function(id) { ns = NS(id) useShinyjs() tabsetPanel(id=ns("tabs"), type="pills" ,tabPanel("Open", value="open", modOpenInput(paste0(ns(""), "open"))) ,tabPanel("Buy/Sell", value="buy", modBuyInput(paste0(ns(""), "buy"))) ,tabPanel("Put/Call", value="put", modPutInput(paste0(ns(""), "put"))) # #JGG Cuando activo estos se jode la cosa # # ,tabPanel("Sell", value="sell", modSellInput(paste0(ns(""), "sell"))) # # ,tabPanel("XFer", value="xfer", modXFerInput(paste0(ns(""), "xfer"))) ) } <file_sep>/YATAModels/R/IND_DEMA.R IND_DEMA <- R6Class("IND_DEMA", inherit=IND_MA, public = list( name="Double-Exponential Moving Average" ,symbol="DEMA" ,initialize = function() { super$initialize() } ,calculate = function(TTickers, date) { window = self$getParameter("window") xt = private$getXTS(TTickers, pref=(window * 2)) if (nrow(xt) < window) return (NULL) DEMA = TTR::DEMA(xt[,TTickers$PRICE], n=window, wilder=FALSE) private$data = as.data.frame(DEMA[((window * 2)+ 1):nrow(DEMA),]) private$setDataTypes("ctc", "DEMA") private$calcVariation("DEMA") private$setColNames() } ,plot = function(p, TTickers) { if (nrow(private$data) == 0) return(p) col1 = private$setColNames(self$symbol) YATACore::plotLine(p, TTickers$df[,self$xAxis], private$data[,col1],hoverText=self$symbol) } ) ) <file_sep>/YATAManualTech/0201-config.Rmd # Configuracion Here is a review of existing methods. ## Prerequisitos ## configuracion Se asume la siguiente estructura de directorios: Para mostrar la ayuda es necesario crear los siguientes enlaces simbolicos mklink /D user ..\..\..\YATAManualUser\_book mklink /D tech ..\..\..\YATAManualTech\_book YATAWeb\www\man ## Paquetes <file_sep>/YATAClient/YATAEndPoints/src/main/java/com/jgg/client/wss/suscripcion.java package com.jgg.client.wss; import com.google.gson.Gson; public class suscripcion { public final static transient suscripcion TICKER = new suscripcion("1002"); public final static transient suscripcion HEARTBEAT = new suscripcion("1010"); public final static transient suscripcion BASE_COIN_DAILY_VOLUME_STATS = new suscripcion("1003"); public final static transient suscripcion USDT_BTC = new suscripcion("121"); public final static transient suscripcion USDT_ETH = new suscripcion("149"); public final String command; public final String channel; public suscripcion(String channel) { this.command = "subscribe"; this.channel = channel; } @Override public String toString() { return new Gson().toJson(this); } } <file_sep>/YATAConfig/SQL/ctc_dat_ind_parms.sql USE CTC; DELETE FROM PROVIDERS; INSERT INTO PROVIDERS ( ID, NAME) VALUES ("POL", "Poloniex"); INSERT INTO PROVIDERS ( ID, NAME) VALUES ("MKTCAP", "MarketCap"); COMMIT; <file_sep>/YATAClient/YATAEndPoints/src/main/java/com/jgg/client/wss/App.java package com.jgg.client.wss; import java.net.URI; import java.net.URISyntaxException; /** * Hello world! * */ public class App { wssclient wss = null; private final String BASE = "wss://api2.poloniex.com"; public static void main( String[] args ) { App app = new App(); app.start(); } void start() { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (wss != null) wss.close(); } }); System.out.println( "Hello World!" ); try { wss = new wssclient(new URI(BASE)); wss.connect(); suscripcion s = suscripcion.TICKER; wss.send(s.toString()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void end() { } } <file_sep>/YATAWeb/ui/modAnalysisServer.R library(shinyjs) modAnalysis <- function(input, output, session, parent) { shinyjs::runjs(paste0("YATAPanels('", session$ns(""), "')")) # Control la carga # LOADED = 7 # LOAD_MONEDA = 1 # Carga los tickers # LOAD_MODELO = 2 # Carga el modelo sin indicadores # LOAD_INDICATORS = 4 # Si hay tickers y modelo, carga indicadores # LOAD_ALL = 15 plotItems = list("None" = 0, "Price" = 1, "Volume" = 2, "MACD" = 3) vars <- reactiveValues( loaded = F ,tab = 2 ,provider = "POL" ,base = "USDT" ,counter = "BTC" ,scope = 0 ,sessions = list() ,session = NULL # Current ,plots = c(1,2,0) ,plotTypes = c(1,2,0) ,dtTo = Sys.Date() # dfd = NULL # Datos # ,loaded = 0 # 1 - Moneda, 2 - Modelo, 4 - Otro # # Tabla de tickers, se inicializa para que exista en init # ,tickers = NULL # TBLTickers$new("Tickers") # Tabla de tickers # ,changed = FALSE # ,parms = NULL # ,thres = NULL # ,clicks = 0 # ,mainSize = 12 # ,pendingDTFrom = F # ,pendingDTTo = F # ,toolbox = c(F,F,F,F) ) ######################################################################################## ### PRIVATE CODE ######################################################################################## updateData <- function(calculate = F) { # lapply(vars$sessions, function(x) { # eval(x)$getSessionDataInterval(vars$base, vars$counter, input$dtFrom, input$dtTo)}) session = vars$sessions[[vars$tab]] session$getSessionDataInterval(vars$base, vars$counter, input$dtFrom, vars$dtTo) # ,getSessionDataInterval = function(base, counter, from, to) { # print("Update Data") # panel = as.integer(input$tabTrading) if (calculate) {case$model$calculateIndicators(vars$tickers, force=T)} # browser() #plot = renderPlot(vars, case$model, panel, input, calculate) # tbl = DT::renderDataTable({ makeTable(panel, vars, case$model) }) # # if (panel == TERM_SHORT) { output$plotShort = renderPlotly({plot}); output$tblShort = tbl } # if (panel == TERM_MEDIUM) { output$plotMedium = renderPlotly({plot}); output$tblMedium = tbl } # if (panel == TERM_LONG) { output$plotLong = renderPlotly({plot}); output$tblLong = tbl } } renderInfo = function() { session = vars$sessions[[vars$tab]] textOuput("lblHeader", paste(session$base, session/counter, sep="/")) output$plot = renderPlotly({renderPlot(session)}) # if (is.null(session) || is.null(session$df)) return (NULL) # vars$plots # heights = list(c(1.0), c(0.6, 0.4), c(0.5, 0.25, 0.25), c(0.4, 0.2, 0.2, 0.2)) # DT::renderDataTable({ renderTable() }) # items = length(sources) # plots = list() # df = tickers$df # # idx = 0 # while (idx < items) { # idx = idx + 1 # p = plot_ly() # # if (!is.null(sources[idx]) && !is.na(sources[idx])) { # p = YATACore::plotBase(p, types[idx], x=df[,tickers$DATE] # , y=df[,sources[idx]] # , open = df[,tickers$OPEN] # , close = df[,tickers$CLOSE] # , high = df[,tickers$HIGH] # , low = df[,tickers$LOW] # , hoverText = tickers$symbol) # if (!is.null(p)) plots = list.append(plots, plotly_build(hide_legend(p))) # } # } # # rows = items - sum(is.na(sources)) } renderPlot = function (session) { heights = list(c(1.0), c(0.6, 0.4), c(0.5, 0.25, 0.25), c(0.4, 0.2, 0.2, 0.2)) numPlots = 0 plots = list() #browser() for (idx in 1:length(vars$plots)) { if (vars$plots[[idx]] == 0) next numPlots = numPlots + 1 yData = switch(as.integer(vars$plots[[idx]]), session$df[,session$CLOSE], session$df[,session$VOLUME]) p = plot_ly() p = YATACore::plotBase(p, as.integer(vars$plotTypes[[idx]]) , x=session$df[,session$TMS] , y=yData , open = session$df[,tickers$OPEN] , close = session$df[,tickers$CLOSE] , high = session$df[,tickers$HIGH] , low = session$df[,tickers$LOW] , hoverText = session$counter) if (!is.null(p)) plots = list.append(plots, plotly_build(hide_legend(p))) } sp = subplot( plots, nrows = numPlots, shareX=T, heights=heights[[numPlots]]) %>% config(displayModeBar=F) sp$elementId = NULL sp } ######################################################################################## ### OBSERVERS ######################################################################################## observeEvent(input$tabs, { vars$tab = as.integer(input$tabs) renderInfo() #click("btnSave") }) observeEvent(input$cboPlot1, { if (input$cboPlot1 == input$cboPlot2) updateSelectInput(session, "cboPlot2", selected = vars$plots[1]) if (input$cboPlot1 == input$cboPlot3) updateSelectInput(session, "cboPlot3", selected = vars$plots[1]) vars$plots[1] = input$cboPlot1 updateSelectInput(session, "cboType1", label=names(plotItems)[as.integer(input$cboPlot1)]) }) observeEvent(input$cboPlot2, { if (input$cboPlot2 == input$cboPlot1) updateSelectInput(session, "cboPlot1", selected = vars$plots[2]) if (input$cboPlot2 == input$cboPlot3) updateSelectInput(session, "cboPlot3", selected = vars$plots[2]) vars$plots[2] = input$cboPlot2 updateSelectInput(session, "cboType2", label=names(plotItems)[as.integer(input$cboPlot2)]) }) observeEvent(input$cboPlot3, { if (input$cboPlot3 == input$cboPlot1) updateSelectInput(session, "cboPlot1", selected = vars$plots[3]) if (input$cboPlot3 == input$cboPlot2) updateSelectInput(session, "cboPlot2", selected = vars$plots[3]) vars$plots[3] = input$cboPlot3 updateSelectInput(session, "cboType3", label=names(plotItems)[as.integer(input$cboPlot3)]) }) observeEvent(input$cboType1, { vars$plotTypes[1] = input$cboType1 }) observeEvent(input$cboType2, { vars$plotTypes[2] = input$cboType2 }) observeEvent(input$cboType3, { vars$plotTypes[3] = input$cboType3 }) # observeEvent(input$cboScope, { # browser() # per = c("W1", "D1", "H8") # if (input$cboScope == 1) per = c("D1", "H8", "H2") # Intraday # if (input$cboScope == 2) per = c("W1", "D1", "H8") # Day # if (input$cboScope == 3) per = c("M1", "W1", "D1") # Week # if (input$cboScope == 4) per = c("M1", "W1", "D1") # Month # vars$sessions = list(TBLSession$new(per[1]),TBLSession$new(per[2]),TBLSession$new(per[3])) # }) observeEvent(input$btnSave, { browser() shinyjs::runjs("YATAToggleSideBar(1, 0)") # if (input$cboMonedas == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MONEDA); return (NULL) } # updateActionButton(session, "tradTitle", label = input$cboMonedas) vars$base = input$cboBases vars$counter = input$cboMonedas vars$scope = input$cboScope updateData() }) # updateSelectInput(session, "cboMonedas", choices=cboMonedas_load(),selected=NULL) # updateSelectInput(session, "cboModels" , choices=cboModels_load()) # # observeEvent(input$tabTrading, { if (vars$loaded > 0) updateData(input, EQU(vars$loaded, LOADED)) }) # observeEvent(input$cboMonedas, { print("event moneda"); # if (input$cboMonedas == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MONEDA); return (NULL) } # updateActionButton(session, "tradTitle", label = input$cboMonedas) # # shinyjs::enable("btnSave") # vars$tickers = YATAData$new(case$profile$scope, input$cboMonedas) # rng = vars$tickers$getRange(YATAENV$getRangeInterval()) # vars$pendingDTFrom = T # vars$pendingDTTo = T # updateDateInput(session, "dtFrom", min=rng[1], max=rng[2], value=rng[3]) # updateDateInput(session, "dtTo", min=rng[1], max=rng[2], value=rng[2]) # vars$tickers$filterByDate(rng[3], rng[2]) # vars$loaded = bitwOr(vars$loaded, LOAD_MONEDA) # if (AND(vars$loaded, LOAD_MODELO)) { # case$model = loadIndicators(case$model, vars$tickers$scopes) # vars$loaded = bitwOr(vars$loaded, LOAD_INDICATORS) # } # updateData(input, EQU(vars$loaded, LOADED)) # # vars$dfd = vars$tickers$df # }, ignoreNULL=T, ignoreInit = T) # # # observeEvent(input$cboModels, { print("event Models") # shinyjs::enable("btnSave") # if (input$cboModels == 0) { vars$loaded = bitwAnd(vars$loaded, LOAD_ALL - LOAD_MODELO); return(NULL) } # case$model = YATAModels::loadModel(input$cboModels) # vars$loaded = bitwOr(vars$loaded, LOAD_MODELO) # if (AND(vars$loaded, LOAD_MONEDA)) { # case$model = loadIndicators(case$model, vars$tickers$scopes) # vars$loaded = bitwOr(vars$loaded, LOAD_INDICATORS) # } # updateData(input, EQU(vars$loaded, LOADED)) # }, ignoreNULL=T, ignoreInit = T) # # # # observeEvent(input$chkShowInd, {if (input$chkShowInd) { # # case$model$setParameters(getNumericGroup(input,vars$parms)) # # #JGG Revisar, no es una lista al uso # # #case$model$setThresholds(getNumericGroup(input,vars$thres)) # # ##case$model$calculateIndicatorsGlobal(vars$tickers) # # }}) # observeEvent(input$dtFrom, {if (vars$pendingDTFrom) { vars$pendingDTFrom = F; return (NULL) } # if (AND(vars$loaded, LOAD_MONEDA)) {print("event dtFrom"); # vars$tickers$filterByDate(input$dtFrom, input$dtTo) # case$model$calculated = FALSE # updateData(input, EQU(vars$loaded,LOADED)) # } # }, ignoreNULL=F, ignoreInit = T) # observeEvent(input$dtTo, { if (vars$pendingDTTo) { vars$pendingDTTo = F; return (NULL) } # if (AND(vars$loaded, LOAD_MONEDA)) { print("event dtTo"); # vars$tickers$filterByDate(input$dtFrom, input$dtTo) # case$model$calculated = FALSE # updateData(input, EQU(vars$loaded,LOADED)) # } # }, ignoreNULL=F, ignoreInit = T) # observeEvent(input$btnSave, { # updateParameter(PARM_CURRENCY, input$cboMoneda) # updateParameter(PARM_MODEL, input$cboModel) # shinyjs::disable("btnSave") # }) # # # First time ################################################################################################### ### PRIVATE CODE ################################################################################################### # makeTable = function(panel, vars, model) { # df = vars$tickers$getTickers(panel)$df # if (!is.null(case$model) && EQU(vars$loaded, LOADED)) { # for (ind in case$model$getIndicators(panel)) { # cols = ind$getData() # if (!is.null(cols)) df = cbind(df,cols) # } # } # .prepareTable(df) # } # # adjustToolbox = function(tabId) { # browser() # pnlIds = c("pnlShort", "pnlMedium", "pnlEmpty", "pnlLong") # tbIds = c("tbShort", "tbMedium", "tbEmpty", "tbLong") # print("entra en adjust") # newSize = "col-sm-10" # oldSize = "col-sm-12" # if (vars$toolbox[tabId]) { # newSize = "col-sm-12" # oldSize = "col-sm-10" # } # shinyjs::removeCssClass (id=pnlIds[tabId], oldSize) # shinyjs::toggle(id = tbIds[tabId]) # vars$toolbox[tabId] = !(vars$toolbox[tabId]) # shinyjs::addCssClass (id=pnlIds[tabId], newSize) # } # # # Lo devuelve cada vez que entra aqui # return(reactive({vars$changed})) # } # # # btnLoad_click <- function(input, output, session, vars) { # # if (validate()) return(showModal(dataError())) # # # Create user profile # profile = YATAProfile$new() # profile$name = input$txtPrfName # profile$profile = input$rdoPrfProfile # profile$capital = input$txtPrfImpInitial # profile$scope = input$rdoPrfScope # # # Create configuration for case # config = YATAConfig$new() # config$symbol = input$moneda # config$initial = input$txtPrfImpInitial # config$from = input$dtFrom # config$to = input$dtTo # config$mode = input$rdoProcess # config$delay = input$processDelay # # # Initialize case # case$profile = profile # case$config = config # case$tickers = vars$tickers # case$current = 0 # case$oper = NULL # # case$config$summFileName = setSummaryFileName(case) # case$config$summFileData = setSummaryFileData(case) # # calculateIndicators(case) # # # Create Portofolio # portfolio <<- YATAPortfolio$new() # portfolio$addActive(YATAActive$new(input$moneda)) # portfolio$flowFIAT(config$from, config$initial) # } # cboMonedas_load <- function() { # print("Load Monedas") # tIdx = DBCTC$getTable(TCTC_INDEX) # data = tIdx$df %>% arrange(Name) # setNames(c(0, data[,tIdx$SYMBOL]),c(" ", data[,tIdx$NAME])) # } # cboModels_load <- function() { # print("Load Modelos") # df = YATACore::loadModelsByScope(case$profile$getScope()) # setNames(c(0, df$ID_MODEL), c(" ", df$DESCR)) # } # # updateManual <- function(input, output, session, model) { # fp = paste(YATAENV$modelsMan, model$doc, sep="/") # # if (file.exists(fp)) { # output$modelDoc = renderUI({ # HTML(markdown::markdownToHTML(knit(fp, quiet = TRUE),fragment.only = TRUE)) # }) # } # else { # output$modelDoc = renderUI({"<h2>No hay documentacion</h2>"}) # } # } # # setParmsGroup = function(parms) { # if (length(parms) == 0) return (NULL) # # LL <- vector("list",length(parms)) # nm = names(parms) # for(i in 1:length(vars$parms)){ # LL[[i]] <- list(numericInput(ns(paste0("txt", nm[i])), label = nm[i], value = parms[[i]])) # } # return(LL) # # } # getNumericGroup = function(input, parms) { # # if (length(parms) == 0) return (NULL) # ll <- vector("list",length(parms)) # nm = names(parms) # # for(i in 1:length(parms)) { # # cat(eval(parse(text=paste0("input$txt", nm[i]))), "\n") # ll[[i]][1] = eval(parse(text=paste0("input$txt", nm[i]))) # } # names(ll) = nm # ll # } # # loadTickers = function(scope, moneda) { # pos = which(SCOPES == scope) # YATACore::openConnection() # t1 = NULL # t3 = NULL # if (pos > 1) t1 = TBLTickers$new(SCOPES[pos - 1], moneda) # t2 = TBLTickers$new(SCOPES[pos], moneda) # if (pos < length(SCOPES)) t3 = TBLTickers$new(SCOPES[pos + 1], moneda) # # YATACore::closeConnection() # list(t1,t2,t3) # } # # adjustPanel = function(expand, left, vars) { # shinyjs::removeCssClass (id="pnlMain", paste0("col-sm-", vars$mainSize)) # if (expand) vars$mainSize = vars$mainSize + 2 # if (!expand) vars$mainSize = vars$mainSize - 2 # shinyjs::addCssClass (id="pnlMain", paste0("col-sm-", vars$mainSize)) # if (left) { # shinyjs::toggle(id = "pnlLeft") # shinyjs::toggle(id = "SBLOpen") # } # else { # shinyjs::toggle(id = "pnlRight") # shinyjs::toggle(id = "SBROpen") # } # } if (!vars$loaded) { updateSelectInput(session, "cboProvider", choices=comboClearings(), selected="POL") updateSelectInput(session, "cboBases", choices=comboBases(NULL), selected="USDT") updateSelectInput(session, "cboMonedas", choices=comboCounters(), selected="BTC") updateDateInput(session, "dtFrom", value = Sys.Date() - months(3)) updateDateInput(session, "dtTo", value = Sys.Date()) per = c("W1", "D1", "H8") vars$sessions = list(TBLSession$new(per[1]),TBLSession$new(per[2]),TBLSession$new(per[3])) vars$loaded = T updateData(F) } }<file_sep>/YATACore/R/R6_YATAOperation.R YATAOperation <- R6Class("YATAOperation", public = list( initialize = function() { private$flows = TBLFlow$new() private$portfolio = TBLPortfolio$new() private$opers = TBLOperation$new() } ,transfer = function(from, to, currency, amount) { idOper = getYATAID() beginTrx(TRUE) private$makeTransfer(idOper, from, to, currency, amount) if (from != "Cash") private$portfolio$updatePosition(idOper, from, currency, amount * -1, Sys.time(), TRUE) if (to != "Cash") private$portfolio$updatePosition(idOper, to, currency, amount , Sys.time(), TRUE) commitTrx(TRUE) } ,add = function(type, clearing, base, counter, amount, proposal, limit, stop) { idOper = getYATAID() beginTrx(TRUE) private$opers$add(idOper, type, clearing, base, counter, amount, proposal, stop, limit) commitTrx(TRUE) idOper } ) ,private = list(flows = NULL, portfolio = NULL, opers = NULL ,makeTransfer = function(idOper, from, to, currency, amount) { idFlow1 = getYATAID() idFlow2 = getYATAID() ref = as.numeric(Sys.time()) tms = Sys.time() parms = NULL f = private$flows fields = c( f$ID_OPER, f$ID_FLOW, f$TYPE, f$CLEARING, f$BASE ,f$CURRENCY, f$PROPOSAL, f$EXECUTED, f$TMS_PROPOSAL, f$TMS_EXECUTED, f$REFERENCE) if (from != "Cash") { val = amount * -1 ref = 0 if (to != "Cash") ref = idFlow2 values = list(idOper, idFlow1, 90, from, currency, currency, val, val, tms, tms, idFlow2) names(values) = fields f$insert(values) } if (to != "Cash") { ref = 0 if (from != "Cash") ref = idFlow1 values = list(idOper, idFlow2, 91, from, currency, currency, amount, amount, tms, tms, idFlow1) names(values) = fields f$insert(values) } } ) ) <file_sep>/YATAManualTech/0410-operation.Rmd # Operation Mas que pensar el trading como la accion de comprar y luego vender preferimos verlo como operaciones en las que tomamos posicion en una determinada moneda por un determinado motivo y en algun momento deshacemos esa operacion. Por eso preferimos los terminos "_tomar_" y "_deshacer_" posicion, esto nos permite ampliar la informacion de la operacion registrando los motivos por los que se "entra" y se "sale" De acuerdo con esta nomenclatura, una operación tiene al menos dos patas: El momento en que se realiza la compra y el momento en el que se deshace (vende) esa posicion. A su vez, esta información se mantendrá en el "Diario de Operaciones" el cual es el que nos permite estudiar y analizar nuestro comportamiento como Trader y sobre todo, aprender de nuestros errores. Un caso especial es la transferencia de monedas entre camaras; en este caso no se genera una operacion si no un unico flujo <file_sep>/YATACore/R/PKG_IO.R library(R6) library(zoo) #' Es un wrapper para los diferentes fuentes de datos openConnection = function(DB="CTC") { conn = .SQLDBConnect(DB) conn } closeConnection = function(conn=NULL) { # cnx = conn # if (is.null(conn) && !is.null(vars$SQLConn)) cnx = vars$SQLConn # .SQLDBDisconnect(cnx) # if (is.null(conn) && !is.null(vars$SQLConn)) vars$SQLConn = NULL if (!is.null(conn)) .SQLDBDisconnect(conn) } beginTrx = function(newConn = F) { .SQLTran(1, newConn) } commitTrx = function(newConn = F) { .SQLTran(2, newConn) } rollbackTrx = function(newConn = F) { .SQLTran(3, newConn) } executeQuery = function(stmt, parms=NULL, isolated=F) { .SQLDataFrame(stmt, parms, isolated) } executeUpdate = function(stmt, parms=NULL, isolated=F) { .SQLExecute (stmt, parms, isolated) } getMetadata = function(table) { .SQLMetadata(table) } ################################################# # Carga Tablas ################################################# #' @export loadTable <- function (table, isolated=T) { .SQLLoadTable(table, isolated) } #' @export writeTable <- function (table, data, isolated=T) { .SQLWriteTable(table, data, isolated) } #' @export loadParameters <- function() { .SQLloadParameters() } loadProvider <- function(provider) { .SQLLoadProvider(provider) } #' @export loadCTCPairs <- function(source=NA, target=NA) { .SQLGetCurrencyPairs(source,target) } #' @export loadModelsByScope <- function(scope) { sc = scope if (sc == SCOPE_NONE) sc = SCOPE_ALL df = .SQLLoadModels() subset(df, bitwAnd(df$FLG_SCOPE, sc) > 0) } ################################################# # Recupera datos ################################################# getMessageLocale = function(code, lang, region) { msg = .SQLGetMessage(code, lang, region) } #' @export getModel <- function(idModel) { .SQLGetModel(idModel) } #' @export getModelIndicators <- function(idModel) { .SQLGetModelIndicators(idModel) } getLastSessions <- function() { .SQLGetLastSessions() } loadProfile <- function(tableName) { .SQLLoadProfile() } #' @export loadModelIndicators <- function(idModel, idScope) { .SQLLoadModelIndicators(scope) } #' @export getIndicator <- function(idIndicator) { .SQLGetIndicator(idIndicator) } #' @export getIndicatorParameters <- function(idInd, scope, term) { .SQLGetIndicatorParameters(idInd, scope, term) } #' @export loadModelGroups <- function(tbName) { if (YATAENV$modelsDBType == IO_CSV) .CSVLoadModelGroups(tbName) .XLSLoadModelGroups(tbName) } #' @export loadModelModels <- function(tbName) { if (YATAENV$modelsDBType == IO_CSV) .CSVLoadModelModels(tbName) .XLSLoadModelModels(tbName) } #' @export loadCTCIndex <- function(tbName) { if (YATAENV$dataSourceDBType == IO_CSV) df = .CSVLoadCTCIndex(tbName) if (YATAENV$dataSourceDBType == IO_SQL) df = .SQLLoadCTCIndex(tbName) if (YATAENV$dataSourceDBType == IO_XLS) df = .XLSLoadCTCIndex(tbName) df } # Carga los tickers de latabla asociada y para la moneda indicada #' @export loadSessions <- function(symbol, source, fiat) { if (YATAENV$dataSourceDBType == IO_CSV) df = .CSVLoadSessions(symbol, source, fiat) if (YATAENV$dataSourceDBType == IO_XLS) df = .XLSLoadSessions(symbol, source, fiat) if (YATAENV$dataSourceDBType == IO_SQL) df = .SQLLoadSessions(symbol, source, fiat) if (!is.null(df)) df = df %>% arrange(df$Date) df } #' @export loadCurrency <- function(symbol) { if (YATAENV$sourceType == SRC_XLS) return(.XLSLoadCurrency(symbol)) } #' @export updateParameters <- function(key, value) { .SQLUpdateParameters(key, value) } loadCases <- function(cases) { .XLSloadCases() } #' @export writeSummary <- function(data, container, component) { # Defecto XLS #if (YATAENV$outputType == IO_CSV) return(.CSVWriteSummary(data, container, component)) #if (YATAENV$outputType == IO_XLS) return(.CSVWriteSummary(container, component)) return(.CSVWriteData(data, container, component)) } #' @export appendSummary <- function(data, container, component) { # Defecto XLS #if (YATAENV$outputType == IO_CSV) return(.CSVWriteSummary(data, container, component)) #if (YATAENV$outputType == IO_XLS) return(.CSVWriteSummary(container, component)) return(.CSVAppendData(data, container, component)) } .createModel <- function(record) { name=record[1,CASE_MODEL] if (!is.na(record[1,CASE_VERSION])) name = paste(name,record[1,CASE_VERSION],sep=".") base=eval(parse(.makeDir(DIRS["models"],"Model_Base.R"))) file=.makeDir(DIRS["models"], paste(paste("Model_",name,sep=""),"R",sep=".")) mod=eval(parse(file)) model = eval(parse(text=paste(MODEL_PREFIX, name, "$new()", sep=""))) model } setSummaryFileName <- function(case) { .XLSsetSummaryFileName(case) } setSummaryFileData <- function(case) { .XLSsetSummaryFileData(case) } .createModel <- function(record) { name=record[1,CASE_MODEL] if (!is.na(record[1,CASE_VERSION])) name = paste(name,record[1,CASE_VERSION],sep=".") base=eval(parse(.makeDir(DIRS["models"],"Model_Base.R"))) file=.makeDir(DIRS["models"], paste(paste("Model_",name,sep=""),"R",sep=".")) mod=eval(parse(file)) model = eval(parse(text=paste(MODEL_PREFIX, name, "$new()", sep=""))) model } .createTableTickers <- function(name) { TBLTickers = R6::R6Class("TBLTickers", inherit=YATATable, public = list( DATE="Date" ,OPEN="Open" ,HIGH="High" ,LOW="Low" ,CLOSE="Close" ,VOLUME="Volume" ,CAP="MarketCap" ,refresh = function() { super$refresh(".loadCTCTickers", self$name) } ) ) TBLTickers$new(name) } <file_sep>/YATACore/R/TBL_Messages.R TBLMessages = R6::R6Class("TBLMessages", inherit=YATATable, public = list( # Column names LANG = "XX" ,REGION = "XX" ,initialize = function() { self$name="Messages"; } ,getMessage = function(code) { msg = private$cache[[code]] if (!is.null(msg)) return(msg) msg = private$getMSG(code) if (length(private$cache) == private$cacheSize) { private$cache = private$cache[-1] } nm = c(names(private$cache), code) private$cache = c(private$cache, msg) names(private$cache) = nm msg } ) ,private = list ( cache = list() ,cacheSize = 10 ,getMSG = function(code) { df = getMessageLocale(code, "XX", "XX") df[1, "MSG"] } ) ) <file_sep>/YATACore/R/TBL_Operation.R # Implementa la tabla de cambios: last, ask, bid, etc. TBLOperation = R6::R6Class("TBLOperation", inherit=YATATable, public = list( ID = "ID_OPER" ,TYPE = "TYPE" ,CLEARING = "CLEARING" ,BASE = "BASE" ,COUNTER = "COUNTER" ,AMOUNT = "AMOUNT" ,IN_PROPOSAL = "IN_PROPOSAL" ,IN_EXECUTED = "IN_EXECUTED" ,IN_REASON = "IN_REASON" ,STOP = "OPSTOP" ,LIMIT = "OPLIMIT" ,OUT_PROPOSAL = "OUT_PROPOSAL" ,OUT_EXECUTED = "OUT_EXECUTED" ,OUT_REASON = "OUT_REASON" ,TMS_IN = "TMS_IN" ,TMS_OUT = "TMS_OUT" ,TMS_LAST = "TMS_LAST" ,PRICE = "PRICE" ,initialize = function() { self$name = "Operations" self$table = "Operations" } ,refresh = function() { if (is.null(private$bases)) { private$firstTime() return (invisible(self)) } tmp = private$getTickers() if (nrow(tmp) == 0) return (invisible(self)) private$makeLast(tmp) # Append data for graph for (base in private$bases) { df = tmp %>% filter(EXC == base) private$dfList[[which(private$bases == base)]] = rbind(private$dfList[[which(private$bases == base)]], df) } invisible(self) } ,add = function(id, type, clearing, base, counter, amount, proposal, stop, limit) { fields = c( self$ID ,self$TYPE, self$CLEARING ,self$BASE ,self$COUNTER ,self$AMOUNT ,self$IN_PROPOSAL ,self$STOP ,self$LIMIT ,self$TMS_IN ,self$TMS_LAST) values = list( id ,type ,clearing ,base ,counter ,amount ,proposal ,stop ,limit ,Sys.time(), Sys.time()) names(values) = fields self$insert(values) } ,getOpenPending = function() { qry = paste("SELECT * FROM ", self$table, " WHERE ", self$IN_EXECUTED, "IS NULL") self$df = executeQuery(qry) self$df } ,print = function() { print(self$name) } ) ,private = list( bases = NULL ,dfFirst = NULL ,dfLast = list() ,dfList = list() ,dfSession = NULL ,firstTime = function() { private$dfFirst = private$getTickers() if (nrow(private$dfFirst) == 0) return (invisible(self)) private$bases = unique(private$dfFirst$EXC) dfSes = getLastSessions() private$dfSession = dfSes[,c("CTC", "EXC", "CLOSE")] private$dfSession = join( private$dfSession ,private$dfFirst[,c("CTC", "EXC", "Last")] ,by = c("CTC", "EXC")) colnames(private$dfSession) = c("CTC", "EXC", "Close", "Session") for (base in private$bases) { df = private$dfFirst %>% filter(EXC == base) private$dfList = list.append(private$dfList, df) } private$makeLast(private$dfFirst) } ,makeLast = function(last) { last = join(last, private$dfSession, by = c("CTC", "EXC")) last = private$adjustTypes(last) last[,"Close"] = as.fiat(last[,"Close"]) last[,"Session"] = as.fiat(last[,"Session"]) columns = c("TMS", "EXC", "CTC", "Last", "Ask", "Bid", "High", "Low", "Volume", "Change", "Session", "Close") last = last[,columns] private$dfLast = list() for (base in private$bases) { df = last %>% filter(EXC == base) private$dfLast = list.append(private$dfLast, df) } } ,getTickers = function() { tmp = YATAProviders::getTickers() private$adjustTypes(tmp) } # ,calculateChange = function(last) { # tmp = join( private$dfSession, last[,c("EXC","CTC", "Last")],by = c("CTC", "EXC")) # tmp$Session = (tmp[,4] / tmp[,3]) - 1 # tmp[,3:4] = NULL # tmp = replace(tmp, is.na(tmp), 0) # df = merge(last, tmp, by = c("CTC", "EXC")) # df # } # ,calculateChangeDay = function(last) { # browser() # tmp = join( private$dfSession[,c("EXC","CTC", "Close")] # ,last[,c("EXC","CTC", "Last")] # ,by = c("CTC", "EXC")) # tmp$Session = (tmp[,4] / tmp[,3]) - 1 # tmp[,3:4] = NULL # tmp = replace(tmp, is.na(tmp), 0) # df = merge(last, tmp, by = c("CTC", "EXC")) # df # # # } ,adjustTypes = function(tmp) { tmp[,self$TMS] = as.datet(tmp[,self$TMS]) tmp[,self$HIGH] = as.fiat(tmp[,self$HIGH]) tmp[,self$LOW] = as.fiat(tmp[,self$LOW]) tmp[,self$LAST] = as.fiat(tmp[,self$LAST]) tmp[,self$ASK] = as.fiat(tmp[,self$ASK]) tmp[,self$BID] = as.fiat(tmp[,self$BID]) tmp[,self$CHANGE] = as.percentage(tmp[,self$CHANGE]) tmp[,self$VOLUME] = as.long(tmp[,self$VOLUME]) tmp } ) ) <file_sep>/YATAWeb/ui/modCurrencyServer.R modCurrency <- function(input, output, session, symbol) { plotTypes = c(PLOT_LINEAR, PLOT_LOG, PLOT_BAR, PLOT_CANDLE) plotSources = c("Price", "Volume", "Variation", NA) vars <- reactiveValues( loaded = F ,nDays = 60 ) print("Entra en el modulo") makeTableSession = function(df) { # Remove auxiliar column: PRICE p=which(colnames(df) == "Price") if (length(p) > 0) tmp = df[,-p[1]] tblHead = .makeHead(df) dt = datatable(df, container = tblHead, rownames = FALSE) dt = .formatColumns(df, dt) dt } renderTableData = function() { dt = makeTableSession(vars$tickers$reverse()) output$tblCTC = DT::renderDataTable({ dt }) } renderTablePos = function() { df = data.frame(CTC=symbol, Position=3000, PM1=3000, PM2=3000) output$tblPos = DT::renderDataTable({ as.data.table(df) }) } renderPlot = function() { tmp = TBLSession$new(symbol, TBL_DAY, YATAENV$currency) tmp$filterByRows(vars$nDays * -1) vars$tickers = tmp sources = c( plotSources[as.integer(input$swPlt1S)] ,plotSources[as.integer(input$swPlt2S)] ,plotSources[as.integer(input$swPlt3S)]) types = c( plotTypes[as.integer(input$swPlt1T)] ,plotTypes[as.integer(input$swPlt2T)] ,plotTypes[as.integer(input$swPlt3T)]) output$plotCTC = renderPlotly({renderPlotSession(vars$tickers, sources, types)}) } observeEvent(input$btnConfig, { print("Parate")}) observeEvent(input$btnPlots, { renderPlot() }) if (!vars$loaded) { vars$loaded = T renderPlot() renderTableData() renderTablePos() } } <file_sep>/YATAModels/R/IND_WMA.R source("R/IND_MA.R") IND_WMA <- R6Class("IND_WMA", inherit=IND_MA, public = list( name="Weigthed Moving Average" ,symbol="WMA" ,initialize = function() { super$initialize(list(window=7,offset=0.5,sigma=6)) ind1 = YATAIndicator$new( self$name, self$symbol, type=IND_LINE, blocks=3 ,parms=list(window=7, offset=0.5, sigma=6)) private$addIndicators(ind1) } # ,calculate <- function(data, ind, columns, n, offset, sigma) { ,calculate = function(data, ind) { if (ind$name != "ALMA") return (super$calculate(data, ind)) xt=private$getXTS(data) n = private$parameters[["window"]] offset = private$parameters[["offset"]] sigma = private$parameters[["sigma" ]] res1 = TTR::ALMA(xt[,data$PRICE] ,n,offset,sigma) res2 = TTR::ALMA(xt[,data$VOLUME],n,offset,sigma) list(list(private$setDF(res1, ind$columns)), list(private$setDF(res2, paste0(ind$columns, "_v")))) } ) ) <file_sep>/YATACore/R/IND_Patterns.R #Pattern indicators are classic technical indicators like the head-and-shoulders. They involve detecting #some pattern in the data and triggering a trading signal if found. When we are detecting these patterns #with computers, these indicators are often called binary or ternary because they have two or three possible #values, -1 (short), 0 (neutral), and 1 (long). #Rule sets for these indicators are simple because they are essentially built in to the indicator. Practical #rule sets including these indicators often combine or index pattern indicators along with other indicators.<file_sep>/YATAConfig/SQL/ctt_dat.sql source ctc_dat_parms.sql source ctc_dat_parms.sql source ctc_dat_ctc.sql source ctc_dat_pairs.sql source ctc_dat_portfolio.sql source ctc_dat_ind.sql<file_sep>/YATAManualTech/0700-models.Rmd # Models and indicators Some _significant_ applications are demonstrated in this chapter. ## Scope and targets Un modelo puede aplicar hasta a 3 conjunto de datos: * Largo * Medio * Corto Un indicador aplica normalmente a un tipo de dato (target), por ejemplo: * Precio * Close * Open * Volumen y sobre ese target aplica los parametros del indicador, esto quiere decir que sobre un mismo dato se puede aplicar un mismo indicador varias veces con diferente parametrizacion (evidentemente si los dos indicadores comparten sus parametros el resultado es redundante); por ejemplo, se puede aplicar una media corta y una media larga sobre el precio. Los indicadores se guardan en una lista/vector de manera secuencial, lo cual nos da un indice unico y conocido a cada indicador Luego tenemos una matriz de 3 dimensiones; X = 3 Los scopes y = 8 Los targets De esta manera, los siguientes datos ```{r, echo=F} library(abind) m0 = array(0, dim=c(3,4)) m0[1,1] = 1 m0[1,3] = 2 m0[2,2] = 3 m0[3,4] = 4 ``` ```{r} m0 ``` se intrepreta como: Para el scope 1, se aplican los indicadores 1 y 2 para el scope 2, se aplica el indicador 3 para el scope 3, se aplica el indicador 4 Para smplificar el algoritmo, añadimos la otra dimension: m1 = array(0, dim=c(3,4)) m0 = abind(m0,m1, along=3) con lo que dim(m0) = [3,4,2] Si ahora deseamos añadir el indicador i5 al scope 1 con el target 4, el proceso es el siguiente desde tgt= 1 hasta la dimension 3 (ahora 2) hacer Si m0[1,4, tgt] == 0 m0[1,4, tgt] = i5 si tgt == dimension 3 estariamos en la ultima capa # Creamos otra capa de ceros m0 = abind(m0, array(0, dim=c(3,4)) fin si break fin si Ahora para seleccionar los indicadores de un determiando scope, simplemente hacemos m0[scope,,] lo cual nos devolvera una matrix donde las filas son los targets y las columnas son los indicadores a aplicar ## ejemplo completo 1.- Cada scope usa un indicador ```{r, } m = array(0, dim=c(3,4)) m[1,1] = 1 m[2,2] = 2 m[3,3] = 3 m = abind(m, array(0, dim=c(3,4)), along=3) m ``` 2.- Cogemos los indicadores para el scope 2 ```{r} m[2,,] ``` Y sobre esto buscamos los indices que no son cero. 3.- Añadimos el indicador i5 al scope 2, target = 3 ```{r} sc = 2 tgt = 3 ind = 5 max = dim(m)[3] for (i in 1:max) { if (m[sc, tgt, i] == 0) { m[sc, tgt, i] = ind if (i == max) { m = abind(m, array(0, dim=c(3,4)), along=3) } break } } m ``` Ahora si cogemos los indicadores del scope 2: ```{r} m[2,,] ``` 4.- Ahora añadimos el indicador i6 al mismo scope y al target 2 ```{r} sc = 2 tgt = 2 ind = 6 max = dim(m)[3] for (i in 1:max) { if (m[sc, tgt, i] == 0) { m[sc, tgt, i] = ind if (i == max) { m = abind(m, array(0, dim=c(3,4)), along=3) } break } } m ``` Como se puede ver, el ultimo indicador se ha ido a la segunda capa y se ha creado otra nueva, y su slice los tiene incluidos ```{r} m[2,,] ``` m[2,3,1] == 0 => si m[2,3,1] = 5 si m0[1,4] = 0, simplemente se actualiza ese p <- plot_ly( + x = c(0, 0, 1, 1, 0, 0, 1, 1), + y = c(0, 1, 1, 0, 0, 1, 1, 0), + z = c(0, 0, 0, 0, 1, 1, 1, 1), + i = c(7, 0, 0, 0, 4, 4, 2, 6, 4, 0, 3, 7), + j = c(3, 4, 1, 2, 5, 6, 5, 5, 0, 1, 2, 2), + k = c(0, 7, 2, 3, 6, 7, 1, 2, 5, 5, 7, 6), + facecolor = rep(toRGB(viridisLite::inferno(6)), each = 2) + ,type="mesh3d") > p > m = matrix(0, dim=c(3,4)) ## Example tw o <file_sep>/YATAWeb/global.R if ("YATAModels" %in% (.packages())) detach("package:YATAModels", unload=T, force=T) if ("YATACore" %in% (.packages())) detach("package:YATACore", unload=T, force=T) # if ("YATAProviders" %in% (.packages())) detach("package:YATAProviders", unload=T) # Shiny library(shiny) library(shinyjs) library(shinyBS) library(shinythemes) # library(shinydashboard) library(shinydashboardPlus) library(shinyWidgets) # library(shinyjqui) # library(V8) library(htmltools) library(htmlwidgets) # General library(dplyr) library(data.table) library(stringr) library(rlist) library(R6) library(readr) library(knitr) # Plots library(ggplot2) library(gridExtra) library(plotly) library(RColorBrewer) # Quant library(lubridate) library(zoo) # YATA library(YATAModels) library(YATACore) # shhh(library(XLConnect,quietly = T)) # shhh(library(knitr ,quietly = T)) # shhh(library(chron ,quietly = T)) library(DT) library(markdown) # shhh(library(readr ,quietly = T)) # shhh(library(gsubfn ,quietly = T)) #require(YATAModels) #require(YATAProviders) require(YATACore) rm(list=ls()) .globals <- new.env(parent = emptyenv()) options( warn = -1 ,DT.options = list(dom = "t", bPaginate = FALSE, rownames = FALSE, scrollX = F) # ,java.parameters = "-Xmx2048m" # ,shiny.reactlog=TRUE # ,shiny.trace=TRUE ) plotly::config(plot_ly(), displaylogo = FALSE, collaborate = FALSE, displayModeBar = FALSE, responsive=TRUE) files.widgets = list.files("widgets", pattern="*\\.R$", full.names=TRUE, ignore.case=F) sapply(files.widgets,source) # Codigo auxiiar files.r = list.files("R", pattern="*\\.R$", full.names=TRUE, ignore.case=F) sapply(files.r, source) # Modulos de interfaz UI files.sources = list.files("ui", pattern="*\\.R$", full.names=TRUE, ignore.case=F) sapply(files.sources,source) # source("locale/messages_ES.R", local=T) # Datos globales # SQLConn <<- NULL # Create YATAENV as Global YATACore::createEnvironment() YATAENV$dataSourceDBName = "CTC" # YATAENV$dataSourceDBType = IO_SQL # YATAENV$modelsDBType = IO_SQL # case = YATACore::YATACase$new() # case$profile = YATACore::TBLProfile$new() #JGG addResourcePath("man", "d:/R/YATA/YATAManualUser") ###################################### ### Paneles ###################################### PNL_TST = "tst" PNL_OL = "ol" PNL_PRF = "prf" PNL_TRAD = "trad" PNL_ANA = "ana" PNL_SIM = "sim" PNL_CONF = "conf" PNL_HELP = "manual" PNL_SYS = "sys" PNL_IND = "ind" PNL_MAN_USR = "user" PNL_MAN_TECH = "tech" ###################################### ### Factores globales ###################################### PLOT = YATACore::FACT_PLOT$new() onStop(function() { cat("Doing application cleanup\n") #cleanEnvironment() }) # onSessionEnded(function() { # #called after the client has disconnected. # cat("Doing application cleanup\n") # })<file_sep>/YATAWeb/ui/modIndicatorsUI.R modIndicatorsInput <- function(id) { ns <- NS(id) useShinyjs() panelTool = box(width=NULL , title = p("Toolbox",actionButton( ns("SBLClose"), "",icon = icon("remove"), class = "btn-xs")) ) panelLeft = box( width=NULL , title = p("Config",actionButton( ns("SBLClose"), "",icon = icon("remove"), class = "btn-xs")) ,solidHeader = T, status = "primary" ,textInput(ns("txtPrfName"), label = "Nombre", value = "Javier") ,selectInput(ns("rdoPrfProfile"), label=NULL, selected = PRF_MODERATE , choices=makeList( c(PRF_SAVER,PRF_CONSERVATIVE,PRF_MODERATE,PRF_BOLD,PRF_DARED) ,c(LBL.SAVER,LBL.CONSERVATIVE,LBL.MODERATE,LBL.BOLD,LBL.DARED))) ,numericInput(ns("txtPrfImpInitial"), label = "Capital", value=10000, min=1000, step=500) ,hr() ,selectInput(ns("cboMonedas"), label = "Moneda", choices = NULL, selected=NULL) ,dateInput(ns("dtFrom"),"Desde", value = "2012-02-29", format = "dd/mm/yy", startview = "year") ,dateInput(ns("dtTo"),NULL, value = "2012-02-29", format = "dd/mm/yy", startview = "year") ,hr() ,selectInput(ns("rdoPrfScope"), label=NULL, selected=3 ,choices = c("Intraday" = 1,"Short"=2,"Medium"=3,"Long"=4)) ,selectInput(ns("cboModels"), label="Modelo", choices=NULL, selected=NULL) ,hr() ,disabled(bsButton(ns("btnSave"), label = "Guardar", style="success", size="large")) ) panelRight = box( width=NULL ,title = p("Config",actionButton( ns("SBRClose"), "",icon = icon("remove"), class = "btn-xs")) ,solidHeader = T ,status = "primary" ,wellPanel(radioButtons(ns("rdoPlot"), label="Graph",selected = PLOT_LINEAR , choices = list( "Linear" = PLOT_LINEAR ,"Log" = PLOT_LOG ,"Candles" = PLOT_CANDLE) )) ,wellPanel(checkboxGroupInput(ns("chkIndicators"), label = NULL) ,checkboxInput(ns("chkShowInd"), label=LBL.SHOW_IND, value = TRUE) ,wellPanel(radioButtons(ns("rdoProcess"), label="Mode",selected = MODE_AUTOMATIC ,choices = list( "Automatic" = MODE_AUTOMATIC ,"Inquiry" = MODE_INQUIRY ,"Manual" = MODE_MANUAL))) ) ) panelMain = box( width=NULL ,title = p("Config",actionButton( ns("SBLOpen"), "",icon = icon("angle-left"), class = "btn-xs") ,actionButton( ns("SBROpen"), "",icon = icon("angle-right"), class = "btn-sm")) ,solidHeader = T ,status = "primary" ,fluidRow(plotlyOutput(ns("plotLong"), width="100%",height="500px")) ,fluidRow( box(width=2,id="box0",title="caja 0", status="primary",checkboxGroupInput(ns("chkInds0"), label = NULL)) ,box(width=2,id="box1",title="caja 1", status="primary",checkboxGroupInput(ns("chkInds1"), label = NULL)) ,box(width=2,id="box2",title="caja 2", status="primary",checkboxGroupInput(ns("chkInds2"), label = NULL)) ,box(width=2,id="box3",title="caja 3", status="primary",checkboxGroupInput(ns("chkInds3"), label = NULL)) ,box(width=2,id="box4",title="caja 4", status="primary",checkboxGroupInput(ns("chkInds4"), label = NULL)) ,box(width=2,id="box5",title="caja 5", status="primary",checkboxGroupInput(ns("chkInds5"), label = NULL)) ) ) tagList(fluidRow( hidden(column(id=ns("pnlLeft"), panelLeft, width=2)) ,column(id=ns("pnlMain"), panelMain, width=12) ,hidden(column(id=ns("pnlRight"), panelRight, width=2)) )) }<file_sep>/YATAClient/YATAClient/src/main/java/com/jgg/yata/client/providers/BittexProvider.java package com.jgg.yata.client.providers; import java.sql.Timestamp; import java.util.*; import com.google.gson.*; import com.jgg.endpoint.http.HTTPSClient; import com.jgg.yata.client.pojos.Market; import com.jgg.yata.client.pojos.Ticker; public class BittexProvider implements Provider { //private final String WSSBase = "wss://api2.poloniex.com"; private final String HTTPBase = "https://bittrex.com/api/v1.1/public/"; private final String TICKERS = "command=returnTicker"; private final String MARKETS = "getmarketsummaries"; public Map<String, Ticker> getTickers() throws Exception { HTTPSClient client = new HTTPSClient(); String resp = client.getHttps(HTTPBase, MARKETS); return null; //return (mountMarkets(resp)); } public Map<String, Market> getMarkets() throws Exception { HTTPSClient client = new HTTPSClient(); String resp = client.getRest(HTTPBase, MARKETS); return (mountMarkets(resp)); } private Map<String, Market> mountMarkets(String resp) { Map<String, Market> map = new HashMap<String, Market>(); Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(resp).getAsJsonObject(); JsonArray arr = obj.get("result").getAsJsonArray(); for(int i = 0; i < arr.size(); i++) { BittrexMarket bMkt = gson.fromJson(arr.get(i), BittrexMarket.class); Market mkt = mountMarket(bMkt); map.put(mkt.getKey(),mkt); } return map; } private Market mountMarket(BittrexMarket bMkt) { Market mkt = new Market(); String names[] = bMkt.getMarketName().split("-"); mkt.setFrom(names[0]); mkt.setTo(names[1]); mkt.setOpen (1 / bMkt.getPrevDay()); mkt.setHigh (1 / bMkt.getHigh()); mkt.setLow (1 / bMkt.getLow()); mkt.setClose(1 / bMkt.getLast()); mkt.setBid (1 / bMkt.getBid()); mkt.setAsk (1 / bMkt.getAsk()); mkt.setVolume(bMkt.getBaseVolume()); mkt.setBidOrders(bMkt.getOpenBuyOrders()); mkt.setAskOrders(bMkt.getOpenSellOrders()); mkt.setDt(Timestamp.valueOf(bMkt.getTimeStamp().replace('T', ' ')).getTime()); return (mkt); } } <file_sep>/YATACore/R/layouts/LAY_Models.R #' Layout of Models Database #' # Groups GRP.TABLE = "Groups" GRP.ID = "IdGroup" GRP.ACTIVE = "Active" GRP_NAME = "Name" MOD.TABLE = "Models" MOD.ID = "IdModel" MOD.SYMBOL = "Model" MOD.GROUP = "Group" MOC.ACTIVE = "Active" MOD.SOURCE = "Source" MOD.DESC = "Description" <file_sep>/YATAModels/R/IND_Spline.R library(R6) IND_Spline <- R6Class("IND_Spline", inherit=YATAIndicator, public = list( name="Linear trend" ,symbolBase="MA" ,symbol="MA" #' @description Calculate the best spline line for the data #' @param data Values to spline #' @param ind Not used #' @param columns Not used ,Spline = function(data=NULL, ind=NULL, columns=NULL) { res1 = supsmu(data$df[,data$ORDER], data$df[,data$PRICE]) res2 = supsmu(data$df[,data$ORDER], data$df[,data$VOLUME]) list(list(res1[["y"]]), list(res2[["y"]])) } ,initialize = function(parms=NULL,thres=NULL) { super$initialize(parms,thres) } ) ,private = list( ) ) <file_sep>/YATACore/R/PKG_Plots.R plotLineTypes = c("solid", "dot", "dash", "longdash", "dashdot", "longdashdot") plotToolbar = function(p) { p %>% config(displaylogo = FALSE, collaborate = FALSE # ,modeBarButtonsToRemove = c( # 'sendDataToCloud' # ,'autoScale2d' # ,'resetScale2d' # ,'toggleSpikelines' # ,'hoverClosestCartesian' # ,'hoverCompareCartesian' # ,'zoom2d' # ,'pan2d' # ,'select2d' # ,'lasso2d' # ,'zoomIn2d' # ,'zoomOut2d' # ) ) } .hoverlbl = function(title, x, y) { paste('<b>', title, '</b><br>' , 'Date: ', as.Date(x, format="%d/%m/%Y") , '<br>Value: ', round(y, digits=0)) } #' @export plotBase = function(plot, type, x, y=NULL, title=NULL, attr=NULL, ...) { if (is.null(y) || is.na(y)) return (NULL) PLOT = FACT_PLOT$new() if (type == PLOT$LOG) return (plotLog (plot, x, y, ...)) if (type == PLOT$BAR) return (plotBar (plot, x, y, ...)) if (type == PLOT$CANDLE) { p = list(...) return (plotCandle(plot, x, p$open, p$close, p$high, p$low, ...)) } #if (type == PLOT$LINE) return ( plotLine(plot, x, y, title, attr, ...) } #' @export plotLine = function(plot, x, y, title=NULL, attr=NULL, ...) { name = title l=list(width=0.75, dash="solid") if (!is.null(attr)) l = attr add_trace(plot, x=x, y=y, type = "scatter", mode = "lines" , line=l , name = title , hoverinfo = 'text' , text = ~.hoverlbl(title, x, y) ) } #' @export plotMarker = function(plot, x, y, hover=c(""), line=NULL, ...) { title = hover[1] if (length(hover) > 1) title = paste0(title, " (", hover[2], ")") p = add_trace(plot, x=x, y=y, type = "scatter", mode = "lines+markers" , line=list(width=0.75, dash=lType) , name = title , hoverinfo = 'text' , text = ~.hoverlbl(title, x, y) ) p } #' @export plotLines = function(plot, x, data, hoverText) { cols = ncol(data) if (cols > 2) lTypes = c(plotLineTypes[2], plotLineTypes[3], plotLineTypes[2]) if (cols > 4) lTypes = c(plotLineTypes[4], lTypes, plotLineTypes[4]) for (i in 1:cols) { title = hoverText[1] if (length(hoverText) > 1) title = paste0(hoverText[1], " (", hoverText[i+1], ")") plot = plotLine(plot, x, as.vector(data[,i]), cols[((i-1) %% cols) + 1], hoverText = title) } plot } #' @export plotBar = function(plot, x, y, ...) { colors = c('rgba(0,0,255,1)', 'rgba(0,255,0,1)', 'rgba(255,0,0,1)') FUN=function(x) { if (length(x) != 2) return (1) if (is.na(x[1]) || is.na(x[2])) return (1) if (x[1] == x[2]) return (1) if (x[2] == 0) return (1) vv = x[1]/x[2]; if ( vv > 1.03) rr = 3 else { if (vv < .97) rr = 2 else rr = 1 } rr } cc = rollapply(y, 2, FUN, fill=0, align="right") add_trace(plot, x=x, y=y, type='bar', orientation='v' , marker=list(color=colors[cc]) # , hoverinfo = 'text' # , name = hoverText # , text = ~.hoverlbl(hoverText, x, y) ) } #' @export plotCandle = function(plot, x, open, close, high, low, ...) { p = list(...) title = p$hover[1] if (length(p$hover) > 1) title = paste0(title, " (", p$hover[2], ")") add_trace(plot, type = "candlestick" , x=x, open=open, close=close, high=high, low=low , line=list(width=0.75) ,alist(attrs) , name = title , hoverinfo = 'text' , text = ~.hoverlbl(title, x, close) ) %>% layout(xaxis = list(rangeslider = list(visible = F))) } #' @export plotLog = function(plot, x, y, lType="solid", hoverText) { title = hoverText[1] if (length(hoverText) > 1) title = paste0(title, " (", hoverText[2], ")") plot = add_trace(plot, x=x, y=y, type = "scatter", mode = "lines" , line=list(width=0.75, dash=lType) , name = title , hoverinfo = 'text' , text = ~.hoverlbl(title, x, y) ) plotly::layout(plot, yaxis = list(type = "log")) } #' @export plotLogs = function(plot, x, data, hoverText) { cols = ncol(data) if (cols > 2) lTypes = c(plotLineTypes[2], plotLineTypes[3], plotLineTypes[2]) if (cols > 4) lTypes = c(plotLineTypes[4], lTypes, plotLineTypes[4]) for (i in 1:cols) { title = hoverText[1] if (length(hoverText) > 1) title = paste0(hoverText[1], " (", hoverText[i+1], ")") plot = plotLog(plot, x, as.vector(data[,i]), cols[((i-1) %% cols) + 1], hoverText = title) } plot } # Tipo de lineas # Sets the dash style of lines. # Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") # or a dash length list in px (eg "5px,10px,2px,2px"). # plotLine = function(data, indicator, plots) { # for (iList in 1:length(indicator$result)) { # ind = indicator$result[[iList]] # for (idx in 1:length(ind)) { # cName = indicator$columns[[idx]] # df = .plotMakeDF(data, ind[[idx]], cName) # plots[[iList]] = add_trace(plots[[iList]],x=df[,1],y=df[,2],name=cName,type="scatter",mode="lines") # } # } # plots # } plotSegment = function(data, indicator, plots) { res = indicator$result[[1]] inter = res$coefficients[1] slope = res$coefficients[2] plots[[1]] = add_segments(plots[[1]], x = data$df[1,"Date"], xend = data$df[nrow(data$df),"Date"] , y = inter, yend = inter + (nrow(data$df) * slope)) plots } plotTrend = function(data, indicator, plots) { # ticks = data$tickers # df = ticks$getData() # res = indicator$result # inter = res$coefficients[1] # slope = res$coefficients[2] # # x=c(df[1,ticks$DATE], df[nrow(df),ticks$DATE]) # y = c(inter, nrow(df) * slope) # plots[[1]] = add_trace(plots[[1]], x=x, y=y, mode="lines") plots } plotOverlay = function(data, indicator, plots) { styles = list( list(width = 1, dash = 'solid') ,list(width = 0.6, dash = 'dash' ) ,list(width = 0.3, dash = 'dot' )) for (idx in 1:length(indicator$result)) { groups = round(length(indicator$columns)) df = cbind(data$df[,data$DATE],indicator$result[[idx]]) colnames(df) = c(data$DATE, indicator$columns) nCol = 1 for (col in indicator$columns) { plots[[idx]] = add_trace(plots[[idx]], x=df[,data$DATE], y=df[,col], name=col ,type="scatter", mode="lines", line=styles[[(nCol %% groups)+1]]) nCol = nCol + 1 } } plots } plotOverlay2 = function(data, indicator, plots) { styles = list( list(width = 1, dash = 'solid') ,list(width = 0.6, dash = 'dash' ) ,list(width = 0.3, dash = 'dot' )) for (idx in 1:length(indicator$result)) { groups = round(length(indicator$columns)) df = cbind(data$df[,data$DATE],indicator$result[[idx]]) colnames(df) = c(data$DATE, indicator$columns) nCol = 1 for (col in indicator$columns) { plots[[idx]] = add_trace(plots[[idx]], x=df[,data$DATE], y=df[,col], name=col ,type="scatter", mode="lines", line=styles[[(nCol %% groups)+1]]) nCol = nCol + 1 } } plots } plotMaxMin = function(data, indicator, plots) { dfr = as.data.frame(indicator$result) dfb = data$df col = parse(text=paste0("dfb$",data$PRICE)) names(dfr) = "MaxMin" max = dfr %>% group_by(MaxMin) %>% summarise(veces=n()) %>% arrange(desc(MaxMin)) %>% head(n=3) dfM = dfb[eval(col) %in% c(max$MaxMin),] plots[[1]] = add_trace(plots[[1]], data=dfM, x=~Date, y=~Price, mode="markers", marker=list(color="green")) min = dfr %>% group_by(MaxMin) %>% summarise(veces=n()) %>% arrange(desc(MaxMin)) %>% head(n=3) min$MaxMin = min$MaxMin * -1 dfm = dfb[eval(col) %in% c(min$MaxMin),] plots[[1]] = add_trace(plots[[1]], data=dfm, x=~Date, y=~Price, mode="markers", marker=list(color="red")) plots } .plotMakeDF = function(data, ind, colName) { df = as.data.frame(data$df[,data$DATE]) df = cbind(df, ind) colnames(df) = c(data$DATE, colName) df } .plotAttr = function(...) { p = eval(substitute(alist(...))) eval(p$title, env=parent.env(parent.frame())) p = list(...) res = list() if (!is.null(p$hover)) { title = p$hover[1] if (length(p$hover) > 1) title = paste0(title, " (", p$hover[2], ")") res = list.append(res, name=title) res = list.append(res, hoverinfo = 'text') res = list.append(res, text = quote(~.hoverlbl(title, x, y))) } if (!is.null(p$title)) res = list.append(res, name=p$title) res } <file_sep>/YATAWeb/ui/modTestServer.R modTest <- function(input, output, session, parent) { }<file_sep>/YATACore/R/R6_YATAProvider.R YATAProvider <- R6Class("YATAProvider", public = list( name = NULL ,prefix = NULL ,initialize = function(provider) { self$name = provider self$prefix = "POL" } ) ) <file_sep>/YATAConfig/SQL/ctc_dat_pairs.sql USE CTC; DELETE FROM CURRENCIES_CLEARING; INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BCN" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BTS" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BURST" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "CLAM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "DGB" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "DOGE" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "DASH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "GAME" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "HUC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "LTC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "OMNI" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "NAV" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "NMC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "NXT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "PPC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "STR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "SYS" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "VIA" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "VTC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "XCP" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "XMR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "XPM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "XRP" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "XEM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "ETH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "SC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "FCT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "DCR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "LSK" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "LBC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "STEEM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "SBD" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "ETC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "REP" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "ARDR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "ZEC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "STRAT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "PASC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "GNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BCH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "ZRX" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "CVC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "OMG" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "GAS" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "STORJ" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "EOS" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "SNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "KNC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BAT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "LOOM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "QTUM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "MANA" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "FOAM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BCHABC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "BCHSV" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "NMR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "POLY" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "BTC" , "LPT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "BTC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "DOGE" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "DASH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "LTC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "NXT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "STR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "XMR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "XRP" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "ETH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "SC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "LSK" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "ETC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "REP" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "ZEC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "GNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "BCH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "ZRX" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "EOS" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "SNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "KNC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "BAT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "LOOM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "QTUM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "BNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDT" , "MANA" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "XMR" , "BCN" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "XMR" , "DASH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "XMR" , "LTC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "XMR" , "NXT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "XMR" , "ZEC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "LSK" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "STEEM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "ETC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "REP" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "ZEC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "GNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "BCH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "ZRX" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "CVC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "OMG" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "GAS" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "EOS" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "SNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "KNC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "BAT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "LOOM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "QTUM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "BNT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "ETH" , "MANA" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "BTC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "DOGE" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "LTC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "STR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "USDT" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "XMR" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "XRP" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "ETH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "ZEC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "BCH" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "FOAM" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "BCHABC" ); INSERT INTO CURRENCIES_CLEARING (CLEARING, BASE, COUNTER) VALUES ( "POL", "USDC" , "BCHSV" ); UPDATE CURRENCIES_CLEARING SET LAST_UPD = TIMESTAMP(0); COMMIT; <file_sep>/YATACore/R/R6_YATAVars.R # Mantiene las variables globales de YATACode # Debe ir en PKG_Main # YATAVARS <- R6::R6Class("YATAVARS" # ,public = list( # SQLConn = list() # ,lastErr = NULL # ,tmpConn = NULL # ,addConn = function (SQLConn) { # self$SQLConn = c(SQLConn, self$SQLConn) # } # ,removeConn = function() { # tmp = NULL # if (length(self$SQLConn) > 0) { # tmp = self$SQLConn[1] # self$SQLConn = self$SQLConn[-1] # } # tmp # } # ) # # ) <file_sep>/YATACore/R/TBL_SessionOld.R TBLSessionOld = R6::R6Class("TBLSessionOld", inherit=YATATable, public = list( symbol = NULL ,DATE = "Date" ,OPEN = "Open" ,HIGH = "High" ,LOW = "Low" ,CLOSE = "Close" ,VOLUME = "Volume" ,PRICE = "Price" ,VALUE = "Close" ,CHANGE = "Change" ,fiat = NULL ,refresh = function() { if (is.null(self$dfa)) { self$dfa = loadSessions(self$symbol, self$table, self$fiat) self$dfa$Change = rollapplyr(self$dfa[,self$VALUE], 2, FUN = calculateChange, fill = 0) self$dfa = private$adjustTypes(self$dfa) } self$df = self$dfa if (nrow(self$df) > 0) self$df[,self$PRICE] = self$df[,self$VALUE] invisible(self) } ,reverse = function() { tmp = self$df[seq(dim(self$df)[1],1),] private$adjustTypes(tmp) } ,getRange = function(rng=0) { beg = self$dfa[1,self$DATE] start = beg last = self$dfa[nrow(self$dfa), self$DATE] current = Sys.Date() year(start) = year(current) month(start) = 1 if (month(current) < 6) {year(start) = year(start) - 1 ; month(start) = 6} if (start <= beg) start = beg # if (rng > 0 && nrow(self$dfa) > rng) { # start = as.Date(self$dfa[nrow(self$dfa) - rng, self$DATE]) # } c(beg, last, start) } ,filterByDate = function(from, to) { private$makeDF(self$dfa %>% filter(Date >= from, Date <= to)) } ,filterByRows = function(from, to=0) { if (to == 0) to = nrow(self$dfa) if (from < 0) from = to + from + 1 if (from <= 0) from = 1 private$makeDF(self$dfa[from:to,]) } ,getTrend = function() { lm(self$df[,self$PRICE] ~ c(1:nrow(self$df)))$coefficients[2] } ,getTrendAngle = function() { atan(self$getTrend() * nrow(self$df)) * 180 / pi } ,getData = function() { self$df } ,getBaseData = function() { self$df[,self$DATE, self$PRICE] } ,getCurrentData = function(regs) { tmp = self$clone() tmp$filterByRows(1,regs) tmp } ,getCurrentTicker = function(reg) { self$df[reg,] } ,print = function() { print(self$name) } ,initialize = function(symbol, tbName, fiat, source = NULL) { if (is.null(source)) { self$name = tbName self$symbol = symbol self$table = tbName self$fiat = fiat super$initialize(refresh=FALSE); self$refresh() } else { self$name = source$name self$symbol = source$symbol self$table = source$table self$fiat = source$fiat self$df = source$df private$calculateVariation() } } ) ,private = list( makeDF = function(dfa) { self$df = dfa self$df = private$adjustTypes(self$df) self$df[,self$PRICE] = dfa[,self$VALUE] self$df } ,adjustTypes = function(df) { df[,self$DATE] = as.dated(df[,self$DATE]) df[,self$OPEN] = as.fiat(df[,self$OPEN]) df[,self$CLOSE] = as.fiat(df[,self$CLOSE]) df[,self$HIGH] = as.fiat(df[,self$HIGH]) df[,self$LOW] = as.fiat(df[,self$LOW]) df[,self$VOLUME] = as.long(df[,self$VOLUME]) df } ,calculateVariation = function() { for (col in colnames(self$df)) { if ("numeric" %in% class(self$df[,col])) { self$df[,col] = rollapplyr(self$df[,col], 2, calculateChange, fill = 0) self$df[,col] = as.percentage(self$df[,col]) } } } ) ) <file_sep>/YATACore/R/PKG_Types.R percentage <- function(value) { result <- value class(result) <- c("percentage", class(value)) result } print.percentage <- function(x, ...) { x <- unclass(x) attributes(x) <- NULL NextMethod() } `+.percentage` <- function(x, y) { NextMethod() } `-.percentage` <- function(x, y) { NextMethod() } `/.percentage` <- function(x, y) { NextMethod() } `*.percentage` <- function(x, y) { NextMethod() } `^.percentage` <- function(x, y) { NextMethod() } as.percentage <- function(x) { percentage(x) } fiat <- function(value) { result <- value class(result) <- c("fiat", class(value)) result } print.fiat <- function(x, ...) { x <- unclass(x) attributes(x) <- NULL NextMethod() } `+.fiat` <- function(x, y) { NextMethod() } `-.fiat` <- function(x, y) { NextMethod() } `/.fiat` <- function(x, y) { NextMethod() } `*.fiat` <- function(x, y) { NextMethod() } `^.fiat` <- function(x, y) { NextMethod() } as.fiat <- function(x) { fiat(x) } ctc <- function(value) { result <- value class(result) <- c("ctc", class(value)) result } print.ctc <- function(x, ...) { x <- unclass(x) attributes(x) <- NULL sprintf("%.06f", x) } `+.ctc` <- function(x, y) { NextMethod() } `-.ctc` <- function(x, y) { NextMethod() } `/.ctc` <- function(x, y) { NextMethod() } `*.ctc` <- function(x, y) { NextMethod() } `^.ctc` <- function(x, y) { NextMethod() } as.ctc <- function(x) { ctc(x) } long <- function(value) { result <- value class(result) <- c("long", class(value)) result } print.long <- function(x, ...) { x <- unclass(x) attributes(x) <- NULL NextMethod() } `+.long` <- function(x, y) { NextMethod() } `-.long` <- function(x, y) { NextMethod() } `/.long` <- function(x, y) { NextMethod() } `*.long` <- function(x, y) { NextMethod() } `^.long` <- function(x, y) { NextMethod() } as.long <- function(x) { long(x) } number <- function(value) { result <- value class(result) <- c("number", class(value)) result } print.number <- function(x, ...) { x <- unclass(x) attributes(x) <- NULL NextMethod() } `+.number` <- function(x, y) { NextMethod() } `-.number` <- function(x, y) { NextMethod() } `/.number` <- function(x, y) { NextMethod() } `*.number` <- function(x, y) { NextMethod() } `^.number` <- function(x, y) { NextMethod() } as.number <- function(x) { number(x) } dated <- function(value) { result <- value class(result) <- c("dated", class(value)) result } print.dated <- function(x, ...) { x <- unclass(x) attributes(x) <- NULL NextMethod() } as.dated <- function(x) { dated(x) } datet <- function(value) { result <- value class(result) <- c("datet", class(value)) result } print.datet <- function(x, ...) { x <- unclass(x) attributes(x) <- NULL NextMethod() } as.datet <- function(x) { datet(x) } <file_sep>/YATACore/R/R6_YATAConfig.R YATAConfig <- R6Class("YATAConfig", public = list( symbol = NULL ,currency = "EUR" ,initial = 0.0 ,from = NULL ,to = NULL ,dec = 2 ,delay = 0 # retraso en decimas de segundo para dibujar ,mode = MODE_AUTOMATIC # Modo de simulacion ,summFileName = NULL ,summFileData=NULL ) ) <file_sep>/YATAModels/R/IND_EMA.R IND_EMA <- R6Class("IND_EMA", inherit=IND_MA, public = list( name="Media movil Exponencial" ,symbol="EMA" ,initialize = function() { super$initialize() } ,getDescription = function() { private$makeMD() } ,calculate = function(TTickers, date) { window = self$getParameter("window") xt = private$getXTS(TTickers, pref=window) if (nrow(xt) < window) return (NULL) EMA = TTR::EMA(xt[,TTickers$PRICE], n=window, wilder=FALSE) private$data = as.data.frame(EMA[(window + 1):nrow(EMA),]) private$calcVariation("EMA") private$setColNames() } ,plot = function(p, TTickers) { if (nrow(private$data) == 0) return(p) col1 = private$setColNames(self$symbol) YATACore::plotLine(p, TTickers$df[,self$xAxis], private$data[,col1],hoverText=self$symbol) } ) ,private = list( makeMD = function() { lines = c( "Media móvil ponderada exponencialmente" ,"$$\\sum_{i=1}^n X_i$$" ) data = "" for (line in lines) { data = paste(data, line, sep="\n") } data } ) ) <file_sep>/YATAWeb/widgets/YATAPage.R YATAPage <- function(title, ..., id = NULL, selected = NULL, header = NULL, footer = NULL, leftSide = c("menu-right", "menu-left"), rightSide = c("menu-left", "menu-right"), fluid = TRUE, theme = NULL, windowTitle = title #,tabs = NULL ) { #addDependencies() # alias title so we can avoid conflicts w/ title in withTags pageTitle <- title # navbar class based on options # navbarClass <- "navbar navbar-expand-lg fixed-top navbar-dark bg-primary" navbarClass <- "navbar-main" if (!is.null(id)) selected <- restoreInput(id = id, default = selected) #JGG list(...) coge todo lo que no esta nombrado: shijs, tags$, etc # build the tabset tabs <- list(...) tabset <- buildTabset(tabs, "nav navbar-nav", NULL, id, selected) # function to return plain or fluid class name className <- function(name) { if (fluid) paste(name, "-fluid", sep="") else name } # Limpiar lis = tabset[[1]][[3]][[1]] lin = lis[grepl("data-value", lis)] tabset[[1]][[3]][[1]] = lin containerDiv <- div(class=className("container"), div(class="navbar-header" ,span(class="navbar-brand", pageTitle) ,span(hidden(textInput("nsPreffix", label = NULL, value = ""))) ) ) # Limpiar navlist tabs = tabset$navList # mask = grepl("data-value", tabs[[3]][[1]]) # tabs = tabs[[3]][[1]][mask] ls = alist(leftSide) rs = alist(rightSide) navbarResponsive = div(id="navbarResponsive", display="flex") if (!is.null(leftSide)) navbarResponsive = tagAppendChild(navbarResponsive, YATAIconNav(TRUE, leftSide)) navbarResponsive = tagAppendChild(navbarResponsive, div(tabs)) #div(tabset$navList)) if (!is.null(rightSide)) navbarResponsive = tagAppendChild(navbarResponsive, YATAIconNav(FALSE,rightSide)) containerDiv = tagAppendChild(containerDiv, navbarResponsive) mainDiv = div(id="YATAMainSide") # , class="col-sm-12") leftDiv = div(id="YATALeftSide", style="background-color:powderblue;") rightDiv = div(id="YATARightSide", style="background-color:red;") mainDiv <- tagAppendChild(mainDiv, tabset$content) # build the main tab content div contentDiv <- div(id="main-container", class=className("main-container")) if (!is.null(header)) contentDiv <- tagAppendChild(contentDiv, div(class="row", header)) contentDiv <- tagAppendChild(contentDiv, hidden(leftDiv)) contentDiv <- tagAppendChild(contentDiv, mainDiv) contentDiv <- tagAppendChild(contentDiv, hidden(rightDiv)) if (!is.null(footer)) contentDiv <- tagAppendChild(contentDiv, div(class="row", footer)) # build the page YATABootstrapPage( title = windowTitle, theme = theme, tags$nav(class=navbarClass, role="navigation", containerDiv), contentDiv ) } # Helpers to build tabsetPanels (& Co.) and their elements markTabAsSelected <- function(x) { attr(x, "selected") <- TRUE x } isTabSelected <- function(x) { isTRUE(attr(x, "selected", exact = TRUE)) } containsSelectedTab <- function(tabs) { any(vapply(tabs, isTabSelected, logical(1))) } findAndMarkSelectedTab <- function(tabs, selected, foundSelected) { tabs <- lapply(tabs, function(div) { if (foundSelected || is.character(div)) { # Strings are not selectable items } else if (inherits(div, "shiny.navbarmenu")) { # Recur for navbarMenus res <- findAndMarkSelectedTab(div$tabs, selected, foundSelected) div$tabs <- res$tabs foundSelected <<- res$foundSelected } else { # Base case: regular tab item. If the `selected` argument is # provided, check for a match in the existing tabs; else, # mark first available item as selected if (is.null(selected)) { foundSelected <<- TRUE div <- markTabAsSelected(div) } else { tabValue <- div$attribs$`data-value` %OR% div$attribs$title if (identical(selected, tabValue)) { foundSelected <<- TRUE div <- markTabAsSelected(div) } } } return(div) }) return(list(tabs = tabs, foundSelected = foundSelected)) } # Returns the icon object (or NULL if none), provided either a # tabPanel, OR the icon class getIcon <- function(tab = NULL, iconClass = NULL) { if (!is.null(tab)) iconClass <- tab$attribs$`data-icon-class` if (!is.null(iconClass)) { if (grepl("fa-", iconClass, fixed = TRUE)) { # for font-awesome we specify fixed-width iconClass <- paste(iconClass, "fa-fw") } icon(name = NULL, class = iconClass) } else NULL } # Text filter for navbarMenu's (plain text) separators navbarMenuTextFilter <- function(text) { if (grepl("^\\-+$", text)) tags$li(class = "divider") else tags$li(class = "dropdown-header", text) } # This function is called internally by navbarPage, tabsetPanel # and navlistPanel buildTabset <- function(tabs, ulClass, textFilter = NULL, id = NULL, selected = NULL, foundSelected = FALSE) { res <- findAndMarkSelectedTab(tabs, selected, foundSelected) tabs <- res$tabs #JGG No se por que, pero incluye un tag vacio al principio #tabs[[1]] = NULL foundSelected <- res$foundSelected # add input class if we have an id if (!is.null(id)) ulClass <- paste(ulClass, "shiny-tab-input") if (anyNamed(tabs)) { nms <- names(tabs) nms <- nms[nzchar(nms)] stop("Tabs should all be unnamed arguments, but some are named: ", paste(nms, collapse = ", ")) } tabsetId <- p_randomInt(1000, 10000) tabs <- lapply(seq_len(length(tabs)), buildTabItem, tabsetId = tabsetId, foundSelected = foundSelected, tabs = tabs, textFilter = textFilter) tabNavList <- tags$ul(class = ulClass, id = id, `data-tabsetid` = tabsetId, lapply(tabs, "[[", 1)) tabContent <- tags$div(class = "tab-content", `data-tabsetid` = tabsetId, lapply(tabs, "[[", 2)) list(navList = tabNavList, content = tabContent) } # Builds tabPanel/navbarMenu items (this function used to be # declared inside the buildTabset() function and it's been # refactored for clarity and reusability). Called internally # by buildTabset. buildTabItem <- function(index, tabsetId, foundSelected, tabs = NULL, divTag = NULL, textFilter = NULL) { divTag <- if (!is.null(divTag)) divTag else tabs[[index]] if (is.character(divTag) && !is.null(textFilter)) { # text item: pass it to the textFilter if it exists liTag <- textFilter(divTag) divTag <- NULL } else if (inherits(divTag, "shiny.navbarmenu")) { # navbarMenu item: build the child tabset tabset <- buildTabset(divTag$tabs, "dropdown-menu", navbarMenuTextFilter, foundSelected = foundSelected) # if this navbarMenu contains a selected item, mark it active containsSelected <- containsSelectedTab(divTag$tabs) liTag <- tags$li( class = paste0("dropdown", if (containsSelected) " active"), tags$a(href = "#", class = "dropdown-toggle", `data-toggle` = "dropdown", `data-value` = divTag$menuName, getIcon(iconClass = divTag$iconClass), divTag$title, tags$b(class = "caret") ), tabset$navList # inner tabPanels items ) # list of tab content divs from the child tabset divTag <- tabset$content$children } else { # tabPanel item: create the tab's liTag and divTag tabId <- paste("tab", tabsetId, index, sep = "-") liTag <- tags$li( tags$a( href = paste("#", tabId, sep = ""), `data-toggle` = "tab", `data-value` = divTag$attribs$`data-value`, getIcon(iconClass = divTag$attribs$`data-icon-class`), divTag$attribs$title ) ) # if this tabPanel is selected item, mark it active if (isTabSelected(divTag)) { liTag$attribs$class <- "active" divTag$attribs$class <- "tab-pane active" } divTag$attribs$id <- tabId divTag$attribs$title <- NULL } return(list(liTag = liTag, divTag = divTag)) } #JGG #' @include shinyUtils.R #JGG NULL #JGG #JGG #' Create a Bootstrap page #JGG #' #JGG #' Create a Shiny UI page that loads the CSS and JavaScript for #JGG #' \href{http://getbootstrap.com/}{Bootstrap}, and has no content in the page #JGG #' body (other than what you provide). #JGG #' #JGG #' This function is primarily intended for users who are proficient in HTML/CSS, #JGG #' and know how to lay out pages in Bootstrap. Most applications should use #JGG #' \code{\link{fluidPage}} along with layout functions like #JGG #' \code{\link{fluidRow}} and \code{\link{sidebarLayout}}. #JGG #' #JGG #' @param ... The contents of the document body. #JGG #' @param title The browser window title (defaults to the host URL of the page) #JGG #' @param responsive This option is deprecated; it is no longer optional with #JGG #' Bootstrap 3. #JGG #' @param theme Alternative Bootstrap stylesheet (normally a css file within the #JGG #' www directory, e.g. \code{www/bootstrap.css}) #JGG #' #JGG #' @return A UI defintion that can be passed to the \link{shinyUI} function. #JGG #' #JGG #' @note The \code{basicPage} function is deprecated, you should use the #JGG #' \code{\link{fluidPage}} function instead. #JGG #' #JGG #' @seealso \code{\link{fluidPage}}, \code{\link{fixedPage}} #JGG #' @export YATABootstrapPage <- function(..., title = NULL, theme = NULL) { bootstrapLib <- function(theme = NULL) { htmlDependency("bootstrap", "3.3.7", c( href = "shared/bootstrap", file = system.file("www/shared/bootstrap", package = "shiny") ), script = c( "js/bootstrap.min.js", # These shims are necessary for IE 8 compatibility "shim/html5shiv.min.js", "shim/respond.min.js" ), stylesheet = if (is.null(theme)) "css/bootstrap.min.css", meta = list(viewport = "width=device-width, initial-scale=1") ) } YATALibs <- function(theme = NULL) { bootstrapLib(theme) # deps = list() # deps = list.append(deps, bootstrapLib(theme)) # browser() # for (dirname in list.files("www")) { # #dirName = paste("www", dirs, sep="/") # files = list.files(paste0("www/",dirname), recursive=TRUE) # lcss = files[grepl(".css$", files)] # ljs = files[grepl(".js$", files)] # hDep = htmlDependency(dirname, "1.0", src=dirname, stylesheet = lcss, script=ljs) # deps = list.append(deps, hDep) # # for (css in files[grepl(".css$", files)]) { # # tags$head(tags$link(rel = "stylesheet", type = "text/css", href=paste(dirs, css, sep="/"))) # # # htmlDependency(dirs, "1.0", src=dirName, stylesheet = css) # # } # # for (js in files[grepl(".js$", files)]) { # # htmlDependency(dirs, "1.0", src=dirName, script = css) # # } # # } # deps } attachDependencies( tagList( if (!is.null(title)) tags$head(tags$title(title)), if (!is.null(theme)) { tags$head(tags$link(rel="stylesheet", type="text/css", href = theme)) } ,htmlDependency( "font-awesome", "5.3.1" , "www/shared/fontawesome" , package = "shiny" , stylesheet = c("css/all.min.css", "css/v4-shims.min.css")) ,htmlDependency("YATA", "1.0", src="www/yata", script="yata.js", stylesheet="yata.css") ,htmlDependency( "dashboardplus", "1.0" , src="www/dashboardplus" , script="dashboardplus.js" , stylesheet=c("_all-skins.css", "AdminLTE.css")) # ,htmlDependency("materialdesign", "1.0", src="www/materialdesign", script=c("init.js", "material.min.js", "ripples.min.js") # , stylesheet=c("all-md-skins.min.css", "bootstrap-material-design.min.css", "MaterialAdminLTE.min.css", "ripples.min.css")) # remainder of tags passed to the function ,list(...) ) ,YATALibs() ) } #JGG #JGG #' Bootstrap libraries #JGG #' #JGG #' This function returns a set of web dependencies necessary for using Bootstrap #JGG #' components in a web page. #JGG #' #JGG #' It isn't necessary to call this function if you use #JGG #' \code{\link{bootstrapPage}} or others which use \code{bootstrapPage}, such #JGG #' \code{\link{basicPage}}, \code{\link{fluidPage}}, \code{\link{fillPage}}, #JGG #' \code{\link{pageWithSidebar}}, and \code{\link{navbarPage}}, because they #JGG #' already include the Bootstrap web dependencies. #JGG #' #JGG #' @inheritParams bootstrapPage #JGG #' @export #JGG bootstrapLib <- function(theme = NULL) { #JGG htmlDependency("bootstrap", "3.3.7", #JGG c( #JGG href = "shared/bootstrap", #JGG file = system.file("www/shared/bootstrap", package = "shiny") #JGG ), #JGG script = c( #JGG "js/bootstrap.min.js", #JGG # These shims are necessary for IE 8 compatibility #JGG "shim/html5shiv.min.js", #JGG "shim/respond.min.js" #JGG ), #JGG stylesheet = if (is.null(theme)) "css/bootstrap.min.css", #JGG meta = list(viewport = "width=device-width, initial-scale=1") #JGG ) #JGG } #JGG #JGG #' @rdname bootstrapPage #JGG #' @export #JGG basicPage <- function(...) { #JGG bootstrapPage(div(class="container-fluid", list(...))) #JGG } #JGG #JGG #JGG #' Create a page that fills the window #JGG #' #JGG #' \code{fillPage} creates a page whose height and width always fill the #JGG #' available area of the browser window. #JGG #' #JGG #' The \code{\link{fluidPage}} and \code{\link{fixedPage}} functions are used #JGG #' for creating web pages that are laid out from the top down, leaving #JGG #' whitespace at the bottom if the page content's height is smaller than the #JGG #' browser window, and scrolling if the content is larger than the window. #JGG #' #JGG #' \code{fillPage} is designed to latch the document body's size to the size of #JGG #' the window. This makes it possible to fill it with content that also scales #JGG #' to the size of the window. #JGG #' #JGG #' For example, \code{fluidPage(plotOutput("plot", height = "100\%"))} will not #JGG #' work as expected; the plot element's effective height will be \code{0}, #JGG #' because the plot's containing elements (\code{<div>} and \code{<body>}) have #JGG #' \emph{automatic} height; that is, they determine their own height based on #JGG #' the height of their contained elements. However, #JGG #' \code{fillPage(plotOutput("plot", height = "100\%"))} will work because #JGG #' \code{fillPage} fixes the \code{<body>} height at 100\% of the window height. #JGG #' #JGG #' Note that \code{fillPage(plotOutput("plot"))} will not cause the plot to fill #JGG #' the page. Like most Shiny output widgets, \code{plotOutput}'s default height #JGG #' is a fixed number of pixels. You must explicitly set \code{height = "100\%"} #JGG #' if you want a plot (or htmlwidget, say) to fill its container. #JGG #' #JGG #' One must be careful what layouts/panels/elements come between the #JGG #' \code{fillPage} and the plots/widgets. Any container that has an automatic #JGG #' height will cause children with \code{height = "100\%"} to misbehave. Stick #JGG #' to functions that are designed for fill layouts, such as the ones in this #JGG #' package. #JGG #' #JGG #' @param ... Elements to include within the page. #JGG #' @param padding Padding to use for the body. This can be a numeric vector #JGG #' (which will be interpreted as pixels) or a character vector with valid CSS #JGG #' lengths. The length can be between one and four. If one, then that value #JGG #' will be used for all four sides. If two, then the first value will be used #JGG #' for the top and bottom, while the second value will be used for left and #JGG #' right. If three, then the first will be used for top, the second will be #JGG #' left and right, and the third will be bottom. If four, then the values will #JGG #' be interpreted as top, right, bottom, and left respectively. #JGG #' @param title The title to use for the browser window/tab (it will not be #JGG #' shown in the document). #JGG #' @param bootstrap If \code{TRUE}, load the Bootstrap CSS library. #JGG #' @param theme URL to alternative Bootstrap stylesheet. #JGG #' #JGG #' @examples #JGG #' fillPage( #JGG #' tags$style(type = "text/css", #JGG #' ".half-fill { width: 50%; height: 100%; }", #JGG #' "#one { float: left; background-color: #ddddff; }", #JGG #' "#two { float: right; background-color: #ccffcc; }" #JGG #' ), #JGG #' div(id = "one", class = "half-fill", #JGG #' "Left half" #JGG #' ), #JGG #' div(id = "two", class = "half-fill", #JGG #' "Right half" #JGG #' ), #JGG #' padding = 10 #JGG #' ) #JGG #' #JGG #' fillPage( #JGG #' fillRow( #JGG #' div(style = "background-color: red; width: 100%; height: 100%;"), #JGG #' div(style = "background-color: blue; width: 100%; height: 100%;") #JGG #' ) #JGG #' ) #JGG #' @export #JGG fillPage <- function(..., padding = 0, title = NULL, bootstrap = TRUE, #JGG theme = NULL) { #JGG #JGG fillCSS <- tags$head(tags$style(type = "text/css", #JGG "html, body { width: 100%; height: 100%; overflow: hidden; }", #JGG sprintf("body { padding: %s; margin: 0; }", collapseSizes(padding)) #JGG )) #JGG #JGG if (isTRUE(bootstrap)) { #JGG bootstrapPage(title = title, theme = theme, fillCSS, ...) #JGG } else { #JGG tagList( #JGG fillCSS, #JGG if (!is.null(title)) tags$head(tags$title(title)), #JGG ... #JGG ) #JGG } #JGG } #JGG #JGG collapseSizes <- function(padding) { #JGG paste( #JGG sapply(padding, shiny::validateCssUnit, USE.NAMES = FALSE), #JGG collapse = " ") #JGG } #JGG #JGG #' Create a page with a sidebar #JGG #' #JGG #' Create a Shiny UI that contains a header with the application title, a #JGG #' sidebar for input controls, and a main area for output. #JGG #' #JGG #' @param headerPanel The \link{headerPanel} with the application title #JGG #' @param sidebarPanel The \link{sidebarPanel} containing input controls #JGG #' @param mainPanel The \link{mainPanel} containing outputs #JGG #JGG #' @return A UI defintion that can be passed to the \link{shinyUI} function #JGG #' #JGG #' @note This function is deprecated. You should use \code{\link{fluidPage}} #JGG #' along with \code{\link{sidebarLayout}} to implement a page with a sidebar. #JGG #' #JGG #' @examples #JGG #' # Define UI #JGG #' pageWithSidebar( #JGG #' #JGG #' # Application title #JGG #' headerPanel("Hello Shiny!"), #JGG #' #JGG #' # Sidebar with a slider input #JGG #' sidebarPanel( #JGG #' sliderInput("obs", #JGG #' "Number of observations:", #JGG #' min = 0, #JGG #' max = 1000, #JGG #' value = 500) #JGG #' ), #JGG #' #JGG #' # Show a plot of the generated distribution #JGG #' mainPanel( #JGG #' plotOutput("distPlot") #JGG #' ) #JGG #' ) #JGG #' @export #JGG pageWithSidebar <- function(headerPanel, #JGG sidebarPanel, #JGG mainPanel) { #JGG #JGG bootstrapPage( #JGG # basic application container divs #JGG div( #JGG class="container-fluid", #JGG div(class="row", #JGG headerPanel #JGG ), #JGG div(class="row", #JGG sidebarPanel, #JGG mainPanel #JGG ) #JGG ) #JGG ) #JGG } #JGG #JGG #' Create a page with a top level navigation bar #JGG #' #JGG #' Create a page that contains a top level navigation bar that can be used to #JGG #' toggle a set of \code{\link{tabPanel}} elements. #JGG #' #JGG #' @param title The title to display in the navbar #JGG #' @param ... \code{\link{tabPanel}} elements to include in the page. The #JGG #' \code{navbarMenu} function also accepts strings, which will be used as menu #JGG #' section headers. If the string is a set of dashes like \code{"----"} a #JGG #' horizontal separator will be displayed in the menu. #JGG #' @param id If provided, you can use \code{input$}\emph{\code{id}} in your #JGG #' server logic to determine which of the current tabs is active. The value #JGG #' will correspond to the \code{value} argument that is passed to #JGG #' \code{\link{tabPanel}}. #JGG #' @param selected The \code{value} (or, if none was supplied, the \code{title}) #JGG #' of the tab that should be selected by default. If \code{NULL}, the first #JGG #' tab will be selected. #JGG #' @param position Determines whether the navbar should be displayed at the top #JGG #' of the page with normal scrolling behavior (\code{"static-top"}), pinned at #JGG #' the top (\code{"fixed-top"}), or pinned at the bottom #JGG #' (\code{"fixed-bottom"}). Note that using \code{"fixed-top"} or #JGG #' \code{"fixed-bottom"} will cause the navbar to overlay your body content, #JGG #' unless you add padding, e.g.: \code{tags$style(type="text/css", "body #JGG #' {padding-top: 70px;}")} #JGG #' @param header Tag or list of tags to display as a common header above all #JGG #' tabPanels. #JGG #' @param footer Tag or list of tags to display as a common footer below all #JGG #' tabPanels #JGG #' @param inverse \code{TRUE} to use a dark background and light text for the #JGG #' navigation bar #JGG #' @param collapsible \code{TRUE} to automatically collapse the navigation #JGG #' elements into a menu when the width of the browser is less than 940 pixels #JGG #' (useful for viewing on smaller touchscreen device) #JGG #' @param collapsable Deprecated; use \code{collapsible} instead. #JGG #' @param fluid \code{TRUE} to use a fluid layout. \code{FALSE} to use a fixed #JGG #' layout. #JGG #' @param responsive This option is deprecated; it is no longer optional with #JGG #' Bootstrap 3. #JGG #' @param theme Alternative Bootstrap stylesheet (normally a css file within the #JGG #' www directory). For example, to use the theme located at #JGG #' \code{www/bootstrap.css} you would use \code{theme = "bootstrap.css"}. #JGG #' @param windowTitle The title that should be displayed by the browser window. #JGG #' Useful if \code{title} is not a string. #JGG #' @param icon Optional icon to appear on a \code{navbarMenu} tab. #JGG #' #JGG #' @return A UI defintion that can be passed to the \link{shinyUI} function. #JGG #' #JGG #' @details The \code{navbarMenu} function can be used to create an embedded #JGG #' menu within the navbar that in turns includes additional tabPanels (see #JGG #' example below). #JGG #' #JGG #' @seealso \code{\link{tabPanel}}, \code{\link{tabsetPanel}}, #JGG #' \code{\link{updateNavbarPage}}, \code{\link{insertTab}}, #JGG #' \code{\link{showTab}} #JGG #' #JGG #' @examples #JGG #' navbarPage("App Title", #JGG #' tabPanel("Plot"), #JGG #' tabPanel("Summary"), #JGG #' tabPanel("Table") #JGG #' ) #JGG #' #JGG #' navbarPage("App Title", #JGG #' tabPanel("Plot"), #JGG #' navbarMenu("More", #JGG #' tabPanel("Summary"), #JGG #' "----", #JGG #' "Section header", #JGG #' tabPanel("Table") #JGG #' ) #JGG #' ) #JGG #' @export #JGG #' @param menuName A name that identifies this \code{navbarMenu}. This #JGG #' is needed if you want to insert/remove or show/hide an entire #JGG #' \code{navbarMenu}. #JGG #' #JGG #' @rdname navbarPage #JGG #' @export #JGG navbarMenu <- function(title, ..., menuName = title, icon = NULL) { #JGG structure(list(title = title, #JGG menuName = menuName, #JGG tabs = list(...), #JGG iconClass = iconClass(icon)), #JGG class = "shiny.navbarmenu") #JGG } #JGG #JGG #' Create a header panel #JGG #' #JGG #' Create a header panel containing an application title. #JGG #' #JGG #' @param title An application title to display #JGG #' @param windowTitle The title that should be displayed by the browser window. #JGG #' Useful if \code{title} is not a string. #JGG #' @return A headerPanel that can be passed to \link{pageWithSidebar} #JGG #' #JGG #' @examples #JGG #' headerPanel("Hello Shiny!") #JGG #' @export #JGG headerPanel <- function(title, windowTitle=title) { #JGG tagList( #JGG tags$head(tags$title(windowTitle)), #JGG div(class="col-sm-12", #JGG h1(title) #JGG ) #JGG ) #JGG } #JGG #JGG #' Create a well panel #JGG #' #JGG #' Creates a panel with a slightly inset border and grey background. Equivalent #JGG #' to Bootstrap's \code{well} CSS class. #JGG #' #JGG #' @param ... UI elements to include inside the panel. #JGG #' @return The newly created panel. #JGG #' @export #JGG wellPanel <- function(...) { #JGG div(class="well", ...) #JGG } #JGG #JGG #' Create a sidebar panel #JGG #' #JGG #' Create a sidebar panel containing input controls that can in turn be passed #JGG #' to \code{\link{sidebarLayout}}. #JGG #' #JGG #' @param ... UI elements to include on the sidebar #JGG #' @param width The width of the sidebar. For fluid layouts this is out of 12 #JGG #' total units; for fixed layouts it is out of whatever the width of the #JGG #' sidebar's parent column is. #JGG #' @return A sidebar that can be passed to \code{\link{sidebarLayout}} #JGG #' #JGG #' @examples #JGG #' # Sidebar with controls to select a dataset and specify #JGG #' # the number of observations to view #JGG #' sidebarPanel( #JGG #' selectInput("dataset", "Choose a dataset:", #JGG #' choices = c("rock", "pressure", "cars")), #JGG #' #JGG #' numericInput("obs", "Observations:", 10) #JGG #' ) #JGG #' @export #JGG sidebarPanel <- function(..., width = 4) { #JGG div(class=paste0("col-sm-", width), #JGG tags$form(class="well", #JGG ... #JGG ) #JGG ) #JGG } #JGG #JGG #' Create a main panel #JGG #' #JGG #' Create a main panel containing output elements that can in turn be passed to #JGG #' \code{\link{sidebarLayout}}. #JGG #' #JGG #' @param ... Output elements to include in the main panel #JGG #' @param width The width of the main panel. For fluid layouts this is out of 12 #JGG #' total units; for fixed layouts it is out of whatever the width of the main #JGG #' panel's parent column is. #JGG #' @return A main panel that can be passed to \code{\link{sidebarLayout}}. #JGG #' #JGG #' @examples #JGG #' # Show the caption and plot of the requested variable against mpg #JGG #' mainPanel( #JGG #' h3(textOutput("caption")), #JGG #' plotOutput("mpgPlot") #JGG #' ) #JGG #' @export #JGG mainPanel <- function(..., width = 8) { #JGG div(class=paste0("col-sm-", width), #JGG ... #JGG ) #JGG } #JGG #JGG #' Conditional Panel #JGG #' #JGG #' Creates a panel that is visible or not, depending on the value of a #JGG #' JavaScript expression. The JS expression is evaluated once at startup and #JGG #' whenever Shiny detects a relevant change in input/output. #JGG #' #JGG #' In the JS expression, you can refer to \code{input} and \code{output} #JGG #' JavaScript objects that contain the current values of input and output. For #JGG #' example, if you have an input with an id of \code{foo}, then you can use #JGG #' \code{input.foo} to read its value. (Be sure not to modify the input/output #JGG #' objects, as this may cause unpredictable behavior.) #JGG #' #JGG #' @param condition A JavaScript expression that will be evaluated repeatedly to #JGG #' determine whether the panel should be displayed. #JGG #' @param ns The \code{\link[=NS]{namespace}} object of the current module, if #JGG #' any. #JGG #' @param ... Elements to include in the panel. #JGG #' #JGG #' @note You are not recommended to use special JavaScript characters such as a #JGG #' period \code{.} in the input id's, but if you do use them anyway, for #JGG #' example, \code{inputId = "foo.bar"}, you will have to use #JGG #' \code{input["foo.bar"]} instead of \code{input.foo.bar} to read the input #JGG #' value. #JGG #' @examples #JGG #' ## Only run this example in interactive R sessions #JGG #' if (interactive()) { #JGG #' ui <- fluidPage( #JGG #' sidebarPanel( #JGG #' selectInput("plotType", "Plot Type", #JGG #' c(Scatter = "scatter", Histogram = "hist") #JGG #' ), #JGG #' # Only show this panel if the plot type is a histogram #JGG #' conditionalPanel( #JGG #' condition = "input.plotType == 'hist'", #JGG #' selectInput( #JGG #' "breaks", "Breaks", #JGG #' c("Sturges", "Scott", "Freedman-Diaconis", "[Custom]" = "custom") #JGG #' ), #JGG #' # Only show this panel if Custom is selected #JGG #' conditionalPanel( #JGG #' condition = "input.breaks == 'custom'", #JGG #' sliderInput("breakCount", "Break Count", min = 1, max = 50, value = 10) #JGG #' ) #JGG #' ) #JGG #' ), #JGG #' mainPanel( #JGG #' plotOutput("plot") #JGG #' ) #JGG #' ) #JGG #' #JGG #' server <- function(input, output) { #JGG #' x <- rnorm(100) #JGG #' y <- rnorm(100) #JGG #' #JGG #' output$plot <- renderPlot({ #JGG #' if (input$plotType == "scatter") { #JGG #' plot(x, y) #JGG #' } else { #JGG #' breaks <- input$breaks #JGG #' if (breaks == "custom") { #JGG #' breaks <- input$breakCount #JGG #' } #JGG #' #JGG #' hist(x, breaks = breaks) #JGG #' } #JGG #' }) #JGG #' } #JGG #' #JGG #' shinyApp(ui, server) #JGG #' } #JGG #' @export #JGG conditionalPanel <- function(condition, ..., ns = NS(NULL)) { #JGG div(`data-display-if`=condition, `data-ns-prefix`=ns(""), ...) #JGG } #JGG #JGG #' Create a help text element #JGG #' #JGG #' Create help text which can be added to an input form to provide additional #JGG #' explanation or context. #JGG #' #JGG #' @param ... One or more help text strings (or other inline HTML elements) #JGG #' @return A help text element that can be added to a UI definition. #JGG #' #JGG #' @examples #JGG #' helpText("Note: while the data view will show only", #JGG #' "the specified number of observations, the", #JGG #' "summary will be based on the full dataset.") #JGG #' @export #JGG helpText <- function(...) { #JGG span(class="help-block", ...) #JGG } #JGG #JGG #JGG #' Create a tab panel #JGG #' #JGG #' Create a tab panel that can be included within a \code{\link{tabsetPanel}}. #JGG #' #JGG #' @param title Display title for tab #JGG #' @param ... UI elements to include within the tab #JGG #' @param value The value that should be sent when \code{tabsetPanel} reports #JGG #' that this tab is selected. If omitted and \code{tabsetPanel} has an #JGG #' \code{id}, then the title will be used.. #JGG #' @param icon Optional icon to appear on the tab. This attribute is only #JGG #' valid when using a \code{tabPanel} within a \code{\link{navbarPage}}. #JGG #' @return A tab that can be passed to \code{\link{tabsetPanel}} #JGG #' #JGG #' @seealso \code{\link{tabsetPanel}} #JGG #' #JGG #' @examples #JGG #' # Show a tabset that includes a plot, summary, and #JGG #' # table view of the generated distribution #JGG #' mainPanel( #JGG #' tabsetPanel( #JGG #' tabPanel("Plot", plotOutput("plot")), #JGG #' tabPanel("Summary", verbatimTextOutput("summary")), #JGG #' tabPanel("Table", tableOutput("table")) #JGG #' ) #JGG #' ) #JGG #' @export #JGG tabPanel <- function(title, ..., value = title, icon = NULL) { #JGG divTag <- div(class="tab-pane", #JGG title=title, #JGG `data-value`=value, #JGG `data-icon-class` = iconClass(icon), #JGG ...) #JGG } #JGG #JGG #' Create a tabset panel #JGG #' #JGG #' Create a tabset that contains \code{\link{tabPanel}} elements. Tabsets are #JGG #' useful for dividing output into multiple independently viewable sections. #JGG #' #JGG #' @param ... \code{\link{tabPanel}} elements to include in the tabset #JGG #' @param id If provided, you can use \code{input$}\emph{\code{id}} in your #JGG #' server logic to determine which of the current tabs is active. The value #JGG #' will correspond to the \code{value} argument that is passed to #JGG #' \code{\link{tabPanel}}. #JGG #' @param selected The \code{value} (or, if none was supplied, the \code{title}) #JGG #' of the tab that should be selected by default. If \code{NULL}, the first #JGG #' tab will be selected. #JGG #' @param type Use "tabs" for the standard look; Use "pills" for a more plain #JGG #' look where tabs are selected using a background fill color. #JGG #' @param position This argument is deprecated; it has been discontinued in #JGG #' Bootstrap 3. #JGG #' @return A tabset that can be passed to \code{\link{mainPanel}} #JGG #' #JGG #' @seealso \code{\link{tabPanel}}, \code{\link{updateTabsetPanel}}, #JGG #' \code{\link{insertTab}}, \code{\link{showTab}} #JGG #' #JGG #' @examples #JGG #' # Show a tabset that includes a plot, summary, and #JGG #' # table view of the generated distribution #JGG #' mainPanel( #JGG #' tabsetPanel( #JGG #' tabPanel("Plot", plotOutput("plot")), #JGG #' tabPanel("Summary", verbatimTextOutput("summary")), #JGG #' tabPanel("Table", tableOutput("table")) #JGG #' ) #JGG #' ) #JGG #' @export #JGG tabsetPanel <- function(..., #JGG id = NULL, #JGG selected = NULL, #JGG type = c("tabs", "pills"), #JGG position = NULL) { #JGG if (!is.null(position)) { #JGG shinyDeprecated(msg = paste("tabsetPanel: argument 'position' is deprecated;", #JGG "it has been discontinued in Bootstrap 3."), #JGG version = "0.10.2.2") #JGG } #JGG #JGG if (!is.null(id)) #JGG selected <- restoreInput(id = id, default = selected) #JGG #JGG # build the tabset #JGG tabs <- list(...) #JGG type <- match.arg(type) #JGG #JGG tabset <- buildTabset(tabs, paste0("nav nav-", type), NULL, id, selected) #JGG #JGG # create the content #JGG first <- tabset$navList #JGG second <- tabset$content #JGG #JGG # create the tab div #JGG tags$div(class = "tabbable", first, second) #JGG } #JGG #JGG #' Create a navigation list panel #JGG #' #JGG #' Create a navigation list panel that provides a list of links on the left #JGG #' which navigate to a set of tabPanels displayed to the right. #JGG #' #JGG #' @param ... \code{\link{tabPanel}} elements to include in the navlist #JGG #' @param id If provided, you can use \code{input$}\emph{\code{id}} in your #JGG #' server logic to determine which of the current navlist items is active. The #JGG #' value will correspond to the \code{value} argument that is passed to #JGG #' \code{\link{tabPanel}}. #JGG #' @param selected The \code{value} (or, if none was supplied, the \code{title}) #JGG #' of the navigation item that should be selected by default. If \code{NULL}, #JGG #' the first navigation will be selected. #JGG #' @param well \code{TRUE} to place a well (gray rounded rectangle) around the #JGG #' navigation list. #JGG #' @param fluid \code{TRUE} to use fluid layout; \code{FALSE} to use fixed #JGG #' layout. #JGG #' @param widths Column withs of the navigation list and tabset content areas #JGG #' respectively. #JGG #' #JGG #' @details You can include headers within the \code{navlistPanel} by including #JGG #' plain text elements in the list. Versions of Shiny before 0.11 supported #JGG #' separators with "------", but as of 0.11, separators were no longer #JGG #' supported. This is because version 0.11 switched to Bootstrap 3, which #JGG #' doesn't support separators. #JGG #' #JGG #' @seealso \code{\link{tabPanel}}, \code{\link{updateNavlistPanel}}, #JGG #' \code{\link{insertTab}}, \code{\link{showTab}} #JGG #' #JGG #' @examples #JGG #' fluidPage( #JGG #' #JGG #' titlePanel("Application Title"), #JGG #' #JGG #' navlistPanel( #JGG #' "Header", #JGG #' tabPanel("First"), #JGG #' tabPanel("Second"), #JGG #' tabPanel("Third") #JGG #' ) #JGG #' ) #JGG #' @export #JGG navlistPanel <- function(..., #JGG id = NULL, #JGG selected = NULL, #JGG well = TRUE, #JGG fluid = TRUE, #JGG widths = c(4, 8)) { #JGG #JGG # text filter for headers #JGG textFilter <- function(text) { #JGG tags$li(class="navbar-brand", text) #JGG } #JGG #JGG if (!is.null(id)) #JGG selected <- restoreInput(id = id, default = selected) #JGG #JGG # build the tabset #JGG tabs <- list(...) #JGG tabset <- buildTabset(tabs, #JGG "nav nav-pills nav-stacked", #JGG textFilter, #JGG id, #JGG selected) #JGG #JGG # create the columns #JGG columns <- list( #JGG column(widths[[1]], class=ifelse(well, "well", ""), tabset$navList), #JGG column(widths[[2]], tabset$content) #JGG ) #JGG #JGG # return the row #JGG if (fluid) #JGG fluidRow(columns) #JGG else #JGG fixedRow(columns) #JGG } #JGG #JGG #' Create a text output element #JGG #' #JGG #' Render a reactive output variable as text within an application page. The #JGG #' text will be included within an HTML \code{div} tag by default. #JGG #' @param outputId output variable to read the value from #JGG #' @param container a function to generate an HTML element to contain the text #JGG #' @param inline use an inline (\code{span()}) or block container (\code{div()}) #JGG #' for the output #JGG #' @return A text output element that can be included in a panel #JGG #' @details Text is HTML-escaped prior to rendering. This element is often used #JGG #' to display \link{renderText} output variables. #JGG #' @examples #JGG #' h3(textOutput("caption")) #JGG #' @export #JGG textOutput <- function(outputId, container = if (inline) span else div, inline = FALSE) { #JGG container(id = outputId, class = "shiny-text-output") #JGG } #JGG #JGG #' Create a verbatim text output element #JGG #' #JGG #' Render a reactive output variable as verbatim text within an #JGG #' application page. The text will be included within an HTML \code{pre} tag. #JGG #' @param outputId output variable to read the value from #JGG #' @param placeholder if the output is empty or \code{NULL}, should an empty #JGG #' rectangle be displayed to serve as a placeholder? (does not affect #JGG #' behavior when the the output in nonempty) #JGG #' @return A verbatim text output element that can be included in a panel #JGG #' @details Text is HTML-escaped prior to rendering. This element is often used #JGG #' with the \link{renderPrint} function to preserve fixed-width formatting #JGG #' of printed objects. #JGG #' @examples #JGG #' ## Only run this example in interactive R sessions #JGG #' if (interactive()) { #JGG #' shinyApp( #JGG #' ui = basicPage( #JGG #' textInput("txt", "Enter the text to display below:"), #JGG #' verbatimTextOutput("default"), #JGG #' verbatimTextOutput("placeholder", placeholder = TRUE) #JGG #' ), #JGG #' server = function(input, output) { #JGG #' output$default <- renderText({ input$txt }) #JGG #' output$placeholder <- renderText({ input$txt }) #JGG #' } #JGG #' ) #JGG #' } #JGG #' @export #JGG verbatimTextOutput <- function(outputId, placeholder = FALSE) { #JGG pre(id = outputId, #JGG class = paste(c("shiny-text-output", if (!placeholder) "noplaceholder"), #JGG collapse = " ") #JGG ) #JGG } #JGG #JGG #JGG #' @name plotOutput #JGG #' @rdname plotOutput #JGG #' @export #JGG imageOutput <- function(outputId, width = "100%", height="400px", #JGG click = NULL, dblclick = NULL, #JGG hover = NULL, hoverDelay = NULL, hoverDelayType = NULL, #JGG brush = NULL, #JGG clickId = NULL, hoverId = NULL, #JGG inline = FALSE) { #JGG #JGG if (!is.null(clickId)) { #JGG shinyDeprecated( #JGG msg = paste("The 'clickId' argument is deprecated. ", #JGG "Please use 'click' instead. ", #JGG "See ?imageOutput or ?plotOutput for more information."), #JGG version = "0.11.1" #JGG ) #JGG click <- clickId #JGG } #JGG #JGG if (!is.null(hoverId)) { #JGG shinyDeprecated( #JGG msg = paste("The 'hoverId' argument is deprecated. ", #JGG "Please use 'hover' instead. ", #JGG "See ?imageOutput or ?plotOutput for more information."), #JGG version = "0.11.1" #JGG ) #JGG hover <- hoverId #JGG } #JGG #JGG if (!is.null(hoverDelay) || !is.null(hoverDelayType)) { #JGG shinyDeprecated( #JGG msg = paste("The 'hoverDelay'and 'hoverDelayType' arguments are deprecated. ", #JGG "Please use 'hoverOpts' instead. ", #JGG "See ?imageOutput or ?plotOutput for more information."), #JGG version = "0.11.1" #JGG ) #JGG hover <- hoverOpts(id = hover, delay = hoverDelay, delayType = hoverDelayType) #JGG } #JGG #JGG style <- if (!inline) { #JGG paste("width:", validateCssUnit(width), ";", "height:", validateCssUnit(height)) #JGG } #JGG #JGG #JGG # Build up arguments for call to div() or span() #JGG args <- list( #JGG id = outputId, #JGG class = "shiny-image-output", #JGG style = style #JGG ) #JGG #JGG # Given a named list with options, replace names like "delayType" with #JGG # "data-hover-delay-type" (given a prefix "hover") #JGG formatOptNames <- function(opts, prefix) { #JGG newNames <- paste("data", prefix, names(opts), sep = "-") #JGG # Replace capital letters with "-" and lowercase letter #JGG newNames <- gsub("([A-Z])", "-\\L\\1", newNames, perl = TRUE) #JGG names(opts) <- newNames #JGG opts #JGG } #JGG #JGG if (!is.null(click)) { #JGG # If click is a string, turn it into clickOpts object #JGG if (is.character(click)) { #JGG click <- clickOpts(id = click) #JGG } #JGG args <- c(args, formatOptNames(click, "click")) #JGG } #JGG #JGG if (!is.null(dblclick)) { #JGG if (is.character(dblclick)) { #JGG dblclick <- clickOpts(id = dblclick) #JGG } #JGG args <- c(args, formatOptNames(dblclick, "dblclick")) #JGG } #JGG #JGG if (!is.null(hover)) { #JGG if (is.character(hover)) { #JGG hover <- hoverOpts(id = hover) #JGG } #JGG args <- c(args, formatOptNames(hover, "hover")) #JGG } #JGG #JGG if (!is.null(brush)) { #JGG if (is.character(brush)) { #JGG brush <- brushOpts(id = brush) #JGG } #JGG args <- c(args, formatOptNames(brush, "brush")) #JGG } #JGG #JGG container <- if (inline) span else div #JGG do.call(container, args) #JGG } #JGG #JGG #' Create an plot or image output element #JGG #' #JGG #' Render a \code{\link{renderPlot}} or \code{\link{renderImage}} within an #JGG #' application page. #JGG #' #JGG #' @section Interactive plots: #JGG #' #JGG #' Plots and images in Shiny support mouse-based interaction, via clicking, #JGG #' double-clicking, hovering, and brushing. When these interaction events #JGG #' occur, the mouse coordinates will be sent to the server as \code{input$} #JGG #' variables, as specified by \code{click}, \code{dblclick}, \code{hover}, or #JGG #' \code{brush}. #JGG #' #JGG #' For \code{plotOutput}, the coordinates will be sent scaled to the data #JGG #' space, if possible. (At the moment, plots generated by base graphics and #JGG #' ggplot2 support this scaling, although plots generated by lattice and #JGG #' others do not.) If scaling is not possible, the raw pixel coordinates will #JGG #' be sent. For \code{imageOutput}, the coordinates will be sent in raw pixel #JGG #' coordinates. #JGG #' #JGG #' With ggplot2 graphics, the code in \code{renderPlot} should return a ggplot #JGG #' object; if instead the code prints the ggplot2 object with something like #JGG #' \code{print(p)}, then the coordinates for interactive graphics will not be #JGG #' properly scaled to the data space. #JGG #' #JGG #' @param outputId output variable to read the plot/image from. #JGG #' @param width,height Image width/height. Must be a valid CSS unit (like #JGG #' \code{"100\%"}, \code{"400px"}, \code{"auto"}) or a number, which will be #JGG #' coerced to a string and have \code{"px"} appended. These two arguments are #JGG #' ignored when \code{inline = TRUE}, in which case the width/height of a plot #JGG #' must be specified in \code{renderPlot()}. Note that, for height, using #JGG #' \code{"auto"} or \code{"100\%"} generally will not work as expected, #JGG #' because of how height is computed with HTML/CSS. #JGG #' @param click This can be \code{NULL} (the default), a string, or an object #JGG #' created by the \code{\link{clickOpts}} function. If you use a value like #JGG #' \code{"plot_click"} (or equivalently, \code{clickOpts(id="plot_click")}), #JGG #' the plot will send coordinates to the server whenever it is clicked, and #JGG #' the value will be accessible via \code{input$plot_click}. The value will be #JGG #' a named list with \code{x} and \code{y} elements indicating the mouse #JGG #' position. #JGG #' @param dblclick This is just like the \code{click} argument, but for #JGG #' double-click events. #JGG #' @param hover Similar to the \code{click} argument, this can be \code{NULL} #JGG #' (the default), a string, or an object created by the #JGG #' \code{\link{hoverOpts}} function. If you use a value like #JGG #' \code{"plot_hover"} (or equivalently, \code{hoverOpts(id="plot_hover")}), #JGG #' the plot will send coordinates to the server pauses on the plot, and the #JGG #' value will be accessible via \code{input$plot_hover}. The value will be a #JGG #' named list with \code{x} and \code{y} elements indicating the mouse #JGG #' position. To control the hover time or hover delay type, you must use #JGG #' \code{\link{hoverOpts}}. #JGG #' @param clickId Deprecated; use \code{click} instead. Also see the #JGG #' \code{\link{clickOpts}} function. #JGG #' @param hoverId Deprecated; use \code{hover} instead. Also see the #JGG #' \code{\link{hoverOpts}} function. #JGG #' @param hoverDelay Deprecated; use \code{hover} instead. Also see the #JGG #' \code{\link{hoverOpts}} function. #JGG #' @param hoverDelayType Deprecated; use \code{hover} instead. Also see the #JGG #' \code{\link{hoverOpts}} function. #JGG #' @param brush Similar to the \code{click} argument, this can be \code{NULL} #JGG #' (the default), a string, or an object created by the #JGG #' \code{\link{brushOpts}} function. If you use a value like #JGG #' \code{"plot_brush"} (or equivalently, \code{brushOpts(id="plot_brush")}), #JGG #' the plot will allow the user to "brush" in the plotting area, and will send #JGG #' information about the brushed area to the server, and the value will be #JGG #' accessible via \code{input$plot_brush}. Brushing means that the user will #JGG #' be able to draw a rectangle in the plotting area and drag it around. The #JGG #' value will be a named list with \code{xmin}, \code{xmax}, \code{ymin}, and #JGG #' \code{ymax} elements indicating the brush area. To control the brush #JGG #' behavior, use \code{\link{brushOpts}}. Multiple #JGG #' \code{imageOutput}/\code{plotOutput} calls may share the same \code{id} #JGG #' value; brushing one image or plot will cause any other brushes with the #JGG #' same \code{id} to disappear. #JGG #' @inheritParams textOutput #JGG #' @note The arguments \code{clickId} and \code{hoverId} only work for R base #JGG #' graphics (see the \pkg{\link[graphics:graphics-package]{graphics}} package). They do not work for #JGG #' \pkg{\link[grid:grid-package]{grid}}-based graphics, such as \pkg{ggplot2}, #JGG #' \pkg{lattice}, and so on. #JGG #' #JGG #' @return A plot or image output element that can be included in a panel. #JGG #' @seealso For the corresponding server-side functions, see #JGG #' \code{\link{renderPlot}} and \code{\link{renderImage}}. #JGG #' #JGG #' @examples #JGG #' # Only run these examples in interactive R sessions #JGG #' if (interactive()) { #JGG #' #JGG #' # A basic shiny app with a plotOutput #JGG #' shinyApp( #JGG #' ui = fluidPage( #JGG #' sidebarLayout( #JGG #' sidebarPanel( #JGG #' actionButton("newplot", "New plot") #JGG #' ), #JGG #' mainPanel( #JGG #' plotOutput("plot") #JGG #' ) #JGG #' ) #JGG #' ), #JGG #' server = function(input, output) { #JGG #' output$plot <- renderPlot({ #JGG #' input$newplot #JGG #' # Add a little noise to the cars data #JGG #' cars2 <- cars + rnorm(nrow(cars)) #JGG #' plot(cars2) #JGG #' }) #JGG #' } #JGG #' ) #JGG #' #JGG #' #JGG #' # A demonstration of clicking, hovering, and brushing #JGG #' shinyApp( #JGG #' ui = basicPage( #JGG #' fluidRow( #JGG #' column(width = 4, #JGG #' plotOutput("plot", height=300, #JGG #' click = "plot_click", # Equiv, to click=clickOpts(id="plot_click") #JGG #' hover = hoverOpts(id = "plot_hover", delayType = "throttle"), #JGG #' brush = brushOpts(id = "plot_brush") #JGG #' ), #JGG #' h4("Clicked points"), #JGG #' tableOutput("plot_clickedpoints"), #JGG #' h4("Brushed points"), #JGG #' tableOutput("plot_brushedpoints") #JGG #' ), #JGG #' column(width = 4, #JGG #' verbatimTextOutput("plot_clickinfo"), #JGG #' verbatimTextOutput("plot_hoverinfo") #JGG #' ), #JGG #' column(width = 4, #JGG #' wellPanel(actionButton("newplot", "New plot")), #JGG #' verbatimTextOutput("plot_brushinfo") #JGG #' ) #JGG #' ) #JGG #' ), #JGG #' server = function(input, output, session) { #JGG #' data <- reactive({ #JGG #' input$newplot #JGG #' # Add a little noise to the cars data so the points move #JGG #' cars + rnorm(nrow(cars)) #JGG #' }) #JGG #' output$plot <- renderPlot({ #JGG #' d <- data() #JGG #' plot(d$speed, d$dist) #JGG #' }) #JGG #' output$plot_clickinfo <- renderPrint({ #JGG #' cat("Click:\n") #JGG #' str(input$plot_click) #JGG #' }) #JGG #' output$plot_hoverinfo <- renderPrint({ #JGG #' cat("Hover (throttled):\n") #JGG #' str(input$plot_hover) #JGG #' }) #JGG #' output$plot_brushinfo <- renderPrint({ #JGG #' cat("Brush (debounced):\n") #JGG #' str(input$plot_brush) #JGG #' }) #JGG #' output$plot_clickedpoints <- renderTable({ #JGG #' # For base graphics, we need to specify columns, though for ggplot2, #JGG #' # it's usually not necessary. #JGG #' res <- nearPoints(data(), input$plot_click, "speed", "dist") #JGG #' if (nrow(res) == 0) #JGG #' return() #JGG #' res #JGG #' }) #JGG #' output$plot_brushedpoints <- renderTable({ #JGG #' res <- brushedPoints(data(), input$plot_brush, "speed", "dist") #JGG #' if (nrow(res) == 0) #JGG #' return() #JGG #' res #JGG #' }) #JGG #' } #JGG #' ) #JGG #' #JGG #' #JGG #' # Demo of clicking, hovering, brushing with imageOutput #JGG #' # Note that coordinates are in pixels #JGG #' shinyApp( #JGG #' ui = basicPage( #JGG #' fluidRow( #JGG #' column(width = 4, #JGG #' imageOutput("image", height=300, #JGG #' click = "image_click", #JGG #' hover = hoverOpts( #JGG #' id = "image_hover", #JGG #' delay = 500, #JGG #' delayType = "throttle" #JGG #' ), #JGG #' brush = brushOpts(id = "image_brush") #JGG #' ) #JGG #' ), #JGG #' column(width = 4, #JGG #' verbatimTextOutput("image_clickinfo"), #JGG #' verbatimTextOutput("image_hoverinfo") #JGG #' ), #JGG #' column(width = 4, #JGG #' wellPanel(actionButton("newimage", "New image")), #JGG #' verbatimTextOutput("image_brushinfo") #JGG #' ) #JGG #' ) #JGG #' ), #JGG #' server = function(input, output, session) { #JGG #' output$image <- renderImage({ #JGG #' input$newimage #JGG #' #JGG #' # Get width and height of image output #JGG #' width <- session$clientData$output_image_width #JGG #' height <- session$clientData$output_image_height #JGG #' #JGG #' # Write to a temporary PNG file #JGG #' outfile <- tempfile(fileext = ".png") #JGG #' #JGG #' png(outfile, width=width, height=height) #JGG #' plot(rnorm(200), rnorm(200)) #JGG #' dev.off() #JGG #' #JGG #' # Return a list containing information about the image #JGG #' list( #JGG #' src = outfile, #JGG #' contentType = "image/png", #JGG #' width = width, #JGG #' height = height, #JGG #' alt = "This is alternate text" #JGG #' ) #JGG #' }) #JGG #' output$image_clickinfo <- renderPrint({ #JGG #' cat("Click:\n") #JGG #' str(input$image_click) #JGG #' }) #JGG #' output$image_hoverinfo <- renderPrint({ #JGG #' cat("Hover (throttled):\n") #JGG #' str(input$image_hover) #JGG #' }) #JGG #' output$image_brushinfo <- renderPrint({ #JGG #' cat("Brush (debounced):\n") #JGG #' str(input$image_brush) #JGG #' }) #JGG #' } #JGG #' ) #JGG #' #JGG #' } #JGG #' @export #JGG plotOutput <- function(outputId, width = "100%", height="400px", #JGG click = NULL, dblclick = NULL, #JGG hover = NULL, hoverDelay = NULL, hoverDelayType = NULL, #JGG brush = NULL, #JGG clickId = NULL, hoverId = NULL, #JGG inline = FALSE) { #JGG #JGG # Result is the same as imageOutput, except for HTML class #JGG res <- imageOutput(outputId, width, height, click, dblclick, #JGG hover, hoverDelay, hoverDelayType, brush, #JGG clickId, hoverId, inline) #JGG #JGG res$attribs$class <- "shiny-plot-output" #JGG res #JGG } #JGG #JGG #' Create a table output element #JGG #' #JGG #' Render a \code{\link{renderTable}} or \code{\link{renderDataTable}} within an #JGG #' application page. \code{renderTable} uses a standard HTML table, while #JGG #' \code{renderDataTable} uses the DataTables Javascript library to create an #JGG #' interactive table with more features. #JGG #' #JGG #' @param outputId output variable to read the table from #JGG #' @return A table output element that can be included in a panel #JGG #' #JGG #' @seealso \code{\link{renderTable}}, \code{\link{renderDataTable}}. #JGG #' @examples #JGG #' ## Only run this example in interactive R sessions #JGG #' if (interactive()) { #JGG #' # table example #JGG #' shinyApp( #JGG #' ui = fluidPage( #JGG #' fluidRow( #JGG #' column(12, #JGG #' tableOutput('table') #JGG #' ) #JGG #' ) #JGG #' ), #JGG #' server = function(input, output) { #JGG #' output$table <- renderTable(iris) #JGG #' } #JGG #' ) #JGG #' #JGG #' #JGG #' # DataTables example #JGG #' shinyApp( #JGG #' ui = fluidPage( #JGG #' fluidRow( #JGG #' column(12, #JGG #' dataTableOutput('table') #JGG #' ) #JGG #' ) #JGG #' ), #JGG #' server = function(input, output) { #JGG #' output$table <- renderDataTable(iris) #JGG #' } #JGG #' ) #JGG #' } #JGG #' @export #JGG tableOutput <- function(outputId) { #JGG div(id = outputId, class="shiny-html-output") #JGG } #JGG #JGG dataTableDependency <- list( #JGG htmlDependency( #JGG "datatables", "1.10.5", c(href = "shared/datatables"), #JGG script = "js/jquery.dataTables.min.js" #JGG ), #JGG htmlDependency( #JGG "datatables-bootstrap", "1.10.5", c(href = "shared/datatables"), #JGG stylesheet = c("css/dataTables.bootstrap.css", "css/dataTables.extra.css"), #JGG script = "js/dataTables.bootstrap.js" #JGG ) #JGG ) #JGG #JGG #' @rdname tableOutput #JGG #' @export #JGG dataTableOutput <- function(outputId) { #JGG attachDependencies( #JGG div(id = outputId, class="shiny-datatable-output"), #JGG dataTableDependency #JGG ) #JGG } #JGG #JGG #' Create an HTML output element #JGG #' #JGG #' Render a reactive output variable as HTML within an application page. The #JGG #' text will be included within an HTML \code{div} tag, and is presumed to #JGG #' contain HTML content which should not be escaped. #JGG #' #JGG #' \code{uiOutput} is intended to be used with \code{renderUI} on the server #JGG #' side. It is currently just an alias for \code{htmlOutput}. #JGG #' #JGG #' @param outputId output variable to read the value from #JGG #' @param ... Other arguments to pass to the container tag function. This is #JGG #' useful for providing additional classes for the tag. #JGG #' @inheritParams textOutput #JGG #' @return An HTML output element that can be included in a panel #JGG #' @examples #JGG #' htmlOutput("summary") #JGG #' #JGG #' # Using a custom container and class #JGG #' tags$ul( #JGG #' htmlOutput("summary", container = tags$li, class = "custom-li-output") #JGG #' ) #JGG #' @export #JGG htmlOutput <- function(outputId, inline = FALSE, #JGG container = if (inline) span else div, ...) #JGG { #JGG if (anyUnnamed(list(...))) { #JGG warning("Unnamed elements in ... will be replaced with dynamic UI.") #JGG } #JGG container(id = outputId, class="shiny-html-output", ...) #JGG } #JGG #JGG #' @rdname htmlOutput #JGG #' @export #JGG uiOutput <- htmlOutput #JGG #JGG #' Create a download button or link #JGG #' #JGG #' Use these functions to create a download button or link; when clicked, it #JGG #' will initiate a browser download. The filename and contents are specified by #JGG #' the corresponding \code{\link{downloadHandler}} defined in the server #JGG #' function. #JGG #' #JGG #' @param outputId The name of the output slot that the \code{downloadHandler} #JGG #' is assigned to. #JGG #' @param label The label that should appear on the button. #JGG #' @param class Additional CSS classes to apply to the tag, if any. #JGG #' @param ... Other arguments to pass to the container tag function. #JGG #' #JGG #' @examples #JGG #' \dontrun{ #JGG #' # In server.R: #JGG #' output$downloadData <- downloadHandler( #JGG #' filename = function() { #JGG #' paste('data-', Sys.Date(), '.csv', sep='') #JGG #' }, #JGG #' content = function(con) { #JGG #' write.csv(data, con) #JGG #' } #JGG #' ) #JGG #' #JGG #' # In ui.R: #JGG #' downloadLink('downloadData', 'Download') #JGG #' } #JGG #' #JGG #' @aliases downloadLink #JGG #' @seealso \code{\link{downloadHandler}} #JGG #' @export #JGG downloadButton <- function(outputId, #JGG label="Download", #JGG class=NULL, ...) { #JGG aTag <- tags$a(id=outputId, #JGG class=paste('btn btn-default shiny-download-link', class), #JGG href='', #JGG target='_blank', #JGG download=NA, #JGG icon("download"), #JGG label, ...) #JGG } #JGG #JGG #' @rdname downloadButton #JGG #' @export #JGG downloadLink <- function(outputId, label="Download", class=NULL, ...) { #JGG tags$a(id=outputId, #JGG class=paste(c('shiny-download-link', class), collapse=" "), #JGG href='', #JGG target='_blank', #JGG download=NA, #JGG label, ...) #JGG } #JGG #JGG #JGG #' Create an icon #JGG #' #JGG #' Create an icon for use within a page. Icons can appear on their own, inside #JGG #' of a button, or as an icon for a \code{\link{tabPanel}} within a #JGG #' \code{\link{navbarPage}}. #JGG #' #JGG #' @param name Name of icon. Icons are drawn from the #JGG #' \href{https://fontawesome.com/}{Font Awesome Free} (currently icons from #JGG #' the v5.3.1 set are supported with the v4 naming convention) and #JGG #' \href{http://getbootstrap.com/components/#glyphicons}{Glyphicons} #JGG #' libraries. Note that the "fa-" and "glyphicon-" prefixes should not be used #JGG #' in icon names (i.e. the "fa-calendar" icon should be referred to as #JGG #' "calendar") #JGG #' @param class Additional classes to customize the style of the icon (see the #JGG #' \href{http://fontawesome.io/examples/}{usage examples} for details on #JGG #' supported styles). #JGG #' @param lib Icon library to use ("font-awesome" or "glyphicon") #JGG #' #JGG #' @return An icon element #JGG #' #JGG #' @seealso For lists of available icons, see #JGG #' \href{http://fontawesome.io/icons/}{http://fontawesome.io/icons/} and #JGG #' \href{http://getbootstrap.com/components/#glyphicons}{http://getbootstrap.com/components/#glyphicons}. #JGG #' #JGG #' #JGG #' @examples #JGG #' # add an icon to a submit button #JGG #' submitButton("Update View", icon = icon("refresh")) #JGG #' #JGG #' navbarPage("App Title", #JGG #' tabPanel("Plot", icon = icon("bar-chart-o")), #JGG #' tabPanel("Summary", icon = icon("list-alt")), #JGG #' tabPanel("Table", icon = icon("table")) #JGG #' ) #JGG #' #JGG #JGG # #' @export #JGG # icon <- function(name, class = NULL, lib = "font-awesome") { #JGG # prefixes <- list( #JGG # "font-awesome" = "fa", #JGG # "glyphicon" = "glyphicon" #JGG # ) #JGG # prefix <- prefixes[[lib]] #JGG # #JGG # # determine stylesheet #JGG # if (is.null(prefix)) { #JGG # stop("Unknown font library '", lib, "' specified. Must be one of ", #JGG # paste0('"', names(prefixes), '"', collapse = ", ")) #JGG # } #JGG # #JGG # # build the icon class (allow name to be null so that other functions #JGG # # e.g. buildTabset can pass an explicit class value) #JGG # iconClass <- "" #JGG # if (!is.null(name)) { #JGG # prefix_class <- prefix #JGG # if (prefix_class == "fa" && name %in% font_awesome_brands) { #JGG # prefix_class <- "fab" #JGG # } #JGG # iconClass <- paste0(prefix_class, " ", prefix, "-", name) #JGG # } #JGG # if (!is.null(class)) #JGG # iconClass <- paste(iconClass, class) #JGG # #JGG # iconTag <- tags$i(class = iconClass) #JGG # #JGG # # font-awesome needs an additional dependency (glyphicon is in bootstrap) #JGG # if (lib == "font-awesome") { #JGG # htmlDependencies(iconTag) <- htmlDependency( #JGG # "font-awesome", "5.3.1", "www/shared/fontawesome", package = "shiny", #JGG # stylesheet = c( #JGG # "css/all.min.css", #JGG # "css/v4-shims.min.css" #JGG # ) #JGG # ) #JGG # } #JGG # #JGG # htmltools::browsable(iconTag) #JGG # } #JGG #JGG # Helper funtion to extract the class from an icon #JGG iconClass <- function(icon) { #JGG if (!is.null(icon)) icon$attribs$class #JGG } #JGG <file_sep>/YATAModels/R/IND_SMA.1.R source("R/IND_MA.R") IND_SMA.1 <- R6Class("IND_SMA.1", inherit=IND_MA, public = list( name="Media movil Threshold" ,symbol="SMAT" ) ,private = list( .parameters = list(range=7) ,.thresholds = list(buy=3.0,sell=3.0) ) ) <file_sep>/YATAWeb/ui/partials/modTrading/modBuyServer.R modBuy <- function(input, output, session, id) { useShinyjs() vars <- reactiveValues( loaded = F ,opers = YATAOperation$new() ) ####################################################################### # Private Code ####################################################################### loadPage = function() { updateSelectInput(session, "cboCamera", choices=comboClearings(FALSE)) updateSelectInput(session, "cboCTC", choices=comboCurrencies()) } validateForm = function() { NULL } cleanForm = function() { } ####################################################################### # Server Code ####################################################################### if (!vars$loaded) loadPage() observeEvent(input$cboCamera, { if (nchar(input$cboCamera) == 0) return (NULL) updateSelectInput(session, "cboBase", choices=comboBases(input$cboCamera)) }) observeEvent(input$btnOK, { msg = validateForm() if (!is.null(msg)) { output$lblStatus <- renderText(paste("<span class='msgErr'>", msg, "</span>")) return (NULL) } browser() idOper = vars$opers$add(10, input$cboCamera, input$cboBase, input$cboCTC, input$impAmount , input$impProposal, input$impLimit, input$impStop) output$lblStatus = renderText(paste("<span class='msgOK'>", getMessage("OK.OPER", idOper), "</span>")) }) }<file_sep>/YATAModels/R/IND_MaxMin.R library(R6) IND_MaxMin <- R6Class("IND_MaxMin", inherit=YATAIndicator, public = list( name="Maximos y minimos" ,symbolBase="MM" ,symbol="MM" ,getDescription = function() { private$makeMD() } ,calculate = function(data) { browser() } # ,calculateAction = function(case, portfolio) { # lInd = self$getIndicators() # ind = lInd[[self$symbol]] # dfi = as.data.frame(ind$result[[1]]) # dft = case$tickers$df # # fila = case$current # pCurrent = dft[fila, DF_PRICE] # pInd = dfi[fila, 1] # # if (is.na(pInd) || pInd == 0 || pCurrent == pInd) return (c(0,100,100)) # # var = pCurrent / pInd # if (var == 1) return (c(0,100,100)) # # prf = case$profile$profile # thres = ifelse(var > 1,private$thresholds[["sell"]],private$thresholds[["buy"]]) # action = applyThreshold(prf, var, thres) # action # } # ,calculateOperation = function(portfolio, case, action) { # reg = case$tickers$df[case$current,] # cap = portfolio$saldo() # pos = portfolio$getActive()$position # sym = case$config$symbol # # # Por temas de redondeo, el capital puede ser menor de 0 # if (action[1] > 0 && cap > 1) return (YATAOperation$new(sym, reg[1,DF_DATE], cap, reg[1,DF_PRICE])) # if (action[1] < 0 && pos > 0) return (YATAOperation$new(sym, reg[1,DF_DATE], pos * -1, reg[1,DF_PRICE])) # NULL # } ,initialize = function(parms=NULL,thres=NULL) { super$initialize(parms,thres) } ) ,private = list( makeMD = function() { lines = c( "Muestra los maximos y minimos relativos" ) data = "" for (line in lines) { data = paste(data, line, sep="\n") } data } ,maxmin = function(data, extreme=T) { df = data$df[,data$PRICE] Mm = rollapply(df,3,FUN=.detect_max_min,fill=0,align="center") # Tratamiento de infinitos if (sum(Mm == Inf) > 0) Mm <- process_inf(df,Mm,which(Mm == Inf), "left") if (sum(Mm == -Inf) > 0) Mm <- process_inf(df,Mm,which(Mm == -Inf), "right") list(Mm) } # Los maximos son para un rango dado, aquellos por encima del mayor de los minimos # Lo minimos a la inversa # Si dos de lostres puntos son iguales, devuelve +/- Inf para procesarlos despues ,.detect_max_min = function(x) { if (x[2] > x[1] && x[2] > x[3]) return( x[2]) if (x[2] < x[1] && x[2] < x[3]) return(-x[2]) if (x[2] == x[1]) { if (x[2] > x[3]) return(+Inf) if (x[2] < x[3]) return(-Inf) } if (x[2] == x[3]) { if (x[2] > x[1]) return(+Inf) if (x[2] < x[1]) return(-Inf) } return(0) } # Detecta los maximos y minimos relativos # En caso de alineacion, se marca el especificado en align ,process_inf = function(data, Mm, rows, align) { beg = rows[1] end = rows[2] left = data[beg - 1,1] i = 2 while ( i <= length(rows)) { if (i < length(rows) && (rows[i] - rows[i - 1]) == 1) { end = rows[i] } else { Mm[beg:end] = 0 if (rows[i] < length(Mm)) { right = data[end + 1,1] val = 0 if (left < data[beg,1] && data[beg,1] > right) val = data[beg,1] if (left > data[beg,1] && data[beg,1] < right) val = data[beg,1] * -1 if (val != 0) { if (align == "left") { Mm[beg] = val } else { Mm[end] = val } } } beg=rows[i] } i = i + 1 } Mm } ,MaxMin2 = function(data) { data$Mm = rollapply(c(data$precio, data$Mm),4,function(x, y) {detect_max_min(x)} ,fill=0,align="right",by.column=T) data } ) ) <file_sep>/YATAModels/R/IND_MACD.R source("R/IND_Oscillator.R") IND_MACD <- R6Class("IND_MACD", inherit=IND_Oscillator, public = list( name="Convergence-Divergence Average Mobile" ,symbol="MACD" ,initialize = function() { super$initialize() } ,calculate = function(TTickers, date) { applySign = function(x) { if (sign(x[2]) == sign(x[1])) return (0) if (sign(x[1]) == -1) return (+1) return (-1) } nFast = self$getParameter("nfast") nSlow = self$getParameter("nslow") nSig = self$getParameter("nsig") maType = self$getParameter("matype", "EMA") prev = max(nFast, nSlow, nSig) xt = private$getXTS(TTickers, pref=prev) if (nrow(xt) < prev) return (NULL) tryCatch({ macd = TTR::MACD(xt[,TTickers$PRICE], nFast, nSlow, nSig, maType=maType) private$data = as.data.frame(macd[(prev + 1):nrow(macd),]) private$setDataTypes("number", c("macd", "signal")) private$calcVariation("macd") private$data[,"act"] = rollapply(private$data[,"var"], 2, applySign, fill=0, align="right") private$setColNames() } ,error = function(e) { return (NULL) } ) } # Dibuja sus graficos ,plot = function(p, TTickers) { if (!is.null(private$data)) { p = YATACore::plotBar (p, TTickers$df[,self$xAxis], private$data[,private$setColNames("macd")],hoverText=self$symbol) p = YATACore::plotLine(p, TTickers$df[,self$xAxis], private$data[,private$setColNames("signal")],hoverText=c(self$symbol, "Signal")) } p } ) ) <file_sep>/YATACore/R/R6_YATAActive.R YATAActive <- R6Class("YATAActive", private = list( opers = NULL # Operaciones ), public = list( name = NULL # Name looks like launch print ,position = 0.0 # Unidades ,balance = 0 # Valor ,last = 0.0 # Ultimo precio ,initialize = function(name) { if (missing(name)) stop(MSG_NO_NAME("Active")) self$name = name private$opers = TBLOperation$new() } ,addFlow = function(date = NULL, uds = NULL, price = NULL) { if (is.null(date) || is.null(uds) || is.null(price)) stop(MSG_BAD_ARGS()) private$opers$add(date, uds, price); self$position = self$position + uds self$balance = self$position * price invisible(self) } ,getOperations = function(value) { if (!missing(value)) stop(MSG_METHOD_READ_ONLY("Operations")) private$opers } ,getLastTrading = function(value) { if (!missing(value)) stop(MSG_METHOD_READ_ONLY("getLastTrading")) private$opers$getLast() } ,print = function() { cat(sprintf("%s:\t %f\n",self$name, self$position)) } ) ,active = list( movimientos = function(value) { if (!missing(value)) stop(MSG_METHOD_READ_ONLY("Flows")) as.data.frame(private$.opers[-1,]) } ) ) <file_sep>/YATAWeb/ui/modOnLineServer.R modOnLine <- function(input, output, session) { shinyjs::runjs(paste0("YATAPanels('", session$ns(""), "')")) sources = c("Last"=1, "Ask"=2, "Bid"=3, "High"=4, "Low"=5, "Volume"=6) type = c("Value"=1, "Last Change"=2, "Session Change"=3, "Day Change"=4) vars <- reactiveValues(loaded = F ,active = T # Is in mode auto update? ,interval = 1 # autoupdate in minutes ,count = 0 # Count of minutes ,points = 0 ,field = "LAST" ,plot = 1 ,tickers = NULL # R6YATATickers ,dfPlot = NULL # Dataframe for plot ,bases = NULL ,dfPlot = NULL # data for plot by tab ,dfTables = NULL # Items to show in plot by tab ,tab = NULL ,varField = "CLOSE" # Campo para mostrar mejores/peores ,varRows = 5 # Filas a mostrar ,varPrc = 5 # Porcentaje para highlight ,baseInfo = list() ) ######################################################################################## ### PRIVATE CODE ######################################################################################## loader <- function() { vars$tickers = YATATickers$new() if (vars$tickers$inError) return(NULL) bases = vars$tickers$getBases() updateMenuTab(session, "olMenu", choices=bases) vars$interval = input$mins # count = 1 # for (base in bases) { # sel = ifelse (count == 1, TRUE, FALSE) # count = count + 1 # appendTab(inputId = "tabs", # tabPanel(base,id=base,value=base # #,fluidRow(plotlyOutput(paste0(session$ns(""), "plot",base), width="98%",height="500px")) # # ,fluidRow( column(width=6, DT::dataTableOutput(paste0(session$ns(""), "tbl",base))) # # ,column(width=3, DT::dataTableOutput(paste0(session$ns(""), "tbl",base, "up"))) # # ,column(width=3, DT::dataTableOutput(paste0(session$ns(""), "tbl",base, "down"))) # # ) # ), select = sel) # } output$lblMins = renderText(vars$count) vars$loaded = T } filterColumns <- function(df, info) { df = df %>% filter(COUNTER %in% info$selected) if (!info$showBTC) df = df %>% filter(COUNTER != "BTC") if (is.null(info$rangeValue)) { info$rangeValue = c(min(df[,vars$tickers$LAST]), max(df[,vars$tickers$LAST])) } #JGG Pendiente #df = df %>% dplyr::filter(between(Last, info$rangeValue[1], info$rangeValue[2])) df } renderPlot <- function() { p <- plot_ly(source=vars$dfPlot) %>% layout (legend = list(orientation = 'h', xanchor="center", x=0.5)) cols = colnames(vars$dfPlot) for (ctc in cols[-1]) { # First col is TMS p = YATACore::plotMarker (p, vars$dfPlot[,1], vars$dfPlot[,ctc], hoverText=ctc) } p = p %>% layout(margin = list(l=50, r=0, b=5, t=5, pad=0)) p = YATACore::plotToolbar(p) output$plot = renderPlotly({p}) } prepareData <- function() { vars$tickers$setBase(vars$tab) tickers = vars$tickers info = vars$baseInfo[[vars$tab]] if (is.null(info)) info = createInfo(vars$tab) df = getDataFrame(tickers) df = filterColumns(df, info) vars$dfPlot = tidyr::spread(df[,c(tickers$TMS, tickers$COUNTER, vars$field)], tickers$COUNTER, vars$field) # Tabla general dfLast = filterColumns(vars$tickers$getLast(), info) t1 = makeTableTickers(dfLast, YATAENV$fiat$getDecimals(vars$tab)) # Tabla mejores tmp = dfLast[, c("COUNTER", "LAST", vars$varField)] colnames(tmp) = c("COUNTER", "LAST", "VAR") tmp1 = tmp[tmp$VAR >= 0,] tmp1 = tmp1[order(-tmp1$VAR),] tmp1[,3] = as.percentage(tmp1[,3]) t2 = datatable(tmp1[1:vars$varRows,], rownames = FALSE) t2 = .formatColumns(tmp1, t2, decFiat) #Tabla peores tmp1 = tmp[tmp$VAR <= 0,] tmp1 = tmp1[order(tmp1$VAR),] tmp1[,3] = as.percentage(tmp1[,3]) t3 = datatable(tmp1[1:vars$varRows,], rownames = FALSE) t3 = .formatColumns(tmp1, t3, decFiat) vars$dfTables = list(t1,t2,t3) } renderTab <- function() { prepareData() output$lblHeader = renderText(paste("Last update:", Sys.time())) renderPlot() output$tblData = DT::renderDataTable({ vars$dfTables[[1]] }) output$tblDataUp = DT::renderDataTable({ vars$dfTables[[2]] }) output$tblDataDown = DT::renderDataTable({ vars$dfTables[[3]] }) } getDataFrame <- function(tickers) { df = NULL idx = as.integer(input$graph) if (idx == 1) df = tickers$getTickers(reverse=F) if (idx == 2) df = tickers$getVarLast(reverse=F) if (idx == 3) df = tickers$getVarFirst(reverse=F) if (idx == 4) df = tickers$getVarSession(reverse=F) df } createInfo <- function(ctc) { counters = vars$tickers$getCounters() info = YATAOLInfo$new() info$base = vars$tab info$showBTC = TRUE info$choices = counters info$selected = counters vars$baseInfo = list.append(info) names(vars$baseInfo) = c(names(vars$baseInfo), ctc) info } updateRightBar <- function() { info = vars$baseInfo[[vars$tab]] updateSwitchInput(session, "swBTC",value = info$showBTC) updatePickerInput(session, "chkCTC", choices = info$choices, selected = info$selected) updateNoUiSliderInput(session, "sldRngVal", value = info$rangeValue) updateNoUiSliderInput(session, "sldRngPrc", value = info$rangePercentagge) } makeTableTickers = function(df, decFiat) { ranges = c(vars$varPrc * -1, vars$varPrc) colors = c('#FF0000', '', '#00e500') tmp = df # Remove auxiliar columns: EXC, TMS tmp[,c("BASE", "TMS")] = NULL dt = datatable(tmp, rownames = FALSE) dt = .formatColumns(tmp, dt, decFiat) dt = dt %>% formatStyle( 'VAR', target='cell', backgroundColor = styleInterval(ranges, colors)) dt = dt %>% formatStyle( 'SESSION', target='cell', backgroundColor = styleInterval(ranges, colors)) dt = dt %>% formatStyle( 'CLOSE', target='cell', backgroundColor = styleInterval(ranges, colors)) dt } if (!vars$loaded) loader() ######################################################################################## ### OBSERVERS ######################################################################################## observeEvent(input$olMenu, { if (nchar(input$olMenu) == 0) return (NULL) vars$tab = input$olMenu updateRightBar() renderTab() }) observeEvent(input$btnInfo, { shinyjs::runjs("iconNavJS(1)") info = vars$baseInfo[[input$tabs]] info$selected = input$chkCTC info$showBTC = input$swBTC info$rangeValue = input$sldRngVal info$rangePercentage = input$sldRngPrc }) observeEvent(input$btnConfig, { # Hay que guardarlos en las variables por que puede que no se # haya pulsado el boton pero si cambiado los valores shinyjs::runjs("YATAToggleSideBar(1, 0)") vars$interval = input$mins vars$tickers$setPoints(input$rows) vars$source = input$field vars$plot = input$graph vars$varField = input$rdoRange vars$varRows = input$sldRows vars$varPrc = input$sldVar renderPlot() }) observeEvent(input$btnCancel, { if (!vars$active) updateButton(session,paste0(session$ns(""),"btnCancel") ,label = " Stop subscription" ,icon = icon("remove") ,style = "danger") if (vars$active) updateButton(session,paste0(session$ns(""),"btnCancel") ,label = " Start subscription" ,icon = icon("clock") ,style = "success") vars$active = !vars$active shinyjs::runjs(paste0("toggleLabel('", session$ns(""), "main')")) shinyjs::runjs("iconNavJS(0)") }) observe({ if(!vars$active) return (NULL) invalidateLater(60000, session) # Update each minute isolate({ vars$count = vars$count - 1 if (vars$count <= 0) { vars$tickers$refresh() # Append data if (vars$loaded && !is.null(vars$tab)) renderTab() vars$count = vars$interval } output$lblMins = renderText(as.character(vars$count)) }) }) } <file_sep>/YATAModels/R/IND_SMA.0.R source("R/IND_MA.R") IND_SMA.0 <- R6Class("IND_SMA.0", inherit=IND_MA, public = list( name="Media movil simple" ,symbol="SMA" ) ) <file_sep>/YATAManualUser/04-conceptos.Rmd # Conceptos ## Precios __PMC__: Precio Medio Constante Dado un activo con una determinada posicion, es el precio al que se podria liquidar la posicion en moneda constante sin perdida de beneficio. El Precio Medio Constante para una activo _a_, se calcula como: $$PMC_a = \frac{\sum_{i=1}^{n}(V_i * P_i)}{Position_i}$$ __PMT__: Precio Medio Teorico Durante una simulación se intenta evaluar la rentabilidad de algun modelo cuantitativo, por lo que al finalizar el proceso,la posición de la cartera estará formada por una cierta cantidad no negativa en moneda fiduciaria (p.e. Euros) y al menos una posición no negativa en una criptomoneda. Si se efectua la valoración de la cartera al precio actual, el efecto seria el equivalente a deshacer la posición en esa(s) criptomoneda(s), lo cual seria incorrecto porque no se ha desecho la posición. Tampoco sería correcto aplicar el Precio Medio Constante, puesto que su efecto anularia la rentabilidad. Introudcimos el concepto ***Precio Medio Teorico (PMT)*** como un indicador para evaluar la situación teoria de una cartera en un momento dado considerando la inversión realizada en la(s) criptomoneda(s) como su precio de valoración. $$PMT_a = \frac{\sum_{i=1}^{n}P_i}{Position_i}$$ <file_sep>/YATAConfig/SQL/ctc_dat_providers.sql USE CTC; DELETE FROM PROVIDERS; INSERT INTO PROVIDERS (SYMBOL, NAME) VALUES ('POL', 'Poloniex' ); INSERT INTO PROVIDERS (SYMBOL, NAME) VALUES ('MKTCAP', 'CoinMarketCap' ); COMMIT; <file_sep>/YATAClient/YATAClient/src/main/java/com/jgg/yata/client/providers/ProviderPoloniex.java package com.jgg.yata.client.providers; import java.util.*; import java.util.Map.Entry; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.jgg.endpoint.http.HTTPSClient; import com.jgg.yata.client.pojos.*; public class ProviderPoloniex implements Provider { //private final String WSSBase = "wss://api2.poloniex.com"; private final String HTTPBase = "https://poloniex.com/public"; private final String TICKERS = "command=returnTicker"; @Override public Map<String, Ticker> getTickers() throws Exception { HTTPSClient client = new HTTPSClient(); String resp = client.getHttps(HTTPBase, TICKERS); return (mountTickers(resp)); } public Map<String, Market> getMarkets() throws Exception { HTTPSClient client = new HTTPSClient(); String resp = client.getHttps(HTTPBase, TICKERS); return (mountMarkets(resp)); } /** * La lista de pares es: * USDT-Moneda si cotiza * BTC-Moneda si no cotiza * @param resp */ private Map<String, Ticker> mountTickers(String resp) { List<CTCPair> lst = getPairList(resp); Map<String, Ticker> m = getTickers(lst, "USDT"); Ticker t = m.get("BTC"); return (addTickers(lst, m, "BTC", t.getLast())); } private Map<String, Market> mountMarkets(String resp) { return null; } private List<CTCPair> getPairList(String resp) { List<CTCPair> lst = new ArrayList<CTCPair>(); Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(resp).getAsJsonObject(); Iterator<Entry<String, JsonElement>> it = obj.entrySet().iterator(); while (it.hasNext()) { Entry<String, JsonElement> el = it.next(); CTCPair m = new CTCPair(); String toks[] = el.getKey().split("_"); m.setFrom(toks[0]); m.setTo(toks[1]); Ticker t = gson.fromJson(el.getValue(), Ticker.class); t.setSymbol(m.getTo()); m.setTicker(t); lst.add(m); } return lst; } private Map<String, Ticker> getTickers(List<CTCPair> lst, String base) { Map<String, Ticker> map = new HashMap<String, Ticker>(); for (CTCPair c : lst) { if (c.getFrom().compareTo(base) == 0) map.put(c.getTo(), c.getTicker()); } return map; } private Map<String, Ticker> addTickers(List<CTCPair> lst, Map<String, Ticker> m, String base, float price) { for (CTCPair c : lst) { if (c.getFrom().compareTo(base) == 0) { if (!m.containsKey(c.getTo()) ) { c.getTicker().convertToUSDT(price); m.put(c.getTo(), c.getTicker()); } } } return m; } } <file_sep>/YATACore/R/PKG_IO_XLS.R library(XLConnect) .XLSLoadModelGroups <- function(shName) { wbName = filePath(YATAENV$modelsDBDir, name=YATAENV$modelsDBName, ext="xlsx") XLSLoadSheet(wbName, shName) } .XLSLoadModelModels <- function(shName) { wbName = filePath(YATAENV$modelsDBDir, name=YATAENV$modelsDBName, ext="xlsx") XLSLoadSheet(wbName, shName) } .XLSLoadCTCIndex <- function(shName) { wbName = filePath(YATAENV$dataSourceDir, name=YATAENV$dataSourceDBName, ext="xlsx") XLSLoadSheet(wbName, shName) } .XLSLoadCTCTickers <- function(symbol) { xlcFreeMemory() fp = filePath(YATAENV$dataSourceDir, name=YATAENV$dataSourceDBName, ext="xlsx") df = XLConnect::readWorksheetFromFile(fp, symbol) df } .XLSloadCases <- function() { xlcFreeMemory() xx = filePath(YATAENV$dataSourceDir, name=DB_CASES, ext="xlsx") sh = XLConnect::readWorksheetFromFile(xx, TCASES_CASES, startRow=2) sh } XLSLoadSheet <- function(file,sheet,start=1) { XLConnect::readWorksheetFromFile(file, sheet) } ############################################################################3 .XLSsetSummaryFileName <- function(case) { fileName = .translateText(YATAENV$templateSummaryFile, case) file.path(YATAENV$outDir, paste(fileName, "xlsx", sep=".")) } .XLSsetSummaryFileData <- function(case) { .translateText(YATAENV$templateSummaryData, case) } <file_sep>/YATACore/R/TBL_Accounts.R TBLAccounts = R6::R6Class("TBLAccounts", inherit=YATATable, public = list( # Column names ID_CLEARING = "ID_CLEARING" ,ID_CURRENCY = "CURRENCY" ,NAME = "NAME" ,BALANCE = "BALANCE" ,CC = "CC" ,initialize = function() { self$name="Accounts"; self$table = "ACCOUNTS"; super$refresh() tctc = TBLCurrencies$new() tmp = tctc$df[, c(tctc$SYMBOL, tctc$NAME)] self$dfa = merge(self$dfa, tmp, by.x = self$ID_CURRENCY, by.y = tctc$SYMBOL) self$df = self$dfa } ,getCombo = function(clearing) { if (!is.null(clearing) && nchar(clearing) > 0) { df = self$df %>% filter(ID_CLEARING == clearing) setNames(df[, self$ID_CURRENCY], self$df[,self$NAME]) } } ) ,private = list ( ) ) <file_sep>/YATAModels/R/IND_Trend.R library(R6) IND_Trend <- R6Class("IND_Trend", inherit=IND__BASE, public = list( name="Linear trend" ,symbolBase="LT" ,symbol="LT" ,plot.attr = list( colors=c("#FF0000","#00FF00") ,sizes=c(1,2,3) ,styles=c("dashed", "dashed")) ,initialize = function(parms=NULL) { super$initialize(parms) } ,calculate = function(TTickers, date) { l = list(x=seq(1,nrow(TTickers$df),1),y=TTickers$df[,self$target]) df = as.data.frame(l, col.names=c("x","y")) private$model = lm(y ~ x, df) } ,plot = function(p, TTickers) { val = private$model %>% fitted.values() line.attr=list( color=self$plot.attr[["colors"]][1] , width=self$plot.attr[["sizes"]][1]) p = p %>% add_trace(x=TTickers$df[,self$xAxis], y=val, line=line.attr) p } # ,calculateAction = function(case, portfolio) { # lInd = self$getIndicators() # ind = lInd[[self$symbol]] # dfi = as.data.frame(ind$result[[1]]) # dft = case$tickers$df # # fila = case$current # pCurrent = dft[fila, DF_PRICE] # pInd = dfi[fila, 1] # # if (is.na(pInd) || pInd == 0 || pCurrent == pInd) return (c(0,100,100)) # # var = pCurrent / pInd # if (var == 1) return (c(0,100,100)) # # prf = case$profile$profile # thres = ifelse(var > 1,private$thresholds[["sell"]],private$thresholds[["buy"]]) # action = applyThreshold(prf, var, thres) # action # } # ,calculateOperation = function(portfolio, case, action) { # reg = case$tickers$df[case$current,] # cap = portfolio$saldo() # pos = portfolio$getActive()$position # sym = case$config$symbol # # # Por temas de redondeo, el capital puede ser menor de 0 # if (action[1] > 0 && cap > 1) return (YATAOperation$new(sym, reg[1,DF_DATE], cap, reg[1,DF_PRICE])) # if (action[1] < 0 && pos > 0) return (YATAOperation$new(sym, reg[1,DF_DATE], pos * -1, reg[1,DF_PRICE])) # NULL # } ) ,private = list( model = NULL ) ) <file_sep>/YATAModels/R/IND_VWAP.R source("R/IND_MA.R") IND_VWAPR <- R6Class("IND_VWAPR", inherit=IND_MA, public = list( name="Media movil simple" ,symbol="SMA" ) )
14627b56408f0a349e624ff6b50f6e90b0eb39ce
[ "SQL", "Markdown", "JavaScript", "Java", "R", "RMarkdown" ]
177
RMarkdown
Grandez/YATA
a944ce553c2386a1b68e2b10acd71d8154d84aeb
290b52c1428bb967a57d362cb7256fa090dd6926
refs/heads/master
<repo_name>czaplej/css-vars-2-ts<file_sep>/README.md # css-vars-2-ts [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/czaplej/css-vars-2-ts/blob/master/LICENSE.md) [![npm latest package](https://img.shields.io/npm/v/css-vars-2-ts/latest.svg)](https://www.npmjs.com/package/css-vars-2-ts) ### Generate typescript interfaces and constants from .css/.scss/.sass This library was generated with [Nx](https://nx.dev). <!-- TOC --> - [Installation](#installation) - [Usage](#usage) - [Options](#options) - [License](#license) <!-- /TOC --> ## Installation For the best CLI, we recommend installing `css-vars-2-ts` globally via `npm` or `yarn`: #### npm ```bash npm install -g css-vars-2-ts ``` #### yarn ```bash yarn global add css-vars-2-ts ``` or ```bash yarn add css-vars-2-ts -D ``` ## Usage ### Input `./vars.css` ```css body[data-theme='light'] { --colors-background: #fff; --colors-primary: #17a2b8; --colors-secondary: #798892; --colors-success: #43a047; --colors-info: #846eab; --colors-warning: #ffc247; --colors-danger: #f55d5d; --colors-dark: #3c484f; --colors-inverse: #495057; --colors-gray: #d6dee5; --colors-light: #f8f9fa; --colors-default: #e9ecef; --colors-primary-light: #dee4ee; --colors-success-light: #ecfaec; --colors-info-light: #f2fafa; --colors-warning-light: #fdf7e6; --colors-danger-light: #fff2ef; --colors-body-bg: #f8f9fa; --colors-white: #fff; --colors-gray-light: #f8f9fa; --colors-border-color: #c4c4c4; --colors-green-light: #00c853; --colors-disabled: #f3f3f3; --colors-textInfoBg: #f8cbd0; --colors-textInfoBorder: #a6a1a4; --colors-lineHeader: #7d7d7d; --lightness: 0.8; --spacing-gutter-vertical: 2.4rem; --spacing-gutter-horizontal: 2.4rem; --spacing-header-spacing-small: 0.5rem; --spacing-header-spacing-medium: 1rem; --spacing-header-spacing-large: 2rem; } body[data-theme='dark'] { --colors-background: #fff; --colors-primary: #17a2b8; --colors-secondary: #798892; --colors-success: #43a047; --colors-info: #846eab; --colors-warning: #ffc247; --colors-danger: #f55d5d; --colors-dark: #3c484f; --colors-inverse: #495057; --colors-gray: #d6dee5; --colors-light: #f8f9fa; --colors-default: #e9ecef; --colors-primary-light: #dee4ee; --colors-success-light: #ecfaec; --colors-info-light: #f2fafa; --colors-warning-light: #fdf7e6; --colors-danger-light: #fff2ef; --colors-body-bg: #f8f9fa; --colors-white: #fff; --colors-gray-light: #f8f9fa; --colors-border-color: #c4c4c4; --colors-green-light: #00c853; --colors-disabled: #f3f3f3; --colors-textInfoBg: #f8cbd0; --colors-textInfoBorder: #a6a1a4; --colors-lineHeader: #7d7d7d; --lightness: 0.2; --spacing-gutter-vertical: 2.4rem; --spacing-gutter-horizontal: 2.4rem; --spacing-header-spacing-small: 0.5rem; --spacing-header-spacing-medium: 1rem; --spacing-header-spacing-large: 2rem; } ``` ### Command ```bash css-vars-2-ts vars.css ``` ### Output `./vars-const.ts` ```ts export const themes = { light: { colors: { background: 'var(--colors-background)', primary: 'var(--colors-primary)', secondary: 'var(--colors-secondary)', success: 'var(--colors-success)', info: 'var(--colors-info)', warning: 'var(--colors-warning)', danger: 'var(--colors-danger)', dark: 'var(--colors-dark)', inverse: 'var(--colors-inverse)', gray: 'var(--colors-gray)', light: 'var(--colors-light)', default: 'var(--colors-default)', primaryLight: 'var(--colors-primary-light)', successLight: 'var(--colors-success-light)', infoLight: 'var(--colors-info-light)', warningLight: 'var(--colors-warning-light)', dangerLight: 'var(--colors-danger-light)', bodyBg: 'var(--colors-body-bg)', white: 'var(--colors-white)', grayLight: 'var(--colors-gray-light)', borderColor: 'var(--colors-border-color)', greenLight: 'var(--colors-green-light)', disabled: 'var(--colors-disabled)', textInfoBg: 'var(--colors-textInfoBg)', textInfoBorder: 'var(--colors-textInfoBorder)', lineHeader: 'var(--colors-lineHeader)', }, lightness: 'var(--lightness)', spacing: { gutterVertical: 'var(--spacing-gutter-vertical)', gutterHorizontal: 'var(--spacing-gutter-horizontal)', headerSpacingSmall: 'var(--spacing-header-spacing-small)', headerSpacingMedium: 'var(--spacing-header-spacing-medium)', headerSpacingLarge: 'var(--spacing-header-spacing-large)', }, }, dark: { colors: { background: 'var(--colors-background)', primary: 'var(--colors-primary)', secondary: 'var(--colors-secondary)', success: 'var(--colors-success)', info: 'var(--colors-info)', warning: 'var(--colors-warning)', danger: 'var(--colors-danger)', dark: 'var(--colors-dark)', inverse: 'var(--colors-inverse)', gray: 'var(--colors-gray)', light: 'var(--colors-light)', default: 'var(--colors-default)', primaryLight: 'var(--colors-primary-light)', successLight: 'var(--colors-success-light)', infoLight: 'var(--colors-info-light)', warningLight: 'var(--colors-warning-light)', dangerLight: 'var(--colors-danger-light)', bodyBg: 'var(--colors-body-bg)', white: 'var(--colors-white)', grayLight: 'var(--colors-gray-light)', borderColor: 'var(--colors-border-color)', greenLight: 'var(--colors-green-light)', disabled: 'var(--colors-disabled)', textInfoBg: 'var(--colors-textInfoBg)', textInfoBorder: 'var(--colors-textInfoBorder)', lineHeader: 'var(--colors-lineHeader)', }, lightness: 'var(--lightness)', spacing: { gutterVertical: 'var(--spacing-gutter-vertical)', gutterHorizontal: 'var(--spacing-gutter-horizontal)', headerSpacingSmall: 'var(--spacing-header-spacing-small)', headerSpacingMedium: 'var(--spacing-header-spacing-medium)', headerSpacingLarge: 'var(--spacing-header-spacing-large)', }, }, }; ``` `./vars-model.ts` ```ts export interface Themes { light: Light; dark: Light; } export interface Light { colors: Colors; lightness: string; spacing: Spacing; } export interface Spacing { gutterVertical: string; gutterHorizontal: string; headerSpacingSmall: string; headerSpacingMedium: string; headerSpacingLarge: string; } export interface Colors { background: string; primary: string; secondary: string; success: string; info: string; warning: string; danger: string; dark: string; inverse: string; gray: string; light: string; default: string; primaryLight: string; successLight: string; infoLight: string; warningLight: string; dangerLight: string; bodyBg: string; white: string; grayLight: string; borderColor: string; greenLight: string; disabled: string; textInfoBg: string; textInfoBorder: string; lineHeader: string; } ``` ### Options #### target A directory where the generated files are placed. Type: `string` Default: `./` #### targetName A file name for constant. Type: `string` Default: `{css-file-name}-const.ts` #### targetModelName A file name for interfaces. Type: `string` Default: `{css-file-name}-model.ts` #### help Show all available args. Type: `boolean` Default: `false` ## License The package is Open Source Software released under the [MIT licensed](LICENSE.md). <file_sep>/lib/check-help-arg.ts import { info } from './log-helper'; import chalk from 'chalk'; export function checkHelpArg(help: boolean) { if (help || !process.argv[2]) { info(`${chalk.bold("I'm glad that U started using css-vars-2-ts")}`); info('Available arguments:'); info('--help get information about all arguments'); info('--target A directory where the generated files are placed.'); info('--targetName A file name for constant.'); info('--targetModelName A file name for interfaces.'); info('For more information please check out github page'); throw ''; } } <file_sep>/lib/create-tmp-file.ts import fs from 'fs'; export function createTempFile(filePath: string) { if (fs.existsSync(filePath)) { return fs.readFileSync(filePath); } return undefined; } <file_sep>/lib/generate-files.ts import * as fs from 'fs'; import * as util from 'util'; import JsonToTS from 'json-to-ts'; import * as path from 'path'; import sass from 'node-sass'; import { createTempFile } from './create-tmp-file'; import { capitalizeFirstLetter } from './utils'; import { generateVariablesObject } from './generate-variables-object'; // special regex get from string all between curly brackets and between brackets FE: [data-theme=light] {...} const regex = /\[.*?\] {([^}]+)}/g; const regexGetCSSVariables = /--(.*)/g; const getThemeNameRegex = /\[(.*)]/g; export function generateFiles( filePath: string, targetPath: string, targetName = './generatedFile.ts', targetModelName = './generatedFileModel.ts' ) { const styles = sass.renderSync({ file: filePath }).css.toString(); let result = {}; const themes = styles.match(regex); for (const theme of themes) { const themeObject = {}; const nameOfTheme = theme .match(getThemeNameRegex)[0] .replace('[', '') .replace(']', '') .split('=')[1] .replace('"', '') .replace('"', '') .replace("'", '') .replace("'", ''); const vars = theme.match(regexGetCSSVariables).map((x) => x.split(':')[0]); themeObject[nameOfTheme] = {}; generateVariablesObject(themeObject[nameOfTheme], vars); result = { ...result, [nameOfTheme]: themeObject[nameOfTheme] }; } const [constTsFilePath, modelTsFilePath] = [ path.resolve(targetPath, targetName), path.resolve(targetPath, targetModelName), ]; const [tmpconstTsFile, tmpmodelTsFile] = [ createTempFile(constTsFilePath), createTempFile(modelTsFilePath), ]; // Generate out files fs.writeFile( constTsFilePath, `export const themes = ${util.inspect(result)}`, { encoding: 'utf8' }, (err) => { if (err) { throw err.message; } } ); fs.writeFile( modelTsFilePath, JsonToTS(result) .map((x) => x .replace('RootObject', 'Themes') .replace('interface', 'export interface') ) .join('\n'), { encoding: 'utf8' }, (err) => { if (err) { //Rollback previous file fs.writeFileSync(constTsFilePath, tmpconstTsFile); throw err.message; } } ); } <file_sep>/bin/css-vars-2-ts.ts #!/usr/bin/env node import yargs from 'yargs-parser'; import * as path from 'path'; import { generateFiles } from '../lib/generate-files'; import { error, success } from '../lib/log-helper'; import { checkHelpArg } from '../lib/check-help-arg'; try { const { target, targetName, targetModelName, help } = yargs( process.argv.slice(2) ); checkHelpArg(help); const filePath = path.resolve(process.cwd(), process.argv[2]); const targetPath = path.resolve(process.cwd(), target || './'); const { length } = filePath.split('/'); const fileName = filePath.split('/')[length - 1].split('.')[0]; generateFiles( filePath, targetPath, targetName || `${fileName}-const.ts`, targetModelName || `${fileName}-model.ts` ); success('Successfully generated files'); } catch (e) { error(e); } <file_sep>/lib/log-helper.ts import chalk from 'chalk'; export const { log } = console, error = (message: string) => log(chalk.red(message)), success = (message: string) => log(chalk.green(message)); export const info = (message: string) => log(chalk(message)); <file_sep>/lib/generate-variables-object.ts import { capitalizeFirstLetter } from './utils'; export function generateVariablesObject<T extends unknown>( obj: T, vars: string[] ) { for (const var1 of vars) { const [objectName, ...rest] = var1 .replace('-', '') .replace('-', '') .split('-'); const [first, ...capitalize] = rest; const capitalizedArr = capitalize.map((x) => capitalizeFirstLetter(x)); const valueName = [first, ...capitalizedArr].join(''); if (obj[objectName] !== undefined) { obj[objectName] = { ...obj[objectName], [valueName]: `var(${var1})` }; } else { if (!first) { obj[objectName] = `var(${var1})`; } else { obj[objectName] = { [valueName]: `var(${var1})` }; } } } }
fc334e4eb02e1107ffc70421578f5b2ebe6d6e8e
[ "Markdown", "TypeScript", "JavaScript" ]
7
Markdown
czaplej/css-vars-2-ts
3e68dabe44cc4908794e07d566c383e2206608b3
486e42ad41f606ac2eb6a76fdf5e39ad0d0c9390
refs/heads/master
<file_sep>'use strict'; const config = require('./config'); var express = require('express'); var smoochController = require('./controllers/smooch'); var app = express(); app.use('/api/', require('./api')); smoochController.setUpWebhook(app).then(() => { app.listen(config.get('PORT') || 3000); }); <file_sep>'use strict'; var nconf = require('nconf'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; var configFile = __dirname + '/' + process.env.NODE_ENV + '.json'; nconf.env() .file({ file: configFile }); module.exports = nconf;<file_sep># Pizzabot Ever had that silly idea of building an app for fun, but you don't want to build an interface for it and everything? If your idea is basic enough to accept an input and provide an output, then why don't you do that through a conversation, over SMS? Here's my silly idea : ever wondered how many pizzas you should order? Well, someone at [Gawker](http://gawker.com/how-many-pizzas-should-you-order-the-pizza-equation-wi-1697815579) came up with the basic math to do it and it works surprisingly well. Now, let's make that a service people can text and get their answer. By combining [Smooch](https://smooch.io?utm_source=pizzabot), [Twilio](https://twilio.com), and [api.ai](https://api.ai), you can do this quite easily. Smooch allows you a Twilio number to your server using webhooks. Smooch will send the message to your server everytime someone texts your Twilio number. With that message, the server forwards it to api.ai. Then, you can leverage the intents we previously created on api.ai to take action on these messages. api.ai has this really nice [dialog](https://docs.api.ai/docs/dialogs) feature that allows you to initiate a serie of questions to get answers. If a message triggers one of your intent, but didn't provide some of your required parameters, the dialog kicks in and start asking questions until the user provides the answer. When it's done, api.ai response marks the action as completed and gives you all the parameters you defined. At this point, you can take action on that. The concept of this server is pretty much : let api.ai do the talking and once it sends us a completed action, let's decide if it's actionable or not. For this server, I decided to let api.ai do the smalltalk and to handle pizza count calculations and bill splitting. From that point, it's really up to you to decide whatever action you should handle. Enough talk, just try it! Text something at (no longer in service) and see for yourself! This server basically need only these environment variables to run on Heroku : | Variable | Description | |--------- | ----------- | | HOST | URL of the server | | SMOOCH_KEYID | Smooch key Id (found in your Smooch app settings) | | SMOOCH_SECRET | Smooch secret (found right next to the key id) | | API_AI_SUBSCRIPTION_KEY | api.ai subscription key (found in your agent settings) | | API_AI_CLIENT_ACCESS | api.ai client access key (found right next to the subscription key) | <file_sep>'use strict'; class APIError extends Error { constructor(code, message) { super(); this.code = code; this.message = message; } } module.exports.APIError = APIError; let errors = { BadContentType: { code: 406, message: 'Request must sent JSON.' }, Unauthorized: { code: 401, message: 'Unauthorized.' }, UserEmailExists: { code: 409, message: 'User email already taken.' } }; Object.keys(errors).forEach(key => { let code = errors[key].code; let message = errors[key].message; module.exports[key] = class extends APIError { constructor() { super(code, message); } } });<file_sep>'use strict'; var jwt = require('jsonwebtoken'); var Smooch = require('smooch-core'); var urljoin = require('urljoin'); var config = require('../config'); var errors = require('../errors'); var aiController = require('./api-ai'); const webhookUrl = urljoin(config.get('HOST'), 'api/webhooks/smooch'); const core = new Smooch({ keyId: config.get('SMOOCH_KEYID'), secret: config.get('SMOOCH_SECRET'), scope: 'app' }); module.exports.setUpWebhook = (app) => { return core.webhooks.list() .then((response) => { console.log(response) let webhook = response && response.webhooks.find((w) => { return w.target === webhookUrl }); if (!webhook) { return core.webhooks.create({ target: webhookUrl }); } }).catch(console.log); }; module.exports.handleWebhook = (payload) => { return Promise.resolve().then(() => { console.log(payload); let message = payload.messages[0]; if (message.role === 'appUser') { return aiController.call(payload.appUser._id, message.text); } }); } module.exports.sendMessage = (userId, text, from, metadata) => { console.log('sending message', text) from || (from = { }); metadata || (metadata = { }); return core.conversations.sendMessage(userId, { text: text, role: 'appMaker', name: from.name || 'Pizzabot', avatarUrl: from.avatarUrl, metadata: metadata }); } <file_sep>'use strict'; var smoochController = require('../controllers/smooch'); module.exports.smooch = (req, res, next) => { smoochController.handleWebhook(req.body).catch(next).then(() => { res.end(); }); }; <file_sep>'use strict'; const config = require('../config'); const apiai = require('apiai'); const smoochController = require('./smooch'); const PIZZA_RATIO = 3.0 / 8.0; module.exports.call = (userId, message) => { const apiApp = apiai(config.get('API_AI_CLIENT_ACCESS'), config.get('API_AI_SUBSCRIPTION_KEY'), { sessionId: userId }); return new Promise((resolve, reject) => { let request = apiApp.textRequest(message); request.on('response', (response) => { console.log(response) let result = response.result; console.log(result); if (result.actionIncomplete) { smoochController.sendMessage(userId, result.fulfillment.speech); resolve(result); } else { handleAction(userId, result.action, result.parameters, result.fulfillment).then(() => { resolve(result); }); } }); request.on('error', (err) => { reject(err); }); request.end(); }); }; let handleAction = module.exports.handleAction = (userId, action, parameters, fulfillment) => { if (!action) { return; } if (action.startsWith('smalltalk.')) { return smoochController.sendMessage(userId, fulfillment.speech); } switch (action) { case 'compute_pizza_count': return handlePizzaCount(userId, parameters.count); case 'calculator.math': return smoochController.sendMessage(userId, parameters.result); case 'bill_split': return handleBillSplitting(userId, parameters.amount, parameters.people, parameters.tip); default: return smoochController.sendMessage(userId, 'I\'m sorry but I can\'t process what you are asking.'); } }; let handlePizzaCount = (userId, count) => { return Promise.resolve().then(() => { let message; count = +count; if (count === 0) { message = 'Hmmmm ok...'; } else if (count === 1) { message = 'A small pizza should do.' } else if (count === 2) { message = 'Two small or one medium should be enough.' } else { let largePizzas = Math.floor(count * PIZZA_RATIO); const modulo = count * PIZZA_RATIO - largePizzas; let extraPizza; if (modulo >= 0.5) { largePizzas += 1; } else if (modulo >= 0.2) { extraPizza = 'medium'; } else if (modulo > 0) { extraPizza = 'small'; } message = `You should order ${largePizzas} large pizza${largePizzas > 1 || largePizzas === 0 ? 's' : '' }`; if (extraPizza) { message += ` and maybe 1 ${extraPizza} pizza`; } message += '.'; } return smoochController.sendMessage(userId, message); }).catch(console.log); }; let handleBillSplitting = (userId, amount, people, tip) => { return Promise.resolve().then(() => { let fullAmount = amount * (1 + tip / 100); let parts = parseFloat(fullAmount / people).toFixed(2); return smoochController.sendMessage(userId, `That makes ${parts}$ each.`); }).catch(console.log); }
81bc42bbe4bde4ffa0d07f74b351f7c08835a90f
[ "JavaScript", "Markdown" ]
7
JavaScript
lemieux/pizzabot
32c1f2d6e33633c23e16bd7da9dfb36a4f6a3720
e1c72d321bf77a48dae0e9d4e933d16e83168636
refs/heads/master
<repo_name>julio1927/ICMKV2<file_sep>/src/App.js import React from "react"; import "./App.css"; import Layout from "./hoc/layout/Layout"; import ReactAux from "./hoc/ReactAux/ReactAux"; function App() { return ( <ReactAux> <Layout> <div className="App"> <h1>ICMK Website V2</h1> </div> </Layout> </ReactAux> ); } export default App;
879fac50a473ab3b0ef00d64844ad1b8fe975a7f
[ "JavaScript" ]
1
JavaScript
julio1927/ICMKV2
03889da277571039ad4ca6f5cde788768604094c
beb6b0e3e7c7cbb8250e2dbb5dce58b3e344b711
refs/heads/master
<repo_name>yonigev/PPLAss3.2<file_sep>/hw3-part3-tests.ts import * as assert from "assert"; import {evalParse4} from './L4-eval-box'; assert.deepEqual(evalParse4(` (L4 (define loop (lambda (x) (loop x))) ((lambda ((f lazy)) 1) (loop 0)))`), 1); assert.deepEqual(evalParse4(` (L4 (if ((lambda ((x lazy)) (= x 10)) 10) #t #f))`), true); assert.deepEqual(evalParse4(` (L4 (define loop (lambda (x) (loop x))) ((lambda ((f lazy)) 1) (loop 0)))`),1); assert.deepEqual(evalParse4(` (L4 (define f (lambda (a (b lazy)) a)) (f 1 (/ 1 0)))`),1); assert.deepEqual(evalParse4(` (L4 (define loop (lambda (x) (loop x))) ((lambda (x) ((lambda ((y lazy)) (if (= x 0) 1 y)) (loop 0)) )0))`),1);
a24836af7cf06081f2d087feaabd30c56cb15941
[ "TypeScript" ]
1
TypeScript
yonigev/PPLAss3.2
c7c4d45f8ec466e25ef1309e643fc287239cb510
c2202e5017e95331a2568984a52f95d54369b37a
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1.Count_Chars_in_a_String { class Program { static void Main(string[] args) { //string arr = Console.ReadLine(); //char[] nums = arr.ToCharArray(); char[] nums = Console.ReadLine().Where(x => x != ' ').ToArray(); var counts = new Dictionary<char, int>(); foreach (var num in nums) { if (counts.ContainsKey(num)) { counts[num]++; } else { counts[num] = 1; } } foreach (var num in counts) { Console.WriteLine($"{num.Key} -> {num.Value}"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2.A_Miner_Task { class Program { static void Main(string[] args) { var resoursec = new Dictionary<string, int>(); string resource = string.Empty; while ((resource = Console.ReadLine()) != "stop") { int quantity = int.Parse(Console.ReadLine()); if (!resoursec.ContainsKey(resource)) { resoursec[resource] = quantity; } else { resoursec[resource] = resoursec[resource] + quantity; } } foreach (var kvp in resoursec) { Console.WriteLine($"{kvp.Key} -> {kvp.Value}"); } } } }
2caba72bd6c213baf0f3e1c31fd965a80ce1d486
[ "C#" ]
2
C#
don-kokone/AssociativeArrays
6a2d3d417cb00588397809f1b5d106a63582c7f9
1baf231e69ec13a6bbfad5a276f6466a158e1849
refs/heads/master
<file_sep>FROM nkahoang/docker-v8js-php:php7.3-fpm-v8js7.9 COPY www.conf /usr/local/etc/php-fpm.d/www.conf WORKDIR /app #Install Matrix prereqs https://matrix.squiz.net/resources/requirements RUN apt update RUN apt install -y libxslt1-dev libpq-dev libpng-dev libpspell-dev libldap2-dev sudo ssh uuid-dev RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \ && docker-php-ext-install pdo pdo_pgsql pgsql RUN docker-php-ext-install xsl gd pspell intl ldap soap RUN pecl install -o -f redis \ && rm -rf /tmp/pear \ && echo "extension=redis.so" > /usr/local/etc/php/conf.d/redis.ini RUN pecl install -o -f uuid \ && rm -rf /tmp/pear \ && echo "extension=uuid.so" > /usr/local/etc/php/conf.d/uuid.ini RUN docker-php-ext-install pcntl #Copy matrix source into webroot COPY src /src COPY public /public #Copy preconfigured db config file and install script COPY install.sh /install.sh COPY db.inc /db.inc COPY initialise.php /initialise.php #CMD ["php-fpm", "--nodaemonize"] ENTRYPOINT ["/install.sh"] <file_sep>version: "3.4" services: db: build: context: "./db" restart: always environment: - DB_PASS=qqq - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} volumes: - db_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s timeout: 5s retries: 5 redis: image: redis # ports: # - "6380:6379" restart: always php: build: context: "./php" hostname: "cm_php" volumes: - "app_code:/app" depends_on: - "db" environment: - MATRIX_URL - FILE_BRIDGE_PATH nginx: build: context: "./nginx" hostname: "cm_nginx" ports: - "${HTTP_PORT:-80}:80" volumes: - "app_code:/app" depends_on: - "php" environment: PS1: "\\u@\\h:\\w\\$$ " networks: default: aliases: - ${MATRIX_URL} volumes: app_code: db_data: <file_sep>Any extensions here (`*.tgz`) will be installed. Available at https://marketplace.squiz.net/extensions Tested with: * Content API Extension * JSON Web Token Extension * Data Search Extension * Drop-in-apps Connector <file_sep>FROM nginx:1.15.8 COPY matrix-common /etc/nginx/matrix-common COPY gzip /etc/nginx/gzip COPY matrixdemo.conf /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/nginx.conf WORKDIR /app <file_sep>wget https://matrix.squiz.net/__data/assets/file/0030/37965/matrix-6.15.0.tgz mkdir source tar -xzf matrix-6.15.0.tgz -C source/ cd source/ npm install npm run build cd .. #copy the built source into the docker-compose set up, then delete the node_modules folder before building the images cp -R source/ php/src/ rm -rf php/src/source/node_modules/ #set up environment variables for domain and postgres password (required) echo MATRIX_URL=`ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'` > .env echo POSTGRES_PASSWORD=<PASSWORD> >> .env docker-compose up -d docker-compose logs -f #Wait for installation to complete, should see "NOTICE: ready to handle connections" <file_sep><?php $db_conf = array ( 'db' => array ( 'DSN' => 'pgsql:dbname=squiz_matrix host=db', 'user' => 'matrix', 'password' => 'qqq', 'type' => 'pgsql', ), 'db2' => array ( 'DSN' => 'pgsql:dbname=squiz_matrix host=db', 'user' => 'matrix', 'password' => 'qqq', 'type' => 'pgsql', ), 'db3' => array ( 'DSN' => 'pgsql:dbname=squiz_matrix host=db', 'user' => 'matrix_secondary', 'password' => 'qqq', 'type' => 'pgsql', ), 'dbcache' => NULL, 'dbsearch' => NULL, ); return $db_conf; ?> <file_sep>Files placed here are copied into data/public/ in the Matrix install. Useful for dropping directories to be used for a File Bridge asset. Use in conjunction with the FILE_BRIDGE_PATH env var to set <file_sep>#!/bin/bash set -e POSTGRES="psql --username ${POSTGRES_USER}" echo "Creating database: squiz_matrix" $POSTGRES <<EOSQL CREATE DATABASE squiz_matrix OWNER matrix; alter database squiz_matrix SET bytea_output TO 'escape'; EOSQL <file_sep>#!/bin/bash FILE=/app/data/private/system/.ssh/matrix_ssh_key.pub if [ -f "$FILE" ]; then echo 'Matrix already installed, skipping' else echo "$FILE does not exist" echo "Waiting 5 seconds to give postgres a chance to come up because docker-compose healthcheck appears to not actually work" sleep 5 echo 'Copying Matrix source to volume' #tar -xzf /src/matrix*.tgz -C /app/ cp -R /src/source/* /app #Remove exotic and extraneous packages that most people don't use. Comment out any lines you want to keep rm -rf /app/packages/ecommerce #rm -rf /app/packages/ldap rm -rf /app/packages/marketo rm -rf /app/packages/sharepoint #rm -rf /app/packages/sugar rm -rf /app/packages/trim #Extract all supplied extensions prior to installation find /src/packages/*.tgz -exec tar -xzf {} -C /app/ \; echo 'Installing'; php /app/install/step_01.php /app chown -R www-data:www-data /app cp /db.inc /app/data/private/conf/ cp /initialise.php /app/initialise.php sudo -u www-data php /app/initialise.php $MATRIX_URL sudo -u www-data php /app/install/step_02.php /app/ sudo -u www-data php /app/install/step_03.php /app/ echo "<?php define('FILE_BRIDGE_PATH', SQ_DATA_PATH.'$FILE_BRIDGE_PATH');?>" > data/private/conf/file_bridge.inc cp -r /public/* /app/data/public/ grep "SQ_CONF_SYSTEM_ROOT_URLS" /app/data/private/conf/main.inc fi php-fpm --nodaemonize <file_sep># docker-compose config for Squiz Matrix CMS version 6 ## Disclaimer This fairly shonky and intended for internal test and dev servers only. Do not use in production. This repo is for Squiz Matrix 6. For 5.5 use https://github.com/cjc/composed-matrix ## What is it? A docker-compose configuration to quickly run up an instance of Squiz Matrix CMS: * Suports Matrix 6.15+ (last tested with 6.15) * PHP 7.3 with V8js support * Postgres DB container * Redis session storage * Supports automatic installation of extensions on startup * Cut down "core" Matrix with old extensions removed * bulkmail * ecommerce * ~~ldap~~ (Not removed for V6 because the new `application_monitoring` package depends on it * marketo * sharepoint * ~~sugar~~ (Not removed anymore because User has a hard dependency on it :disappointed:) * trim ## tl;dr ```bash git clone <EMAIL>:cjc/composed-matrix-6.git cd composed-matrix-6 ./tldr.sh ``` ## Application code This repo doesn't contain the code for Matirx, you need to download it and any extensions you want. For version 6 you'll need to extract and run `npm install && npm run build` ``` php/src/source/... php/src/packages/json_web_token.tgz php/src/packages/dropinapps_connector-1.0.3.tgz php/src/packages/data_search.tgz php/src/packages/content_api.tgz ``` ## Extension support Matrix extensions from https://marketplace.squiz.net/extensions can be installed by dropping the tgz file into `php/src/packages`. Tested with Content API and JSON Web Token. ## Containers * webserver - based on `nginx` * application - based on `nkahoang/docker-v8js-php:php7.3-fpm-v8js7.9` * database - based on `postgres:latest` * session storage - `redis` <file_sep><?php ini_set('memory_limit', -1); error_reporting(E_ALL); $SYSTEM_ROOT = '/app'; require_once $SYSTEM_ROOT.'/core/include/init.inc'; require_once SQ_INCLUDE_PATH.'/system_config.inc'; $URL = $_SERVER['argv'][1]; $GLOBALS['SQ_SYSTEM']->getKernel()->setInstalling(true); $GLOBALS['SQ_SYSTEM']->setRunLevel(SQ_RUN_LEVEL_FORCED); $cfg = new System_Config(); $cfg->save(Array(), FALSE); $vars['SQ_CONF_SYSTEM_ROOT_URLS'] = $URL; $vars['SQ_CONF_ALLOW_IP_CHANGE'] = '1'; $cfg->save($vars); echo "Matrix config initialised.\n"; ?> <file_sep>#!/bin/bash set -e POSTGRES="psql --username ${POSTGRES_USER}" echo "Creating database roles: matrix, matrix_secondary" $POSTGRES <<-EOSQL CREATE USER matrix WITH CREATEDB PASSWORD '${DB_PASS}'; CREATE USER matrix_secondary WITH CREATEDB PASSWORD '${DB_PASS}'; EOSQL <file_sep>Place a copy of the matrix source here as `matrix*.tgz`, available from https://matrix.squiz.net/releases/vm
b049789de2fad76c8bc44860d080c2da0e120e48
[ "YAML", "Markdown", "PHP", "Dockerfile", "Shell" ]
13
Dockerfile
cjc/composed-matrix-6
879ce78728c7553f542d5a40031a0ffee8a11d30
93b376f35998d4d52d451b740382a9fead29bf6f
refs/heads/master
<repo_name>aRusenov/Team--Harper-Lee-<file_sep>/Game/Game/MovingUnit.cs  using System; namespace Game { public class MovingUnit: GameUnit { public Point Speed { get; protected set; } // Moving coordinates public MovingUnit(Point topLeft, char[,] body, Point speed, ConsoleColor color=ConsoleColor.White) : base(topLeft, body, color) { this.Speed = speed; } protected virtual void UpdatePosition() { this.TopLeftCoords += this.Speed; } public override void Move() { this.UpdatePosition(); } } } <file_sep>/Game/Game/GameProgram.cs namespace Game { using System; using System.Threading; class GameProgram { const int WorldRows = 30; const int WorldCols = 60; //const int RacketLength = 6; static void Initialize(Engine engine) { char[,] hero = ImageProducer.GetImage(@"..\..\images\hero.txt"); Player player = new Player(new Point(20, 10), hero); engine.AddPlayer(player); char[,] cat = ImageProducer.GetImage(@"..\..\images\cat.txt"); for (int i = 0; i < 5; i++) { Enemy enemy = new Enemy(new Point(5, 10*(i+1)), cat, new Point(0, -1), ConsoleColor.Red); //Thread.Sleep(50); engine.AddObject(enemy); } } static void Main() { IConsoleRenderer renderer = new ConsoleRenderer(WorldRows, WorldCols); IUserInterface keyboard = new KeyboardInterface(); Engine gameEngine = new Engine(renderer, keyboard); keyboard.OnLeftPressed += (sender, eventInfo) => { gameEngine.MovePlayerLeft(); }; keyboard.OnRightPressed += (sender, eventInfo) => { gameEngine.MovePlayerRight(); }; keyboard.OnUpPressed += (sender, eventInfo) => { gameEngine.MovePlayerUp(); }; keyboard.OnDownPressed += (sender, eventInfo) => { gameEngine.MovePlayerDown(); }; Initialize(gameEngine); gameEngine.Run(); } } } <file_sep>/Game/Game/IConsoleRenderer.cs using System; using System.Collections.Generic; namespace Game { public interface IConsoleRenderer { void ReDraw(IObjectRenderable obj, bool something); void WriteOnPosition( string text, Point topLeft, int width, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Black); void DrawTextBoxTopLeft( string text, int left = 0, int top = 0, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Black); void ClearDestroyedObjects(List<GameUnit> destroyedObjects); } } <file_sep>/Game/Game/IObjectRenderable.cs using System; namespace Game { public interface IObjectRenderable { Point GetTopLeftCoords(); char[,] GetImage(); ConsoleColor ImageColor { get; set; } } } <file_sep>/Game/Game/Engine.cs namespace Game { using System; using System.Collections.Generic; using System.Threading; public class Engine { private IConsoleRenderer renderer; // Console printer private IUserInterface userInterface; //event handler private List<MovingUnit> movingObjects; // add moving objects private List<GameUnit> staticObjects; //static private List<GameUnit> allObjects; //list with all objects on the screne private Player player; //player public Engine(IConsoleRenderer renderer, IUserInterface userInterface) { this.renderer = renderer; this.userInterface = userInterface; this.staticObjects = new List<GameUnit>(); this.movingObjects = new List<MovingUnit>(); this.allObjects = new List<GameUnit>(); } private void AddStaticObject(GameUnit obj) { this.staticObjects.Add(obj); this.allObjects.Add(obj); } private void AddMovingObject(MovingUnit obj) { this.movingObjects.Add(obj); this.allObjects.Add(obj); } public void AddPlayer(GameUnit obj) { //first remove old player from the list this.player = obj as Player; GameUnit foundUnit = allObjects.Find(x => x.GetTopLeftCoords() == player.GetTopLeftCoords()); allObjects.Remove(foundUnit); this.player = obj as Player; //add the new player this.AddStaticObject(obj); } public virtual void MovePlayerLeft() { this.player.MoveLeft(); // move player left } public virtual void MovePlayerRight() { this.player.MoveRight(); // move player right } public virtual void MovePlayerDown() { this.player.MoveDown(); } public virtual void MovePlayerUp() { this.player.MoveUp(); } public virtual void AddObject(GameUnit obj) { if (obj is MovingUnit) { this.AddMovingObject(obj as MovingUnit); } else { if (obj is Player) { AddPlayer(obj); } else { this.AddStaticObject(obj); } } } public virtual void Run() { Sounds.SFX(Sounds.SoundEffects.Move); while (true) { Thread.Sleep(300); this.userInterface.ProcessInput(); // process event from the console //Print health points of the player this.renderer.WriteOnPosition("HP: " + (player.HealthPoints / 10)+"%", new Point(1, 0), 8); this.renderer.WriteOnPosition(new string('\u2588', player.HealthPoints / 10), new Point(1, 8), 10, ConsoleColor.Red, ConsoleColor.White); //Print all game units and move them if necessary foreach (var obj in this.allObjects) { this.renderer.ReDraw(obj, true); obj.Move(); this.renderer.ReDraw(obj, false); } CollisionDispatcher.HandleCollisions(this.movingObjects, this.staticObjects); // handle all collisions //collect all destroyed objects List<GameUnit> destroyedObjects = allObjects.FindAll(obj => obj.IsDestroyed); this.allObjects.RemoveAll(obj => obj.IsDestroyed); this.movingObjects.RemoveAll(obj => obj.IsDestroyed); this.staticObjects.RemoveAll(obj => obj.IsDestroyed); this.renderer.ClearDestroyedObjects(destroyedObjects); // clear all destroyed objects } } } } <file_sep>/Game/Game/Player.cs using System; namespace Game { public class Player:GameUnit,ICollidable { public new const string CollisionGroupString = "player"; public int HealthPoints {get; set;} private int currTopLeftRow; private int currTopLeftCol; public Player(Point topLeft, char[,] image, ConsoleColor color = ConsoleColor.Magenta) : base(topLeft, image, color) { this.image = image; currTopLeftRow = topLeft.Row; currTopLeftCol = topLeft.Col; this.HealthPoints = 100; } public override char[,] GetImage() { char[,] newImage = new char[this.image.GetLength(0), this.image.GetLength(1)]; for (int row = 0; row < newImage.GetLength(0); row++) { for (int col = 0; col < newImage.GetLength(1); col++) { newImage[row,col] = this.image[row,col]; } } return this.image; } public void MoveLeft() { currTopLeftCol--; } public void MoveRight() { currTopLeftCol++; } public void MoveUp() { currTopLeftRow--; } public void MoveDown() { currTopLeftRow++; } public override string GetCollisionGroupString() { return Player.CollisionGroupString; } public override bool CanCollideWith(string otherCollisionGroupString) { return otherCollisionGroupString == "wall" || otherCollisionGroupString == Player.CollisionGroupString || otherCollisionGroupString == "enemy"; } public override void RespondToCollision(CollisionData collisionData) { if (collisionData.CollisionForceDirection.Row * this.currTopLeftRow < 0) { // .... } if (collisionData.CollisionForceDirection.Col * this.currTopLeftCol < 0) { //...... } if (collisionData.hitObjectsCollisionGroupStrings.Contains("enemy")) { this.HealthPoints -= 10; } } public override void Move() { if (this.currTopLeftRow<0) { this.currTopLeftRow = 0; } if (this.currTopLeftCol<0) { this.currTopLeftCol = 0; } this.TopLeftCoords = new Point(currTopLeftRow, currTopLeftCol); } } } <file_sep>/Game/Game/ICollidable.cs using System.Collections.Generic; namespace Game { public interface ICollidable { bool CanCollideWith(string objectType); List<Point> GetCollisionProfile(); void RespondToCollision(CollisionData collisionData); string GetCollisionGroupString(); } } <file_sep>/Game/Game/Enemy.cs using System; namespace Game { public class Enemy : MovingUnit { public new const string CollisionGroupString = "enemy"; public Enemy(Point topLeft, char[,] image, Point speed, ConsoleColor color) : base(topLeft, image, speed, color) { } public override bool CanCollideWith(string otherCollisionGroupString) { return otherCollisionGroupString == "player" || otherCollisionGroupString == "enemy"; } public override string GetCollisionGroupString() { return Enemy.CollisionGroupString; } public override void RespondToCollision(CollisionData collisionData) { if (collisionData.CollisionForceDirection.Row * this.Speed.Row < 0) { this.Speed.Row = 1; } if (collisionData.CollisionForceDirection.Col * this.Speed.Col < 0) { this.Speed.Col = 0; } if (collisionData.hitObjectsCollisionGroupStrings.Contains("enemy")) { //this.Speed.Row = 1; //this.Speed.Col = 0; } else { this.isDestroyed = true; } } public override void Move() { if (this.topLeftCoords.Row<1) { this.Speed.Row = 1; } if (this.topLeftCoords.Col < 1) { this.Speed.Col = 0; } this.UpdatePosition(); } } } <file_sep>/Game/Game/Point.cs namespace Game { public class Point { public int Row { get; set; } public int Col { get; set; } public Point(int row, int col) { this.Row = row; this.Col = col; } public static Point operator +(Point a, Point b) { return new Point(a.Row + b.Row, a.Col + b.Col); } public static Point operator -(Point a, Point b) { return new Point(a.Row - b.Row, a.Col - b.Col); } public override bool Equals(object obj) // So two point can be compared { Point objAsMatrixCoords = obj as Point; return objAsMatrixCoords.Row == this.Row && objAsMatrixCoords.Col == this.Col; } public override int GetHashCode() { return base.GetHashCode(); } } } <file_sep>/Game/Game/IObjectProducer.cs using System.Collections.Generic; namespace Game { public interface IObjectProducer { IEnumerable<GameUnit> ProduceObjects(); } } <file_sep>/Game/Game/Sounds.cs namespace Game { using System; using System.IO; using System.Media; using System.Threading; public static class Sounds { public enum SoundEffects { Move, EnemyIsDestroyed, BossIsDestroyed, RecieveBonus, GameOver } static int[,] musicSheet; public static void SFX(SoundEffects sfx) { switch (sfx) { case SoundEffects.Move: PlaySoundFromFile(@"..\..\music\music.wav"); break; } } private static void PlaySoundFromFile(string filePath) { using (SoundPlayer player = new SoundPlayer(filePath)) { player.Play(); } } public static void Music() { if (File.Exists(@"..\..\music.mus")) { StreamReader musicFile = new StreamReader(@"..\..\music.mus"); LoadMusicFromFile(musicFile); } else if (File.Exists(@"music.mus")) { StreamReader musicFile = new StreamReader(@"music.mus"); LoadMusicFromFile(musicFile); } else { throw new FileNotFoundException(); } new Thread(() => SomeMusic()).Start(); } static void LoadMusicFromFile(StreamReader loadMusic) { int lines = int.Parse(loadMusic.ReadLine()); musicSheet = new int[lines, 2]; for (int i = 0; i < lines; i++) { string[] musicLine = loadMusic.ReadLine().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); musicSheet[i, 0] = int.Parse(musicLine[0]); musicSheet[i, 1] = int.Parse(musicLine[1]); } } public static void SomeMusic() { while (true) { for (int line = 0; line < musicSheet.GetLength(0); line++) { if (musicSheet[line, 1] != 0) { Console.Beep(musicSheet[line, 0], musicSheet[line, 1]); } else { Thread.Sleep(musicSheet[line, 0]); } } } } } } <file_sep>/Game/Game/ConsoleRenderer.cs using System; using System.Collections.Generic; using System.Text; namespace Game { public class ConsoleRenderer: IConsoleRenderer { int renderFieldMatrixRows; int renderFieldMatrixCols; char[,] renderGameFieldMatrix; public void WriteOnPosition( string text, Point topLeft, int width, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Black) { Console.SetCursorPosition(topLeft.Col, topLeft.Row); Console.ForegroundColor = foregroundColor; Console.BackgroundColor = backgroundColor; int countEmptySpaces = width - text.Length; Console.Write(text + new string(' ', countEmptySpaces>=0?countEmptySpaces:0)); } public static void WriteOnPosition( char character, int left = 0, int top = 0, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Black) { Console.SetCursorPosition(left, top); Console.ForegroundColor = foregroundColor; Console.BackgroundColor = backgroundColor; Console.Write(character); } public void DrawTextBoxTopLeft( string text, int left = 0, int top = 0, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Black) { // ╔═════════╗ // ║Some Text║ // ╚═════════╝ WriteOnPosition('╔', left, top, foregroundColor, backgroundColor); WriteOnPosition('╗', left + text.Length + 1, top, foregroundColor, backgroundColor); WriteOnPosition('╚', left, top + 2, foregroundColor, backgroundColor); WriteOnPosition('╝', left + text.Length + 1, top + 2, foregroundColor, backgroundColor); WriteOnPosition('║', left, top + 1, foregroundColor, backgroundColor); WriteOnPosition('║', left + text.Length + 1, top + 1, foregroundColor, backgroundColor); WriteOnPosition(new string('═', text.Length), left + 1, top, foregroundColor, backgroundColor); WriteOnPosition(new string('═', text.Length), left + 1, top + 2, foregroundColor, backgroundColor); WriteOnPosition(text, left + 1, top + 1, foregroundColor, backgroundColor); } public ConsoleRenderer(int visibleConsoleRows, int visibleConsoleCols) { renderGameFieldMatrix = new char[visibleConsoleRows, visibleConsoleCols]; this.renderFieldMatrixRows = renderGameFieldMatrix.GetLength(0); this.renderFieldMatrixCols = renderGameFieldMatrix.GetLength(1); } public void ReDraw(IObjectRenderable obj, bool clear) { Console.CursorVisible = false; Console.ResetColor(); Console.ForegroundColor = obj.ImageColor; Point objTopLeftCoords = obj.GetTopLeftCoords(); int imageRows = obj.GetImage().GetLength(0); int imageCols = obj.GetImage().GetLength(1); int lastRow = Math.Min(objTopLeftCoords.Row + imageRows, this.renderFieldMatrixRows); int lastCol = Math.Min(objTopLeftCoords.Col + imageCols, this.renderFieldMatrixCols); for (int row = obj.GetTopLeftCoords().Row; row < lastRow; row++) { for (int col = obj.GetTopLeftCoords().Col; col < lastCol; col++) { Console.SetCursorPosition(col,row); if (clear) { Console.Write(' '); } else { Console.Write(obj.GetImage()[row - obj.GetTopLeftCoords().Row, col - obj.GetTopLeftCoords().Col]); } } } } public void ClearDestroyedObjects(List<GameUnit> destroyedObjects) { foreach (var obj in destroyedObjects) { Point objTopLeftCoords = obj.GetTopLeftCoords(); int imageRows = obj.GetImage().GetLength(0); int imageCols = obj.GetImage().GetLength(1); int lastRow = Math.Min(objTopLeftCoords.Row + imageRows, this.renderFieldMatrixRows); int lastCol = Math.Min(objTopLeftCoords.Col + imageCols, this.renderFieldMatrixCols); for (int row = obj.GetTopLeftCoords().Row; row < lastRow; row++) { for (int col = obj.GetTopLeftCoords().Col; col < lastCol; col++) { Console.SetCursorPosition(col,row); Console.Write(' '); } } } } private static void WriteOnPosition( string text, int left = 0, int top = 0, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Black) { Console.SetCursorPosition(left, top); Console.ForegroundColor = foregroundColor; Console.BackgroundColor = backgroundColor; Console.Write(text); } } }
46bca47ae92d9cd5fa35ba8ce3e86992d9366669
[ "C#" ]
12
C#
aRusenov/Team--Harper-Lee-
2cec92721583dc85ffdbcd250e4ce249f35b7625
50a51ec2d5f540e9e07b2e9d148b79b16bd196ef
refs/heads/master
<file_sep>import { Component, ChangeDetectorRef, ViewChild } from '@angular/core'; import { NavController, NavParams, Content } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; @Component({ selector: 'page-contact-us', templateUrl: 'contact-us.html', }) export class ContactUsPage { @ViewChild(Content) content: Content; @ViewChild('footerInput') footerInput; showToolbar: boolean = false; hasChange: boolean = false; kirimPesan: string = ""; userInput: any = {"email":"", "subject":"Feedback", "message":""} result:any = []; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common) { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } window.addEventListener('native.keyboardshow', (e) => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + 'px'; }); window.addEventListener('native.keyboardhide', () => { this.footerInput.nativeElement.style.bottom = '0'; }); } ionViewDidLoad() { } checkValue() { if (this.userInput.email.length >= 6 && this.userInput.message.length >= 6) { this.hasChange = true; } else { this.hasChange = false; } } send() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('subject', this.userInput.subject); postData.append('body', this.userInput.message); postData.append('name', this.result.name); postData.append('email', this.userInput.email); postData.append('type', 'feedback'); let userData = this.apiService.post("v1/feedback", postData); userData.subscribe((result) => { res = result; console.log(res); this.common.presentToast(res.data); this.userInput = {"email":"", "subject":"", "message":""} this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } scrollTop() { var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } } <file_sep>import { Component } from '@angular/core'; import { MenuController, NavController, Platform } from 'ionic-angular'; import { Common } from '../../providers/common/common'; import { WellcomePage } from '../wellcome/wellcome'; export interface Slide { title: string; description: string; image: string; } @Component({ selector: 'page-tutorial', templateUrl: 'tutorial.html', }) export class TutorialPage { slides: Slide[]; showSkip = true; dir: string = 'ltr'; showToolbar:boolean = false; constructor(public navCtrl: NavController, public menu: MenuController, public platform: Platform, public common: Common/*, private statusBar: StatusBar*/) { this.dir = platform.dir(); this.slides = [{ title: 'NAVIGASI LAHAN', description: 'Geser kiri atau kanan pada lahan akan membuka pilihan untuk lahan tersebut', image: 'assets/img/1.png', }, { title: 'PILIHAN LAHAN', description: 'dengan menekan tombol titik tiga pada sudut kanan lahan anda akan menemukan pilihan untuk lahan terpilih seperti menambahkan komoditas, mengubah, melihat bahkan menghapus', image: 'assets/img/2.png', }, { title: 'TUTORIAL III', description: 'DESKRIPSI TUTORIAL', image: 'assets/img/ica-slidebox-img-3.png', }]; if (localStorage.getItem('skipIntro')) { this.startApp(); } } ionViewDidLoad() { } startApp() { this.common.presentLoading(); localStorage.setItem('skipIntro', 'true'); setTimeout(() => this.toWelcomePage(), 0); } toWelcomePage() { this.navCtrl.setRoot(WellcomePage, {openPage: 1}, { animate: true, direction: 'forward' }); this.common.closeLoading(); } onSlideChangeStart(slider) { this.showSkip = !slider.isEnd(); } ionViewDidEnter() { // the root left menu should be disabled on the tutorial page this.menu.enable(false); //this.menu.close(); } ionViewWillLeave() { // enable the root left menu when leaving the tutorial page //this.menu.enable(true); } } <file_sep>import { Component, ChangeDetectorRef, ViewChild } from '@angular/core'; import { NavController, NavParams, Content } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; @Component({ selector: 'page-profile-edit', templateUrl: 'profile-edit.html', }) export class ProfileEditPage { @ViewChild(Content) content: Content; @ViewChild('footerInput') footerInput; showToolbar:boolean = false; hasChange: boolean = false; result:any = []; userData: any = []; user: any = {"nama":"", "email":"", "kontak":"", "gender":""}; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common) { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } window.addEventListener('native.keyboardshow', (e) => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + 'px'; }); window.addEventListener('native.keyboardhide', () => { this.footerInput.nativeElement.style.bottom = '0'; }); } ionViewDidLoad() { this.getMe(); } ionViewWillLoad() { } getMe() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let userData = this.apiService.post("v1/user/me", postData); userData.subscribe((result) => { this.userData = result['data']; this.user.nama = this.userData.nama; this.user.email = this.userData.email; this.user.kontak = this.userData.kontak; this.user.gender = this.userData.kelamin; }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); }); } back() { this.navCtrl.pop(); } save() { this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('nama', this.userData.nama); postData.append('email', this.userData.email); postData.append('kontak', this.userData.kontak); postData.append('gender', this.userData.kelamin); let userData = this.apiService.post("v1/user/profile", postData); userData.subscribe((result) => { console.log(result); this.navCtrl.pop().then(() => { this.navParams.get("callback")("1"); }); this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } scrollTop() { var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } checkValue() { if (this.user.nama != this.userData.nama || this.user.email != this.userData.email || this.user.kontak != this.userData.kontak || this.user.gender != this.userData.kelamin) { this.hasChange = true; } else { this.hasChange = false; } } } <file_sep>import { Component, ViewChild, ChangeDetectorRef } from "@angular/core"; import { NavController, NavParams, ToastController, MenuController, Content, Platform, Events, ModalController } from "ionic-angular"; import { Socket } from "ng-socket-io"; import { Observable } from "rxjs/Observable"; import { Http, Headers } from "@angular/http"; import { Common } from "../../providers/common/common"; import { OnlineListPage } from "../online-list/online-list"; @Component({ selector: "page-chat", templateUrl: "chat.html" }) export class ChatPage { @ViewChild(Content) content: Content; @ViewChild("messageInput") messageInput; @ViewChild("footerInput") footerInput; showToolbar: boolean = false; messages = []; nickname = ""; message = ""; to = "DaVchezt"; connected: boolean = false; typingMessage: any; typing = false; typingUser: any; constructor( public navCtrl: NavController, public navParams: NavParams, private socket: Socket, private toastCtrl: ToastController, public menu: MenuController, public ref: ChangeDetectorRef, platform: Platform, private http: Http, public common: Common, public events: Events, public modalCtrl: ModalController ) { let data = JSON.parse(localStorage.getItem('userData')); this.nickname = data.type == 1 ? "(Agronimis) " + data.name : data.name; // this.nickname = this.navParams.get("nickname"); // if (this.nickname == null) { // this.nickname = this.navParams.get("openTab"); // } if (platform.is("android")) { window.addEventListener("native.keyboardshow", e => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + "px"; }); window.addEventListener("native.keyboardhide", () => { this.footerInput.nativeElement.style.bottom = "56px"; }); } this.getStartTyping().subscribe(message => { if (message['from'] != this.nickname) { this.typing = true; this.typingUser = message['from']; } }); this.getStopTyping().subscribe(message => { if (message['from'] != this.nickname) { this.typing = false; this.typingUser = message['from']; } }); this.getMessages().subscribe(message => { if (message['from'] == this.nickname) { // console.log("OK"); } this.messages.push(message); this.scrollBottom(); }); } ionViewWillEnter() { this.messages = []; this.getData(); this.socket.emit('enter-room'); this.events.publish('read'); } ionViewWillLeave() { this.events.publish('unread'); window.addEventListener('native.keyboardshow', (e) => { console.log(e) }); window.addEventListener('native.keyboardhide', (e) => { console.log(e) }); this.socket.emit('leave-room'); } getData() { this.common.presentLoading(); this.http.get('http://localhost:8080/chat', { // this.http.get('https://agrifarm-server.herokuapp.com/chat', { headers: new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': "Bearer <KEY>" }) }).subscribe(data => { let object = data.json(); let messagesCount = object.count; this.messages = object.chats; if (messagesCount >= 5) { this.scrollBottom(); } // this.focus(); this.common.closeLoading(); }, (error) => { console.log(error); this.common.closeLoading(); }) } sendMessage() { this.messageInput.setBlur(); this.socket.emit('add-message', { text: this.message }); this.message = ''; this.socket.emit('stop-typing', { from: this.nickname }); this.socket.emit('new-message'); this.scrollBottom(); } getMessages() { let observable = new Observable(observer => { this.socket.on('message', (data) => { observer.next(data); }); }) return observable; } getUsers() { let observable = new Observable(observer => { this.socket.on('users-changed', (data) => { observer.next(data); }); }); return observable; } getStartTyping() { let observable = new Observable(observer => { this.socket.on('start_typing', (data) => { observer.next(data); }); }) return observable; } getStopTyping() { let observable = new Observable(observer => { this.socket.on('stop_typing', (data) => { observer.next(data); }); }) return observable; } isTyping(event) { if (event.keyCode == 13) return; this.socket.emit('start-typing', { form: this.nickname }); if (this.typingMessage) { clearTimeout(this.typingMessage); } this.typingMessage = setTimeout(() => { this.socket.emit('stop-typing', { form: this.nickname }); }, 2000); } scrollBottom() { var that = this; this.content.resize(); setTimeout(function() { that.content.scrollToBottom(); }, 300); } showToast(msg) { let toast = this.toastCtrl.create({ message: msg, duration: 2000, showCloseButton: true, closeButtonText: "OK" }); toast.present(); } relative_time = (date: number) => { if (!date) return; var now = new Date().getTime() / 1000; var elapsed = Math.round(now - date); if (elapsed <= 1) { return "Baru saja"; } var rounded, title; if (elapsed > 31104000) { rounded = elapsed / 31104000; title = "tahun"; } else if (elapsed > 2592000) { rounded = elapsed / 2592000; title = "bulan"; } else if (elapsed > 604800) { elapsed = elapsed / 604800; title = "minggu"; } else if (elapsed > 86400) { rounded = elapsed / 86400; title = "hari"; } else if (elapsed > 3600) { rounded = elapsed / 3600; title = "jam"; } else if (elapsed > 60) { rounded = elapsed / 60; title = "menit"; } else if (elapsed >= 1) { rounded = elapsed / 1; title = "detik"; } if (rounded > 1) { rounded = Math.round(rounded); return rounded + " " + title + " yang lalu"; } }; getHHMM = (t: number) => { let d = new Date(t * 1000); let h = d.getHours(); let m = d.getMinutes(); let a = ""; let ms = ""; if (h > 0 && h < 12) { a = "AM"; } else { if (h == 0) a = "AM"; else a = "PM"; } if (m < 10) ms = "0" + m; else ms = "" + m; return (h == 0 || h == 12 ? 12 : h % 12) + ":" + ms + " " + a; }; onScroll($event: any) { if ($event) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 20; this.ref.detectChanges(); } } onKeypress(event) { if (event.keyCode == 13) console.log("enter"); // console.log("keypress" + event.keyCode); } onKeyDown(event) { if (event.keyCode == 13) return; // console.log("keydown" + event.keyCode); } onKeyUp(event) { if (event.keyCode == 13) return; // console.log("keyup" + event.keyCode); } doRefresh(refresher) { this.messages = []; this.getData(); refresher.complete(); } viewOnline() { const modal = this.modalCtrl.create(OnlineListPage); modal.present(); modal.onDidDismiss((data) => { if (data) { this.messageInput.value += '@' + data + ' '; } }); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherProvider { // apiKey: string = "362a425ff7e7c587c4029ca3a6fb46e2"; apiKey: string = "<KEY>"; weatherURL: string = "http://api.openweathermap.org/data/2.5/weather"; forecastURL: string = "http://api.openweathermap.org/data/2.5/forecast"; weatherParams = { lat:null, lon:null, units:"metric", lang:"id", appid:this.apiKey }; forecastParams = { lat:null, lon:null, units:"metric", lang:"id", appid:this.apiKey }; request: Observable<any>; weatherIcons = { "200": { "label": "thunderstorm with light rain", "icon": "storm-showers" }, "201": { "label": "thunderstorm with rain", "icon": "storm-showers" }, "202": { "label": "thunderstorm with heavy rain", "icon": "storm-showers" }, "210": { "label": "light thunderstorm", "icon": "storm-showers" }, "211": { "label": "thunderstorm", "icon": "thunderstorm" }, "212": { "label": "heavy thunderstorm", "icon": "thunderstorm" }, "221": { "label": "ragged thunderstorm", "icon": "thunderstorm" }, "230": { "label": "thunderstorm with light drizzle", "icon": "storm-showers" }, "231": { "label": "thunderstorm with drizzle", "icon": "storm-showers" }, "232": { "label": "thunderstorm with heavy drizzle", "icon": "storm-showers" }, "300": { "label": "light intensity drizzle", "icon": "sprinkle" }, "301": { "label": "drizzle", "icon": "sprinkle" }, "302": { "label": "heavy intensity drizzle", "icon": "sprinkle" }, "310": { "label": "light intensity drizzle rain", "icon": "sprinkle" }, "311": { "label": "drizzle rain", "icon": "sprinkle" }, "312": { "label": "heavy intensity drizzle rain", "icon": "sprinkle" }, "313": { "label": "shower rain and drizzle", "icon": "sprinkle" }, "314": { "label": "heavy shower rain and drizzle", "icon": "sprinkle" }, "321": { "label": "shower drizzle", "icon": "sprinkle" }, "500": { "label": "light rain", "icon": "rain" }, "501": { "label": "moderate rain", "icon": "rain" }, "502": { "label": "heavy intensity rain", "icon": "rain" }, "503": { "label": "very heavy rain", "icon": "rain" }, "504": { "label": "extreme rain", "icon": "rain" }, "511": { "label": "freezing rain", "icon": "rain-mix" }, "520": { "label": "light intensity shower rain", "icon": "showers" }, "521": { "label": "shower rain", "icon": "showers" }, "522": { "label": "heavy intensity shower rain", "icon": "showers" }, "531": { "label": "ragged shower rain", "icon": "showers" }, "600": { "label": "light snow", "icon": "snow" }, "601": { "label": "snow", "icon": "snow" }, "602": { "label": "heavy snow", "icon": "snow" }, "611": { "label": "sleet", "icon": "sleet" }, "612": { "label": "shower sleet", "icon": "sleet" }, "615": { "label": "light rain and snow", "icon": "rain-mix" }, "616": { "label": "rain and snow", "icon": "rain-mix" }, "620": { "label": "light shower snow", "icon": "rain-mix" }, "621": { "label": "shower snow", "icon": "rain-mix" }, "622": { "label": "heavy shower snow", "icon": "rain-mix" }, "701": { "label": "mist", "icon": "sprinkle" }, "711": { "label": "smoke", "icon": "smoke" }, "721": { "label": "haze", "icon": "day-haze" }, "731": { "label": "sand, dust whirls", "icon": "cloudy-gusts" }, "741": { "label": "fog", "icon": "fog" }, "751": { "label": "sand", "icon": "cloudy-gusts" }, "761": { "label": "dust", "icon": "dust" }, "762": { "label": "volcanic ash", "icon": "smog" }, "771": { "label": "squalls", "icon": "day-windy" }, "781": { "label": "tornado", "icon": "tornado" }, "800": { "label": "clear sky", "icon": "sunny" }, "801": { "label": "few clouds", "icon": "cloudy" }, "802": { "label": "scattered clouds", "icon": "cloudy" }, "803": { "label": "broken clouds", "icon": "cloudy" }, "804": { "label": "overcast clouds", "icon": "cloudy" }, "900": { "label": "tornado", "icon": "tornado" }, "901": { "label": "tropical storm", "icon": "hurricane" }, "902": { "label": "hurricane", "icon": "hurricane" }, "903": { "label": "cold", "icon": "snowflake-cold" }, "904": { "label": "hot", "icon": "hot" }, "905": { "label": "windy", "icon": "windy" }, "906": { "label": "hail", "icon": "hail" }, "951": { "label": "calm", "icon": "sunny" }, "952": { "label": "light breeze", "icon": "cloudy-gusts" }, "953": { "label": "gentle breeze", "icon": "cloudy-gusts" }, "954": { "label": "moderate breeze", "icon": "cloudy-gusts" }, "955": { "label": "fresh breeze", "icon": "cloudy-gusts" }, "956": { "label": "strong breeze", "icon": "cloudy-gusts" }, "957": { "label": "high wind, near gale", "icon": "cloudy-gusts" }, "958": { "label": "gale", "icon": "cloudy-gusts" }, "959": { "label": "severe gale", "icon": "cloudy-gusts" }, "960": { "label": "storm", "icon": "thunderstorm" }, "961": { "label": "violent storm", "icon": "thunderstorm" }, "962": { "label": "hurricane", "icon": "cloudy-gusts" } }; constructor(public httpClient: HttpClient, public http: Http) { } getWeatherByCity(city: string) { return new Promise((resolve, reject) => { this.http.get(this.weatherURL, { params:{ q:city, units:"metric", lang:"id", appid:this.apiKey} }) .subscribe((res) => { resolve(res.json()); }, (err) => { reject(err); }); }); } getWeather(latitude: number, longitude: number) { this.weatherParams.lat = latitude; this.weatherParams.lon = longitude; return this.request = this.httpClient.get(this.weatherURL, { params: this.weatherParams }); } getForecast(latitude: number, longitude: number) { this.forecastParams.lat = latitude; this.forecastParams.lon = longitude; return this.request = this.httpClient.get(this.forecastURL, { params: this.forecastParams }); } } <file_sep>import { Component, ViewChild, ChangeDetectorRef } from "@angular/core"; import { NavController, NavParams, MenuController, Platform, Keyboard, Content, Events } from "ionic-angular"; import { Observable } from "rxjs/Observable"; import { Api } from "../../providers/api/api"; import { Common } from "../../providers/common/common"; import { RegisterPage } from "../register/register"; import { DashboardTabsPage } from "../dashboard-tabs/dashboard-tabs"; @Component({ selector: "page-login", templateUrl: "login.html" }) export class LoginPage { @ViewChild(Content) content: Content; @ViewChild("inputPassword") inputFocus; result: any = []; data: Observable<any>; resposeData: any; userData = { username: "", password: "", login: "true" }; showPasswordText: boolean = false; showToolbar: boolean; constructor( public navCtrl: NavController, public navParams: NavParams, public menu: MenuController, public apiService: Api, public common: Common, private platform: Platform, private keyboard: Keyboard, public ref: ChangeDetectorRef, public events: Events ) {} ionViewDidLoad() {} ionViewDidEnter() { // this.menu.enable(false); } ionViewWillLeave() { // this.menu.enable(true); } ionViewDidLeave() { // this.menu.enable(true); } ngOnInit() { this.platform.ready().then(() => { this.keyboard.hideFormAccessoryBar(true); }); } scrollTop() { var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } moveFocus(event, done?: boolean) { if (event.keyCode != 13) return; if (done) { this.inputFocus.setBlur(); this.login(); } else { this.inputFocus.setFocus(); } } login() { if ( this.userData.username.length == 0 || this.userData.password.length == 0 ) { this.common.presentToast("Semua bidang wajib di isi"); return; } this.common.presentLoading(); let postData = new FormData(); postData.append("username", this.userData.username); postData.append("password", <PASSWORD>); postData.append("login", this.userData.login); this.data = this.apiService.post("v1/user/login", postData); this.data.subscribe( data => { this.result = data; if (this.result.user_data) { // console.log(this.result.user_data.user_id, " & ", this.result.user_data.token); // localStorage.setItem('userData', JSON.stringify(this.result.user_data)); // setTimeout(() => this.goDashboard(), 500); this.common.closeLoading(); this.events.publish('user:login', this.result.user_data); } else { this.common.presentToast(this.result.data); this.common.closeLoading(); } }, error => { this.common.presentToast("tidak dapat terhubung ke server"); this.common.closeLoading(); console.log(error); } ); } goDashboard() { this.menu.enable(true); this.navCtrl.push(DashboardTabsPage); this.common.closeLoading(); } goRegister() { this.navCtrl.push(RegisterPage); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; // Pages import import { MyApp } from './app.component'; import { PROVIDERS, PAGES, NATIVES, COMPONENTS } from './app.import'; import { HttpClientModule } from '@angular/common/http'; import { HttpModule } from "@angular/http"; import { IonicImageViewerModule } from 'ionic-img-viewer'; import { SocketIoModule, SocketIoConfig } from 'ng-socket-io'; // const config: SocketIoConfig = { url: 'https://agrifarm-server.herokuapp.com', options: {} }; const config: SocketIoConfig = { url: 'http://localhost:8080', options: {} }; @NgModule({ declarations: [ MyApp, COMPONENTS, PAGES ], imports: [ BrowserModule, HttpClientModule, HttpModule, IonicModule.forRoot(MyApp, { mode: 'md', tabsHideOnSubPages: false }), SocketIoModule.forRoot(config), IonicImageViewerModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, PAGES ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, PROVIDERS, NATIVES ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class AppModule {} <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, Platform } from 'ionic-angular'; import { Calendar } from '@ionic-native/calendar'; @Component({ selector: 'page-cal-details', templateUrl: 'cal-details.html', }) export class CalDetailsPage { calName: string = ''; events: any = []; agriFarmEvent: any = []; public date = new Date(); showToolbar:boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams, private calendar: Calendar, private plt: Platform, public ref: ChangeDetectorRef) { this.calName = navParams.get('name'); if (this.plt.is('ios')) { this.calendar.findAllEventsInNamedCalendar(this.calName).then(data => { this.events = data; }); } else if (this.plt.is('android')) { //let startDate = new Date(Date.now()); //let endDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 0); let start = new Date(); start.setDate(start.getDate() - 1); let end = new Date(); end.setDate(end.getDate() + 31); this.calendar.listEventsInRange(start, end).then(data => { for (let item of data) { if (item.calendar_id == 4) { this.agriFarmEvent.push(item); } } this.events = data; console.log(this.agriFarmEvent); }); } } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } ionViewDidLoad() { //console.log('ionViewDidLoad CalDetailsPage'); } /* function relative_time(date) { var now = new Date().getTime(); var elapsed = Math.round(now / 1000) - date; if (elapsed <= 1) { return 'Baru saja'; } var rounded, title; if (elapsed > 31104000) { rounded = elapsed / 31104000; title = 'tahun'; } else if (elapsed > 2592000) { rounded = elapsed / 2592000; title = 'bulan'; } else if (elapsed > 604800) { elapsed = elapsed / 604800; title = 'minggu'; } else if (elapsed > 86400) { rounded = elapsed / 86400; title = 'hari'; } else if (elapsed > 3600) { rounded = elapsed / 3600; title = 'jam'; } else if (elapsed > 60) { rounded = elapsed / 60; title = 'menit'; } else if (elapsed >= 1) { rounded = elapsed / 1; title = 'detik'; } if (rounded > 1) { rounded = Math.round(rounded); return rounded + ' ' + title + ' yang lalu'; } } function getHHMM(t) { var d = new Date(t*1000), h = d.getHours(), m = d.getMinutes(), a = ''; if (h > 0 && h < 12) { a = 'AM'; } else { if (h == 0) a = 'AM'; else a = 'PM'; } if (m < 10) m = '0' + m; return ((h == 0 || h == 12) ? 12 : h % 12) + ':' + m + ' ' + a; }; */ } <file_sep>import { Component, ViewChild, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, Content } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { Geolocation } from '@ionic-native/geolocation'; import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder'; import { Camera, CameraOptions } from '@ionic-native/camera'; @Component({ selector: 'page-edit-lahan', templateUrl: 'edit-lahan.html', }) export class EditLahanPage { @ViewChild(Content) content: Content; @ViewChild('footerInput') footerInput; @ViewChild('namaLahan') namaLahan; showToolbar:boolean = false; lahanId: any; hasChange: boolean = false; result:any = []; lahan: any = {"id":"", "nama":"", "lokasi":"", "latitude":"", "longitude":"", "luas":"", "satuan":"", "foto":""}; userInput: any = []; isTracked: boolean = false; geocoderOptions: NativeGeocoderOptions = { useLocale: true, maxResults: 5, defaultLocale: "id_ID" }; locationResult: any = []; fotoScr: any; fotoChanged: boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common, private geolocation: Geolocation, private nativeGeocoder: NativeGeocoder, private camera: Camera) { this.lahanId = navParams.get('id'); if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); this.getLahan(); } window.addEventListener('native.keyboardshow', (e) => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + 'px'; }); window.addEventListener('native.keyboardhide', () => { this.footerInput.nativeElement.style.bottom = '0'; }); } ionViewDidLoad() { // console.log('ionViewDidLoad EditLahanPage'); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } scrollTop() { var that = this; setTimeout(() => { that.content.scrollToTop(); }, 100); } setFocusNama() { var that = this; setTimeout(() => { //that.namaLahan.setBlur(); that.namaLahan.setFocus(); }, 100); } getLahan() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields let userData = this.apiService.post("v1/lahan/" + this.lahanId, postData); userData.subscribe((result) => { res = result; this.userInput = res.data; this.lahan.id = this.userInput.id; this.lahan.nama = this.userInput.nama; this.lahan.lokasi = this.userInput.lokasi; this.lahan.latitude = this.userInput.latitude; this.lahan.longitude = this.userInput.longitude; this.lahan.luas = this.userInput.luas; this.lahan.satuan = this.userInput.satuan; this.lahan.foto = this.userInput.foto; this.fotoScr = this.apiService.url + "/" + this.lahan.foto; //this.loadMap(this.lahanData.latitude, this.lahanData.longitude); //this.getCuaca(this.lahanData.latitude, this.lahanData.longitude); this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } locate() { this.common.presentLoading(); this.geolocation.getCurrentPosition().then((resp) => { this.userInput.latitude = resp.coords.latitude; this.userInput.longitude = resp.coords.longitude; this.reverseGeocode(resp.coords.latitude, resp.coords.longitude); this.common.closeLoading(); }).catch((error) => { console.log('Error getting location', error); this.common.closeLoading(); }); } forwardGeocode(location: string) { this.nativeGeocoder.forwardGeocode(location, this.geocoderOptions) .then((coordinates: NativeGeocoderForwardResult[]) => { console.log('The coordinates are latitude=' + coordinates[0].latitude + ' and longitude=' + coordinates[0].longitude) //alert(coordinates[0].latitude); //alert(coordinates[0].longitude); }) .catch((error: any) => { console.log(error) }); } reverseGeocode(lat: any, lng: any) { this.nativeGeocoder.reverseGeocode(lat, lng, this.geocoderOptions) .then((result: NativeGeocoderReverseResult[]) => { console.log(JSON.stringify(result[0])); this.locationResult = result[0]; this.userInput.lokasi = this.locationResult.subLocality + ", " + this.locationResult.locality + " — " + this.locationResult.administrativeArea; this.hasChange = true; }) .catch((error: any) => { this.hasChange = false; console.log(error) }); } checkValueLuas() { this.hasChange = false; if (this.userInput.luas != this.lahan.luas) { this.hasChange = true; } } checkValueNama() { this.hasChange = false; if (this.userInput.nama != this.lahan.nama) { this.hasChange = true; } } onChangeSatuan() { this.hasChange = false; if (this.lahan.satuan != this.userInput.satuan) { this.hasChange = true; } } openGalery() { this.common.presentLoading(); const options: CameraOptions = { quality: 75, destinationType: this.camera.DestinationType.DATA_URL, // FILE_URI || DATA_URL encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, sourceType: this.camera.PictureSourceType.PHOTOLIBRARY } this.camera.getPicture(options).then((imageData) => { this.fotoScr = 'data:image/jpeg;base64,' + imageData; this.fotoChanged = true; this.hasChange = true; this.common.closeLoading(); // console.log(imageData); }, (err) => { this.common.closeLoading(); this.common.presentToast(err); }); } openCamera() { this.common.presentLoading(); const options: CameraOptions = { quality: 75, // 100 = crash, 50 default destinationType: this.camera.DestinationType.DATA_URL, // FILE_URI || DATA_URL encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } this.camera.getPicture(options).then((imageData) => { this.fotoScr = 'data:image/jpeg;base64,' + imageData; this.fotoChanged = true; this.hasChange = true; this.common.closeLoading(); // console.log(imageData); }, (err) => { this.common.closeLoading(); this.common.presentToast(err); }); } save() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); postData.append('lokasi', this.locationResult.thoroughfare); postData.append('no', this.locationResult.subThoroughfare); postData.append('kecamatan', this.locationResult.subLocality); postData.append('kabupaten', this.locationResult.locality); postData.append('provinsi', this.locationResult.administrativeArea); postData.append('negara', this.locationResult.countryName); postData.append('kodepos', this.locationResult.postalCode); postData.append('kodenegara', this.locationResult.countryCode); // Lat-Lang postData.append('nama', this.userInput.nama); postData.append('lokasi', this.userInput.lokasi); postData.append('latitude', this.userInput.latitude); postData.append('longitude', this.userInput.longitude); postData.append('luas', this.userInput.luas); postData.append('satuan', this.userInput.satuan); if (this.fotoChanged) { postData.append('foto', this.fotoScr); } let userData = this.apiService.post("v1/lahan/edit/" + this.lahanId, postData); userData.subscribe((result) => { res = result; this.common.closeLoading(); this.common.presentToast(res.data); this.navCtrl.pop().then(() => { this.navParams.get("callback")("lahan"); }); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } back() { this.navCtrl.pop(); } } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { HttpClient } from '@angular/common/http'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { ProfileIdPage } from '../profile-id/profile-id'; import { LahanPage } from '../lahan/lahan'; @Component({ selector: 'page-search', templateUrl: 'search.html', }) export class SearchPage { items: Array<string>; navigasi: string = "komoditas"; showToolbar:boolean = false; result: any = []; lahan: any = []; adaLahan: boolean = false; komoditas: any = []; adaKomoditas: boolean = false; users: any = []; adaUsers: boolean = false; showUser: boolean = false; showLahan: boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public http: HttpClient, public apiService: Api, public common: Common) { } ionViewDidLoad() { this.navigasi = "komoditas"; } ionViewWillLoad() { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); this.showUser = false; if (this.result.type == 1) { this.showUser = true; this.showLahan = true; this.loadUsers(); } this.loadKomoditas(); this.loadLahan(); } } ngOnInit() { // this.setItems(this.navigasi); } setItems(key: string) { if (key == "komoditas") { this.items = this.komoditas; } else if (key == "lahan") { this.items = this.lahan; } else { this.items = this.users; } } filterItems(ev: any) { this.setItems(this.navigasi); let val = ev.target.value; if (val && val.trim() !== '') { this.items = this.items.filter(function(item) { return item['nama'].toLowerCase().includes(val.toLowerCase()); }); } } segmentChanged(event) { this.navigasi = event.value; this.setItems(this.navigasi); // console.log(event.value); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } loadLahan() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let data = this.apiService.post("v1/lahan", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.lahan = data.data; // this.setItems("lahan"); // console.log(this.lahan) this.adaLahan = true; } else { this.adaLahan = false; } } else { this.adaLahan = false; } }, (error) => { console.log(error) }); } loadKomoditas() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let data = this.apiService.post("v1/komoditas", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.komoditas = data.data; this.setItems("komoditas"); this.adaKomoditas = true; } else { this.adaKomoditas = false; } } else { this.adaKomoditas = false; } }, (error) => { console.log(error) }); } loadUsers() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let data = this.apiService.post("v1/user", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.users = data.data; // console.log(this.users) this.adaUsers = true; } else { this.adaUsers = false; } } else { this.adaUsers = false; } }, (error) => { console.log(error) }); } getLuas = (luas: string) => { let rt: string; switch(luas) { case "T": rt = "Tumbak"; break; case "M": rt = "Meter"; break; default: rt = "Hektar"; break; } return rt; } openKomoditas() { } openProfile(id) { this.navCtrl.push(ProfileIdPage, {user_id: id}); } openLahan(id) { this.navCtrl.push(LahanPage, { id: id }); } } <file_sep>import { Component, ViewChild, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, Content, Platform, Navbar, Events } from 'ionic-angular'; import { Common } from '../../providers/common/common'; import { Api } from '../../providers/api/api'; import { DataProvider } from '../../providers/data/data'; import { SocketProvider } from '../../providers/socket/socket'; @Component({ selector: 'page-room-chat', templateUrl: 'room-chat.html', }) export class RoomChatPage { @ViewChild(Content) content: Content; @ViewChild("messageInput") messageInput; @ViewChild("footerInput") footerInput; @ViewChild('navbar') navBar: Navbar; showToolbar: boolean = false; roomId: any = null; typingMessage: any; message: string = ""; isReader: boolean = false; isAgronomisTyping: boolean = false; onMessage: any; onRoom: any; outRoom: any; onStartTyping: any; onStopTyping: any; agronomis: any = { name: null }; user: any = { user_id: null }; subject: any = null; created: any = null; chats: any = []; constructor( public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public events: Events, public common: Common, public apiService: Api, private platform: Platform, private dataServices: DataProvider, private socketServices: SocketProvider ) { this.roomId = this.navParams.get('roomId'); this.user = this.dataServices.user; this.user.user_id = parseInt(this.user.user_id); if (this.platform.is("android")) { window.addEventListener("native.keyboardshow", e => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + "px"; }); window.addEventListener("native.keyboardhide", () => { this.footerInput.nativeElement.style.bottom = "56px"; }); } } ionViewDidLoad() { this.onMessage = this.socketServices.on('message').subscribe(data => { let chat:any = data; if (chat.chat) { this.chats.push(chat.chat); this.scrollBottom(); } }); this.onRoom = this.socketServices.on('in-room').subscribe(data => { let result:any = data; this.isReader = result.room.length === 2 ? true : false; if (this.isReader) this.readMessage(); console.log("room-chat:in-room:", result.room, "isReader:", this.isReader); }); this.outRoom = this.socketServices.on('out-room').subscribe(data => { let result:any = data; this.isReader = result.room.length === 2 ? true : false; console.log("room-chat:out-room:", result.room, "isReader:", this.isReader); }); this.onStartTyping = this.socketServices.on('start-typing').subscribe(data => { let message:any = data; if (message.user === this.agronomis.id) { // console.log('start-typing'); this.isAgronomisTyping = true; } }); this.onStopTyping = this.socketServices.on('stop-typing').subscribe(data => { let message:any = data; if (message.user === this.agronomis.id) { // console.log('stop-typing'); this.isAgronomisTyping = false; } }); this.events.subscribe('user:online', () => { this.agronomis.online = this.dataServices.isOnline(parseInt(this.agronomis.id)); }); this.events.subscribe('user:offline', () => { this.agronomis.online = this.dataServices.isOnline(parseInt(this.agronomis.id)); this.isAgronomisTyping = false; }); this.getRoom(); this.readChat(); this.navBar.backButtonClick = (ev:UIEvent) => { this.navCtrl.pop().then(() => { this.navParams.get("callback")(); }); } } ionViewWillLeave() { this.socketServices.emit('out-room', { room: this.roomId, userId: this.user.user_id }); this.onMessage.unsubscribe(); this.onRoom.unsubscribe(); this.outRoom.unsubscribe(); this.onStartTyping.unsubscribe(); this.onStopTyping.unsubscribe(); } dismiss() { this.navCtrl.pop().then(() => { this.navParams.get("callback")(); }); } onScroll($event: any) { if ($event) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } } scrollBottom() { var that = this; this.content.resize(); setTimeout(function() { if (that.content) { that.content.scrollToBottom(); } }, 300); } isTyping(event) { if (event.keyCode == 13) return; this.socketServices.emit('start-typing', { room: this.roomId, form: this.user.user_id }); if (this.typingMessage) { clearTimeout(this.typingMessage); } this.typingMessage = setTimeout(() => { this.socketServices.emit('stop-typing', { room: this.roomId, form: this.user.user_id }); }, 2000); } getRoom() { this.dataServices.getChat(this.roomId) .subscribe(data => { let room:any = data; this.subject = room.subject; this.created = room.created; this.chats = room.chat; this.chats.reverse(); this.dataServices.getAgronomis(room.agronomis).subscribe(user => { this.agronomis = user; this.agronomis.id = parseInt(this.agronomis.id); this.agronomis.online = this.dataServices.isOnline(room.agronomis); }); if (this.chats.length >= 5) { this.scrollBottom(); } }, error => { console.log(error); }); } sendMessage() { this.messageInput.setBlur(); this.postMessage(); this.message = ''; this.socketServices.emit('stop-typing', { room: this.roomId, from: this.user.user_id }); if (this.typingMessage) { clearTimeout(this.typingMessage); } this.scrollBottom(); } postMessage() { let data = { "from": this.user.user_id, "text": this.message, "read": this.isReader }; this.dataServices.addChat(this.roomId, data) .subscribe(data => { // console.log(data); }, err => { console.log(err); }); } readChat() { this.dataServices.readChat(this.roomId).subscribe(data => { // console.log(data); this.socketServices.emit('in-room', { room: this.roomId, userId: this.user.user_id }); }, err => { console.log(err); }) } readMessage() { var that = this; Object.keys(this.chats).forEach(function(id) { that.chats[id].read = true; // console.log(that.chats[id].read); }); } doRefresh(refresher) { this.chats = []; this.getRoom(); refresher.complete(); } } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { Camera, CameraOptions } from '@ionic-native/camera'; import { HttpClient } from '@angular/common/http'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'page-profile-picture', templateUrl: 'profile-picture.html', }) export class ProfilePicturePage { showToolbar: boolean = false; hasImage: boolean = false; base64Image: string; result = {"latitude":null, "longitude":null, "name":"", "pic":null, "token":"", "type":"", "user_id":"0"}; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, private camera: Camera, public http: HttpClient, public apiService: Api, public common: Common) { if (localStorage.getItem('userData')) { let data = JSON.parse(localStorage.getItem('userData')); this.result = data; } } ionViewDidLoad() { if (this.result.pic != null) { this.base64Image = this.apiService.url + "/" + this.result.pic; } else { this.base64Image = "assets/img/agritama.png"; } } ionViewWillEnter() { } openGalery() { this.common.presentLoading(); const options: CameraOptions = { quality: 75, destinationType: this.camera.DestinationType.DATA_URL, // FILE_URI || DATA_URL encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, sourceType: this.camera.PictureSourceType.PHOTOLIBRARY } this.camera.getPicture(options).then((imageData) => { this.base64Image = 'data:image/jpeg;base64,' + imageData; this.hasImage = true; this.common.closeLoading(); // console.log(imageData); }, (err) => { this.common.closeLoading(); this.common.presentToast(err); }); } openCamera() { this.common.presentLoading(); const options: CameraOptions = { quality: 75, // 100 = crash, 50 default destinationType: this.camera.DestinationType.DATA_URL, // FILE_URI || DATA_URL encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } this.camera.getPicture(options).then((imageData) => { this.base64Image = 'data:image/jpeg;base64,' + imageData; this.hasImage = true; this.common.closeLoading(); // console.log(imageData); }, (err) => { this.common.closeLoading(); this.common.presentToast(err); }); } back() { this.navCtrl.pop(); } save() { this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); postData.append('foto', this.base64Image); let data:Observable<any> = this.apiService.upload("/v1/user/foto", postData); data.subscribe((result) => { console.log(result); this.base64Image = result.data.foto; this.common.closeLoading(); this.common.presentToast("Uploaded at: " + result.data.foto); this.navCtrl.pop().then(() => { this.navParams.get("callback")("1"); }); }, (error) => { console.log(error); this.common.closeLoading(); this.common.presentToast(error); }); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } } <file_sep>import { Component, ViewChild, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, Content, Platform } from 'ionic-angular'; import { Common } from '../../providers/common/common'; import { Api } from '../../providers/api/api'; import { Http, Headers, RequestOptions } from '@angular/http'; import { Socket } from 'ng-socket-io'; @Component({ selector: 'page-room-add', templateUrl: 'room-add.html', }) export class RoomAddPage { @ViewChild(Content) content: Content; @ViewChild('footerInput') footerInput; @ViewChild('messageInput') messageInput; showToolbar: boolean = false; hasChange: boolean = false; hasFocus: boolean = false; message:any = ''; user: any = { user_id: null }; constructor( public navCtrl: NavController, public navParams: NavParams, public common: Common, public apiService: Api, private platform: Platform, private http: Http, public ref: ChangeDetectorRef, private socket: Socket ) { this.user = JSON.parse(localStorage.getItem('userData')); this.user.user_id = parseInt(this.user.user_id); if (this.platform.is('android')) { window.addEventListener('native.keyboardshow', (e) => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + 'px'; }); window.addEventListener('native.keyboardhide', () => { this.footerInput.nativeElement.style.bottom = '0'; }); } } ionViewDidLoad() { // console.log('ionViewDidLoad RoomAddPage'); } save() { if (this.user.user_id === null) { this.user = JSON.parse(localStorage.getItem('userData')); this.user.user_id = parseInt(this.user.user_id); } this.hasChange = false; this.messageInput.setBlur(); let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': "Bearer ey<KEY>" }); let options = new RequestOptions({ headers: headers }); let body = JSON.stringify({ "userId": this.user.user_id, "subject": this.message }); this.http.post('http://localhost:8080/room', body, options).subscribe(data => { let room = data.json(); console.log(room); this.socket.emit('subscribe', room.room_id); // subscribe socket this.dismiss(); }, err => { console.log(err); }) } checkValue() { this.hasFocus = true; if (this.message !== '') { this.hasChange = true; } else { this.hasChange = false; } } onScroll($event: any) { if ($event) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } } scrlTop() { this.hasFocus = false; var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } scrlBottom() { this.hasFocus = true; var that = this; setTimeout(function() { that.content.scrollToBottom(); }, 100); } setBlurInput() { this.messageInput.setBlur(); } dismiss() { this.navCtrl.pop().then(() => { this.navParams.get("callback")("callback dummy data"); }); } } <file_sep>import { Component, ChangeDetectorRef, ViewChild } from '@angular/core'; import { NavController, NavParams, Content } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; @Component({ selector: 'page-settings', templateUrl: 'settings.html', }) export class SettingsPage { @ViewChild(Content) content: Content; @ViewChild('footerInput') footerInput; showToolbar:boolean = false; hasChangeUsername: boolean = false; hasChangePassword: boolean = false; userData: any = {"username":"", "password":""}; userInput: any = {"username":"", "password":"", "refpassword":""}; result:any = []; navigasi: string = "username"; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common) { this.navigasi = "username"; if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } window.addEventListener('native.keyboardshow', (e) => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + 'px'; }); window.addEventListener('native.keyboardhide', () => { this.footerInput.nativeElement.style.bottom = '0'; }); } ionViewDidLoad() { //console.log('ionViewDidLoad SettingsPage'); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } scrollTop() { var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } segmentChanged(event) { // console.log(event.value); } saveUsername() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('username', this.userData.username); postData.append('newusername', this.userInput.username); let userData = this.apiService.post("v1/user/username", postData); userData.subscribe((result) => { res = result; console.log(res); if (res.user_data) { localStorage.setItem('userData', JSON.stringify(res.user_data)); this.common.presentToast("Sukses!, data telah di perbaharui"); this.userData = {"username":"", "password":""}; this.userInput = {"username":"", "password":"", "refpassword":""}; } else { this.common.presentToast(res.data); } this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } savePassword() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('password', <PASSWORD>); postData.append('newpassword', <PASSWORD>); let userData = this.apiService.post("v1/user/password", postData); userData.subscribe((result) => { res = result; console.log(result); if (res.data) { localStorage.setItem('userData', JSON.stringify(res.user_data)); this.common.presentToast("Sukses!, data telah di perbaharui"); this.userData = {"username":"", "password":""}; this.userInput = {"username":"", "password":"", "refpassword":""}; } else { this.common.presentToast(result['data']); } this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } checkValue() { this.hasChangeUsername = false; if (this.userData.username.length != 0 && this.userData.username != this.userInput.username) { if (this.userData.username.length >= 6 && this.userInput.username.length >= 6) { this.hasChangeUsername = true; } } } checkValuePassword() { this.hasChangePassword = false; if (this.userData.password.length != 0 && this.userData.password.length >= 6) { if (this.userInput.password.length != 0 && this.userInput.refpassword.length != 0) { if (this.userInput.password.length >= 6 && this.userInput.refpassword.length >= 6) { if (this.userInput.password == <PASSWORD>) { if (this.userData.password != <PASSWORD>) { this.hasChangePassword = true; } } } } } else { this.hasChangePassword = false; } } } <file_sep>import { Component, Input } from '@angular/core'; @Component({ selector: 'timeline', templateUrl: 'timeline.html' }) export class TimelineComponent { @Input('endIcon') endIcon = "calendar"; constructor() { } } @Component({ selector: 'timeline-item', template: '<ng-content></ng-content>' }) export class TimelineItemComponent { constructor() { } } @Component({ selector:'timeline-time', template: '<ion-badge color="agrifarm" style="padding: 6px 10px;"><ion-icon name="bookmark" icon start style="zoom:0.8;"></ion-icon>&nbsp;&nbsp;{{time.subtitle}}</ion-badge> <!--span>{{time.subtitle}}</span--> <span>{{time.title | date: "dd/MM/yyyy" }}</span>' }) export class TimelineTimeComponent { @Input('time') time = { title:"", subtitle:""}; tmpTime = {} constructor() { } }<file_sep>import { Component } from '@angular/core'; import { NavController, MenuController } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import * as $ from "jquery"; import { Observable } from 'rxjs/Observable'; import { HttpClient } from '@angular/common/http'; import { DashboardTabsPage } from '../dashboard-tabs/dashboard-tabs'; import { LoginPage } from '../login/login'; import { RegisterPage } from '../register/register'; @Component({ selector: 'page-wellcome', templateUrl: 'wellcome.html', }) export class WellcomePage { result: any = []; data: Observable<any>; userData = {"user_id":null, "token":"", "request_token":"1"}; constructor(public navCtrl: NavController, public menu: MenuController, public common: Common, public apiService: Api, public http: HttpClient) { } ionViewWillLoad() { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); this.userData.user_id = parseInt(this.result.user_id); this.userData.token = this.result.token; // this.tokenLogin(); } } ionViewDidLoad() { $('.splash-intro').html('SELAMAT DATANG DI AGRIFARM'); } ionViewDidEnter() { // the root left menu should be disabled on the tutorial page // this.menu.enable(false); //this.menu.close(); } ionViewWillLeave() { // enable the root left menu when leaving the tutorial page //this.menu.enable(true); } tokenLogin() { let postData = new FormData(); postData.append('uid', this.userData.user_id); postData.append('token', this.userData.token); this.common.presentLoading(); this.apiService.postData(postData, "v1/user/token").then((data) => { this.common.closeLoading(); setTimeout(() => this.goDashboard(), 0); }, (err) => { this.common.closeLoading(); setTimeout(() => this.login(), 500); }); } goDashboard() { this.common.closeLoading(); this.menu.enable(true); this.navCtrl.push(DashboardTabsPage); } login() { this.navCtrl.push(LoginPage); } signup() { this.navCtrl.push(RegisterPage); } } <file_sep>import { Component, ChangeDetectorRef, ViewChild } from '@angular/core'; import { NavController, NavParams, Content } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; @Component({ selector: 'page-edit-komoditas', templateUrl: 'edit-komoditas.html', }) export class EditKomoditasPage { @ViewChild(Content) content: Content; showToolbar:boolean = false; hasChange: boolean = false; komoditasId: any; result:any = []; komoditasData: any = []; userInput: any = []; lahanResult:any = []; rumusResult:any = []; today: any = new Date().getTime(); tanam: any; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common) { this.komoditasId = navParams.get('id'); if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); this.getKomoditas(); this.getLahanList(); this.getRumusList(); } } ionViewDidLoad() { } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } scrollTop() { var that = this; setTimeout(() => { that.content.scrollToTop(); }, 100); } checkValue(ev: any) { this.hasChange = false; let val = ev.target.value; if (val.length >= 3) { this.hasChange = true; } } checkValueUsia() { this.hasChange = false; let val = this.userInput.usia; if (val.length >= 1) { this.hasChange = true; } } updatePredict() { this.getPredicTanam(this.userInput.usia); this.scrollTop(); } onChangeKomoditas(val) { this.hasChange = false; //if (val != this.komoditasData.id_rumus) { this.hasChange = true; //} } onChangeLahan(val) { this.hasChange = false; //if (val != this.komoditasData.id_lahan) { this.hasChange = true; //} } save() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('rumus', this.userInput.id_rumus); postData.append('lahan', this.userInput.id_lahan); postData.append('jumlah', this.userInput.jumlah); postData.append('usia', this.userInput.usia); let userData = this.apiService.post("v1/komoditas/edit/" + this.komoditasId, postData); userData.subscribe((result) => { res = result; this.common.closeLoading(); this.common.presentToast(res.data); this.navCtrl.pop().then(() => { this.navParams.get("callback")("komoditas"); }); }, (error) => { console.log(error); this.common.presentToast("terjadi kesalahan"); this.common.closeLoading(); }); } back() { this.navCtrl.pop(); } getKomoditas() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields let userData = this.apiService.post("v1/komoditas/" + this.komoditasId, postData); userData.subscribe((result) => { res = result; this.komoditasData = res.data; this.userInput.id_lahan = this.komoditasData.id_lahan; this.userInput.id_rumus = this.komoditasData.id_rumus; this.userInput.jumlah = this.komoditasData.jumlah; this.userInput.usia = this.komoditasData.usia; this.tanam = this.komoditasData.tanam; //this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); //this.common.closeLoading(); }); } getLahanList() { let res: any = []; //this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields let userData = this.apiService.post("v1/lahan", postData); userData.subscribe((result) => { res = result; this.lahanResult = res.data; //console.log(this.lahanResult) //this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); //this.common.closeLoading(); }); } getRumusList() { let res: any = []; //this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields let userData = this.apiService.post("v1/rumus", postData); userData.subscribe((result) => { res = result; this.rumusResult = res.data; //console.log(this.rumusResult) this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } getNowDate = () => { var returnDate = ""; var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); if (mm < 10) { returnDate += `0${mm}/`; } else { returnDate += `${mm}/`; } if (dd < 10) { returnDate += `0${dd}/`; } else { returnDate += `${dd}/`; } returnDate += yyyy; return returnDate; } getUsia = (tanggal: string) => { let usia; let tanam = new Date(tanggal).getTime(); let date = tanam / 1000; var elapsed = Math.round(this.today / 1000) - date; usia = elapsed / 86400; console.log(Math.round(usia)) return usia; } getPredicTanam(usia: any) { if (usia == null) return; let res: any = []; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); postData.append('usia', usia); // Fields let userData = this.apiService.post("v1/tanam", postData); userData.subscribe((result) => { res = result; this.tanam = res.data; //console.log(this.rumusResult) }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); }); } } <file_sep>import { Component } from '@angular/core'; import { NavController, NavParams, ViewController, ModalController } from 'ionic-angular'; import { AddLahanPage } from '../add-lahan/add-lahan'; @Component({ selector: 'page-popover-dashboard', templateUrl: 'popover-dashboard.html', }) export class PopoverDashboardPage { token: any; id: any; page: any; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public modalCtrl: ModalController) { } ionViewDidLoad() { // console.log('ionViewDidLoad PopoverDashboardPage'); } ngOnInit() { if (this.navParams.data) { this.token = this.navParams.data.token; this.id = this.navParams.data.id; this.page = this.navParams.data.page; } } close() { this.viewCtrl.dismiss(); } add(page) { if (page == 'lahan') { this.presetntAddModal(page); } this.viewCtrl.dismiss(); } refresh() { this.close(); } presetntAddModal(page) { let addModal = this.modalCtrl.create(AddLahanPage, { pageId: page}); addModal.present(); addModal.onDidDismiss(() => { this.navParams.get("callback")("1"); }); } } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, PopoverController, ModalController, ItemSliding, Events, ActionSheetController } from 'ionic-angular'; import { Platform } from 'ionic-angular'; import { Geolocation } from '@ionic-native/geolocation'; import { PopoverDashboardPage } from '../popover-dashboard/popover-dashboard'; import { PopoverPage } from '../popover/popover'; import { WeatherProvider } from '../../providers/weather/weather'; import { DeleteModalPage } from '../delete-modal/delete-modal'; import { AddLahanPage } from '../add-lahan/add-lahan'; import { Common } from '../../providers/common/common'; import { Api } from '../../providers/api/api'; import { ProfileAlamatPage } from '../profile-alamat/profile-alamat'; import { LahanPage } from '../lahan/lahan'; import { EditLahanPage } from '../edit-lahan/edit-lahan'; import { EditKomoditasPage } from '../edit-komoditas/edit-komoditas'; import { AddKomoditasPage } from '../add-komoditas/add-komoditas'; import { SearchPage } from '../search/search'; @Component({ selector: 'page-dashboard', templateUrl: 'dashboard.html', }) export class DashboardPage { navigasi: string = "lahan"; isAndroid: boolean = false; showToolbar:boolean = false; userData = {"user_id":null, "token":"", "request_token":"1"}; // Cuaca weather:any = { coord:{}, weather:[], base:"", main:{}, wind:{}, clouds:{}, dt:0, sys:{}, id:0, name:"", cod:0 }; currentWeather:any = {}; forecast: any = []; location: { city: string, country: string }; adaWeather: boolean = false; lahan: any = []; adaLahan: boolean = false; komoditas: any = []; adaKomoditas: boolean = false; cuacaLahan: any = []; constructor(public navCtrl: NavController, public navParams: NavParams, platform: Platform, public popoverCtrl: PopoverController, public modalCtrl: ModalController, public ref: ChangeDetectorRef, private weatherProvider: WeatherProvider, public events: Events, public apiService: Api, public common: Common, private geolocation: Geolocation, public actionSheetCtrl: ActionSheetController) { this.isAndroid = platform.is('android'); this.navigasi = "lahan"; if (localStorage.getItem('userData')) { let result = JSON.parse(localStorage.getItem('userData')); this.userData.user_id = parseInt(result.user_id); this.userData.token = result.token; } // this.getLahan(); } addLahan() { this.presetntAddModal(); } lihatLahan(item: ItemSliding) { this.navCtrl.push(LahanPage, { id: item['id'], callback: this.callbackLahan }); } editLahan(item: ItemSliding) { this.navCtrl.push(EditLahanPage, { id: item['id'], callback: this.callbackLahan }); } deleteLahan(item: ItemSliding) { let itemId = item['id']; this.presentDeleteModal(itemId, "lahan"); } // Komoditas edit(item: ItemSliding) { this.navCtrl.push(EditKomoditasPage, { id: item['id'], callback: this.callbackLahan }); } view(item: ItemSliding) { this.navCtrl.push(LahanPage, { id:item['id'] }).then((e) => { this.navigasi = "lahan"; }); } delete(item: ItemSliding) { let itemId = item['id']; this.presentDeleteModal(itemId, "komoditas"); } segmentChanged(event) { // console.log(event.value); } ionViewDidLoad() { this.navigasi = "lahan"; // console.log(this.adaKomoditas); } ionViewDidEnter() { // this.events.publish('user:login', Date.now()); this.getLahan(); this.getKomoditas(); } presentDeleteModal(id: number, type: string) { let deleteModal = this.modalCtrl.create(DeleteModalPage, { itemId: id, itemType: type }); deleteModal.present(); deleteModal.onDidDismiss(() => { if (localStorage.getItem('userData')) { let result = JSON.parse(localStorage.getItem('userData')); this.userData.user_id = parseInt(result.user_id); this.userData.token = result.token; } this.getLahan(); this.getKomoditas(); }); } presetntAddModal() { let addModal = this.modalCtrl.create(AddLahanPage, { pageId: 'lahan'}); addModal.present(); addModal.onDidDismiss(() => { if (localStorage.getItem('userData')) { let result = JSON.parse(localStorage.getItem('userData')); this.userData.user_id = parseInt(result.user_id); this.userData.token = result.token; } this.getLahan(); this.getKomoditas(); }); } presentAddKomoditas(lid: number) { let addModal = this.modalCtrl.create(AddKomoditasPage, { pageId: 'komoditas', lahanId: lid }); addModal.present(); addModal.onDidDismiss(() => { if (localStorage.getItem('userData')) { let result = JSON.parse(localStorage.getItem('userData')); this.userData.user_id = parseInt(result.user_id); this.userData.token = result.token; } this.getLahan(); this.getKomoditas(); }); } presentPopover(MyEvent) { let btnid = MyEvent.target.parentElement.getAttribute("id"); let btnname = MyEvent.target.parentElement.getAttribute("name"); let btntype = MyEvent.target.parentElement.getAttribute("type"); let popover = this.popoverCtrl.create(PopoverPage, {id: btnid, name: btnname, type: btntype, callback: this.actionMore }); popover.present({ ev: MyEvent }); } presentActionSheet(id_lahan, name, type) { // console.log(id_lahan); // console.log(name); // console.log(type); const actionSheet = this.actionSheetCtrl.create({ title: 'Lengkapi', buttons: [{ text: 'Tambah Komoditas', role: 'destructive', icon: 'add', handler: () => { this.presentAddKomoditas(id_lahan); } }, // { // text: 'Lihat Lahan', // icon: 'laptop', // handler: () => { // this.navCtrl.push(LahanPage, { id: id_lahan }).then((e) => { // this.navigasi = "lahan"; // }); // } // }, { text: 'Ubah Lahan', icon: 'create', handler: () => { this.navCtrl.push(EditLahanPage, { id: id_lahan, callback: this.callbackLahan }); } },{ text: 'Hapus Lahan', icon: 'trash', handler: () => { this.presentDeleteModal(id_lahan, "lahan"); } },{ text: 'Tutup', role: 'cancel', icon: 'close', cssClass: 'border-top', handler: () => { } }] }); actionSheet.present(); } presentPopoverDashboard(navigasi) { let popover = this.popoverCtrl.create(PopoverDashboardPage, { id: this.userData.user_id, token: this.userData.token, page: this.navigasi, callback: this.callbackLahan }); popover.present({ ev: navigasi }); } // Cuaca ionViewWillEnter() { let result = {"latitude":null, "longitude":null}; if (localStorage.getItem('userData')) { let data = JSON.parse(localStorage.getItem('userData')); result.latitude = data.latitude; result.longitude = data.longitude; } if (result.latitude != null && result.longitude != null) { this.adaWeather = true; } else { this.adaWeather = false; } if (this.adaWeather) { // console.log("start weather services"); this.getCuaca(result.latitude, result.longitude); } } getLahan() { let postData = new FormData(); postData.append('uid', this.userData.user_id); postData.append('token', this.userData.token); let data = this.apiService.post("v1/lahan", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.lahan = data.data; for (let lhn of data.data) { let lat = lhn.latitude; let lng = lhn.longitude; let idLahan = lhn.id; this.getCuacaLahan(idLahan, lat, lng); } this.adaLahan = true; } else { this.adaLahan = false; } } else { this.adaLahan = false; } }, (error) => { this.adaLahan = false; }); } getKomoditas() { let postData = new FormData(); postData.append('uid', this.userData.user_id); postData.append('token', this.userData.token); let data = this.apiService.post("v1/komoditas", postData); data.subscribe((result) => { let data: any = []; data = result; // console.log(data) if (data.data.length > 0) { if (data.data[0].id) { this.komoditas = data.data; this.adaKomoditas = true; } else { this.adaKomoditas = false; } } else { this.adaKomoditas = false; } }, (error) => { this.adaKomoditas = false; }); } getLuas = (luas: string) => { let rt: string; switch(luas) { case "T": rt = "Tumbak"; break; case "M": rt = "Meter"; break; default: rt = "Hektar"; break; } return rt; } findCuaca = (id:any) => { for (let cu of this.cuacaLahan) { if (cu.id == id) { // console.log(cu); return cu.cuaca; } } return false; } locate() { this.common.presentLoading(); this.geolocation.getCurrentPosition().then((resp) => { // resp.coords.latitude // resp.coords.longitude this.getCuaca(resp.coords.latitude, resp.coords.longitude); this.common.closeLoading(); }).catch((error) => { console.log('Error getting location', error); this.common.closeLoading(); }); } getCuacaLahan(idLahan: number, lat: number, lng: number) { let weathers: any = []; let currentWeather: any = []; this.weatherProvider.getWeather(lat, lng) .subscribe((result) => { weathers = result; currentWeather = weathers.weather[0]; var prefix = 'wi wi-'; var code = weathers.weather[0].id; var icon = this.weatherProvider.weatherIcons[code].icon; if (!(code > 699 && code < 800) && !(code > 899 && code < 1000)) { icon = 'day-' + icon; } icon = prefix + icon; currentWeather.icon = icon; this.cuacaLahan.push({ id:idLahan, cuaca: currentWeather }); }, (error) => { console.log(error); }); } getCuaca = (lat: number, lng: number) => { this.weatherProvider.getWeather(lat, lng) .subscribe((result) => { this.weather = result; this.currentWeather = this.weather.weather[0]; var prefix = 'wi wi-'; var code = this.weather.weather[0].id; var icon = this.weatherProvider.weatherIcons[code].icon; if (!(code > 699 && code < 800) && !(code > 899 && code < 1000)) { icon = 'day-' + icon; } icon = prefix + icon; this.currentWeather.icon = icon; //console.log(this.weather); }, (error) => { console.log(error); }); this.weatherProvider.getForecast(lat, lng) .subscribe((result) => { this.forecast = result; //console.log(result); }, (error) => { console.log(error); }); } GetIcon = (id: number) => { var prefix = 'wi wi-'; var icon = this.weatherProvider.weatherIcons[id].icon; // If we are not in the ranges mentioned above, add a day/night prefix. if (!(id > 699 && id < 800) && !(id > 899 && id < 1000)) { icon = 'day-' + icon; } // Finally tack on the prefix. icon = prefix + icon; return icon; } GetDay = (time: number) => { let day = new Date(time*1000).toISOString(); let d = new Date(day); let weekday = []; weekday[0] = "Minggu"; weekday[1] = "Senin"; weekday[2] = "Selasa"; weekday[3] = "Rabu"; weekday[4] = "Kamis"; weekday[5] = "Jum'at"; weekday[6] = "Sabtu"; let n = weekday[d.getDay()]; return n; } GetTime = (time: number) => { return new Date(time * 1000);//.toISOString(); } windDirection = (deg) => { if (deg > 11.25 && deg < 33.75){ return "Utara Timur Laut"; }else if (deg > 33.75 && deg < 56.25){ return "Timur Timur Laut"; }else if (deg > 56.25 && deg < 78.75){ return "Timur"; }else if (deg > 78.75 && deg < 101.25){ return "Timur Tengara"; }else if (deg > 101.25 && deg < 123.75){ return "Timur Menenggara"; }else if (deg > 123.75 && deg < 146.25){ return "Tenggara"; }else if (deg > 146.25 && deg < 168.75){ return "Selatan Menenggara"; }else if (deg > 168.75 && deg < 191.25){ return "Selatan"; }else if (deg > 191.25 && deg < 213.75){ return "Selatan Barat Daya"; }else if (deg > 213.75 && deg < 236.25){ return "Barat Daya"; }else if (deg > 236.25 && deg < 258.75){ return "Barat Barat Daya"; }else if (deg > 258.75 && deg < 281.25){ return "Barat"; }else if (deg > 281.25 && deg < 303.75){ return "Barat Barat Laut"; }else if (deg > 303.75 && deg < 326.25){ return "Barat Laut"; }else if (deg > 326.25 && deg < 348.75){ return "Utara Barat Laut"; }else{ return "Utara"; } } nameToIndo = (val) => { //let val = this.navParams.get("weatherInfo") if(val == "Rain"){ return 'Hujan'; } else if(val == "Clear"){ return 'Cerah'; } else if(val == "Clouds"){ return 'Berawan'; } else if(val == "Drizzle"){ return 'Gerimis'; } else if(val == "Snow"){ return 'Salju'; } else if(val == "ThunderStorm"){ return 'Hujan badai'; } else { return 'Cerah'; } } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } openAlamat() { this.navCtrl.push(ProfileAlamatPage, { callback: this.callback }); } openSearch() { this.navCtrl.push(SearchPage, { callback: this.callback }); } callback = (data?) => { this.common.presentLoading(); let resultData: any = [];; let postData = new FormData(); postData.append('uid', this.userData.user_id); postData.append('token', this.userData.token); postData.append('update', data ? data : "1"); let userData = this.apiService.post("v1/user/me", postData); userData.subscribe((result) => { resultData = result; localStorage.setItem('userData', JSON.stringify(resultData.data)); let res = {"latitude":null, "longitude":null}; res.latitude = resultData.data.latitude; res.longitude = resultData.data.longitude; if (res.latitude != null && res.longitude != null) { this.adaWeather = true; this.getCuaca(res.latitude, res.longitude); } this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } callbackLahan = (data?) => { if (data == 'komoditas') { this.navigasi = "komoditas"; this.getKomoditas(); } else { this.navigasi = "lahan"; this.getLahan(); } } actionMore = (data) => { // console.log(data); if (data.type == 'lahan') { if (data.action == 'view') { this.navCtrl.push(LahanPage, { id: data.id, callback: this.callbackLahan }); } else if(data.action == 'edit') { this.navCtrl.push(EditLahanPage, { id: data.id, callback: this.callbackLahan }); } else if (data.action == 'add') { // console.log(data.id) this.presentAddKomoditas(data.id); } else { this.presentDeleteModal(data.id, "lahan"); } } else { if(data.action == 'edit') { this.navCtrl.push(EditKomoditasPage, { id: data.id, callback: this.callbackLahan }); } else { this.presentDeleteModal(data.id, "komoditas"); } } } } <file_sep>import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class Api { // url: string = 'https://agritama.farm/api'; url: string = 'http://localhost'; constructor(public httpClient: HttpClient, public http: Http) { } // --------------------------------------------------------------------- get(endpoint: string, params?: any, reqOpts?: any) { if (!reqOpts) { reqOpts = { params: new HttpParams() }; } if (params) { reqOpts.params = new HttpParams(); for (let k in params) { reqOpts.params = reqOpts.params.set(k, params[k]); } } return this.httpClient.get(this.url + '/' + endpoint, reqOpts); } _get(endpoint: string, reqOpts?: any) { return this.http.get(this.url + '/' + endpoint, reqOpts); } // --------------------------------------------------------------------- post(endpoint: string, body: any, reqOpts?: any) { return this.httpClient.post(this.url + '/' + endpoint, body, reqOpts); } _post(endpoint: string, body: any, reqOpts?: any) { return this.http.post(this.url + '/' + endpoint, body, reqOpts); } // --------------------------------------------------------------------- put(endpoint: string, body: any, reqOpts?: any) { return this.httpClient.put(this.url + '/' + endpoint, body, reqOpts); } _put(endpoint: string, body: any, reqOpts?: any) { return this.http.put(this.url + '/' + endpoint, body, reqOpts); } // --------------------------------------------------------------------- delete(endpoint: string, reqOpts?: any) { return this.httpClient.delete(this.url + '/' + endpoint, reqOpts); } _delete(endpoint: string, reqOpts?: any) { return this.http.delete(this.url + '/' + endpoint, reqOpts); } // --------------------------------------------------------------------- patch(endpoint: string, body: any, reqOpts?: any) { return this.httpClient.patch(this.url + '/' + endpoint, body, reqOpts); } _patch(endpoint: string, body: any, reqOpts?: any) { return this.http.patch(this.url + '/' + endpoint, body, reqOpts); } // --------------------------------------------------------------------- upload(endpoint: string, body: any) { return this.httpClient.post(this.url + '/' + endpoint, body); } _upload(endpoint: string, body: any, reqOpts?: any) { return this.http.post(this.url + '/' + endpoint, body, reqOpts); } // --------------------------------------------------------------------- postData(credentials, endpoint) { return new Promise((resolve, reject) => { let headers = new Headers(); this.http.post(this.url + '/' + endpoint, credentials, { headers: headers }). subscribe(res => { resolve(res.json()); }, (err) => { reject(err); }); }); } // --------------------------------------------------------------------- postToken(endpoint, body, token) { return new Promise((resolve, reject) => { let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Accept', 'application/json'); headers.append('Authorization', 'Bearer ' + token); this.http.post(this.url + '/' + endpoint, body, { headers: headers }). subscribe(res => { resolve(res.json()); }, (err) => { reject(err); }); }); } // --------------------------------------------------------------------- getData(endpoint) { return new Promise((resolve, reject) => { this.http.get(this.url + '/' + endpoint). subscribe(res => { resolve(res.json()); }, (err) => { reject(err); }); }); } } <file_sep>Open Weather Map wi-owm-200: thunderstorm wi-owm-201: thunderstorm wi-owm-202: thunderstorm wi-owm-210: lightning wi-owm-211: lightning wi-owm-212: lightning wi-owm-221: lightning wi-owm-230: thunderstorm wi-owm-231: thunderstorm wi-owm-232: thunderstorm wi-owm-300: sprinkle wi-owm-301: sprinkle wi-owm-302: rain wi-owm-310: rain-mix wi-owm-311: rain wi-owm-312: rain wi-owm-313: showers wi-owm-314: rain wi-owm-321: sprinkle wi-owm-500: sprinkle wi-owm-501: rain wi-owm-502: rain wi-owm-503: rain wi-owm-504: rain wi-owm-511: rain-mix wi-owm-520: showers wi-owm-521: showers wi-owm-522: showers wi-owm-531: storm-showers wi-owm-600: snow wi-owm-601: snow wi-owm-602: sleet wi-owm-611: rain-mix wi-owm-612: rain-mix wi-owm-615: rain-mix wi-owm-616: rain-mix wi-owm-620: rain-mix wi-owm-621: snow wi-owm-622: snow wi-owm-701: showers wi-owm-711: smoke wi-owm-721: day-haze wi-owm-731: dust wi-owm-741: fog wi-owm-761: dust wi-owm-762: dust wi-owm-771: cloudy-gusts wi-owm-781: tornado wi-owm-800: day-sunny wi-owm-801: cloudy-gusts wi-owm-802: cloudy-gusts wi-owm-803: cloudy-gusts wi-owm-804: cloudy wi-owm-900: tornado wi-owm-901: storm-showers wi-owm-902: hurricane wi-owm-903: snowflake-cold wi-owm-904: hot wi-owm-905: windy wi-owm-906: hail wi-owm-957: strong-wind wi-owm-day-200: day-thunderstorm wi-owm-day-201: day-thunderstorm wi-owm-day-202: day-thunderstorm wi-owm-day-210: day-lightning wi-owm-day-211: day-lightning wi-owm-day-212: day-lightning wi-owm-day-221: day-lightning wi-owm-day-230: day-thunderstorm wi-owm-day-231: day-thunderstorm wi-owm-day-232: day-thunderstorm wi-owm-day-300: day-sprinkle wi-owm-day-301: day-sprinkle wi-owm-day-302: day-rain wi-owm-day-310: day-rain wi-owm-day-311: day-rain wi-owm-day-312: day-rain wi-owm-day-313: day-rain wi-owm-day-314: day-rain wi-owm-day-321: day-sprinkle wi-owm-day-500: day-sprinkle wi-owm-day-501: day-rain wi-owm-day-502: day-rain wi-owm-day-503: day-rain wi-owm-day-504: day-rain wi-owm-day-511: day-rain-mix wi-owm-day-520: day-showers wi-owm-day-521: day-showers wi-owm-day-522: day-showers wi-owm-day-531: day-storm-showers wi-owm-day-600: day-snow wi-owm-day-601: day-sleet wi-owm-day-602: day-snow wi-owm-day-611: day-rain-mix wi-owm-day-612: day-rain-mix wi-owm-day-615: day-rain-mix wi-owm-day-616: day-rain-mix wi-owm-day-620: day-rain-mix wi-owm-day-621: day-snow wi-owm-day-622: day-snow wi-owm-day-701: day-showers wi-owm-day-711: smoke wi-owm-day-721: day-haze wi-owm-day-731: dust wi-owm-day-741: day-fog wi-owm-day-761: dust wi-owm-day-762: dust wi-owm-day-781: tornado wi-owm-day-800: day-sunny wi-owm-day-801: day-cloudy-gusts wi-owm-day-802: day-cloudy-gusts wi-owm-day-803: day-cloudy-gusts wi-owm-day-804: day-sunny-overcast wi-owm-day-900: tornado wi-owm-day-902: hurricane wi-owm-day-903: snowflake-cold wi-owm-day-904: hot wi-owm-day-906: day-hail wi-owm-day-957: strong-wind wi-owm-night-200: night-alt-thunderstorm wi-owm-night-201: night-alt-thunderstorm wi-owm-night-202: night-alt-thunderstorm wi-owm-night-210: night-alt-lightning wi-owm-night-211: night-alt-lightning wi-owm-night-212: night-alt-lightning wi-owm-night-221: night-alt-lightning wi-owm-night-230: night-alt-thunderstorm wi-owm-night-231: night-alt-thunderstorm wi-owm-night-232: night-alt-thunderstorm wi-owm-night-300: night-alt-sprinkle wi-owm-night-301: night-alt-sprinkle wi-owm-night-302: night-alt-rain wi-owm-night-310: night-alt-rain wi-owm-night-311: night-alt-rain wi-owm-night-312: night-alt-rain wi-owm-night-313: night-alt-rain wi-owm-night-314: night-alt-rain wi-owm-night-321: night-alt-sprinkle wi-owm-night-500: night-alt-sprinkle wi-owm-night-501: night-alt-rain wi-owm-night-502: night-alt-rain wi-owm-night-503: night-alt-rain wi-owm-night-504: night-alt-rain wi-owm-night-511: night-alt-rain-mix wi-owm-night-520: night-alt-showers wi-owm-night-521: night-alt-showers wi-owm-night-522: night-alt-showers wi-owm-night-531: night-alt-storm-showers wi-owm-night-600: night-alt-snow wi-owm-night-601: night-alt-sleet wi-owm-night-602: night-alt-snow wi-owm-night-611: night-alt-rain-mix wi-owm-night-612: night-alt-rain-mix wi-owm-night-615: night-alt-rain-mix wi-owm-night-616: night-alt-rain-mix wi-owm-night-620: night-alt-rain-mix wi-owm-night-621: night-alt-snow wi-owm-night-622: night-alt-snow wi-owm-night-701: night-alt-showers wi-owm-night-711: smoke wi-owm-night-721: day-haze wi-owm-night-731: dust wi-owm-night-741: night-fog wi-owm-night-761: dust wi-owm-night-762: dust wi-owm-night-781: tornado wi-owm-night-800: night-clear wi-owm-night-801: night-alt-cloudy-gusts wi-owm-night-802: night-alt-cloudy-gusts wi-owm-night-803: night-alt-cloudy-gusts wi-owm-night-804: night-alt-cloudy wi-owm-night-900: tornado wi-owm-night-902: hurricane wi-owm-night-903: snowflake-cold wi-owm-night-904: hot wi-owm-night-906: night-alt-hail wi-owm-night-957: strong-wind ```JS req.then(function(resp) { var prefix = 'wi wi-'; var code = resp.weather[0].id; var icon = weatherIcons[code].icon; // If we are not in the ranges mentioned above, add a day/night prefix. if (!(code > 699 && code < 800) && !(code > 899 && code < 1000)) { icon = 'day-' + icon; } // Finally tack on the prefix. icon = prefix + icon; }); https://api.whatsapp.com/send?phone=081222172119&text=test whatsapp://send?phone=081222172119&text Color index Alpha in HEX RGBA Alpha % Hex Num 100% FF 255 99% FC 252 98% FA 250 97% F7 247 96% F5 245 95% F2 242 94% F0 240 93% ED 237 92% EB 235 91% E8 232 90% E6 230 89% E3 227 88% E0 224 87% DE 222 86% DB 219 85% D9 217 84% D6 214 83% D4 212 82% D1 209 81% CF 207 80% CC 204 79% C9 201 78% C7 199 77% C4 196 76% C2 194 75% BF 191 74% BD 189 73% BA 186 72% B8 184 71% B5 181 70% B3 179 69% B0 176 68% AD 173 67% AB 171 66% A8 168 65% A6 166 64% A3 163 63% A1 161 62% 9E 158 61% 9C 156 60% 99 153 59% 96 150 58% 94 148 57% 91 145 56% 8F 143 55% 8C 140 54% 8A 138 53% 87 135 52% 85 133 51% 82 130 50% 80 128 49% 7D 125 48% 7A 122 47% 78 120 46% 75 117 45% 73 115 44% 70 112 43% 6E 110 42% 6B 107 41% 69 105 40% 66 102 39% 63 99 38% 61 97 37% 5E 94 36% 5C 92 35% 59 89 34% 57 87 33% 54 84 32% 52 82 31% 4F 79 30% 4D 77 29% 4A 74 28% 47 71 27% 45 69 26% 42 66 25% 40 64 24% 3D 61 23% 3B 59 22% 38 56 21% 36 54 20% 33 51 19% 30 48 18% 2E 46 17% 2B 43 16% 29 41 15% 26 38 14% 24 36 13% 21 33 12% 1F 31 11% 1C 28 10% 1A 26 9% 17 23 8% 14 20 7% 12 18 6% 0F 15 5% 0D 13 4% 0A 10 3% 08 8 2% 05 5 1% 03 3 0% 00 0 onViewDidLoad void Runs when the page has loaded. This event only happens once per page being created. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The ionViewDidLoad event is good place to put your setup code for the page. ionViewWillEnter void Runs when the page is about to enter and become the active page. ionViewDidEnter void Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page. ionViewWillLeave void Runs when the page is about to leave and no longer be the active page. ionViewDidLeave void Runs when the page has finished leaving and is no longer the active page. ionViewWillUnload void Runs when the page is about to be destroyed and have its elements removed. ionViewCanEnter boolean/Promise Runs before the view can enter. This can be used as a sort of “guard” in authenticated views where you need to check permissions before the view can enter ionViewCanLeave boolean/Promise Runs before the view can leave. This can be used as a sort of “guard” in authenticated views where you need to check permissions before the view can leave<file_sep>import { Component, ChangeDetectorRef, ViewChild } from '@angular/core'; import { NavController, NavParams, Platform, AlertController, Content } from 'ionic-angular'; import { Calendar } from '@ionic-native/calendar'; import { CalDetailsPage } from '../cal-details/cal-details'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { LahanPage } from '../lahan/lahan'; @Component({ selector: 'page-calendar', templateUrl: 'calendar.html', }) export class CalendarPage { @ViewChild(Content) content: Content; calendars:any = []; agriFarmCalendar:any = []; showToolbar:boolean = false; result: any = []; jadwal: any = []; jadwalSemua: any = []; today: any = new Date(); adaJadwal: boolean = false; adaJadwalSemua: boolean = false; items: any = []; // Calendar date: any; daysInThisMonth: any; daysInLastMonth: any; daysInNextMonth: any; monthNames: string[]; currentMonth: any; currentYear: any; currentDate: any; eventList: any; selectedEvent: any; isSelected: any; currentClick: any; constructor(public navCtrl: NavController, public navParams: NavParams, private calendar: Calendar, private plt: Platform, public ref: ChangeDetectorRef, private alertCtrl: AlertController, public apiService: Api, public common: Common) { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } this.plt.ready().then(() => { this.calendar.listCalendars().then((data) => { this.calendars = data; for (let cal of data) { if (cal.name == "<EMAIL>") { this.agriFarmCalendar = cal; } } console.log(data); }, (err) => { console.log(err); }); }); } onScroll($event: any){ // hari ini 320 // panen mendatang 455 let scrollTop = $event.scrollTop; // console.log(scrollTop); this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } ionViewDidLoad() { //console.log('ionViewDidLoad CalendarPage'); } scrollTo(to) { this.content.scrollTo(0, to, 500); } ionViewWillEnter() { this.date = new Date(); this.monthNames = ["Januari","Februari","Maret","April","Mei","Juni","Juli","Augustus","September","Oktober","November","Desember"]; this.getDaysOfMonth(); this.loadEventThisMonth(); this.getJadwal(); this.getSemuaJadwal(); } getJadwal() { let resultData: any = []; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let userData = this.apiService.post("v1/kalendar/tanggal", postData); userData.subscribe((result) => { resultData = result; this.jadwal = resultData.data; this.adaJadwal = false; if (this.jadwal.length > 0) { this.adaJadwal = true; } }, (error) => { console.log(error); this.common.presentToast(error); }); } getSemuaJadwal() { let resultData: any = [];; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let userData = this.apiService.post("v1/kalendar/jadwal", postData); userData.subscribe((result) => { resultData = result; this.adaJadwalSemua = false; this.jadwalSemua = resultData.data; this.items = this.jadwalSemua; if (this.jadwalSemua.length > 0) { this.adaJadwalSemua = true; } }, (error) => { console.log(error); this.common.presentToast(error); }); } openLahan(id) { this.navCtrl.push(LahanPage, { id: id }); } createCalendar() { this.calendar.createCalendar("Agri Farm").then( (msg) => { console.log(msg); }, (err) => { console.log(err); } ); } deleteCalendar() { this.calendar.deleteCalendar("Agri Farm").then( (msg) => { console.log(msg); }, (err) => { console.log(err); } ); } addEvent(cal) { let date = new Date(); let options = { calendarId: cal.id, calendarName: cal.name, url: 'https://google.com', firstReminderMinutes: 15, calendarColor: '#32db64' }; //this.calendar.createEventInteractivelyWithOptions('Test Events', 'Jakarta', 'Special Notes', date, date, options).then(res => { this.calendar.createEventWithOptions('My new Event', 'Jakarta', 'Special Notes', date, date, options).then(res => { }, err => { console.log('err: ', err); alert('err: ' + err); }); } openCal(cal) { this.navCtrl.push(CalDetailsPage, { name: cal.name }) } getDaysOfMonth() { this.daysInThisMonth = new Array(); this.daysInLastMonth = new Array(); this.daysInNextMonth = new Array(); this.currentMonth = this.monthNames[this.date.getMonth()]; this.currentYear = this.date.getFullYear(); if(this.date.getMonth() === new Date().getMonth()) { this.currentDate = new Date().getDate(); } else { this.currentDate = 999; } var firstDayThisMonth = new Date(this.date.getFullYear(), this.date.getMonth(), 1).getDay(); var prevNumOfDays = new Date(this.date.getFullYear(), this.date.getMonth(), 0).getDate(); for(var i = prevNumOfDays-(firstDayThisMonth-1); i <= prevNumOfDays; i++) { this.daysInLastMonth.push(i); } var thisNumOfDays = new Date(this.date.getFullYear(), this.date.getMonth()+1, 0).getDate(); for (var ii = 0; ii < thisNumOfDays; ii++) { this.daysInThisMonth.push(ii+1); } var lastDayThisMonth = new Date(this.date.getFullYear(), this.date.getMonth()+1, 0).getDay(); // var nextNumOfDays = new Date(this.date.getFullYear(), this.date.getMonth()+2, 0).getDate(); for (var iii = 0; iii < (6-lastDayThisMonth); iii++) { this.daysInNextMonth.push(iii+1); } var totalDays = this.daysInLastMonth.length+this.daysInThisMonth.length+this.daysInNextMonth.length; if(totalDays<36) { for(var iiii = (7-lastDayThisMonth); iiii < ((7-lastDayThisMonth)+7); iiii++) { this.daysInNextMonth.push(iiii); } } } goToNextMonth() { this.date = new Date(this.date.getFullYear(), this.date.getMonth()+2, 0); this.getDaysOfMonth(); this.currentClick = 0; } goToLastMonth() { this.date = new Date(this.date.getFullYear(), this.date.getMonth(), 0); this.getDaysOfMonth(); this.currentClick = 0; } loadEventThisMonth() { this.eventList = new Array(); var startDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1); var endDate = new Date(this.date.getFullYear(), this.date.getMonth()+1, 0); this.calendar.listEventsInRange(startDate, endDate).then( (msg) => { msg.forEach(item => { this.eventList.push(item); }); }, (err) => { console.log(err); } ); } checkEvent(day) { var hasEvent = false; var thisDate1 = this.date.getFullYear()+"-"+(this.date.getMonth()+1)+"-"+day+" 00:00:00"; var thisDate2 = this.date.getFullYear()+"-"+(this.date.getMonth()+1)+"-"+day+" 23:59:59"; this.eventList.forEach(event => { if(((event.startDate >= thisDate1) && (event.startDate <= thisDate2)) || ((event.endDate >= thisDate1) && (event.endDate <= thisDate2))) { hasEvent = true; } }); return hasEvent; } selectDate(day) { this.currentClick = day; this.isSelected = false; this.selectedEvent = new Array(); var thisDate1 = this.date.getFullYear()+"-"+(this.date.getMonth()+1)+"-"+day+" 00:00:00"; var thisDate2 = this.date.getFullYear()+"-"+(this.date.getMonth()+1)+"-"+day+" 23:59:59"; this.eventList.forEach(event => { if(((event.startDate >= thisDate1) && (event.startDate <= thisDate2)) || ((event.endDate >= thisDate1) && (event.endDate <= thisDate2))) { this.isSelected = true; this.selectedEvent.push(event); } }); } deleteEvent(evt) { // console.log(new Date(evt.startDate.replace(/\s/, 'T'))); // console.log(new Date(evt.endDate.replace(/\s/, 'T'))); let alert = this.alertCtrl.create({ title: 'Confirm Delete', message: 'Are you sure want to delete this event?', buttons: [ { text: 'Cancel', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }, { text: 'Ok', handler: () => { this.calendar.deleteEvent(evt.title, evt.location, evt.notes, new Date(evt.startDate.replace(/\s/, 'T')), new Date(evt.endDate.replace(/\s/, 'T'))).then( (msg) => { console.log(msg); this.loadEventThisMonth(); this.selectDate(new Date(evt.startDate.replace(/\s/, 'T')).getDate()); }, (err) => { console.log(err); } ) } } ] }); alert.present(); } } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, ActionSheetController, Events } from 'ionic-angular'; import { HttpClient } from '@angular/common/http'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { UploadFilePage } from '../upload-file/upload-file'; import { ProfilePicturePage } from '../profile-picture/profile-picture'; import { ProfileEditPage } from '../profile-edit/profile-edit'; import { ProfileAlamatPage } from '../profile-alamat/profile-alamat'; import { LocationTrackerPage } from '../location-tracker/location-tracker'; import { LahanPage } from '../lahan/lahan'; @Component({ selector: 'page-profile', templateUrl: 'profile.html', }) export class ProfilePage { base64Image: string; capture:boolean = false; result: any = []; alamat: any =[]; user:any = []; lahan: any = []; adaLahan: boolean = false; komoditas: any = []; adaKomoditas: boolean = false; showToolbar:boolean = false; items: Array<string>; navigasi: string = "lahan"; userData = {"latitude":null, "longitude":null, "name":"", "pic":null, "token":"", "type":"", "user_id":"0"}; constructor(public navCtrl: NavController, public navParams: NavParams, public http: HttpClient, public apiService: Api, public common: Common, public ref: ChangeDetectorRef, public actionSheetCtrl: ActionSheetController, public events: Events) { } ionViewDidLoad() { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } this.navigasi = "lahan"; this.loadFoto(); this.loadAlamat(); this.loadLahan(); this.loadKomoditas(); } loadFoto() { if (this.result.pic != null) { this.base64Image = this.apiService.url + this.result.pic; } else { this.base64Image = "assets/img/agritama.png"; } } loadAlamat() { let resultData: any = [];; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let userData = this.apiService.post("v1/user/" + this.result.user_id, postData); userData.subscribe((result) => { resultData = result; this.user = resultData.data; }, (error) => { console.log(error); this.common.presentToast(error); }); } loadLahan() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let data = this.apiService.post("v1/lahan", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.lahan = data.data; // console.log(this.lahan) this.adaLahan = true; } else { this.adaLahan = false; } } else { this.adaLahan = false; } }, (error) => { }); } loadKomoditas() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let data = this.apiService.post("v1/komoditas", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.komoditas = data.data; // console.log(this.komoditas) this.adaKomoditas = true; } else { this.adaKomoditas = false; } } else { this.adaKomoditas = false; } }, (error) => { }); } getLuas = (luas: string) => { let rt: string; switch(luas) { case "T": rt = "Tumbak"; break; case "M": rt = "Meter"; break; default: rt = "Hektar"; break; } return rt; } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } segmentChanged(event) { this.navigasi = event.value; } goUpload() { this.navCtrl.push(UploadFilePage); } viewLocation() { if (this.user.latitude && this.user.longitude) { this.navCtrl.push(LocationTrackerPage, {lat: this.user.latitude, lng: this.user.longitude}); } } goUploadPicture() { this.navCtrl.push(ProfilePicturePage, { callback: this.callback }); } presentActionSheet() { const actionSheet = this.actionSheetCtrl.create({ title: 'Lengkapi', buttons: [{ text: 'Profil', role: 'destructive', icon: 'person', handler: () => { this.navCtrl.push(ProfileEditPage, { callback: this.callback }); } },{ text: 'Alamat', icon: 'pin', handler: () => { this.navCtrl.push(ProfileAlamatPage, { callback: this.callback }); } },{ text: 'Tutup', role: 'cancel', icon: 'close', cssClass: 'border-top', handler: () => { console.log('Cancel clicked'); } }] }); actionSheet.present(); } callback = (data?) => { this.common.presentLoading(); let resultData: any = [];; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); postData.append('update', data ? data : "1"); let userData = this.apiService.post("v1/user/me", postData); userData.subscribe((result) => { resultData = result; localStorage.setItem('userData', JSON.stringify(resultData.data)); if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } this.loadFoto(); this.loadAlamat(); this.events.publish('user:login', Date.now()); this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } openLahan(id) { this.navCtrl.push(LahanPage, { id: id }); } } <file_sep>import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms'; registerForm = new FormGroup({ nama: new FormControl(), email: new FormControl(), password: new FormControl(), refpassword: new FormControl() }); submitAttempt: boolean = false; label: any = {}; emailRegx: any; passwordRegx: any; nameRegx: any; phoneNumberRegx: any; messageLabel: any; userdata: any; ionViewDidLoad() { this.emailRegx = this.validator.emailRegx; this.passwordRegx = this.validator.passwordRegx; this.nameRegx = this.validator.nameRegx; this.phoneNumberRegx = this.validator.phoneNumberRegx; this.registerForm = this.formBuilder.group({ nama: ['', Validators.compose([Validators.required, this.validator.nameValidator.bind(this)])], email: ['', Validators.compose([Validators.required, this.validator.emailValidator.bind(this)])], password: ['', Validators.compose([Validators.required, this.validator.passwordValidator.bind(this)])], refpassword: ['', Validators.compose([Validators.required])] }, {'validator': this.validator.isMatching}); } <ion-list> <form [formGroup]="registerForm" (ngSubmit)="register()"> <ion-item> <ion-icon name="contact" item-start></ion-icon> <ion-input formControlName="first_name" type="text" placeholder="<NAME>"></ion-input> </ion-item> <ion-item class="no-line error" *ngIf="!registerForm.controls.first_name.valid && (registerForm.controls.first_name.dirty || submitAttempt) && !registerForm.controls.first_name.pending"> <p *ngIf="registerForm.value.first_name != ''">First name not valid</p> <p *ngIf="registerForm.value.first_name == ''">First name required</p> </ion-item> <ion-item> <ion-icon name="contact" item-start></ion-icon> <ion-input formControlName="last_name" type="text" placeholder="<NAME>"></ion-input> </ion-item> <ion-item class="no-line error" *ngIf="!registerForm.controls.last_name.valid && (registerForm.controls.last_name.dirty || submitAttempt) && !registerForm.controls.last_name.pending"> <p *ngIf="registerForm.value.last_name != ''">Last name not valid</p> <p *ngIf="registerForm.value.last_name == ''">Last name required</p> </ion-item> <ion-item> <ion-icon name="mail" item-start></ion-icon> <ion-input formControlName="email" type="email" placeholder="Email"></ion-input> </ion-item> <ion-item class="no-line error" *ngIf="!registerForm.controls.email.valid && (registerForm.controls.email.dirty || submitAttempt) && !registerForm.controls.email.pending"> <p *ngIf="registerForm.value.email != ''">Email not valid</p> <p *ngIf="registerForm.value.email == ''">Email required</p> </ion-item> <ion-item> <ion-icon name="lock" item-start></ion-icon> <ion-input formControlName="password" type="<PASSWORD>" placeholder="<PASSWORD>"></ion-input> </ion-item> <ion-item class="no-line error" *ngIf="!registerForm.controls.password.valid && (registerForm.controls.password.dirty || submitAttempt) && !registerForm.controls.password.pending"> <p *ngIf="registerForm.value.password != ''">Password not valid</p> <p *ngIf="registerForm.value.password == ''">Password required</p> </ion-item> <ion-item> <ion-icon name="lock" item-start></ion-icon> <ion-input formControlName="confirmPassword" type="<PASSWORD>" placeholder="Confirm Password"></ion-input> </ion-item> <ion-item class="no-line error" *ngIf="registerForm.value.password != registerForm.value.confirmPassword && registerForm.value.confirmPassword != '' && (registerForm.controls.confirmPassword.dirty || submitRegisterAttempt) && !registerForm.controls.confirmPassword.pending && registerForm.value.password != '' && registerForm.controls.password.valid"> <p>Confirm password not valid</p> </ion-item> <ion-item class="no-line error" *ngIf="registerForm.value.confirmPassword == '' && (registerForm.controls.confirmPassword.dirty || submitRegisterAttempt) && !registerForm.controls.confirmPassword.pending && registerForm.value.password != '' && registerForm.controls.password.valid"> <p>Confirm password required</p> </ion-item> <ion-item class="signup_btn"> <button ion-button >Sign Up</button> </ion-item> </form> </ion-list><file_sep>import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { TodoListPage } from '../todo-list/todo-list'; import { GroceryListPage } from '../grocery-list/grocery-list'; @Component({ selector: 'page-lists-tabs', templateUrl: 'lists-tabs.html', }) export class ListsTabsPage { tab1 = TodoListPage; tab2 = GroceryListPage; constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { } } <file_sep>import { Injectable } from '@angular/core'; import { LoadingController, ToastController } from 'ionic-angular'; @Injectable() export class Common { public loader: any; public user: { "user_id": "", "token": "", "name": "", "pic": null, "type": 0}; public auth: boolean = false; public userInroom = []; public room = []; constructor(public loadingCtrl: LoadingController, private toastCtrl:ToastController) { //console.log('Hello Common Provider'); } presentLoading() { this.loader = this.loadingCtrl.create({content: "Mohon tunngu ..."}) this.loader.present(); } closeLoading() { this.loader.dismiss(); } presentToast(msg) { let toast = this.toastCtrl.create({ message: msg, duration: 5000, showCloseButton: true, closeButtonText: "ok", position: "bottom" }); toast.present(); } initUser() { if (localStorage.getItem('userData')) { this.user = JSON.parse(localStorage.getItem('userData')); this.auth = true; } this.auth = false; } getUser() { if (localStorage.getItem('userData')) { this.user = JSON.parse(localStorage.getItem('userData')); } return this.user; } timeSince = (date:any) => { let now:any = new Date(); date = new Date(date); let seconds = Math.floor((now - date) / 1000); let interval = Math.floor(seconds / 31536000); if (interval > 1) { return interval + " tahun yang lalu"; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return interval + " bulan yang lalu"; } interval = Math.floor(seconds / 86400); if (interval > 1) { return interval + " hari yang lalu"; } interval = Math.floor(seconds / 3600); if (interval > 1) { return interval + " jam yang lalu"; } interval = Math.floor(seconds / 60); if (interval > 1) { return interval + " menit yang lalu"; } if (interval == 0 ) { return "baru saja"; } return Math.floor(seconds) + " detik yang lalu"; } relative_time = (date?: number) => { if (!date) date = new Date().getTime() / 1000; var now = new Date().getTime() / 1000; var elapsed = Math.round(now - date); if (elapsed <= 1) { return "baru saja"; } var rounded, title; if (elapsed > 31104000) { rounded = elapsed / 31104000; title = "tahun"; } else if (elapsed > 2592000) { rounded = elapsed / 2592000; title = "bulan"; } else if (elapsed > 604800) { elapsed = elapsed / 604800; title = "minggu"; } else if (elapsed > 86400) { rounded = elapsed / 86400; title = "hari"; } else if (elapsed > 3600) { rounded = elapsed / 3600; title = "jam"; } else if (elapsed > 60) { rounded = elapsed / 60; title = "menit"; } else if (elapsed >= 1) { rounded = elapsed / 1; title = "detik"; } if (rounded > 1) { rounded = Math.round(rounded); return rounded + " " + title + " yang lalu"; } }; getHHMM = (t: number) => { let d = new Date(t * 1000); let h = d.getHours(); let m = d.getMinutes(); let a = ""; let ms = ""; if (h > 0 && h < 12) { a = "AM"; } else { if (h == 0) a = "AM"; else a = "PM"; } if (m < 10) ms = "0" + m; else ms = "" + m; return (h == 0 || h == 12 ? 12 : h % 12) + ":" + ms + " " + a; }; timeUntil = (date: string) => { date = date + ""; let dates = date.split("/"); let year = parseInt(dates[0]); let month = parseInt(dates[1]); let day = parseInt(dates[2]); let hour = 0; let minute = 0; let second = 0; let yrr = 0; let eventtext = "menjelang panen"; let endtext = "Waktu panen tiba"; let end = new Date(year, month, day, hour, minute, second); let now = new Date(); if (now.getFullYear() < 1900) yrr = now.getFullYear() + 1900; let sec = second - now.getSeconds(); let min = minute - now.getMinutes(); let hr = hour - now.getHours(); let dy = day - now.getDate(); let mnth = month - now.getMonth(); let yr = year - yrr; let daysinmnth = 32 - new Date(now.getFullYear(),now.getMonth(), 32).getDate(); if (sec < 0) { sec = (sec + 60) % 60; min--; } if (min < 0) { min = (min + 60) % 60; hr--; } if (hr < 0) { hr = (hr + 24) % 24; dy--; } if (dy < 0) { dy = (dy + daysinmnth) % daysinmnth; mnth--; } if (mnth < 0) { mnth = (mnth + 12) % 12; yr--; } let dytext = " hari, "; let mnthtext = " bulan, "; let yrtext = " tahun, "; if (yr == 1) yrtext = " tahun, "; if (mnth == 1) mnthtext = " bulan, "; if (dy == 1) dytext = " hari, "; if(now >= end) { // clearTimeout(timerID); return endtext; } else { // timerID = setTimeout(() => { "timeUntil" }, 1000); return yr + yrtext + mnth + mnthtext + dy + dytext + eventtext; } } timeUntilHours = (date: string) => { let startDate = new Date(); let endDate = new Date(date); let dates = (endDate.getTime() - startDate.getTime()) / (24 * 3600) + ""; return parseInt(dates, 10); } timeUntilDays = (date: string) => { let startDate = new Date(); let endDate = new Date(date); let dates = (endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000) + ""; return parseInt(dates, 10); } timeUntilWeeks = (date: string) => { let startDate = new Date(); let endDate = new Date(date); let dates = (endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000 * 7) + ""; return parseInt(dates, 10); } timeUntilMonths = (date: string) => { let startDate = new Date(); let endDate = new Date(date); return (endDate.getMonth() + 12 * endDate.getFullYear()) - (startDate.getMonth() + 12 * startDate.getFullYear()); } timeUntilYears = (date: string) => { let startDate = new Date(); let endDate = new Date(date); return endDate.getFullYear() - startDate.getFullYear(); } } <file_sep>import { Component, ChangeDetectorRef, ViewChild } from '@angular/core'; import { NavController, NavParams, Content } from 'ionic-angular'; import { Geolocation } from '@ionic-native/geolocation'; import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; @Component({ selector: 'page-profile-alamat', templateUrl: 'profile-alamat.html', }) export class ProfileAlamatPage { @ViewChild(Content) content: Content; showToolbar: boolean = false; geocoderOptions: NativeGeocoderOptions = { useLocale: true, maxResults: 5, defaultLocale: "id_ID" }; locationResult: any = []; isTracked: boolean = false; userLocation = {"latitude": null, "longitude": null}; result:any = []; userData: any = []; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common, private geolocation: Geolocation, private nativeGeocoder: NativeGeocoder) { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } } ionViewDidLoad() { } getMe() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let userData = this.apiService.post("v1/user/me", postData); userData.subscribe((result) => { this.userData = result['data']; }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); }); } back() { this.navCtrl.pop(); } save() { this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('lokasi', this.locationResult.thoroughfare); postData.append('no', this.locationResult.subThoroughfare); postData.append('kecamatan', this.locationResult.subLocality); postData.append('kabupaten', this.locationResult.locality); postData.append('provinsi', this.locationResult.administrativeArea); postData.append('negara', this.locationResult.countryName); postData.append('kodepos', this.locationResult.postalCode); postData.append('kodenegara', this.locationResult.countryCode); // Lat-Lang postData.append('latitude', this.userLocation.latitude); postData.append('longitude', this.userLocation.longitude); let userData = this.apiService.post("v1/user/lat-lng", postData); userData.subscribe((result) => { //console.log(result); this.navCtrl.pop().then(() => { this.postLokasi(); this.navParams.get("callback")("1"); }); this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } postLokasi() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Field if (this.locationResult.length != 0) { postData.append('user_lokasi', this.locationResult.subLocality + ", " + this.locationResult.locality + " — " + this.locationResult.administrativeArea); } else { postData.append('user_lokasi', ""); } let userLokasi = this.apiService.post("v1/user/lokasi", postData); userLokasi.subscribe((result) => { //console.log(result); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); }); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } scrollTop() { var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } locate() { this.common.presentLoading(); this.geolocation.getCurrentPosition().then((resp) => { this.userLocation.latitude = resp.coords.latitude this.userLocation.longitude = resp.coords.longitude this.reverseGeocode(resp.coords.latitude, resp.coords.longitude); this.common.closeLoading(); this.isTracked = true; }).catch((error) => { console.log('Error getting location', error); this.common.closeLoading(); }); } forwardGeocode(location: string) { this.nativeGeocoder.forwardGeocode(location, this.geocoderOptions) .then((coordinates: NativeGeocoderForwardResult[]) => { console.log('The coordinates are latitude=' + coordinates[0].latitude + ' and longitude=' + coordinates[0].longitude) //alert(coordinates[0].latitude); //alert(coordinates[0].longitude); }) .catch((error: any) => { console.log(error) }); } reverseGeocode(lat: any, lng: any) { this.nativeGeocoder.reverseGeocode(lat, lng, this.geocoderOptions) .then((result: NativeGeocoderReverseResult[]) => { console.log(JSON.stringify(result[0])); this.locationResult = result[0]; }) .catch((error: any) => { console.log(error) }); } } <file_sep><ion-header [class.opaque]="showToolbar"> <ion-navbar color="agrifarm"> <ion-title [hidden]="!showToolbar"> Edit Alamat / Lokasi </ion-title> </ion-navbar> </ion-header> <ion-content (ionScroll)="onScroll($event)"> <div class="cover header-md"> <img class="cover" src="assets/img/cover.png" alt="home" style="margin-top: -55px;"> </div> <div margin-top padding *ngIf="!isTracked"> <ion-fab center> <button ion-fab color="agrifarm" (click)="locate()"> <ion-icon name="locate"></ion-icon> </button> </ion-fab> <div margin-top ion-text text-center> <h6 style="position: relative; top: 60px;">Track Lokasi</h6> </div> </div> <ion-card *ngIf="isTracked"> <ion-item> <ion-avatar item-start> <ion-icon name="pin" style="zoom: 2.0; padding: 5px;"></ion-icon> </ion-avatar> <h2 ion-text color="agrifarm">{{locationResult.locality || 'Sumedang'}}</h2> <p ion-text text-left>{{locationResult.subLocality || 'Cipacing'}}</p> <button ion-fab mini item-end (click)="locate()" color="agrifarm"><ion-icon name="locate"></ion-icon></button> </ion-item> <img src="assets/img/cover_p.png" style="height: 120px;"> <div class="card-title"><ion-icon name="pin" color="googleyellow"></ion-icon></div> <div class="card-subtitle">{{locationResult.subLocality || 'Cipacing'}} &mdash; {{locationResult.locality || 'Sumedang'}}</div> <ion-card-content> <ion-grid> <ion-row> <ion-col col-6 no-padding ion-text text-left> Lat: {{userLocation.latitude}} </ion-col> <ion-col col-6 no-padding ion-text text-right> Lng: {{userLocation.longitude}} </ion-col> </ion-row> </ion-grid> <ion-grid> <ion-row> <ion-col col-4 ion-text text-right> Lokasi <br/> No <br/> Kecamatan <br/> Kabupaten <br/> Provinsi <br/> Negara <br/> Kodepos <br/> Kode Negara <br/> </ion-col> <ion-col col-8> <span ion-text color="agrifarmdark">{{locationResult.thoroughfare || 'Jalan Kartika III Block E'}}</span><br/> <span ion-text color="agrifarmdark">{{locationResult.subThoroughfare || '4'}}</span><br/> <span ion-text color="agrifarmdark">{{locationResult.subLocality || 'Cipacing'}}</span><br/> <span ion-text color="agrifarmdark">{{locationResult.locality || 'Sumedang'}}</span><br/> <span ion-text color="agrifarmdark">{{locationResult.administrativeArea || 'Jawa Barat'}}</span><br/> <span ion-text color="agrifarmdark">{{locationResult.countryName || 'Indonesia'}}</span><br/> <span ion-text color="agrifarmdark">{{locationResult.postalCode || '45363'}}</span><br/> <span ion-text color="agrifarmdark">{{locationResult.countryCode || 'ID'}}</span><br/> </ion-col> </ion-row> </ion-grid> </ion-card-content> </ion-card> </ion-content> <ion-footer> <ion-toolbar> <ion-buttons left> <button ion-button clear color="agrifarm" style="padding: 18px;" (click)="back()"> Batal </button> </ion-buttons> <ion-buttons right> <button ion-button clear icon-start solid style="padding: 18px;" color="agrifarm" (click)="save()" [disabled]="!isTracked"> <ion-icon name="checkmark"></ion-icon> Simpan </button> </ion-buttons> </ion-toolbar> </ion-footer> <file_sep>import { Component, ViewChild } from "@angular/core"; import { NavController, NavParams, Tabs, MenuController, Events } from "ionic-angular"; import { DashboardPage } from "../dashboard/dashboard"; import { ChatPage } from "../chat/chat"; import { CalendarPage } from "../calendar/calendar"; import { SearchPage } from "../search/search"; import { RoomListPage } from "../room-list/room-list"; @Component({ selector: "page-dashboard-tabs", templateUrl: "dashboard-tabs.html" }) export class DashboardTabsPage { result: any = []; tab0 = DashboardPage; tab1 = SearchPage; tab2 = CalendarPage; tab3 = RoomListPage; // tab3 = ChatPage; // params = { nickname: "" }; // nickname:any = "Agronimis"; // Revisi chatCount: number = 0; nickname: string = ""; @ViewChild("myTabs") tabsRef: Tabs; constructor( public navCtrl: NavController, public navParams: NavParams, public menu: MenuController, public event: Events ) { let data = JSON.parse(localStorage.getItem('userData')); this.nickname = data.name; // event.subscribe('chat:updated', (data) => { // if (this.nickname != data.sender) { // this.chatCount = data.count; // } // }); // event.subscribe('chat:read', () => { // this.chatCount = 0; // }); } ionViewDidLoad() {} ionViewWillEnter() {} } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { HttpClient } from '@angular/common/http'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { LocationTrackerPage } from '../location-tracker/location-tracker'; @Component({ selector: 'page-profile-id', templateUrl: 'profile-id.html', }) export class ProfileIdPage { base64Image: string; capture:boolean = false; result: any = []; user:any = []; alamat: any =[]; lahan: any = []; adaLahan: boolean = false; komoditas: any = []; adaKomoditas: boolean = false; showToolbar:boolean = false; items: Array<string>; navigasi: string = "lahan"; userData = {"latitude":null, "longitude":null, "name":"", "pic":null, "token":"", "type":"", "user_id":"0"}; user_id: any = 0; constructor(public navCtrl: NavController, public navParams: NavParams, public http: HttpClient, public apiService: Api, public common: Common, public ref: ChangeDetectorRef) { this.user_id = this.navParams.get("user_id"); } ionViewDidLoad() { this.navigasi = "lahan"; } ionViewWillLoad() { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } if (!this.user_id) return; this.loadUser(); this.loadFoto(); } loadUser() { if (!this.user_id) return; let resultData: any = [];; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let userData = this.apiService.post("v1/user/" + this.user_id, postData); userData.subscribe((result) => { resultData = result; this.user = resultData.data; console.log(this.user); this.loadFoto(); this.loadLahan(); this.loadKomoditas(); }, (error) => { console.log(error); this.common.presentToast(error); }); } loadFoto() { if (!this.user_id) return; if (this.user.foto != null) { this.base64Image = this.apiService.url + this.user.foto; } else { this.base64Image = "assets/img/agritama.png"; } } viewLocation() { if (this.user.latitude && this.user.longitude) { this.navCtrl.push(LocationTrackerPage, {lat: this.user.latitude, lng: this.user.longitude}); } } loadLahan() { if (!this.user_id) return; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); postData.append('id', this.user_id); let data = this.apiService.post("v1/lahan", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.lahan = data.data; this.adaLahan = true; } else { this.adaLahan = false; } } else { this.adaLahan = false; } }, (error) => { }); } loadKomoditas() { if (!this.user_id) return; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); postData.append('id', this.user_id); let data = this.apiService.post("v1/komoditas", postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.komoditas = data.data; this.adaKomoditas = true; } else { this.adaKomoditas = false; } } else { this.adaKomoditas = false; } }, (error) => { }); } getLuas = (luas: string) => { let rt: string; switch(luas) { case "T": rt = "Tumbak"; break; case "M": rt = "Meter"; break; default: rt = "Hektar"; break; } return rt; } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } segmentChanged(event) { this.navigasi = event.value; } callback = (data?) => { let resultData: any = [];; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); postData.append('update', data ? data : "1"); let userData = this.apiService.post("v1/user/me", postData); userData.subscribe((result) => { resultData = result; localStorage.setItem('userData', JSON.stringify(resultData.userData)); }, (error) => { console.log(error); this.common.presentToast(error); }); } openWhatsApp = (phone: string) => { window.open("https://api.whatsapp.com/send?phone=" + phone + "&text=Halo!"); } openSms = (phone: string) => { window.open("sms:+" + phone); } openTel = (phone: string) => { window.open("tel:" + phone); } openMail = (email: string) => { window.open("mailto:" + email); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { SocketProvider } from '../socket/socket'; @Injectable() export class DataProvider { socketUrl: string = 'http://localhost:8080'; apiUrl: string = 'http://localhost'; // Array feeds: any = []; rooms: any = []; user: any = []; clients: any = []; // Boolean isAuth: boolean = false; inRoom: boolean = false; // Object chats: any = {}; headers:any = { 'Content-Type': 'application/json', 'Accept': 'application/json' }; constructor(public http: HttpClient, public socket: SocketProvider) { if (localStorage.getItem('userData')) { this.user = JSON.parse(localStorage.getItem('userData')); this.isAuth = true; } } getFeed() { this.http.get(this.socketUrl + '/feed/' + this.user.user_id, { headers:this.headers }) .subscribe(data => { let result:any = data; this.feeds = result.feed; }, error => { console.log("data:provider", error); }); } getRoom(update?:boolean) { this.http.get(this.socketUrl + '/room/' + this.user.user_id, { headers: this.headers }) .subscribe(data => { let room:any = data; if (room.count === 0) return; if (update) this.rooms = []; room.rooms.map(data => { let chat = { id: data.id, subject: data.subject, created: data.created, agronomis: data.agronomis, message: data.chat, new: 0 } if (this.rooms.length === 0) { this.rooms.unshift(chat); } else { if (!this.roomExists(data.id)) { this.rooms.unshift(chat); } } this.updateMessage(data.id); }); if (!update) this.roomsJoin(); }, error => { console.log("data:provider", error); }); } addRoom(body, cb?:any) { this.http.post(this.socketUrl + '/room', body, { headers: this.headers }).subscribe(data => { let room:any = data; // SOCKET JOIN this.socket.joinRoom(room.room_id); if (cb) cb(room); }, err => { console.log(err); }) } updateMessage(roomId) { var that = this; this.http.get(this.socketUrl + "/room/read/" + roomId + "/" + this.user.user_id).subscribe(data => { let unread:any = data; Object.keys(this.rooms).forEach(function(id) { if (that.rooms[id].id === roomId) { that.rooms[id].new = unread.count; } }); }); } newMessage(roomId, chat?:any) { var that = this; Object.keys(this.rooms).forEach(function(id) { if (that.rooms[id].id === roomId) { that.rooms[id].new++; if (chat) { that.rooms[id].message = chat; } } }); } isOnline(userId: number): boolean { if (this.clients.length === 0) return false; const index = this.clients.findIndex(user => user.id_user === userId); return index !== -1 ? true : false; } roomExists(roomId: string): boolean { const index = this.rooms.findIndex(chat => chat.id === roomId); return index !== -1 ? true : false; } roomRemove(roomId) { var that = this; Object.keys(this.rooms).forEach(function(id) { if (that.rooms[id].id === roomId) { that.rooms.splice(parseInt(id), 1); } }); } roomsJoin() { let that = this; Object.keys(this.rooms).forEach(function(id) { that.socket.joinRoom(that.rooms[id].id); console.log('data:provider | joining room:', that.rooms[id].id); }); } roomsLeave() { let that = this; Object.keys(this.rooms).forEach(function(id) { that.socket.leaveRoom(that.rooms[id].id); console.log('data:provider | leaving room:', that.rooms[id].id); }); } getAgronomis(id) { let endpoint = 'v1/nama/' + id; return this.http.get(this.apiUrl + '/' + endpoint); } getChat(roomId) { return this.http.get(this.socketUrl + '/room/id/' + roomId, { headers: this.headers }) } addChat(roomId, data) { let body = JSON.stringify(data); return this.http.post(this.socketUrl + '/room/id/' + roomId, body, { headers: this.headers }); } readChat(roomId) { let body: any = JSON.stringify({ "userId": parseInt(this.user.user_id) }); return this.http.post(this.socketUrl + '/room/read/' + roomId + '/' + this.user.user_id, body, { headers: this.headers }); } } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { Headers, RequestOptions, Http, URLSearchParams } from '@angular/http'; import { LogerProvider } from '../../providers/loger/loger'; @Component({ selector: 'page-no-tabs', templateUrl: 'no-tabs.html', }) export class NoTabsPage { showToolbar:boolean = false; tokenData: Promise<any>; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common, public http: Http, public log: LogerProvider) { } ionViewDidLoad() { //console.log('ionViewDidLoad NoTabsPage'); // this.tokenLogin(); } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } tokenLogin() { let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': "Bearer <KEY>" }); let options = new RequestOptions({ headers: headers }); let body = JSON.stringify({ "user_id": "1" }); let params = new URLSearchParams(); params.append('user_id', '1'); this.http.put('https://agritama.farm/api/test.php', body, { headers: new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Authorization': "Bearer <KEY>" }) }).subscribe(data => { this.log.success(data.json(), true); this.log.info(data.json().req_token, true); }) this.apiService._get('v1/token', { headers: headers, params: params }).subscribe(data => { this.log.info(data.json(), true); }, err => { this.log.error(err, true); }) this.apiService._delete('v1/token', { headers: headers, params: params }).subscribe(data => { this.log.warnig(data.json(), true); }, err => { this.log.error(err, true); }) this.apiService._post('v1/token', body, options).subscribe(data => { this.log.success(data.json(), true); }, err => { this.log.error(err, true); }) this.apiService._put('v1/token', body, options).subscribe(data => { this.log.info(data.json(), true); }, err => { this.log.error(err, true); }) this.apiService._patch('v1/token', body, options).subscribe(data => { this.log.error(data.json(), true); }, err => { this.log.error(err, true); }) } } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { Common } from '../../providers/common/common'; import { Api } from '../../providers/api/api'; import { LahanPage } from '../lahan/lahan'; @Component({ selector: 'page-grocery-list', templateUrl: 'grocery-list.html', }) export class GroceryListPage { showToolbar: boolean = false; result: any = []; jadwal: any = []; items: any = []; adaJadwal: boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public apiService: Api, public common: Common) { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } } ionViewDidLoad() { this.getJadwal(); } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 50; this.ref.detectChanges(); } getJadwal() { let resultData: any = [];; let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let userData = this.apiService.post("v1/kalendar/tanggal", postData); userData.subscribe((result) => { resultData = result; this.adaJadwal = false; this.jadwal = resultData.data; this.items = this.jadwal; if (this.jadwal.length > 0) { this.adaJadwal = true; } // console.log(this.jadwal); }, (error) => { console.log(error); this.common.presentToast(error); }); } viewLahan(id) { this.navCtrl.push(LahanPage, { id: id }); } } <file_sep>import { Component } from "@angular/core"; import { Platform, Keyboard, Events } from "ionic-angular"; import { StatusBar } from "@ionic-native/status-bar"; import { SplashScreen } from "@ionic-native/splash-screen"; import { ScreenOrientation } from "@ionic-native/screen-orientation"; import { HomePage } from "../pages/home/home"; import { WellcomePage } from "../pages/wellcome/wellcome"; import { Common } from "../providers/common/common"; import { Api } from "../providers/api/api"; import { Observable } from "rxjs/Observable"; import { DataProvider } from "../providers/data/data"; import { SocketProvider } from "../providers/socket/socket"; @Component({ templateUrl: "app.html" }) export class MyApp { rootPage: any = WellcomePage; result: any = []; constructor( platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, keyboard: Keyboard, screenOrientation: ScreenOrientation, events: Events, public common: Common, public apiService: Api, private dataServices: DataProvider, private socketServices: SocketProvider ) { platform.ready().then(() => { Observable.fromEvent(window, 'beforeunload').subscribe(event => { this.dataServices.roomsLeave(); this.socketServices.disconnect(); }); // Detect run on background window.addEventListener('pause', () => { console.log('app:pause'); }, false); window.addEventListener('resume', () => { console.log("app:resume"); }, false); // statusBar.styleDefault(); // #AARRGGBB where AA is an alpha value keyboard.hideFormAccessoryBar(false); // lock orientation // screenOrientation.lock(screenOrientation.ORIENTATIONS.PORTRAIT); if (platform.is("android")) { statusBar.backgroundColorByHexString("#803b3737"); } if (localStorage.getItem("userData")) { this.result = JSON.parse(localStorage.getItem("userData")); this.getData(this.result); } else { this.rootPage = WellcomePage; } events.subscribe("user:login", data => { this.getData(data); }); events.subscribe("user:register", data => { this.getData(data); }); events.subscribe("user:logout", time => { this.clearData(); }); splashScreen.hide(); }); } getData(data: any) { this.common.presentLoading(); let postData = new FormData(); postData.append("uid", data.user_id); postData.append("token", data.token); let userData = this.apiService.post("v1/user/token", postData); userData.subscribe(result => { localStorage.setItem('userData', JSON.stringify(data)); let timeOut = localStorage.getItem('userData') ? 100 : 500; setTimeout(() => { this.common.closeLoading(); this.rootPage = HomePage; }, timeOut); }, error => { this.common.closeLoading(); this.rootPage = WellcomePage; } ); } clearData() { this.common.presentLoading(); if (localStorage.getItem("userData")) { localStorage.removeItem("userData"); setTimeout(() => { this.common.closeLoading(); this.rootPage = WellcomePage; }, 100); } } } <file_sep>import { Component } from '@angular/core'; import { NavController, NavParams, ViewController } from 'ionic-angular'; // import { LahanPage } from '../lahan/lahan'; @Component({ selector: 'page-popover', templateUrl: 'popover.html', }) export class PopoverPage { id: any; name: any; type: any; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController) { //console.log(this.navParams.data); } ionViewDidLoad() { } ngOnInit() { if (this.navParams.data) { this.id = this.navParams.data.id; this.name = this.navParams.data.name; this.type = this.navParams.data.type; } } close() { this.viewCtrl.dismiss(); } openLahan() { this.viewCtrl.dismiss().then(() => { this.navParams.get("callback")({id: this.id, action: "view", type: this.type}); }); } addKomoditas() { this.viewCtrl.dismiss().then(() => { this.navParams.get("callback")({id: this.id, action: "add", type: this.type}); }); } edit() { this.viewCtrl.dismiss().then(() => { this.navParams.get("callback")({id: this.id, action: "edit", type: this.type}); }); } hapus() { this.viewCtrl.dismiss().then(() => { this.navParams.get("callback")({id: this.id, action: "delete", type: this.type}); }); } } <file_sep>import { Component, ChangeDetectorRef, ViewChild } from "@angular/core"; import { NavController, NavParams, MenuController, Platform, Keyboard, Content, Events } from "ionic-angular"; import { Observable } from "rxjs/Observable"; import { Api } from "../../providers/api/api"; import { Common } from "../../providers/common/common"; import { DashboardTabsPage } from "../dashboard-tabs/dashboard-tabs"; import { LoginPage } from "../login/login"; @Component({ selector: "page-register", templateUrl: "register.html" }) export class RegisterPage { @ViewChild(Content) content: Content; result: any = []; data: Observable<any>; resposeData: any; userData = { username: "", password: "", refpassword: "", nama: "", gender: "0", phone: "", register: "" }; usePhone: boolean = false; useEmail: boolean = true; showPasswordText: boolean = false; showRefPasswordText: boolean = false; showToolbar: boolean = false; constructor( public navCtrl: NavController, public navParams: NavParams, public menu: MenuController, public apiService: Api, public common: Common, public ref: ChangeDetectorRef, private platform: Platform, private keyboard: Keyboard, public events: Events ) {} ionViewDidLoad() {} ionViewDidEnter() { // the root left menu should be disabled on the tutorial page // this.menu.enable(false); } ionViewWillLeave() { // enable the root left menu when leaving the tutorial page // this.menu.enable(true); } ngOnInit() { this.platform.ready().then(() => { this.keyboard.hideFormAccessoryBar(false); }); } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } scrollTop() { var that = this; setTimeout(function() { // that.content.scrollToTop(); that.content.scrollTo(0, 0); }, 100); } signup() { if ( this.userData.username.length == 0 || this.userData.password.length == 0 || this.userData.refpassword.length == 0 || this.userData.nama.length == 0 || this.userData.phone.length == 0 ) { this.common.presentToast("Semua bidang wajib di isi"); return; } if (this.userData.password.length < 8) { this.common.presentToast("Password tidak boleh kurang dari 8 karakter"); return; } if (this.userData.password != this.userData.refpassword) { this.common.presentToast("Password tidak sama, mohon periksa ulang"); return; } this.common.presentLoading(); let postData = new FormData(); postData.append("username", this.userData.username); postData.append("password", <PASSWORD>); postData.append("nama", this.userData.nama); postData.append("gender", this.userData.gender); postData.append("phone", this.userData.phone); postData.append("register", this.userData.register); this.data = this.apiService.post("v1/user/register", postData); this.data.subscribe( data => { this.result = data; if (this.result.user_data) { // localStorage.setItem("userData", JSON.stringify(this.result.user_data)); // setTimeout(() => this.goDashboard(), 500); this.common.closeLoading(); this.events.publish('user:login', this.result.user_data); } else { this.common.presentToast(this.result.data); this.common.closeLoading(); } }, error => { console.log(error); this.common.presentToast("Kesalahan, tidak dapat terhubung ke server"); this.common.closeLoading(); } ); } goLogin() { this.navCtrl.push(LoginPage); } goDashboard() { this.menu.enable(true); this.navCtrl.push(DashboardTabsPage); this.common.closeLoading(); } usePhoneToggle() { if (this.usePhone) { this.useEmail = false; } else { this.useEmail = true; } } } <file_sep>import { Component } from "@angular/core"; import { NavController, NavParams, ViewController } from "ionic-angular"; import { Common } from "../../providers/common/common"; @Component({ selector: "page-online-list", templateUrl: "online-list.html" }) export class OnlineListPage { userList = []; nickname = ""; constructor( public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public common: Common ) { this.userList = this.common.userInroom; let data = JSON.parse(localStorage.getItem('userData')); this.nickname = data.type == 1 ? "(Agronimis) " + data.name : data.name; } ionViewDidLoad() { } dismiss() { this.viewCtrl.dismiss(); } userSelected(user) { if (user === this.nickname) { return; } this.viewCtrl.dismiss(user); } } <file_sep>import { GoogleMaps, GoogleMap, GoogleMapsEvent, GoogleMapOptions, CameraPosition, MarkerOptions, Marker, LatLng, Circle } from '@ionic-native/google-maps'; import { Component, ChangeDetectorRef, ViewChild } from '@angular/core'; import { NavController, NavParams, ActionSheetController, Content, ModalController } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { WeatherProvider } from '../../providers/weather/weather'; import { mapStyle } from '../lahan/mapStyle'; import { AddKomoditasPage } from '../add-komoditas/add-komoditas'; import { EditLahanPage } from '../edit-lahan/edit-lahan'; import { DeleteModalPage } from '../delete-modal/delete-modal'; import { LocationTrackerPage } from '../location-tracker/location-tracker'; @Component({ selector: 'page-lahan', templateUrl: 'lahan.html', }) export class LahanPage { @ViewChild(Content) content: Content; showToolbar: boolean = false; lahanId: any; lahan: any = []; navigasi: string = "lahan"; komoditas: any = []; adaKomoditas: boolean = false; // Map map: GoogleMap; result: any = []; markerTitle: string = "Lokasi Lahan"; locationResult: any = []; mapOptions: GoogleMapOptions; style:any = []; // Cuaca weather:any = { coord:{}, weather:[], base:"", main:{}, wind:{}, clouds:{}, dt:0, sys:{}, id:0, name:"", cod:0 }; currentWeather:any = {}; forecast: any = []; adaWeather: boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams, public apiService: Api, public common: Common, public ref: ChangeDetectorRef, private weatherProvider: WeatherProvider, public actionSheetCtrl: ActionSheetController, public modalCtrl: ModalController) { this.lahanId = navParams.get('id'); this.navigasi = "komoditas"; this.style = mapStyle; if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); this.getLahan(); } } ionViewDidLoad() { document.getElementsByTagName('html')[0].className += 'ion-tabs-fix'; this.navigasi = "komoditas"; setTimeout(() => { this.initMap(); }, 500); } ionViewDidEnter() { this.loadKomoditas(); } ionViewWillEnter() { // console.log('will enter') } ionViewWillLeave() { // console.log('will leave') const nodeList = document.querySelectorAll('._gmaps_cdv_'); document.getElementsByTagName('html')[0].className = ''; for (let k = 0; k < nodeList.length; ++k) { nodeList.item(k).classList.remove('_gmaps_cdv_'); } } getLahan() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields let userData = this.apiService.post("v1/lahan/" + this.lahanId, postData); userData.subscribe((result) => { res = result; this.lahan = res.data; this.loadMap(this.lahan.latitude, this.lahan.longitude); this.getCuaca(this.lahan.latitude, this.lahan.longitude); this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } loadKomoditas() { let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); let data = this.apiService.post("v1/komoditas/lahan/" + this.lahanId, postData); data.subscribe((result) => { let data: any = []; data = result; if (data.data.length > 0) { if (data.data[0].id) { this.komoditas = data.data; this.adaKomoditas = true; } else { this.adaKomoditas = false; } } else { this.adaKomoditas = false; } }, (error) => { console.log(error) }); } initMap() { let loc = new LatLng(this.lahan.latitude, this.lahan.longitude); this.moveCamera(this.lahan.latitude, this.lahan.longitude); this.createMarker(loc, this.markerTitle, 'orange').then((marker: Marker) => { this.map.addCircle({ center: marker.getPosition(), radius: 10, fillColor: "rgba(0, 0, 255, 0.5)", strokeColor: "rgba(0, 0, 255, 0.75)", strokeWidth: 1 }).then((circle: Circle) => { marker.bindTo("position", circle, "center"); }); marker.showInfoWindow(); marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => { marker.setTitle(this.lahan.lokasi); }); }).catch((err) => { console.log(err); }); } // Map loadMap(latitude: any, longitude: any) { this.mapOptions = { camera: { target: { lat: latitude, lng: longitude }, zoom: 18, tilt: 30 }, controls: { compass: true, //myLocationButton: true, indoorPicker: true, zoom: true }, gestures: { scroll: true, tilt: true, rotate: true, zoom: true }, styles: this.style }; this.map = GoogleMaps.create('map_canvas', this.mapOptions); this.map.setPadding(80, 0, 0, 0); //this.map.on(GoogleMapsEvent.MY_LOCATION_BUTTON_CLICK).subscribe(() => { // this.locate(); //}); } moveCamera(latitude: any, longitude: any) { let options: CameraPosition<any> = { target: { lat: latitude, lng: longitude }, zoom: 18, tilt: 30 } this.map.moveCamera(options); } moveMapCamera(loc: LatLng) { let options: CameraPosition<any> = { target: loc, zoom: 15, tilt: 10 } this.map.moveCamera(options); } createMarker(loc: LatLng, title: string, icon?: string) { let markerOptions: MarkerOptions = { position: loc, title: title, icon: icon? icon: 'red', draggable: true } return this.map.addMarker(markerOptions); } // Cuaca getCuaca = (lat: number, lng: number) => { this.weatherProvider.getWeather(lat, lng) .subscribe((result) => { this.weather = result; this.currentWeather = this.weather.weather[0]; var prefix = 'wi wi-'; var code = this.weather.weather[0].id; var icon = this.weatherProvider.weatherIcons[code].icon; if (!(code > 699 && code < 800) && !(code > 899 && code < 1000)) { icon = 'day-' + icon; } icon = prefix + icon; this.currentWeather.icon = icon; //console.log(this.weather); }, (error) => { console.log(error); }); this.weatherProvider.getForecast(lat, lng) .subscribe((result) => { this.forecast = result; //console.log(result); }, (error) => { console.log(error); }); } GetIcon = (id: number) => { var prefix = 'wi wi-'; var icon = this.weatherProvider.weatherIcons[id].icon; // If we are not in the ranges mentioned above, add a day/night prefix. if (!(id > 699 && id < 800) && !(id > 899 && id < 1000)) { icon = 'day-' + icon; } // Finally tack on the prefix. icon = prefix + icon; return icon; } GetDay = (time: number) => { let day = new Date(time*1000).toISOString(); let d = new Date(day); let weekday = []; weekday[0] = "Minggu"; weekday[1] = "Senin"; weekday[2] = "Selasa"; weekday[3] = "Rabu"; weekday[4] = "Kamis"; weekday[5] = "Jum'at"; weekday[6] = "Sabtu"; let n = weekday[d.getDay()]; return n; } GetTime = (time: number) => { return new Date(time * 1000);//.toISOString(); } windDirection = (deg) => { if (deg > 11.25 && deg < 33.75){ return "Utara Timur Laut"; }else if (deg > 33.75 && deg < 56.25){ return "Timur Timur Laut"; }else if (deg > 56.25 && deg < 78.75){ return "Timur"; }else if (deg > 78.75 && deg < 101.25){ return "Timur Tengara"; }else if (deg > 101.25 && deg < 123.75){ return "Timur Menenggara"; }else if (deg > 123.75 && deg < 146.25){ return "Tenggara"; }else if (deg > 146.25 && deg < 168.75){ return "Selatan Menenggara"; }else if (deg > 168.75 && deg < 191.25){ return "Selatan"; }else if (deg > 191.25 && deg < 213.75){ return "Selatan Barat Daya"; }else if (deg > 213.75 && deg < 236.25){ return "Barat Daya"; }else if (deg > 236.25 && deg < 258.75){ return "Barat Barat Daya"; }else if (deg > 258.75 && deg < 281.25){ return "Barat"; }else if (deg > 281.25 && deg < 303.75){ return "Barat Barat Laut"; }else if (deg > 303.75 && deg < 326.25){ return "Barat Laut"; }else if (deg > 326.25 && deg < 348.75){ return "Utara Barat Laut"; }else{ return "Utara"; } } nameToIndo = (val) => { //let val = this.navParams.get("weatherInfo") if(val == "Rain"){ return 'Hujan'; } else if(val == "Clear"){ return 'Cerah'; } else if(val == "Clouds"){ return 'Berawan'; } else if(val == "Drizzle"){ return 'Gerimis'; } else if(val == "Snow"){ return 'Salju'; } else if(val == "ThunderStorm"){ return 'Hujan badai'; } else { return 'Cerah'; } } viewLocation() { if (this.lahan.latitude && this.lahan.longitude) { this.navCtrl.push(LocationTrackerPage, {lat: this.lahan.latitude, lng: this.lahan.longitude}).then(() => { this.callback(); }); } } presentActionSheet() { const actionSheet = this.actionSheetCtrl.create({ title: 'Lengkapi', buttons: [{ text: 'Tambah Komoditas', role: 'destructive', icon: 'add', handler: () => { this.navCtrl.push(AddKomoditasPage, {pageId: 'komoditas', lahanId: this.lahanId, callback: this.callback}); // this.presentAddKomoditas(this.lahanId); } },{ text: 'Ubah Lahan', icon: 'create', handler: () => { this.navCtrl.push(EditLahanPage, { id: this.lahanId, callback: this.callback }); } },{ text: 'Hapus Lahan', icon: 'trash', handler: () => { this.presentDeleteModal(this.lahanId, "lahan"); } },{ text: 'Tutup', role: 'cancel', icon: 'close', cssClass: 'border-top', handler: () => { console.log('Cancel clicked'); } }] }); actionSheet.present(); } presentDeleteModal(id: number, type: string) { let deleteModal = this.modalCtrl.create(DeleteModalPage, { itemId: id, itemType: type }); deleteModal.present(); deleteModal.onDidDismiss(() => { this.navCtrl.pop().then(() => { this.navParams.get("callback")("lahan"); }); }); } presentAddKomoditas(lid: any) { let addModal = this.modalCtrl.create(AddKomoditasPage, { pageId: 'komoditas', lahanId: lid }); addModal.present(); addModal.onDidDismiss(() => { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); this.loadKomoditas(); } }); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } segmentChanged(event) { this.navigasi = event.value; var that = this; if (this.navigasi == 'cuaca') { this.content.scrollTo(0, 300, 500); } else { that.content.scrollTo(0, 0); } // console.log(event.value); } scrollBottom() { var that = this; setTimeout(function() { that.content.scrollToBottom(); }, 300); } callback = (data?) => { this.getLahan(); this.loadKomoditas(); setTimeout(() => { this.initMap(); }, 500); } } <file_sep>import { Component } from '@angular/core'; import { NavController, NavParams, ViewController } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'page-delete-modal', templateUrl: 'delete-modal.html', }) export class DeleteModalPage { id: number; type: string; callback: any = null; result:any = []; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public apiService: Api, public common: Common) { this.id = this.navParams.get('itemId'); this.type = this.navParams.get('itemType'); this.callback = this.navParams.get("callback"); if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } } ionViewDidLoad() { //console.log('ionViewDidLoad DeleteModalPage'); } dismiss() { this.viewCtrl.dismiss(); } delete() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); let userData: Observable<any>; postData.append('uid', this.result.user_id); postData.append('token', this.result.token); if (this.type == "lahan") { userData = this.apiService.post("v1/lahan/delete/" + this.id, postData); } else { userData = this.apiService.post("v1/komoditas/delete/" + this.id, postData); } userData.subscribe((result) => { res = result; this.common.closeLoading(); this.common.presentToast(res.data + ": data berhasil di hapus"); this.viewCtrl.dismiss().then(() => { if (this.callback) { this.callback("lahan"); } }); }, (error) => { console.log(error); this.common.presentToast("Terjadi kesalahan"); this.common.closeLoading(); }); } } <file_sep>import { Component, ViewChild, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, Content } from 'ionic-angular'; import { Common } from '../../providers/common/common'; import { RoomChatPage } from '../room-chat/room-chat'; import { RoomAddPage } from '../room-add/room-add'; import { DataProvider } from '../../providers/data/data'; @Component({ selector: 'page-room-list', templateUrl: 'room-list.html', }) export class RoomListPage { @ViewChild(Content) content: Content; showToolbar: boolean = false; userData: any = []; constructor( public navCtrl: NavController, public navParams: NavParams, public ref: ChangeDetectorRef, public common: Common, private dataServices: DataProvider ) { this.userData = this.dataServices.user; this.userData.user_id = parseInt(this.userData.user_id); } ionViewWillUnload() { // console.log("ionViewWillUnload"); } ionViewWillLoad() { // console.log("ionViewWillLoad"); } ionViewWillEnter() { // this.onNewMessage = this.socketServices.getMessages().subscribe(data => { // let message: any = data; // if (message.chat) { // this.dataServices.newMessage(message.room, message.chat); // } // else if (message.event) { // console.log("room-list:", message); // } // }); } ionViewWillLeave() { // this.onNewMessage.unsubscribe(); } addRoom() { this.navCtrl.push(RoomAddPage, { callback: this.callback }); } openChat(id) { if (id) { this.navCtrl.push(RoomChatPage, { roomId: id, callback: this.callback }); } } callback = (data?) => { if (data) console.log(data); this.dataServices.getRoom(true); }; onScroll($event: any) { if ($event) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 20; this.ref.detectChanges(); } } } <file_sep>import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, LoadingController, ToastController } from 'ionic-angular'; import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer'; import { Camera, CameraOptions } from '@ionic-native/camera'; import { Api } from '../../providers/api/api'; @Component({ selector: 'page-upload-file', templateUrl: 'upload-file.html', }) export class UploadFilePage { imageURI: any; imageFileName: any; result: any = []; showPreview: boolean = false; showToolbar:boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams, private transfer: FileTransfer, private camera: Camera, public loadingCtrl: LoadingController, public toastCtrl: ToastController, public apiService: Api, public ref: ChangeDetectorRef) { } ionViewDidLoad() { // console.log('ionViewDidLoad UploadFilePage'); if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } getImage() { const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, sourceType: this.camera.PictureSourceType.PHOTOLIBRARY } this.camera.getPicture(options).then((imageData) => { this.imageURI = imageData; }, (err) => { // console.log(err); this.presentToast(err); }); } uploadFile() { let apiURL = this.apiService.url; let loader = this.loadingCtrl.create({ content: "Uploading..." }); loader.present(); const fileTransfer: FileTransferObject = this.transfer.create(); let options: FileUploadOptions = { fileKey: 'upload', fileName: 'ionicfile', chunkedMode: false, mimeType: "image/jpeg", params: { user_id: this.result.user_id, token: this.result.token }, headers: {} } fileTransfer.upload(this.imageURI, apiURL + '/upload', options) .then((data) => { console.log(data) this.imageFileName = apiURL + '/data/avatar/crops/ava_' + this.result.user_id + '_ionicfile.jpg'; loader.dismiss(); this.presentToast("Berhasil"); this.showPreview = true; }, (err) => { console.log(err); loader.dismiss(); this.presentToast(err); }); } presentToast(msg) { let toast = this.toastCtrl.create({ message: msg, duration: 6000, position: 'bottom' }); toast.onDidDismiss(() => { // console.log('Dismissed toast'); }); toast.present(); } } <file_sep>import { GoogleMaps, GoogleMap, GoogleMapsEvent, GoogleMapOptions, CameraPosition, MarkerOptions, Marker, LatLng } from '@ionic-native/google-maps'; import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder'; import { Geolocation } from '@ionic-native/geolocation'; import { Component, ViewChild, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, ViewController, Slides, FabContainer, Content } from 'ionic-angular'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; import { CameraOptions, Camera } from '@ionic-native/camera'; @Component({ selector: 'page-add-lahan', templateUrl: 'add-lahan.html', }) export class AddLahanPage { @ViewChild(Slides) slides: Slides; @ViewChild('footerInput') footerInput; @ViewChild(Content) content: Content; @ViewChild('inputNama') inputNama; @ViewChild('inputLokasi') inputLokasi; @ViewChild('inputLuas') inputLuas; pageId: any; currentPage: number = 0; tottalPages: number; disableBack: boolean = true; disableNext: boolean = true; finish: boolean = false; hasFocus: boolean = false; slide = []; userData = {"nama_lahan":"", "lokasi_lahan":"", "lahan_latutude":"", "lahan_longitude":"", "luas_lahan":"", "satuan_lahan":"T", "foto_lahan":""}; // Map map: GoogleMap; userLocation = {"latitude":null, "longitude":null}; loc: LatLng; bIsShowImage: boolean = false; imgSrc: string; result: any = []; markerTitle: string = "Lokasi Anda saat ini"; markerTitleLoc: string = "Lokasi Lahan"; geocoderOptions: NativeGeocoderOptions = { useLocale: true, maxResults: 5, defaultLocale: "id_ID" }; locationResult: any = []; isTracked: boolean = false; locMarker: Marker; mapOptions: GoogleMapOptions; showToolbar: boolean; callbackFnc: any; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, private geolocation: Geolocation, public apiService: Api, public common: Common, public http: HttpClient, private nativeGeocoder: NativeGeocoder, private camera: Camera, public ref: ChangeDetectorRef) { this.pageId = this.navParams.get('pageId'); this.callbackFnc = this.navParams.get("callback"); this.slide = [{ name: "nama" }, { name: "lokasi" }, { name: "luas" }, { name: "foto" }]; if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } window.addEventListener('native.keyboardshow', (e) => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + 'px'; }); window.addEventListener('native.keyboardhide', () => { this.footerInput.nativeElement.style.bottom = '0'; }); } ionViewDidLoad() { this.slides.lockSwipes(true); // console.log(this.slide.length); } checkValue(event) { let val = event.target.value; if (val.length >= 1) { this.disableNext = false; } else { this.disableNext = true; } } scrlTop() { if (this.currentPage == 1) { this.forwardGeocode(this.userData.lokasi_lahan); } this.hasFocus = false; var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } scrlBottom() { this.hasFocus = true; var that = this; setTimeout(function() { that.content.scrollToBottom(); }, 100); } setBlurInput() { if (this.currentPage == 0) { // Nama Lahan this.inputNama.setBlur(); } if (this.currentPage == 1) { // Lokasi Lahan this.inputLokasi.setBlur(); } if (this.currentPage == 2) { // Luas Lahan this.inputLuas.setBlur(); } } onChangeSatuan(event) { this.disableNext = false; } dismiss() { this.viewCtrl.dismiss(); } goNext() { this.slides.lockSwipes(false); let page = this.currentPage + 1; this.goToSlide(page); } goPrev() { this.slides.lockSwipes(false); let page = this.currentPage - 1; this.goToSlide(page); } goToSlide(page: number) { this.slides.slideTo(page, 100); this.slides.lockSwipes(true); } slideChanged() { let currentIndex = this.slides.getActiveIndex(); this.currentPage = currentIndex; if (this.currentPage == 0) { this.disableBack = true; } else { this.disableBack = false; } if (this.currentPage == this.slide.length - 1) { this.finish = true; } else { this.finish = false; } if (this.currentPage == 1) { this.loadMap(-6.9370992, 107.7813872, 'map_canvas'); this.disableNext = true; } if (this.currentPage == 2) { this.disableNext = true; if (this.userData.luas_lahan.length != 0) { this.disableNext = false; } } if (this.currentPage == 3) { this.saveImage(); } } openGalery() { this.common.presentLoading(); const options: CameraOptions = { quality: 75, destinationType: this.camera.DestinationType.DATA_URL, // FILE_URI || DATA_URL encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, sourceType: this.camera.PictureSourceType.PHOTOLIBRARY } this.camera.getPicture(options).then((imageData) => { this.imgSrc = 'data:image/jpeg;base64,' + imageData; this.userData.foto_lahan = 'data:image/jpeg;base64,' + imageData; this.common.closeLoading(); // console.log(imageData); }, (err) => { this.common.closeLoading(); this.common.presentToast(err); }); } openCamera() { this.common.presentLoading(); const options: CameraOptions = { quality: 75, // 100 = crash, 50 default destinationType: this.camera.DestinationType.DATA_URL, // FILE_URI || DATA_URL encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } this.camera.getPicture(options).then((imageData) => { this.imgSrc = 'data:image/jpeg;base64,' + imageData; this.userData.foto_lahan = 'data:image/jpeg;base64,' + imageData; this.common.closeLoading(); // console.log(imageData); }, (err) => { this.common.closeLoading(); this.common.presentToast(err); }); } save() { this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('nama', this.userData.nama_lahan); postData.append('lokasi', this.userData.lokasi_lahan); postData.append('latitude', this.userData.lahan_latutude); postData.append('longitude', this.userData.lahan_longitude); postData.append('luas', this.userData.luas_lahan); postData.append('satuan', this.userData.satuan_lahan); postData.append('foto', this.userData.foto_lahan); let userData = this.apiService.post("v1/lahan/add", postData); userData.subscribe((result) => { console.log(result); this.common.closeLoading(); if (this.callbackFnc) { this.navCtrl.pop().then(() => { this.callbackFnc("1"); }); } else { this.dismiss(); } }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } openSocial(network: string, fab: FabContainer) { console.log('Share in ' + network); fab.close(); } ionViewWillLeave() { const nodeList = document.querySelectorAll('._gmaps_cdv_'); for (let k = 0; k < nodeList.length; ++k) { nodeList.item(k).classList.remove('_gmaps_cdv_'); } } // Map loadMap(latitude: any, longitude: any, canvas: string) { this.mapOptions = { camera: { target: { lat: latitude, lng: longitude }, zoom: 18, tilt: 30 }, controls: { compass: true, //myLocationButton: true, indoorPicker: true, zoom: true }, gestures: { scroll: true, tilt: true, rotate: true, zoom: true } }; this.map = GoogleMaps.create('map_canvas', this.mapOptions); //this.map.on(GoogleMapsEvent.MY_LOCATION_BUTTON_CLICK).subscribe(() => { // this.locate(); //}); } moveCamera(latitude: any, longitude: any) { let options: CameraPosition<any> = { target: { lat: latitude, lng: longitude }, zoom: 18, tilt: 30 } this.map.moveCamera(options); } moveMapCamera(loc: LatLng) { let options: CameraPosition<any> = { target: loc, zoom: 15, tilt: 10 } this.map.moveCamera(options); } createMarker(loc: LatLng, title: string, icon?: string) { let markerOptions: MarkerOptions = { position: loc, title: title, icon: icon? icon: 'red', snippet: "Perkiraan lokasi lahan berdasarkan lokasi anda saat ini ", animation: "DROP", } return this.map.addMarker(markerOptions); } createMarkerTwoo(latitude, longitude, title: string, icon?: string) { let markerOptions: MarkerOptions = { position: { lat: latitude, lng: longitude }, title: title, icon: icon? icon: 'red', snippet: "Perkiraan lokasi lahan berdasarkan hasil terbaik ", animation: "DROP", } return this.map.addMarker(markerOptions); } saveImage() { this.map.toDataURL().then(this.showImage.bind(this)); } showImage(url: string) { this.bIsShowImage = true; this.imgSrc = url; this.userData.foto_lahan = url; } forwardGeocode(location: string) { this.common.presentLoading(); this.nativeGeocoder.forwardGeocode(location, this.geocoderOptions) .then((coordinates: NativeGeocoderForwardResult[]) => { console.log('The coordinates are latitude=' + coordinates[0].latitude + ' and longitude=' + coordinates[0].longitude); // input data this.userData.lahan_latutude = coordinates[0].latitude; this.userData.lahan_longitude = coordinates[0].longitude; this.moveCamera(coordinates[0].latitude, coordinates[0].longitude); this.reverseGeocode(coordinates[0].latitude, coordinates[0].longitude); this.createMarkerTwoo(coordinates[0].latitude, coordinates[0].longitude, this.markerTitleLoc).then((marker: Marker) => { this.locMarker = marker; marker.showInfoWindow(); marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => { marker.setTitle(this.userData.lokasi_lahan); // this.common.presentToast(marker.getTitle()); }); }).catch((err) => { console.log(err); }); this.common.closeLoading(); this.isTracked = true; this.disableNext = false; }) .catch((error: any) => { console.log(error) this.common.closeLoading(); this.disableNext = true; }); } reverseGeocode(lat: any, lng: any) { this.nativeGeocoder.reverseGeocode(lat, lng, this.geocoderOptions) .then((result: NativeGeocoderReverseResult[]) => { console.log(JSON.stringify(result[0])); this.locationResult = result[0]; this.userData.lokasi_lahan = this.locationResult.subLocality + ", " + this.locationResult.locality + " — " + this.locationResult.administrativeArea; }) .catch((error: any) => { console.log(error) }); } locate() { this.common.presentLoading(); this.bIsShowImage = false; this.geolocation.getCurrentPosition().then((resp) => { this.userLocation.latitude = resp.coords.latitude; this.userLocation.longitude = resp.coords.longitude; // input data this.userData.lahan_latutude = this.userLocation.latitude; this.userData.lahan_longitude = this.userLocation.longitude; this.loc = new LatLng(resp.coords.latitude, resp.coords.longitude); this.moveCamera(resp.coords.latitude, resp.coords.longitude); this.reverseGeocode(resp.coords.latitude, resp.coords.longitude); this.createMarker(this.loc, this.markerTitle).then((marker: Marker) => { this.locMarker = marker; marker.showInfoWindow(); marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => { marker.setTitle(this.userData.lokasi_lahan); // this.common.presentToast(marker.getTitle()); }); }).catch((err) => { console.log(err); }); this.common.closeLoading(); this.isTracked = true; this.disableNext = false; }).catch((error) => { console.log('Error getting location', error); this.common.closeLoading(); this.disableNext = true; }); } uploadFile() { this.common.presentLoading(); let postData = new FormData(); postData.append('file', this.imgSrc); postData.append('user_id', this.result.user_id); postData.append('token', this.result.token); let data:Observable<any> = this.apiService.upload("/upload", postData);// this.http.post(url + "/upload", postData); data.subscribe((result) => { this.imgSrc = result.image_url; this.common.closeLoading(); this.common.presentToast("Uploaded at: " + result.image_url); }, (error) => { this.common.closeLoading(); this.common.presentToast("Tidak dapat menyimpan file di server"); }); } onScroll($event: any){ let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } } <file_sep>import { Component, ViewChild, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams, ViewController, Slides, Content } from 'ionic-angular'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; @Component({ selector: 'page-add-komoditas', templateUrl: 'add-komoditas.html', }) export class AddKomoditasPage { @ViewChild(Slides) slides: Slides; @ViewChild('footerInput') footerInput; @ViewChild(Content) content: Content; @ViewChild('inputJumlah') inputJumlah; @ViewChild('inputUsia') inputUsia; pageId: any; lahanId: any ; currentPage: number = 0; tottalPages: number; disableBack: boolean = true; disableNext: boolean = true; finish: boolean = false; done: boolean = false; saved: boolean = false; slide = []; userData = {"id_lahan":"", "id_rumus":"", "jumlah":"", "usia":"", "tanam":"", "panen":""}; result: any = []; rumusData: any = []; showToolbar: boolean; hasFocus: boolean = false; callbackFnc: any = null; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public apiService: Api, public common: Common, public ref: ChangeDetectorRef) { this.pageId = this.navParams.get('pageId'); this.lahanId = this.navParams.get('lahanId'); this.callbackFnc = this.navParams.get("callback"); this.userData.id_lahan = this.lahanId; this.slide = [ { name: "komoditas" }, { name: "jumlah" }, { name: "usia" }]; if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); this.getRumusList(); } window.addEventListener('native.keyboardshow', (e) => { this.footerInput.nativeElement.style.bottom = (<any>e).keyboardHeight + 'px'; }); window.addEventListener('native.keyboardhide', () => { this.footerInput.nativeElement.style.bottom = '0'; }); } ionViewDidLoad() { this.slides.lockSwipes(true); this.userData.id_lahan = this.lahanId; const nodeList = document.querySelectorAll('._gmaps_cdv_'); for (let k = 0; k < nodeList.length; ++k) { nodeList.item(k).classList.remove('_gmaps_cdv_'); } } dismiss() { if (this.callbackFnc) { this.navCtrl.pop().then(() => { this.callbackFnc("1"); }); } else { this.viewCtrl.dismiss(); } } scrlTop() { this.hasFocus = false; var that = this; setTimeout(function() { that.content.scrollToTop(); }, 100); } scrlBottom() { this.hasFocus = true; var that = this; setTimeout(function() { that.content.scrollToBottom(); }, 100); } setBlurInput() { if (this.currentPage == 1) { // Nama Lahan this.inputJumlah.setBlur(); } if (this.currentPage == 2) { // Lokasi Lahan this.inputUsia.setBlur(); } } onChangeKomoditas(val) { this.disableNext = false; } onChangeLahan(val) { this.disableNext = false; } checkValue(ev) { let val = ev.target.value; this.disableNext = true; if (val.length >= 3) { this.disableNext = false; } } checkValueUsia() { if (this.userData.usia != "") { this.done = true; } else { this.done = false; } } goNext() { this.content.scrollTo(0, 0); this.slides.lockSwipes(false); let page = this.currentPage + 1; this.goToSlide(page); } goPrev() { this.content.scrollTo(0, 0); this.slides.lockSwipes(false); let page = this.currentPage - 1; this.goToSlide(page); } goToSlide(page: number) { this.slides.slideTo(page, 500); this.slides.lockSwipes(true); } slideChanged() { let currentIndex = this.slides.getActiveIndex(); this.currentPage = currentIndex; if (this.currentPage == 0) { this.disableBack = true; } else { this.disableBack = false; } if (this.currentPage == this.slide.length - 1) { this.finish = true; } else { this.finish = false; } if (this.currentPage == 0) { if (this.userData.id_rumus != "") { this.disableNext = false; } else { this.disableNext = true; } } if (this.currentPage == 1) { if (this.userData.jumlah != "") { this.disableNext = false; } else { this.disableNext = true; } } if (this.currentPage == 2) { if (this.userData.usia != "") { this.done = true; } else { this.done = false; } } } save() { // let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields postData.append('id_lahan', this.userData.id_lahan); postData.append('id_rumus', this.userData.id_rumus); postData.append('jumlah', this.userData.jumlah); postData.append('usia', this.userData.usia); let userData = this.apiService.post("v1/komoditas/add", postData); userData.subscribe((result) => { this.content.scrollTo(0, 0); // res = result; // this.rumusData = res.data; this.common.closeLoading(); this.saved = true; /*if (this.callbackFnc) { this.navCtrl.pop().then(() => { this.callbackFnc("1"); }); } else { this.dismiss(); }*/ }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } reset() { this.saved = false; this.done = false; this.disableBack = true; this.disableNext = true; this.userData.id_rumus = ""; this.userData.jumlah = ""; this.userData.usia = ""; this.userData.tanam = ""; this.userData.panen = ""; this.slides.lockSwipes(false); let page = this.currentPage - (this.slide.length - 1); this.slides.slideTo(page, 500); this.slides.lockSwipes(true); } getRumusList() { let res: any = []; this.common.presentLoading(); let postData = new FormData(); postData.append('uid', this.result.user_id); postData.append('token', this.result.token); // Fields let userData = this.apiService.post("v1/rumus", postData); userData.subscribe((result) => { res = result; this.rumusData = res.data; this.common.closeLoading(); }, (error) => { console.log(error); this.common.presentToast("Tidak dapat terhubung ke server"); this.common.closeLoading(); }); } onScroll($event: any) { if ($event === null) return; let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 10; this.ref.detectChanges(); } } <file_sep>// Provider import { Api } from '../providers/api/api'; import { Common } from '../providers/common/common'; import { WeatherProvider } from '../providers/weather/weather'; import { LogerProvider } from '../providers/loger/loger'; import { SocketProvider } from '../providers/socket/socket'; import { DataProvider } from '../providers/data/data'; // Components import { TimelineComponent } from '../components/timeline/timeline'; import { TimelineTimeComponent } from '../components/timeline/timeline'; import { TimelineItemComponent } from '../components/timeline/timeline'; // Pages import { HomePage } from '../pages/home/home'; import { WellcomePage } from '../pages/wellcome/wellcome'; import { TutorialPage } from '../pages/tutorial/tutorial'; import { TimelinePage } from '../pages/timeline/timeline'; import { DashboardTabsPage } from '../pages/dashboard-tabs/dashboard-tabs'; import { LoginPage } from '../pages/login/login'; import { RegisterPage } from '../pages/register/register'; import { DashboardPage } from '../pages/dashboard/dashboard'; import { ListsTabsPage } from '../pages/lists-tabs/lists-tabs'; import { NoTabsPage } from '../pages/no-tabs/no-tabs'; import { SettingsPage } from '../pages/settings/settings'; import { ProfilePage } from '../pages/profile/profile'; import { TodoListPage } from '../pages/todo-list/todo-list'; import { GroceryListPage } from '../pages/grocery-list/grocery-list'; import { UploadFilePage } from '../pages/upload-file/upload-file'; import { LocationTrackerPage } from '../pages/location-tracker/location-tracker'; import { CalendarPage } from '../pages/calendar/calendar'; import { CalDetailsPage } from '../pages/cal-details/cal-details'; import { PopoverPage } from '../pages/popover/popover'; import { PopoverDashboardPage } from '../pages/popover-dashboard/popover-dashboard'; import { ChatPage } from '../pages/chat/chat'; import { DeleteModalPage } from '../pages/delete-modal/delete-modal'; import { AddLahanPage } from '../pages/add-lahan/add-lahan'; import { AddKomoditasPage } from '../pages/add-komoditas/add-komoditas'; import { SearchPage } from '../pages/search/search'; import { ProfilePicturePage } from '../pages/profile-picture/profile-picture'; import { ProfileIdPage } from '../pages/profile-id/profile-id'; import { ProfileEditPage } from '../pages/profile-edit/profile-edit'; import { ProfileAlamatPage } from '../pages/profile-alamat/profile-alamat'; import { ContactUsPage } from '../pages/contact-us/contact-us'; import { LahanPage } from '../pages/lahan/lahan'; import { EditLahanPage } from '../pages/edit-lahan/edit-lahan'; import { EditKomoditasPage } from '../pages/edit-komoditas/edit-komoditas'; import { RoomListPage } from '../pages/room-list/room-list'; import { RoomAddPage } from '../pages/room-add/room-add'; import { RoomEditPage } from '../pages/room-edit/room-edit'; import { RoomDeletePage } from '../pages/room-delete/room-delete'; import { RoomChatPage } from '../pages/room-chat/room-chat'; // Natives import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer'; import { File } from '@ionic-native/file'; import { Camera } from '@ionic-native/camera'; import { Geolocation } from '@ionic-native/geolocation'; import { NativeGeocoder } from '@ionic-native/native-geocoder'; import { GoogleMaps } from '@ionic-native/google-maps'; import { Calendar } from '@ionic-native/calendar'; import { BackgroundGeolocation } from '@ionic-native/background-geolocation'; import { ScreenOrientation } from '@ionic-native/screen-orientation'; import { OnlineListPage } from '../pages/online-list/online-list'; export const NATIVES = [ FileTransfer, FileTransferObject, File, Camera, Geolocation, BackgroundGeolocation, NativeGeocoder, GoogleMaps, Calendar, ScreenOrientation ] export const PROVIDERS = [ Api, Common, WeatherProvider, LogerProvider, SocketProvider, DataProvider ]; export const COMPONENTS = [ TimelineComponent, TimelineTimeComponent, TimelineItemComponent ]; export const PAGES = [ WellcomePage, TimelinePage, TutorialPage, DashboardTabsPage, LoginPage, RegisterPage, DashboardPage, ListsTabsPage, NoTabsPage, SettingsPage, ProfilePage, TodoListPage, GroceryListPage, UploadFilePage, LocationTrackerPage, CalendarPage, CalDetailsPage, PopoverPage, PopoverDashboardPage, ChatPage, DeleteModalPage, AddLahanPage, HomePage, SearchPage, ProfilePicturePage, ProfileIdPage, ProfileEditPage, ProfileAlamatPage, ContactUsPage, LahanPage, EditLahanPage, EditKomoditasPage, AddKomoditasPage, OnlineListPage, RoomListPage, RoomAddPage, RoomEditPage, RoomDeletePage, RoomChatPage ]<file_sep>import { Component, ViewChild } from "@angular/core"; import { NavController, Nav, Platform /*, ToastController*/ } from "ionic-angular"; import { App, Events } from "ionic-angular"; // Pages import { TimelinePage } from "../timeline/timeline"; import { DashboardTabsPage } from "../dashboard-tabs/dashboard-tabs"; import { NoTabsPage } from "../no-tabs/no-tabs"; // import { ChatPage } from '../chat/chat'; import { SettingsPage } from "../settings/settings"; import { ProfilePage } from "../profile/profile"; import { ContactUsPage } from "../contact-us/contact-us"; import { Common } from "../../providers/common/common"; import { Api } from "../../providers/api/api"; import { LogerProvider } from "../../providers/loger/loger"; import { Socket } from "ng-socket-io"; import { DataProvider } from "../../providers/data/data"; import { SocketProvider } from "../../providers/socket/socket"; @Component({ selector: "page-home", templateUrl: "home.html" }) export class HomePage { @ViewChild(Nav) nav: Nav; lastBack: any = Date.now(); allowClose: boolean = false; onMessage: any; onUser: any; pages: Array<{ title: string; icon: string; component: any; openTab?: any }>; pagesTwo: Array<{ title: string; icon: string; component: any; openTab?: any; }>; rootPage: any = DashboardTabsPage; addedChatNav: boolean = false; constructor( public navCtrl: NavController, private platform: Platform, public common: Common, public events: Events, public apiService: Api, private app: App, public log: LogerProvider, private dataServices: DataProvider, private socketServices: SocketProvider ) { this.registerPages(); this.registerBackButton(); } ionViewWillLoad() { let user: any = JSON.parse(localStorage.getItem('userData')); // FIIXME: check for data loaded first this.socketServices.connect(); let timeOut = user.user_id !== undefined ? 100:500; setTimeout(() => { user.user_id = parseInt(user.user_id); this.dataServices.user = user; this.dataServices.getRoom(); this.socketServices.emit('online', user.user_id); }, timeOut); // SOCKET on message this.onMessage = this.socketServices.on('message').subscribe(data => { let message: any = data; if (message.chat) { this.dataServices.newMessage(message.room, message.chat); } }); this.onUser = this.socketServices.on('user').subscribe(data => { let message: any = data; switch(message.event) { case 'join': console.log("home:join:", message); this.dataServices.getRoom(true); break; case 'leave': console.log("home:leave:", message); break; case 'online': console.log("home:online:", message); this.dataServices.clients = message.user; this.events.publish('user:online'); break; case 'offline': console.log("home:offline:", message); this.dataServices.clients = message.user; this.events.publish('user:offline'); break; default: console.log("home:unknown:", message); break; } }); } ionViewWillUnload() { this.onMessage.unsubscribe(); this.onUser.unsubscribe(); this.dataServices.roomsLeave(); this.socketServices.disconnect(); } registerPages() { this.pages = [ { title: "Beranda", icon: "home", component: DashboardTabsPage }, { title: "Profil", icon: "person", component: ProfilePage }, // { title: 'Jadwal', icon: 'list', component: ListsTabsPage }, { title: "Pengaturan", icon: "settings", component: SettingsPage } ]; this.pagesTwo = [ { title: "Tentang Aplikasi", icon: "help-circle", component: NoTabsPage }, { title: "Partnership", icon: "mail", component: ContactUsPage }, { title: "Laporkan Masalah", icon: "bug", component: TimelinePage } ]; } registerBackButton() { this.platform.registerBackButtonAction(() => { const overlay = this.app._appRoot._overlayPortal.getActive(); const nav = this.app.getActiveNav(); const closeDelay = 2000; const spamDelay = 500; if (overlay && overlay.dismiss) { overlay.dismiss(); } else if (nav.canGoBack()) { nav.pop(); } else if (Date.now() - this.lastBack > spamDelay && !this.allowClose) { this.nav.setRoot(DashboardTabsPage, { openTab: 0 }); this.allowClose = true; } else if (Date.now() - this.lastBack < closeDelay && this.allowClose) { this.platform.exitApp(); } else { this.nav.setRoot(DashboardTabsPage, { openTab: 0 }); } this.lastBack = Date.now(); }, 1); } openPage(page) { this.nav.setRoot(page.component, { openTab: page.openTab }); } popPage(page) { this.navCtrl.push(page.component); } logout() { let time = new Date(); this.events.publish("user:logout", time.getTime()); } } <file_sep>import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder'; import { Component, ChangeDetectorRef } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { HttpClient } from '@angular/common/http'; import { Api } from '../../providers/api/api'; import { Common } from '../../providers/common/common'; @Component({ selector: 'page-location-tracker', templateUrl: 'location-tracker.html', }) export class LocationTrackerPage { userLocation = {"latitude":null, "longitude":null}; result: any = []; geocoderOptions: NativeGeocoderOptions = { useLocale: true, maxResults: 5, defaultLocale: "id_ID" }; locationResult: any = []; isTracked: boolean = false; showToolbar:boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams, public apiService: Api, public common: Common, public http: HttpClient, private nativeGeocoder: NativeGeocoder, public ref: ChangeDetectorRef) { this.userLocation.latitude = this.navParams.get('lat'); this.userLocation.longitude = this.navParams.get('lng'); } ionViewDidLoad() { if (localStorage.getItem('userData')) { this.result = JSON.parse(localStorage.getItem('userData')); } this.reverseGeocode(this.userLocation.latitude, this.userLocation.longitude); } ionViewWillLeave() { const nodeList = document.querySelectorAll('._gmaps_cdv_'); for (let k = 0; k < nodeList.length; ++k) { nodeList.item(k).classList.remove('_gmaps_cdv_'); } } onScroll($event: any) { let scrollTop = $event.scrollTop; this.showToolbar = scrollTop >= 80; this.ref.detectChanges(); } ionViewDidLeave() { } forwardGeocode(location: string) { this.nativeGeocoder.forwardGeocode(location, this.geocoderOptions) .then((coordinates: NativeGeocoderForwardResult[]) => { console.log('The coordinates are latitude=' + coordinates[0].latitude + ' and longitude=' + coordinates[0].longitude) }) .catch((error: any) => { console.log(error) }); } reverseGeocode(lat: any, lng: any) { this.nativeGeocoder.reverseGeocode(lat, lng, this.geocoderOptions) .then((result: NativeGeocoderReverseResult[]) => { this.locationResult = result[0]; this.isTracked = true; }) .catch((error: any) => { console.log(error); this.isTracked = true; }); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Socket } from 'ng-socket-io'; import { Observable } from 'rxjs/Observable'; @Injectable() export class SocketProvider { constructor( public http: HttpClient, public socket: Socket ) { } connect() { this.socket.connect(); } disconnect() { this.socket.disconnect(); } joinRoom(roomId) { this.socket.emit('subscribe', roomId); // subscribe socket } leaveRoom(roomId) { this.socket.emit('unsubscribe', roomId); // unsubscribe socket } emit(name: string, data: any) { this.socket.emit(name, data); } on(name) { let observable = new Observable(observer => { this.socket.on(name, (data) => { observer.next(data); }); }) return observable; } } <file_sep>import { Injectable } from '@angular/core'; import { Common } from '../../providers/common/common'; @Injectable() export class LogerProvider { constructor(public common: Common) { } info(input: any, toString?: boolean) { if (toString) input = this.isObject(input) ? JSON.stringify(input, null, 2) : input; console.log('%c📢 INFO => ', 'color: #fff; background: #0091ea; padding: 2px; 4px; border-radius: 4px; border: 2px solid #000', input); if (!toString) this.common.presentToast('📢 ' + input); } warnig(input: any, toString?: boolean) { if (toString) input = this.isObject(input) ? JSON.stringify(input, null, 2) : input; console.warn('%c🚫 WARNING => ', 'color: #000; background: #ffeb3b; padding: 2px; 4px; border-radius: 4px; border: 2px solid #000', input); if (!toString) this.common.presentToast('🚫 ' + input); } error(input: any, toString?: boolean) { if (toString) input = this.isObject(input) ? JSON.stringify(input, null, 2) : input; console.error('%c⛔ ERROR => ', 'color: #fff; background: #e53935; padding: 2px; 4px; border-radius: 4px; border: 2px solid #000', input); if (!toString) this.common.presentToast('⛔ ' + input); } success(input: any, toString?: boolean) { if (toString) input = this.isObject(input) ? JSON.stringify(input, null, 2) : input; console.log('%c📢 SUCCESS => ', 'color: #fff; background: #009385; padding: 2px; 4px; border-radius: 4px; border: 2px solid #000', input); if (!toString) this.common.presentToast('📢 ' + input); } isObject(input): boolean { if (typeof input === 'object') { return true; } return false; } }
5637cb338460b95753fbf30d2f702224f5479f77
[ "Markdown", "TypeScript", "HTML" ]
48
TypeScript
davchezt/a-client
a711f95bba10d5ddd70ab7b5b92c9aff4afdb4c4
2379ebb421c51151a05b58a64af1852835765a0c
refs/heads/master
<file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Administrator */ interface IReleasable { public function release(); } function release(IReleasable $obj) { $obj->release(); unset($obj); } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation; /** * Description of Predicate * * @author <NAME> */ class Predicate extends \Nette\Object { } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Interfaces; /** * Description of interfaces * * @author <NAME> */ interface dbSet { public function isSavedInDb(); public function getDbSaveData(); public static function getWithDBObject(\Foundation\Object\DBStored $object, $dbLoadedData); } interface storageSet { public function getStorageSaveData(); public static function getWithStorageObject(\Foundation\Object\StoredDataObject $object, $storageLoadedData); } interface IStringStorable extends \Serializable { public function jsonSerialize(); //public function serialize(); //public function unserialize($serialized); } interface IIterableDataObjectSet extends \Iterator { public function count(); /** * !! NENI APLIKOVAN COUNT ALL * @return type */ public function countAll(); public function getFirst(); } interface IBaseDataTranslator { public function translate(\Foundation\Object\DataObject $item, $var); public function getTitle(); } interface IExpandable { public static function newForNamespace($namespace, \Nette\Reflection\ClassType $refl = null); }<file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Object; use \Nette\ObjectMixin; /** * Description of DataObject * * @key _default_object_key * @author <NAME> */ class DataObject extends \Nette\Object implements \ArrayAccess, \Iterator, \IReleasable { protected $_data = array(); protected $_dataIterator; protected static $r_cache = array(); function __construct($id = null) { if ($id !== null) $this->setId ($id); } protected static $annotationCache = array(); public function setData(array $data) { foreach ($data as $key => $value) { $this[$key] = $value; } } public function getData() { $data = $this->_data; foreach ($this->getReflection()->getProperties(\ReflectionProperty::IS_PUBLIC) as $reflection) { if (!$reflection->isPublic()) continue; $data[$reflection->getName()] = $this[$reflection->getName()]; } return $data; } public function getId() { if ($this->getReflection()->hasAnnotation("key")) { return $this[$this->getReflection()->getAnnotation("key")]; } else { $annotations = array(); foreach ($this->getReflection()->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { if ($property->hasAnnotation('key')) { $annotations[$property->getName()] = $this[$property->getName()]; } } if (count($annotations) == 0) { throw new \Foundation\Exception("Dataobject has no KEY annotation"); } else { return count($annotations) == 1 ? array_pop($annotations) : $annotations; } } } public function setId($id) { if ($this->getReflection()->hasAnnotation("key") && !is_array($id)) { $this[$this->getReflection()->getAnnotation("key")] = $id; } else { $annotations = array(); foreach ($this->getReflection()->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { if ($property->hasAnnotation('key')) { $annotations[] = $property->getName(); } } if (count($annotations) == 0) { throw new \Foundation\Exception("Dataobject has no ID annotation"); } else if (count($annotations) == 1 && !is_array($id)) { $this[$annotations[0]] = $id; } else { foreach ($annotations as $name) { if (isset($id[$name])) { $this[$name] = $id[$name]; } else { throw new \Foundation\Exception('Key is not complete'); } } } } } public function offsetExists($offset) { return (ObjectMixin::has($this, $offset) || isset($this->_data[$offset])); } public function offsetGet($offset) { $r = $this->getReflection(); if ($r->hasProperty($offset) && $r->getProperty($offset)->isPublic()) { return $this->$offset; } else { return isset($this->_data[$offset]) ? $this->_data[$offset] : null; } } public function offsetSet($offset, $value) { $fields = $this->getFields(); if (isset($fields[$offset])) { $this->$offset = $fields[$offset]->set($value); } else { $this->_data[$offset] = $value; } } public function offsetUnset($offset) { if ( ObjectMixin::has($this, $offset) ) { unset ($this->$offset); } else { unset($this->_data[$offset]); } } public function __call($name, $args) { parent::__call($name, $args); } /** * * @return Iterator */ protected function getIterator() { if ($this->_dataIterator == null) { $this->_dataIterator = new \Nette\Iterators\CachingIterator($this->getData()); } return $this->_dataIterator; } public function current() { return $this->getIterator()->current(); } public function key() { return $this->getIterator()->key(); } public function next() { $this->getIterator()->next(); } public function rewind() { $this->_dataIterator = null; $this->getIterator()->rewind(); } public function valid() { return $this->getIterator()->valid(); } /** * * @param type $attr * @return Field */ public function getFieldReflection($fieldName) { foreach (self::getFields() as $key => $value) { if ($fieldName == $key) { return $value; } } throw new \Foundation\Exception("Field not found"); } /** * * @return Field <array> */ public static function getFields($justKeys = false) { $ref = static::getReflection(); return self::getFieldsWithReflection($ref, $justKeys); } public static function getFieldsWithReflection(\Nette\Reflection\ClassType $ref, $justKeys = false) { if (!isset (self::$annotationCache[$ref->getName()])) { foreach ($ref->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { self::$annotationCache[$ref->getName()][$property->getName()] = new Field($ref, $property); } } if ($justKeys) { $ret = array(); foreach (self::$annotationCache[$ref->getName()] as $name => $annotation) { if ($annotation->isKey()) { $ret[$name] = $annotation; } } return $ret; } else { return isset (self::$annotationCache[$ref->getName()]) ? self::$annotationCache[$ref->getName()] : array(); } } /** * * @param \Nette\Reflection\ClassType $withClassReflection * @return string */ public static function getTypeHash(\Nette\Reflection\ClassType $withClassReflection = null) { $ref = $withClassReflection ? $withClassReflection : static::getReflection(); $props = $ref->getProperties(); $text = $ref->hasAnnotation('cached')?"X":"0"; foreach ($props as $prop) { $text .= $prop->getName().($prop->hasAnnotation('lazy')?"M":"0"); } //\Nette\Diagnostics\Debugger::barDump(array('hash:'=>$text), "HFOR: ".$ref->getName()); return md5($text); } /** * Access to reflection. * @return Nette\Reflection\ClassType */ public static function getReflection() { $n = get_called_class(); if (!isset(self::$r_cache[$n])) { self::$r_cache[$n] = new \Nette\Reflection\ClassType($n); } return self::$r_cache[$n]; } /** * * @param type $attr * @param type $value * @return \Foundation\Object\DataObject */ public function setAttr($attr, $value) { $this[$attr] = $value; return $this; } public function getAttr($attr) { return $this[$attr]; } public function release() { if (isset($this->_data)) { foreach ($this->_data as $key => $value) { unset($this[$key]); } unset($this->_data); } foreach (get_object_vars($this) as $key => $value) { unset($this->$key); } if (isset($this->_dataIterator)) unset($this->_dataIterator); return $this; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\DBCache; /** * Description of SessionObjectCache * * @author <NAME> */ class SessionObjectCache extends \Nette\Object { protected static $cache = array(); protected static function getKey($id) { return is_array($id) ? crc32(serialize($id)) : $id; } protected static function getClassKey(\Nette\Reflection\ClassType $reflection) { return crc32($reflection->getName()); } public static function &getObjectWithReflectionAndId(\Nette\Reflection\ClassType $reflection, $id, &$updateData = null) { //\Nette\Diagnostics\Debugger::barDump(array('r'=>$reflection, 'id'=>$id, 'classKey'=>self::getClassKey($reflection), 'key'=>self::getKey($id)), "GETTER"); if (self::hasObjectWithReflectionAndId($reflection, $id)) { $o = self::$cache[self::getClassKey($reflection)][self::getKey($id)]; if ($updateData) { $o->setData((array) $updateData); } return $o; } else { return null; } } public static function hasObjectWithReflectionAndId(\Nette\Reflection\ClassType $reflection, $id) { return isset(self::$cache[self::getClassKey($reflection)]) && isset(self::$cache[self::getClassKey($reflection)][self::getKey($id)]); } public static function addObjectWithReflectionAndId(\Foundation\Object\DataObject $object) { $reflection = $object->getReflection(); if (isset(self::$cache[self::getClassKey($reflection)])) { self::$cache[self::getClassKey($reflection)] = array(); } self::$cache[self::getClassKey($reflection)][self::getKey($object->getId())] = $object; return $object; } public static function unsetObject(\Foundation\Object\DataObject $object) { $reflection = $object->getReflection(); if (isset(self::$cache[self::getClassKey($reflection)], self::$cache[self::getClassKey($reflection)][self::getKey($object->getId())])) { release(self::$cache[self::getClassKey($reflection)][self::getKey($object->getId())]); } } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ class pA extends Foundation\Predicates\pAnd { /** * * @param type $tabArrayOrCsv * @param type $predicate * @param type $o * @return type */ public static function lazy($tabArrayOrCsv = true, $predicate = null, $o = null) { return self::i($predicate, $o)->setLazy($tabArrayOrCsv); } /** * * @param type $predicate * @return \Foundation\Predicates\pAnd */ public static function f($filterArray) { $filterArray = is_array($filterArray) ? $filterArray : array(); $proceed = array(); foreach ($filterArray as $key => $value) { if ($value) { $proceed[$key] = $value; } } return self::i($proceed); } /** * * @param type $predicate * @return type */ public static function i($predicate = null, $o = null) { if ($o || is_array($o)) { $predicate = array($predicate => ($o instanceof \Foundation\Object\DataObject ? $o->getId() : $o)); } return self::init(is_array($predicate) ? $predicate : ($predicate ? array($predicate) : array())); } } class pOr extends \Foundation\Predicates\pOr { /** * * @param type $predicate * @return \Foundation\Predicates\pOr */ public static function i($predicate = null, $o = null) { if ($o) { $predicate = array($predicate => ($o instanceof \Foundation\Object\DataObject ? $o->getId() : $o)); } return self::init(is_array($predicate) ? $predicate : ($predicate ? array($predicate) : array())); } } class filt extends \Foundation\Utils\Filter { } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Set; /** * Description of Dictionary * * @author <NAME> */ class Dictionary extends Set implements \ArrayAccess { public function offsetExists($offset) { return $this->iterator->offsetExists($offset); } public function offsetGet($offset) { return $this->iterator->offsetGet($offset); } public function offsetSet($offset, $value) { $this->validateInputValue($value, $offset); return $this->iterator->offsetSet($offset, $value); } public function offsetUnset($offset) { return $this->iterator->offsetUnset($offset); } protected function validateInputValue($value, $key = null) { } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Object; /** * Description of DataObjectField * * @author <NAME> */ class Field extends \Nette\Object { protected $classReflection; protected $annotations; protected $property; /** * * @var \Nette\Reflection\ClassType */ protected $type; /** * * @var Field */ protected $joined; /** * COLUMN PARAMS * name string pokud je specifikovano, pouzije se jako nazev sloupce * type (INT,VARCHAR, ..) nepovinne - podle rowtype * len int povinne pouze pro varchar * null (true, false) IS NULL / IS NOT NULL * signed (true, false) IS UNSIGNED OR SIGNED */ // SAMPLE ANNOTATION /** * @var int * @column('type'=>'lazyobject', 'len'=>7, 'cached'=>'memcached') */ public function getInsertSequence() { $conf = array(); // column name $conf[] = "[".$this->getStorageName()."]"; // column type $len = $this->getStorageLen(); $conf[] = strtoupper($this->getStorageType()) . ($len === null ? "" : " (". $len .")"); // signed if ($this->isNumeric() && $this->isUnsigned()) { $conf[] = "UNSIGNED"; } $conf[] = $this->isNull() ? "NULL" : "NOT NULL"; //autoincrement if ($this->isAutoIncrement()) { $conf[] = "AUTOINCREMENT"; } //key if ($this->isKey()) { $conf[] = "PRIMARY KEY"; } //comment if ($this->getTitle()) { $conf[] = "COMMENT '" .$this->getTitle() ."'"; } if ($this->isJoined()) { $r = $this->getJoinedFieldAnnotation(); $conf[] = "REFERENCES [" .$r->getTableName() . "] ([".$r->getStorageName()."])"; } return implode(" ", $conf); } public function getTableName() { if (!$this->classReflection->hasAnnotation('table')) { throw new \Foundation\Exception('Referenced dataobject has no table annotation!'); } return $this->classReflection->getAnnotation('table'); } function __construct($object, $attr) { if ($object instanceof \Nette\Reflection\ClassType) { $this->classReflection = $object; } else if ($object instanceof DataObject) { $this->classReflection = $object->getReflection(); } else if (is_string($object)) { $refl = new \Nette\Reflection\ClassType($object); if (!$refl || !$refl->isSubclassOf("\\Foundation\\Object\\DataObject")) { throw new \Foundation\Exception("Object has to be subclass of Foundation\DataObject"); } $this->classReflection = $refl; } if (!$this->classReflection || (!$attr instanceof \Nette\Reflection\Property && !$this->classReflection->hasProperty($attr))) { throw new \Foundation\Exception("Object has to be valid string or subclass of Foundation/DataObject and '$attr' has to exists!"); } if ($attr instanceof \Nette\Reflection\Property) { $this->property = $attr; } else { $this->property = $this->classReflection->getProperty($attr); } $this->annotations = $this->property->getAnnotations(); } protected function getTypeClass() { if ($this->type===null && isset($this->annotations['var'])) { try { $ref = \Nette\Reflection\ClassType::from("\\Foundation\\Object\\Types\\".$this->annotations['var'][0]); $this->type = $ref->newInstanceArgs(); } catch (\ReflectionException $e) { if (strpos($this->annotations['var'][0], "\\")!==null) { try { $this->type = \Nette\Reflection\ClassType::from($this->annotations['var'][0]); } catch (\ReflectionException $e) { } } else { try { $this->type = \Nette\Reflection\ClassType::from($this->classReflection->getNamespaceName() . "\\" .$this->annotations['var'][0]); } catch (\ReflectionException $e) { } } } if ($this->type && !$this->type instanceof Types\type && !($this->type instanceof \Nette\Reflection\ClassType && ($this->type->isSubclassOf("\\Foundation\\Object\\DataObject") || $this->type->isSubclassOf("\\Foundation\\Set\\Set")))) { \Nette\Diagnostics\Debugger::barDump($this->type, "TYPE"); throw new \Foundation\Exception("Type '".$this->property->getName()."' is not primitive, Foundation DataObject or Set."); } } if ($this->type === null) { $this->type = new Types\type(); } return $this->type; } public function isSetOfData() { return $this->getTypeClass() instanceof \Nette\Reflection\ClassType && $this->getTypeClass()->isSubclassOf("\\Foundation\\Set\\Set"); } public function isLazy() { return isset($this->annotations['lazy']); } public function set($var) { //\Nette\Diagnostics\Debugger::barDump(array('field'=>$this, 'var'=>$var, 'tc'=> $this->getTypeClass()), "TRYINGTOSET: ".$this->getName()); if ($var === null) { } else if ($this->getTypeClass() instanceof Types\type) { if ($this->isEnum()) { $e = $this->getEnum(); if (!isset($e[$var])) { throw new \Foundation\Exception('Value "'.$var.'" is not in Enumeration '.$this->getName()); } } $var = $this->getTypeClass()->set($var); } else if ($this->getTypeClass() instanceof \Nette\Reflection\ClassType) { if ($this->getTypeClass()->implementsInterface("\Foundation\Interfaces\IStringStorable") && gettype($var) == "string") { $instance = $this->getTypeClass()->newInstanceArgs(); $instance->unserialize($var); $var = $instance; } else if (get_class($var) != $this->getTypeClass()->getName()) { $data = @unserialize($var); throw new \Nette\NotImplementedException("NENI IMPLEMENTOVAN SET PRO DANY DATOVY TYP!!"); } } return $var; } public function isKey() { if (!isset($this->annotations['key']) && $this->classReflection->hasAnnotation('key')) { $keys = explode(' ', $this->classReflection->getAnnotation('key')); return in_array($this->property->getName(), $keys); } else { return isset($this->annotations['key']); } } public function isAutoIncrement() { //\Nette\Diagnostics\Debugger::barDump($this->annotations , "IS AK"); if (isset($this->annotations['key'], $this->annotations['key'][0]) && $this->isKey()) { return ($this->annotations['key'][0] === "autoincrement" && $this->annotations['key'][0] !== true); } else { return false; } } public function getTitle() { if (isset($this->annotations['title'], $this->annotations['title'][0])) { return $this->annotations['title'][0]; } else { return null; } } public function getName() { return $this->property->getName(); } public function getStorageType() { $a = $this->getColAnnotation(); if (isset($a->type)) { return $a->type; } else if ($this->getTypeClass() instanceof Types\type) { return $this->getTypeClass()->getDbType(); } else { throw new \Foundation\Exception("Col type is not specified for '".$this->getName()."'"); } } public function isNumeric() { $t = $this->getStorageType(); if ($t instanceof Types\type) { return \Nette\Reflection\ClassType::from($t)->hasAnnotaton('unsigned'); } else if ($this->isJoined()) { return $this->getJoinedFieldAnnotation()->isNumeric(); } } public function isUnsigned() { $a = $this->getColAnnotation(); if ($this->isJoined()) { return $this->getJoinedFieldAnnotation()->isUnsigned(); } else if (isset($a->signed)) { return $a->signed ? false : true; } else { return true; } } public function isNull() { $a = $this->getColAnnotation(); if (isset($a->null) || (isset($this->annotations['null'], $this->annotations['null'][0]) && $this->annotations['null'][0])) { return $a->null ? true : false; } else if ($this->isJoined()) { return $this->getJoinedFieldAnnotation()->isNull(); } else { return false; } } public function getStorageLen() { $a = $this->getColAnnotation(); if ($this->isJoined()) { return $this->getJoinedFieldAnnotation()->getStorageLen(); } else if (isset($a->len)) { return $a->len; } else if ($this->getStorageType() == "varchar") { return 120; } else if ($this->getTypeClass() instanceof Types\bool) { return 1; } else { return null; } } public function getStorageName() { $a = $this->getColAnnotation(); if (isset($a->name[0])) { return $a->name[0]; } else { return $this->getName(); } throw new \Foundation\Exception("Cant resolve column name!"); } public function getStorageValue($var) { if ($var === null) { return null; } else if ($this->getTypeClass() instanceof Types\type) { return $this->getTypeClass()->set($var); } else if ($this->getTypeClass() instanceof \Nette\Reflection\ClassType) { if ($var instanceof StoredDataObject) { $k = $var->getId(); if (count($k) != 1) { throw new \Foundation\Exception('There are no or more then one key in "'.$this->getTypeClass()->getName().'" class.'); } return array_pop($k); } else if ($var instanceof DataObject) { return serialize($var); } else { return $var; } } } public function isJoined() { return isset($this->annotations['join'], $this->annotations['join'][0]); } public function getJoinedTypeName() { if ($this->isJoined()) { return $this->annotations['join'][0]; } else { throw new \Foundation\Exception("This field is not 'joined'"); } } /** * * @return \Nette\Reflection\ClassType */ public function getJoinedClassReflection() { return call_user_func($this->getJoinedTypeName() . "::getReflection"); } public function getJoinedClassFields() { $classtype = $this->getJoinedClassFields(); return $classtype->getMethod('getFields')->invoke($classtype->getName(), array('justKeys'=>true)); } public function isEnum() { return isset($this->annotations['enum']); } public function getEnum() { if (isset($this->annotations['enum'], $this->annotations['enum'][0])) { $ret = (array) $this->annotations['enum'][0]; if (is_array($ret)) { if (isset($ret[0]) && $ret[0]===0) unset($ret[0]); return (array) $ret; } else { throw new \Foundation\Exception($this->getName().' enum should be array.'); } } else { throw new \Foundation\Exception($this->getName().' is not enum type'); } } /** * * @return Field */ protected function getJoinedFieldAnnotation() { if ($this->joined === null) { if ($this->isJoined()) { $classtype = $this->getJoinedClassReflection(); //\Nette\Diagnostics\Debugger::barDump($classtype, "CTYPE"); $keys = DataObject::getFieldsWithReflection($classtype, true); if (count($keys) != 1) { throw new \Foundation\Exception('There are no or more then one key in "'.$this->getTypeClass()->getName().'" class.'); } else { $this->joined = array_pop($keys); } } else { throw new \Foundation\Exception("This field is not 'joined'"); } } return $this->joined; } public function getJoinStorageName() { return $this->getJoinedFieldAnnotation()->getStorageName(); } protected function getColAnnotation() { if ($this->isJoined() && $this->getTypeClass() instanceof \Nette\Reflection\ClassType) { return $this->getJoinedFieldAnnotation()->getColAnnotation(); } else if (isset($this->annotations['column'])) { return $this->annotations['column']; } else { return new \stdClass(); } } public function dibiModifier() { $var = '%s'; if (isset($this->annotations['var'])) { try { $ref = \Nette\Reflection\ClassType::from("\\Foundation\\Types\\".$this->annotations['var']); $instance = $ref->newInstanceArgs(); if ($instance instanceof Types\type) { $var = $instance->getDibiWildCard(); } } catch (ReflectionException $e) { } } return $var; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Utils; /** * Description of WSDL * * @author <NAME> */ abstract class WSDLservice extends \Nette\Object { protected $location; protected $uri; protected $functions; /** * * @var SoapClient */ protected $soap; public function __construct() { if ($this->getReflection()->hasAnnotation('location')) { $this->location = $loc = new \Nette\Http\Url($this->getReflection()->getAnnotation('location')); $this->uri = $loc->getScheme() . "://" . $loc->getAuthority() . "/"; } ini_set("soap.wsdl_cache_enabled", "0"); } /** * * @return SoapClient */ protected function getSoap() { if ($this->soap == null) { $this->soap = new \SoapClient($this->location->getAbsoluteUrl()); } return $this->soap; } public function getFunctions() { if ($this->functions===null) { $funcs = $this->getSoap()->__getFunctions(); $this->functions = array(); foreach ($funcs as $func) { $functionname = substr($func, strpos($func, " ")+1, strpos($func, "(")-strpos($func, " ")-1); $result = substr($func, 0, strpos($func, " ")); $this->functions[$functionname] = (object) array( 'function' => $functionname, 'result' => $result ); } } \Nette\Diagnostics\Debugger::barDump($this->getSoap()->__getFunctions(), "FUNC"); return $this->functions; } public function __call($name, $args) { if (key_exists($name, $this->getFunctions())) { \Nette\Diagnostics\Debugger::barDump(array('name'=>$name, 'args'=>$args), "SOAP CALL"); try { $res = $this->getSoap()->__soapCall($name, $args); } catch (\SoapFault $fault) { \Nette\Diagnostics\Debugger::barDump($fault->detail->ExceptionDetail); throw $fault; } \Nette\Diagnostics\Debugger::barDump($res, "RES"); $retArg = $this->functions[$name]->result; $retArg = str_replace(array('Response'), array('Result'), $retArg); //\Nette\Diagnostics\Debugger::barDump($res->$retArg->List[0], "RETARG"); if (isset($res->$retArg)) { if (count($res->$retArg) == 1) { foreach ($res->$retArg as $key => $value) { $key = $key; $value = $value; break; } if (isset($key, $value) && $this->getReflection()->hasMethod('processResponseType'.$key)) { return $this->getReflection()->getMethod('processResponseType'.$key)->invokeArgs($this, array($value)); } } return $res->$retArg; } else { return null; } } return parent::__call($name, $args); } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Object; /** * Description of Memcached * * private tables: _storage_indexes * * @author <NAME> */ class CachedStorage extends StoredDataObject { protected static $storage; /** * * @return Nette\Caching\IStorage */ protected static function getStorage() { if (!self::$storage) { if (!self::getReflection()->hasAnnotation('storage')) { throw new \Foundation\Exception('CachedStorageObject has to have storage annotation'); } self::$storage = \Nette\Environment::getContext()->getService(self::getReflection()->getAnnotation('storage')); } return self::$storage; } protected static function getStorageKey($id) { return self::getReflection()->getAnnotation('table') . "." . (is_array($id) ? implode(".", $id) : $id); } protected function getCleanObject() { $obj = clone $this; $obj->cleanForSaveProcess(); return $obj; } public function cleanForSaveProcess() { $this->_data = array(); foreach ($this->getReflection()->getProperties(\Nette\Reflection\Property::IS_PUBLIC) as $property) { /* @var $property \Nette\Reflection\Property */ if ($property->getValue($this) instanceof DataObject) { if (is_array($property->getValue($this)->getId())) { throw new \Nette\NotImplementedException("Zatím nejsou vyřešené multiple id relations"); } $property->setValue($this, $property->getValue($this)->getId()); } else if ($property->getValue($this) instanceof Set) { } } } public function create() { self::getStorage()->write( $this->getStorageKey($this->getId()), $this, array()); } /** * * @param type $id * @return CachedStorage */ public static function getById($id) { return self::getStorage()->read(self::getStorageKey($id)); } public function update() { self::getStorage()->write( $this->getStorageKey($this->getId()), $this, array()); return $this; } public function remove() { self::getStorage()->remove($this->getStorageKey($this->getId())); return $this; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Set; /** * Description of DBResultSet * * @author <NAME> */ class DBResultSet extends \Nette\Object implements \Foundation\Interfaces\IIterableDataObjectSet, \IReleasable { private $classReflection; /** * * @var DibiResultIterator */ protected $result; protected $count; protected $key; /** * * @var type \ArrayIterator */ protected $references; /** * * @var DibiFluent */ protected $select; public function countAll() { if ($this->count === null && $this->select != null) { $sel = clone $this->select; if (stripos((string) $this->select, ' HAVING ') === false) { if ($this->classReflection->hasAnnotation('table') && $this->classReflection->hasAnnotation('key')) { $sel->removeClause('select')->select('%n.%n', $this->classReflection->getAnnotation('table'), $this->classReflection->getAnnotation('key')); } } $this->count = $sel->removeClause('orderBy')->count(); } return $this->count; } public function setAllCount($count) { $this->count = $count; } public function __construct(\Iterator $result = null, \Nette\Reflection\ClassType $reflection = null, \DibiFluent $countAbleSelect = null) { if (!$reflection->isSubclassOf('\\Foundation\\Object\\StoredDataObject') || !$result instanceof \DibiResultIterator) { throw new \Foundation\Exception("Class is not instance of \Foundation\Object\StoredDataObject"); } if ($result instanceof \DibiResultIterator) { $result->getResult()->setRowClass(null); } //\Nette\Diagnostics\Debugger::barDump($result, "refl"); $this->select = $countAbleSelect; $this->classReflection = $reflection; $this->result = $result; $this->references = new \ArrayIterator(); } public function current() { if ($this->result!=null) { $c = $this->result->current(); if ($c instanceof \Foundation\Object\DBStored) { return $c; } else { $n = $this->classReflection->getName(); return $n::objectWithData($c); } //return $this->classReflection->getMethod('objectWithData')->invoke($this->classReflection->getName(), array('data' => $this->result->current())); } else { return null; } } public function key() { if ($this->result!=null) { /*$ref = new NClassReflection($this->class); $obj = $this->classReflection->getMethod('objectWithData')->invoke($this->classReflection->getName(), $this->result->current()); return $obj->getId();*/ return $this->result->key(); } else { return null; } } public function next() { if ($this->result!=null) { $this->result->next(); } } public function rewind() { if ($this->result!=null) { $this->result->rewind(); } } public function valid() { if ($this->result!=null) { return $this->result->valid(); } else { return false; } } public function count() { if (!isset($this->result, $this->references)) throw new \Foundation\Exception("Result released!"); if ($this->result!=null) { return $this->result->count(); } else { return 0; } } /** * * @return \Foundation\Object\DBStored */ public function getFirst() { if ($this->count()) { $this->rewind(); return $this->current(); } else { return null; } } public function getDistinct($key, $value, $releaseAfterAll = false) { if (!isset($this->result, $this->references)) throw new \Foundation\Exception("Result released!"); $ret = array(); foreach ($this as $item) { if ($key!=null) { $ret[$item[$key]] = $item[$value]; } else { $ret[] = $item[$value]; } } if ($releaseAfterAll) $this->release(); return $ret; } /** * * @param type $key * @return Dictionary */ public function getDictionary($key, $releaseAfterAll = false) { if ($this->references->count() > 0 && $this->key !== null && $this->key == $key) { return new Dictionary($this->references); } $dict = new Dictionary(); foreach ($this as $item) { $dict[$item[$key]] = $item; } if ($this->key !== null && $this->key == $key) { unset($dict); return new Dictionary($this->references); } else { if ($releaseAfterAll) $this->release(); return $dict; } } /** * * @param \Foundation\Predicates\Base $predicate * @return \Foundation\Set\Set */ public function filterWithPredicate($predicate, $releaseAfterAll = false) { if (!$predicate instanceof \Foundation\Predicates\Base) { $predicate = new \Foundation\Predicates\pAnd(is_array($predicate) ? $predicate : array()); } $r = \Foundation\Utils\Filter::filterSetWithPredicate($predicate, $this); if ($releaseAfterAll) $this->release(); return $r; } public function __sleep() { /*$iterator = new \ArrayIterator(); foreach ($this as $value) { $iterator->append($value); } $this->result = $iterator;*/ return array('classReflection', 'count'); } public function release() { if (isset($this->result)) { $this->result->getResult()->free(); unset($this->result); } if (isset($this->references)) unset($this->references); if (isset($this->classReflection)) unset($this->classReflection); if (isset($this->count)) unset($this->count); if (isset($this->key)) unset($this->key); if (isset($this->select)) unset($this->select); } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Set; /** * Description of DBDictionary * * @author <NAME> */ class DBDictionary extends Set implements \ArrayAccess { protected $tablename; /** * * @var \Foundation\Object\DBStored */ protected $parentObject; protected $parentFieldName; protected $keyField; protected $integerField; protected $string45Field; protected $textField; protected $singleValueField; protected $data; function __construct($tablename, \Foundation\Object\DBStored $parentObject, $parentFieldName, $keyField = 'key', $singleValueField = false, $integerField = 'integer', $string45Field = 'string45', $textField = 'text') { $this->tablename = $tablename; $this->parentObject = $parentObject; $this->parentFieldName = $parentFieldName; $this->keyField = $keyField; $this->integerField = $integerField; $this->singleValueField = $singleValueField; $this->string45Field = $string45Field; $this->textField = $textField; $this->singleValueField = $singleValueField; } /** * * @return ArrayIterator */ protected function getResult() { if ($this->data == null) { if ($this->singleValueField) { $sel = $this->getStorage()->select('%n as [key], %n as value', $this->keyField, $this->singleValueField); } else { $sel = $this->getStorage()->select('%n as [key], IFNULL(%n, IFNULL(%n, %n)) as value', $this->keyField, $this->integerField, $this->string45Field, $this->textField); } $this->data = new \ArrayIterator($sel->from('%n', $this->tablename)->fetchPairs('key', 'value')); } return $this->data; } protected function getStorage() { return $this->parentObject->getDbContext(); } public function current() { return $this->getResult()->current(); } public function key() { return $this->getResult()->key(); } public function next() { return $this->getResult()->next(); } public function rewind() { return $this->getResult()->rewind(); } public function valid() { return $this->getResult()->valid(); } public function getDistinct($key, $value) { return $this->getResult()->getArrayCopy(); } public function createIterator(array $withData = null) { $this->iterator = new \ArrayIterator($withData); } public function count() { return $this->getResult()->count(); } /** * !! NENI APLIKOVAN COUNT ALL * @return type */ public function countAll() { return $this->getResult()->count(); } public function offsetExists($offset) { return $this->getResult()->offsetExists($offset); } public function offsetGet($offset) { return $this->getResult()->offsetGet($offset); } public function offsetSet($offset, $value) { return $this->getResult()->offsetSet($offset, $value); } public function offsetUnset($offset) { return $this->getResult()->offsetUnset($offset); } public function update() { if ($this->singleValueField == false) { $insert = array( $this->parentFieldName => array(), $this->keyField => array(), $this->integerField => array(), $this->string45Field => array(), $this->textField => array() ); foreach ($this as $key => $value) { $insert[$this->parentFieldName][] = $this->parentObject->getId(); $insert[$this->keyField][] = $key; \Nette\Diagnostics\Debugger::barDump($value, "val:".$key); if (is_numeric($value) || is_bool($value)) { $insert[$this->integerField][] = $value; $insert[$this->string45Field][] = null; $insert[$this->textField][] = null; } else if (gettype ($value) != "object" && strlen($value)<=45) { $insert[$this->integerField][] = null; $insert[$this->string45Field][] = $value; $insert[$this->textField][] = null; } else { $insert[$this->integerField][] = null; $insert[$this->string45Field][] = null; $insert[$this->textField][] = $value instanceof \Foundation\Interfaces\IStringStorable ? $value->serialize() : $value; } } } else { $insert = array( $this->parentFieldName => array(), $this->keyField => array(), $this->singleValueField => array() ); foreach ($this as $key => $value) { $insert[$this->parentFieldName][] = $this->parentObject->getId(); $insert[$this->keyField][] = $key; $insert[$this->singleValueField][] = $value instanceof \Foundation\Interfaces\IStringStorable ? $value->serialize() : $value; } } $this->getStorage()->begin(); $this->getStorage()->delete($this->tablename)->where('%n = %i', $this->parentFieldName, $this->parentObject->getId())->execute(); $this->getStorage()->query("INSERT INTO %n %m", $this->tablename, $insert); $this->getStorage()->commit(); } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\DBCache; /** * Description of SelectCache * * @storage memCachedDb * @table _object_cache * @key hash */ class ObjectCache extends \Foundation\Object\CachedStorage { /** * @key * @var string */ public $hash; /** * @var string */ public $className; /** * * //var StorageDictionary * @var array */ public $items; protected static $_internalcache = null; protected static function getClassKey(\Nette\Reflection\ClassType $reflection) { return crc32($reflection->getName()); } /** * * @param \Nette\Reflection\ClassType $ref * @return \Foundation\Set\StorageDictionary * @throws \Nette\NotImplementedException */ public static function getAllWithReflection(\Nette\Reflection\ClassType $ref) { $all = self::getSingleItemWithReflection($ref); return $all->items; } protected static function getSingleItemWithReflection(\Nette\Reflection\ClassType $ref) { if (self::$_internalcache == null) self::$_internalcache = new \ArrayObject(); if (!isset(self::$_internalcache[self::getClassKey($ref)])) { $all = self::getById(self::getClassKey($ref)); if (!$all) { $all = new ObjectCache(); $all->hash = self::getClassKey($ref); $all->className = $ref->getName(); $data = call_user_func($ref->getName() .'::getAll', false); $keys = call_user_func($ref->getName() .'::getFields', true); if (count($keys)!=1) throw new \Nette\NotImplementedException("Objectcache needs only one key."); $dbRef = array_pop($keys); /* @var $dbRef \Foundation\Object\Field */ $all->items = $data->getDictionary($dbRef->getStorageName()); $all->create(); } self::$_internalcache[self::getClassKey($ref)] = $all; } //\Nette\Diagnostics\Debugger::barDump($all, "ALL"); //throw new \Nette\Application\ApplicationException(); return self::$_internalcache[self::getClassKey($ref)]; } /** * * @param \Nette\Reflection\ClassType $ref * @param type $id * @return \Foundation\Object\DBStored */ public static function getByIdAndReflection(\Nette\Reflection\ClassType $ref, $id) { $all = self::getAllWithReflection($ref); return $all->offsetExists($id) ? $all->offsetGet($id) : null; } public static function add(\Foundation\Object\DBStored $object) { $all = self::getSingleItemWithReflection($object->getReflection()); $all->items[$object->getId()] = ($object); $all->update(); } public static function save(\Foundation\Object\DBStored $object) { $all = self::getSingleItemWithReflection($object->getReflection()); //\Nette\Diagnostics\Debugger::barDump($all->items[$object->getId()], "INNER"); //\Nette\Diagnostics\Debugger::barDump($object, "MODIFIED"); $all->items[$object->getId()] = $object; $all->update(); } public static function del(\Foundation\Object\DBStored $object) { $all = self::getSingleItemWithReflection($object->getReflection()); unset($all->items[$object->getId()]); $all->update(); } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Object; use Foundation\Predicate; /** * Description of StoredDataObject * */ abstract class StoredDataObject extends DataObject { public static function __callStatic($name, $arguments) { $refl = new \Nette\Reflection\ClassType( new static ); //\Nette\Diagnostics\Debugger::barDump($arguments, $name . " - invoke"); if ($refl->hasMethod($name) && $refl->getMethod($name)->isStatic()) { return $refl->getMethod($name)->invoke($name, $arguments); } else { throw new \Foundation\Exception("Method '$name' not exists in '".$refl->getName()."'"); } } public static function getAll($predicate = null, $limit = null, $offset = null) { return \Nette\Reflection\ClassType::from( new static )->getName(); } //abstract public static function getById($id); public abstract function create(); public abstract function update(); /** * * @param type $data * @return StoredDataObject */ public static function objectWithData($data) { if ($data === null) { return null; } //\Nette\Diagnostics\Debugger::barDump($data); $obj = self::getReflection()->newInstanceArgs(); $obj->setData((array) $data); return $obj; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Utils; /** * Description of Logger * * @author <NAME> */ class Logger extends \Nette\Object { const DEBUG = 'debug', INFO = 'info', WARNING = 'warning', ERROR = 'error', CRITICAL = 'critical'; public static function log($event, $objectOrMessage, $sender = null, $priority = self::INFO) { $appendTo = TEMP_DIR . "/../log/".$priority."-". \Nette\Utils\Strings::webalize($event) .".txt"; $data = date('Y-m-d H:i:s')." [".$event."] ". ($sender ? substr(preg_replace("/\s+/S", " ", var_export($sender, true)), 0, 100) : "")."\n" .\Nette\Utils\Strings::indent($objectOrMessage instanceof \Exception ? $objectOrMessage->getMessage() : (gettype($objectOrMessage) == "string" ? $objectOrMessage : var_export($objectOrMessage, true))); $data .= "\n\n"; if (file_exists($appendTo)) { $data .= file_get_contents($appendTo); } @file_put_contents($appendTo, $data); if ($objectOrMessage instanceof \Exception) { \Nette\Diagnostics\Debugger::log($objectOrMessage, $priority); } else if ($priority == self::CRITICAL) { \Nette\Diagnostics\Debugger::log(new \Foundation\Exception($event . ": ". substr(var_export($objectOrMessage, true), 200)), $priority); } } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Predicates; /** * Description of And * * @author <NAME> */ class pAnd extends Base { protected function getGlue() { return $this->glue !== null ? $this->glue : "AND"; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation; /** * Description of exceptions * * @author <NAME> */ class Exception extends \Exception { } class PredicateException extends Exception { } class BadInputException extends Exception { } class CONS { public static $STATIC_TYPES = array("boolean", "integer", "double", "string"); public static $STATIC_TYPES_W_ARRAY = array("boolean", "integer", "double", "string", "array"); } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Set; /** * Description of Set * * @author <NAME> */ class Set extends \Nette\Object implements \Foundation\Interfaces\IIterableDataObjectSet { /** * @var \ArrayIterator */ protected $iterator; public function __construct(\Iterator &$initialArray = null) { $this->getIterator($initialArray); } public function __wakeup() { if (!$this->iterator instanceof \Iterator) { $this->createIterator(); } } public function current() { return $this->iterator->current(); } public function key() { return $this->iterator->key(); } public function next() { return $this->iterator->next(); } public function rewind() { return $this->iterator->rewind(); } public function valid() { return $this->iterator->valid(); } public function add(\Foundation\Object\DataObject $object) { $this->iterator->append($object); } public function remove(\Foundation\Object\DataObject $object) { foreach ($this as $key => $in) { if ($in === $object) { $this->iterator->offsetUnset($key); return; } } throw new \Nette\Application\ApplicationException("Object not exists"); } public function mergeWithSet(Set $set) { $current = $this->iterator->getArrayCopy(); \Nette\Diagnostics\Debugger::barDump($current, "CURRENT"); \Nette\Diagnostics\Debugger::barDump($set, "SET"); $new = array(); foreach ($set as $key => $value) { $new[$key] = $value; } $new = array_merge($current, $new); $this->createIterator($new); } public function count() { return $this->iterator->count(); } /** * * @param type $key * @return Dictionary */ public function getDictionary($key) { $dict = new Dictionary(); foreach ($this as $item) { $dict[$item[$key]] = $item; } return $dict; } public function getDistinct($key, $value) { $ret = array(); foreach ($this as $item) { if ($key!=null) { $ret[$item[$key]] = $item[$value]; } else { $ret[] = $item[$value]; } } return $ret; } /** * !! NENI APLIKOVAN COUNT ALL * @return type */ public function countAll() { return $this->iterator->count(); } public function getFirst() { if ($this->count()) { $this->rewind(); return $this->current(); } else { return null; } } /** * * @param \Foundation\Predicates\Base $predicate * @return \Foundation\Set\Set */ public function filterWithPredicate(\Foundation\Predicates\Base $predicate) { return \Foundation\Utils\Filter::filterSetWithPredicate($predicate, $this); } /** * * @return \ArrayIterator */ public function getIterator(&$withData = null) { if (!$this->iterator instanceof \Iterator || $withData !== null) { $this->iterator = $withData instanceof \Iterator ? $withData : new \ArrayIterator(is_array($withData) ? $withData : array()); } return $this->iterator; } public function sortWithCallback(\Closure $callback) { if ($this->getIterator() instanceof \ArrayIterator) { $this->getIterator()->uasort($callback); } else { $array = $this->getIterator()->getArrayCopy(); if ($this instanceof Set) { @usort($array, $callback); } else { @uasort($array, $callback); } $this->createIterator($array); } return $this; } } <file_sep>SimpleOrm ========= Just ripped out PHP ORM from my project based on Dibi and Nette. Features ======== ```php $predicate = Predicates\pAnd(array( "name~LIKE"=>'%Somethink%' ))->orderBy('name'); $offset = 10; $limit = 10; $data = Table::getAll($predicate, $limit, $offset); $filtered = $data->filterWithPredicate(Predicates\pAnd(array( "enabled"=>true ))); foreach ($data as $item) { $item->updated = new DateTime(); $item->setCategory(CategoryTable::getAll(pA::i('category_id', 1)->setLazy(), 1)->getFirst()); $item->update(); } ``` Example of single Entity: ```php <?php namespace Foundation\User; /** * * * @key account_group_id * @storage database * @table account_group * @cached */ class AccountGroup extends \Foundation\Object\DBStored { /** * @key autoincrement * @var int * @column(name="account_group_id", type="INT", null=false, len=10, signed=false) */ public $account_group_id; /** * @var string * @column(name="code", type="VARCHAR", null=false, len=20) */ public $code; /** * @var string * @column(name="name", type="VARCHAR", null=false, len=90) */ public $name; /** * @var bool * @column(name="isSuperUser", type="TINYINT", null=false, len=1) */ public $isSuperUser; /** * @return \Foundation\Set\DbSet */ public function getAccountSet() { return new \Foundation\Set\DbSet("account_relations", $this, "account_group_id", new \Nette\Reflection\ClassType("\\Foundation\\User\\Account"), "account_id"); } public function addAccount(\Foundation\User\Account $object) { $this->getAccountSet()->add($object); } public function removeAccount(\Foundation\User\Account $object) { $this->getAccountSet()->remove($object); } //#CUSTOM DECLARATION BEGIN //#CUSTOM DECLARATION END } ``` Requirements ============ - Dibi - Nette Todo ==== - Overall cleanup - Remove dependencies<file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Predicates; /** * Description of Base * * @author <NAME> */ abstract class Base { protected $where = array(); private static $deep; protected $glue; protected $lazy = FALSE; protected $callings = array(); public function isEmpty() { return count($this->callings) == 0 && count($this->where) == 0; } function __construct($predicate) { $this->where = is_array($predicate) ? $predicate : array($predicate); } /** * * @param type $predicate * @return \Foundation\Predicates\Base */ public static function init($predicate) { return new static($predicate); } protected function processOnce(\DibiFluent $sel) { foreach ($this->callings as $value) { $sel->__call($value->name, $value->args); } } public function getLazy() { return $this->lazy; } public function setLazy($lazy = TRUE) { if ($lazy===TRUE || $lazy === FALSE || is_array($lazy)) { $this->lazy = $lazy; } else { if (!is_array($this->lazy)) { $this->lazy = array(); } $tokens = explode(",", $lazy); foreach ($tokens as $tab) { $tab = trim($tab); $this->lazy[] = $tab; } } return $this; } final public function proceed(\DibiFluent $sel, \Nette\Reflection\ClassType $reflection) { $result = array(); self::$deep++; $this->processOnce($sel); foreach ($this->where as $key => $value) { if ($value instanceof \Foundation\Object\DBStored) { $k = $value->getFields(true); $k = array_pop($k); $sel->getCommand(); /* @var $k \Foundation\Object\Field*/ $r = $this->parseItem($reflection->getAnnotation('table') . "." . $k->getStorageName(), $value->getId(), $sel); } else if ($value instanceof Base) { $r = $value->proceed($sel, $reflection); } else if (is_scalar($value) || is_array($value) || $value instanceof \DateTime || $value === null) { $r = $this->parseItem($key, $value, $sel); } else { throw new \Foundation\PredicateException("Predicate array should contain only predicates, scalars or arrays."); } if ($r != null) { $result[] = $r; } } self::$deep--; if (self::$deep == 0 && count($result)>0) { $sel->where("(%sql)", implode(" ".$this->getGlue()." ", $result)); } else if (self::$deep != null && count($result) > 0) { return "(".implode(" ".$this->getGlue()." ", $result).")"; } } protected function expandTextItem($key, $value) { $found = array(); $r = 0; if (preg_match('/^(.*?)\~(.*?)\%(.*?)$/', $key, $found)) { $row = $found[1]; $sign = $found[2]; $modificator = $found[3]; $r = 1; } else if (preg_match('/^(.*?)\%(.*?)$/', $key, $found)) { $row = $found[1]; $sign = "="; $modificator = $found[2]; $r = 2; } else if (preg_match('/^(.*?)\~(.*?)$/', $key, $found)) { $row = $found[1]; $sign = $found[2]; $modificator = "s"; $r = 3; } else { $row = $key; $sign = "="; $modificator = is_int($value) ? "i" : (is_float($value) ? "f" : "s"); $r = 4; } //\Nette\Diagnostics\Debugger::barDump(array('row' => $row, 'sign' => $sign, 'modifier' => $modificator, 'fnd'=>$found), $r);// if ($value instanceof \DateTime && $modificator != 'd') { $modificator = 't'; } if (is_array($value) && strtoupper($sign) != "NOT IN") { $sign = 'IN'; } if (is_array($value)) { $modificator = 'in'; } if ($sign == 'sql' || $modificator == 'sql') { $sign = ''; $modificator = 'sql'; } if ($value === null && $sign != "IS NOT") { $sign = "IS"; } return (object) array('row' => $row, 'sign' => $sign, 'modifier' => $modificator); } protected function parseItem($key, $value, \DibiFluent $sel) { $translator = new \DibiTranslator($sel->getConnection()); $translator->translate(array()); $row = $this->expandTextItem($key, $value); return "[".$row->row."] ".$row->sign." ".$translator->formatValue($value, $row->modifier); } protected function getGlue() { return $this->glue; } /** * * @param type $glue * @return Base */ public function setGlue($glue) { $this->glue = $glue; return $this; } /** * * supports = != < * * @param \Foundation\Object\DataObject $object * */ public function isMatching(\Foundation\Object\DataObject $object) { //\Nette\Diagnostics\Debugger::barDump($object, "isMatching"); $result = strtoupper($this->getGlue()) == "OR" ? false : true; foreach ($this->where as $key => $value) { if ($value instanceof Base) { $result = $value->isMatching($object); } else { $row = $this->expandTextItem($key, $value); //\Nette\Diagnostics\Debugger::barDump($row, "isMatchingRow"); if (preg_match("/\\(\\)$/", $row->row)) { $method = str_replace("()", "", $row->row); $compare = $object->$method(); } else { $compare = $object->{$row->row}; } if ($compare instanceof \Foundation\Object\DataObject && $value instanceof \Foundation\Object\DataObject) { $result = ($compare->getId() == $value->getId()); } if ($row->sign == '=' || $row->sign == "==") { $result = ($value == $compare); } else if ($row->sign == '<') { $result = ($compare < $value); } else if ($row->sign == '>') { $result = ($compare > $value); } else if ($row->sign == '===') { $result = ($compare === $value); } else if ($row->sign == '!=') { $result = ($compare != $value); } else if ($row->sign == '<=') { $result = ($compare <= $value); } else if ($row->sign == '>=') { $result = ($compare >= $value); } else if ($row->sign == 'W') { $result = (\Nette\Utils\Strings::webalize($compare) == $value); } } if ((strtoupper($this->getGlue()) == "OR" && $result == true) || (strtoupper($this->getGlue()) != "OR" && $result == false)) { //\Nette\Diagnostics\Debugger::barDump(strtoupper($this->getGlue()) == "OR", "RESULT IS"); return strtoupper($this->getGlue()) == "OR"; } } //\Nette\Diagnostics\Debugger::barDump(strtoupper($this->getGlue()) != "OR", "RESULT IS"); return strtoupper($this->getGlue()) != "OR"; } public function __call($name, $args) { $this->callings[] = (object) array('name'=>$name, 'args'=>$args); return $this; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Predicates; /** * Description of pOr * * @author <NAME> */ class pOr extends Base { protected function getGlue() { return $this->glue !== null ? $this->glue : "OR"; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Object\Types; /** * Description of types * * @author <NAME> */ class type { public function getDbType() { return "varchar"; } public function getDibiWildCard() { return "%s"; } public function set($var) { return $var; } } /** * @numeric */ class int extends type { public function getDibiWildCard() { return "%i"; } public function getDbType() { return "int"; } public function set($var) { return intval(preg_replace('[^0-9]', '', $var)); } } class string extends type { public function getDibiWildCard() { return '%s'; } public function getDbType() { return "varchar"; } public function set($var) { return trim($var); } } /** * @numeric */ class float extends type { public function getDibiWildCard() { return '%f'; } public function getDbType() { return "float"; } public function set($var) { return floatval(preg_replace('/[^[0-9\.]/', '', $var)); } } /** * @numeric */ class bool extends type { public function getDibiWildCard() { return '%b'; } public function getDbType() { return "tinyint"; } public function set($var) { return $var ? true : false; } } class DateTime extends type { public function getDibiWildCard() { return '%t'; } public function getDbType() { return "datetime"; } public function set($var) { if ($var instanceof \DateTime) { return $var; } else { return new \DateTime($var); } } } class binary extends type { public function getDbType() { return "BLOB"; } public function getDibiWildCard() { return "%bin"; } public function set($var) { return $var; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Set; /** * Description of StorageDictionary * * @author <NAME> */ class StorageDictionary extends Dictionary implements \Foundation\Interfaces\storageSet { public function getStorageSaveData() { if ($this->iterator) { return $this->iterator->getArrayCopy(); } else { return array(); } } public static function getWithStorageObject(\Foundation\Object\StoredDataObject $object, $storageLoadedData) { $obj = self::getReflection()->newInstanceArgs(array('owner'=>$object)); $obj->createIterator($storageLoadedData); return $obj; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Predicates; /** * Description of JoinPredicate * * @author <NAME> */ class pJoin extends pAnd { protected $joinedTable; protected $mainTable; protected $joinedField; protected $mainField; protected $isJoined = false; protected $noLeftJoin = false; /** * * @param type $joinedTable * @param type $mainTable * @param type $joinedField * @param type $mainField * @param type $noLeftJoin * @return pJoin */ public function setJoinProperties($joinedTable, $mainTable, $joinedField, $mainField, $noLeftJoin = false) { $this->joinedTable = $joinedTable; $this->mainTable = $mainTable; $this->joinedField = $joinedField; $this->mainField = $mainField; $this->noLeftJoin = $noLeftJoin; $obj = new pJoin($this); //$this->where[] = $obj; return $obj; } protected function processOnce(\DibiFluent $sel) { if ($this->isJoined==false && isset($this->joinedTable)) { if($this->noLeftJoin){ $sel->join('%n', $this->joinedTable)->on('%n.%n = %n.%n', $this->mainTable, $this->mainField, $this->joinedTable, $this->joinedField); }else{ $sel->leftJoin('%n', $this->joinedTable)->on('%n.%n = %n.%n', $this->mainTable, $this->mainField, $this->joinedTable, $this->joinedField); } $this->isJoined = true; } parent::processOnce($sel); } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Object; use \dibi; /** * Description of DBStored * * @author <NAME> */ abstract class DBStored extends StoredDataObject implements \Serializable { private $referenceCount = 0; private $_ownObjectCache = array(); public function serialize() { if (!isset($this->_data)) var_dump (debug_backtrace()); return serialize($this->getData()); } public function unserialize($serialized) { foreach (unserialize($serialized) as $key => $value) { $this[$key] = $value; } } /** * * @return \DibiConnection */ public static function getDbContext() { $r = self::getReflection(); if (!$r->hasAnnotation('table') || !$r->hasAnnotation('storage')) { throw new \Nette\Application\ApplicationException("Class has no table annotation"); } return \Nette\Environment::getService($r->getAnnotation('storage')); } /** * * @param \Foundation\Predicates\Base $predicate * @param type $limit * @param type $offset * @return \Foundation\Set\DBResultSet */ public static function getAll($predicate = null, $limit = null, $offset = null) { if (!$predicate instanceof \Foundation\Predicates\Base) { $p = new \Foundation\Predicates\pAnd(is_array($predicate) ? $predicate : ($predicate instanceof DBStored ? array($predicate) : array())); } else { $p = $predicate; } $r = self::getReflection(); if (!$r->hasAnnotation('table') || !$r->hasAnnotation('storage')) { throw new \Nette\Application\ApplicationException("Class has no table annotation"); } if ($r->getAnnotation('cached') === TRUE && $p->isEmpty() && $predicate !== false) { return \Foundation\DBCache\ObjectCache::getAllWithReflection($r); } else { $selectData = \Foundation\DBCache\SelectCache::getOrCreateWithObjectReflection($r); $sel = self::getDbContext()->select($selectData->ownSelect)->from("%n", $r->getAnnotation('table')); if (!$p || $p->getLazy() !== TRUE) { $miss = $p->getLazy() === FALSE ? array() : $predicate->getLazy(); foreach ($selectData->joins as $info) { $x = null; preg_match("/^\[([a-zA-Z0-9_]+)\]/", $info['table'], $x); if (!in_array($x[1], $miss)) $sel->leftJoin($info['table'])->on($info['on'])->select($info['select']); } } if ($p!=null) { $p->proceed($sel, $r); } $countable = clone $sel; return new \Foundation\Set\DBResultSet($sel->getIterator($offset, $limit), $r, $countable); } } /** * * @param type $id * @return DBStored */ public static function getById($id) { if ($id === null) throw new \Nette\Application\ApplicationException("ID cannot be NULL"); $fields = array(); $r = self::getReflection(); if (\Foundation\DBCache\SessionObjectCache::hasObjectWithReflectionAndId($r, $id)) { return \Foundation\DBCache\SessionObjectCache::getObjectWithReflectionAndId($r, $id); } if (!$r->hasAnnotation('table') || !$r->hasAnnotation('storage')) { throw new \Nette\Application\ApplicationException("Class has no table annotation"); } if ($r->getAnnotation('cached') === TRUE ) { return \Foundation\DBCache\ObjectCache::getByIdAndReflection($r, $id); } else { $lastname = null; foreach (self::getFields(true) as $field) { $lastname = $field->getName(); $fields[$field->getName()] = $field->getStorageName(); } if (count($fields) != (is_array($id) ? count($id) : 1)) { throw new \Foundation\Exception("ID is incomplete"); } else { $id = is_array($id) ? $id : array($lastname => $id); $predicateArray = array(); \Nette\Diagnostics\Debugger::barDump($id, "ID"); foreach ($fields as $name => $storageName) { if (!isset($id[$name])) throw new \Foundation\Exception("ID is incomplete"); $predicateArray[$r->getAnnotation('table').".".$storageName] = $id[$name]; } } $o = self::getAll(\Foundation\Predicates\pAnd::init($predicateArray), 1)->getFirst(); if ($o) { \Foundation\DBCache\SessionObjectCache::addObjectWithReflectionAndId($o); } return $o; } } /** * * @return DBStored */ public function create() { $r = $this->getReflection(); if (!$r->hasAnnotation('table') || !$r->hasAnnotation('storage')) { throw new \Nette\Application\ApplicationException("Class has no table annotation"); } try { self::getDbContext()->insert($r->getAnnotation('table'), $this->getDbFormatedData(true))->execute(); foreach ($this->getFields(true) as $field) { /* @var $field Field */ if ($field->isAutoIncrement()) { $this->setId(array($field->getName() => self::getDbContext()->insertId())); break; } } } catch (\DibiDriverException $e) { return $this->processException($e, callback($this, "create")); } if ($r->getAnnotation('cached') === TRUE ) { \Foundation\DBCache\ObjectCache::add($this); } return $this; } protected function processException(\DibiDriverException $e, \Nette\Callback $callback, array $args = null) { $r = $this->getReflection(); $this->referenceCount++; if ($r->hasAnnotation('noModify')) throw $e; if (in_array($e->getCode() , array(1146 /* NO TABLE */, 1054 /* NO ROW */))) { $columns = array(); foreach ($this->getFields() as $field) { /* @var $field Field */ $columns[$field->getStorageName()] = "ADD " . $field->getInsertSequence(); } if(!in_array($e->getCode(), array(1146 /* NO ROW */))) { $info = new \DibiTableInfo(new \DibiMySqlReflector( self::getDbContext()->getDriver() ), array( 'name' => $r->getAnnotation('table'))); //\Nette\Diagnostics\Debugger::barDump($info->getColumnNames() , 'CnAMES'); foreach ($info->getColumnNames() as $name) { unset($columns[$name]); } } if ($e->getCode() == 1146) { self::getDbContext()->query("CREATE TABLE %n ( %sql ) COMMENT='' ENGINE='InnoDB' COLLATE 'utf8_general_ci'", $r->getAnnotation('table'), implode(", ", $columns)); } else if ($e->getCode() == 1054) { self::getDbContext()->query("ALTER TABLE %n", $r->getAnnotation('table'), implode(", ", $columns)); } if ($this->referenceCount < 3) { return $callback->invokeArgs(is_array($args) ? $args : array()); $this->referenceCount = 0; } } else { throw $e; } } /** * * @return DBStored */ public function update() { $r = $this->getReflection(); if (!$r->hasAnnotation('table') || !$r->hasAnnotation('storage')) { throw new \Nette\Application\ApplicationException("Class has no table annotation"); } try { $keys = array(); foreach ($this->getFields(true) as $field) { /* @var $field Field */ $keys[$field->getStorageName()] = $field->getStorageValue($this[$field->getName()]); } self::getDbContext()->update($r->getAnnotation('table'), $this->getDbFormatedData(true)) ->where('%and', $keys) ->execute(); } catch (\DibiDriverException $e) { return $this->processException($e, callback($this, "update")); } if ($r->getAnnotation('cached') === TRUE ) { \Foundation\DBCache\ObjectCache::save($this); } return $this; } public function __call($name, $args) { if (preg_match("/^(get|set)/", $name)) { $shortname = preg_replace("/^get|^set/", "", $name); $found = null; foreach ($this->getFields() as $fname =>$field) { /* @var $field Field */ //\Nette\Diagnostics\Debugger::barDump(array('joined'=>$field->isJoined(), 'shortname'=> $shortname, 'compTo'=> $field->isJoined() ? self::translateToMethodName($field->getJoinedTypeName(), $field->getStorageName(), true) : null), "$fname"); if ($field->isJoined() && $shortname == self::translateToMethodName($field->getJoinedTypeName(), $field->getStorageName(), true)) { $found = $field; } } //\Nette\Diagnostics\Debugger::barDump($found, "CALLED: ".$name); if ($found) { if(preg_match("/^set/", $name)) { if (isset($args[0]) && $args[0] instanceof DBStored) { $this[$found->getName()] = $found->set($args[0]->getId()); $this->_ownObjectCache[$found->getName()] = $args[0]; return; } else { throw new \Foundation\Exception('Argument must be DBStored object'); } } else { if ($this[$found->getStorageName()] === null) return null; $reflection = $this->getReflection(); //\Nette\Diagnostics\Debugger::barDump($found->getName(), "NAME"); //\Nette\Diagnostics\Debugger::barDump($this->_ownObjectCache, "OWNCACHE"); if ($found->getJoinedClassReflection()->getAnnotation('cached') === TRUE ) { $this->_ownObjectCache[$found->getName()] = \Foundation\DBCache\ObjectCache::getByIdAndReflection($found->getJoinedClassReflection(), $this[$found->getStorageName()]); } else if (\Foundation\DBCache\SessionObjectCache::hasObjectWithReflectionAndId($found->getJoinedClassReflection(), $this[$found->getStorageName()])) { $this->_ownObjectCache[$found->getName()] = \Foundation\DBCache\SessionObjectCache::getObjectWithReflectionAndId($found->getJoinedClassReflection(), $this[$found->getStorageName()]); } if (!isset($this->_ownObjectCache[$found->getName()])) { $cache = \Foundation\DBCache\SelectCache::getOrCreateWithObjectReflection($reflection); $jtpn = preg_replace("/^(\/|\\\\)/", "", $found->getJoinedTypeName()); $instance = $found->getJoinedClassReflection()->newInstanceArgs(); $noDataInside = true; if (isset($cache->joins[$jtpn])) { $noDataInside = false; foreach ($cache->joins[$jtpn]['translation'] as $fieldName => $alias) { if (!isset($this->_data[$alias]) && !array_key_exists($alias, $this->_data)) { //\Nette\Diagnostics\Debugger::barDump(array('fn'=>$fieldName, 'al'=>$alias, 'data'=>$this->_data), "INCOPLETE"); $noDataInside = true; break; } $instance[$fieldName] = $this->_data[$alias]; } //\Nette\Diagnostics\Debugger::barDump ($instance, "AFTER"); if (!$noDataInside) { $this->_ownObjectCache[$found->getName()] = $instance; } } if ($noDataInside) { //\Nette\Diagnostics\Debugger::barDump($instance, " NIC VEVNITR"); $this->_ownObjectCache[$found->getName()] = $instance->getById($this[$found->getStorageName()]); } } //\Nette\Diagnostics\Debugger::barDump($this->_ownObjectCache, "OWNCACHE AFTER"); return $this->_ownObjectCache[$found->getName()]; } } } parent::__call($name, $args); } /** * * @return DBStored */ public function remove() { $r = $this->getReflection(); if (!$r->hasAnnotation('table') || !$r->hasAnnotation('storage')) { throw new \Nette\Application\ApplicationException("Class has no table annotation"); } try { $keys = array(); foreach ($this->getFields(true) as $field) { /* @var $field Field */ $keys[$field->getStorageName()] = $field->getStorageValue($this[$field->getName()]); } self::getDbContext()->delete($r->getAnnotation('table')) ->where('%and', $keys) ->execute(); } catch (\DibiDriverException $e) { return $this->processException($e, callback($this, "remove")); } if ($r->getAnnotation('cached') === TRUE ) { \Foundation\DBCache\ObjectCache::del($this); } return $this; } protected function getDbFormatedData($withoutAutoincrementKeys = false) { $data = array(); foreach ($this->getFields() as $name => $field) { /* @var $field Field */ if ($withoutAutoincrementKeys == false || !$field->isAutoIncrement()) { $data[$field->getStorageName()] = $field->getStorageValue($this->{$field->getName()}); } } return $data; } public static function translateToMethodName($referencedTableName, $reffererColumnName, $tableNameIsClassName = false) { $table = $tableNameIsClassName ? substr($referencedTableName, strripos($referencedTableName, "\\")+1) : self::translateToClassName($referencedTableName); $column = self::translateToClassName(str_replace(array('_id'), '', $reffererColumnName)); //\Nette\Diagnostics\Debugger::barDump(array('tab'=>$table, 'col'=>$column, 'rr'=>substr($referencedTableName, strripos($referencedTableName, "\\")), 'rrIn'=>$referencedTableName ), "col"); if ($table == $column) { return $table; } else { return $column . $table; } } public static function translateToClassName($name) { return str_replace(' ', '', ucwords(str_replace('_', ' ', $name))); } protected static function isCached() { return self::getReflection()->getAnnotation('cached') === TRUE ; } /** * * @param type $data * @return StoredDataObject */ public static function objectWithData($data, &$referrer = null, &$key = null) { if ($data === null) { return null; } $r = self::getReflection(); $keys = $key ? null : call_user_func($r->getName() .'::getFields', true); if ($key) { $referrer = (is_array($data) ? $data[$key] : $data->{$key}); } else if (count($keys) == 1) { $dbRef = array_pop($keys); $key = $dbRef->getStorageName(); $referrer = (is_array($data) ? $data[$key] : $data->{$key}); } else { $referrer = null; } if ($referrer && \Foundation\DBCache\SessionObjectCache::hasObjectWithReflectionAndId($r, $referrer)) { return \Foundation\DBCache\SessionObjectCache::getObjectWithReflectionAndId($r, $referrer, $data); } else { $obj = $r->newInstanceArgs(); $obj->setData((array) $data); return $obj; } } public function release() { \Foundation\DBCache\SessionObjectCache::unsetObject($this); if (isset($this->_ownObjectCache)) { foreach ($this->_ownObjectCache as $cached) { unset($cached); } unset($this->_ownObjectCache); } return parent::release(); } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Set; /** * Description of DbSet * * @author <NAME> * //key (optional) * //value (required) * //storage */ class DbSet extends Set { protected $tablename; /** * * @var \Foundation\Object\DBStored */ protected $parentObject; protected $parentFieldName; /** * * @var \Nette\Reflection\ClassType */ protected $valueFieldReflection; protected $valueType; protected $arrayOfKeys; protected $data; function __construct($tablename, \Foundation\Object\DBStored $parentObject, $parentFieldName, \Nette\Reflection\ClassType $valueFieldReflection, $valueType, $arrayOfKeys = null) { $this->tablename = $tablename; $this->parentObject = $parentObject; $this->parentFieldName = $parentFieldName; $this->valueFieldReflection = $valueFieldReflection; $this->valueType = $valueType; $this->arrayOfKeys = $arrayOfKeys; } /** * * @return DBResultSet */ protected function getResult() { if ($this->data == null) { $keys = \Foundation\Object\DataObject::getFieldsWithReflection($this->valueFieldReflection, true); $key = array_pop($keys); /* @var $key \Foundation\Object\Field */ $join = new \Foundation\Predicates\pJoin(array($this->tablename.".".$this->parentFieldName => $this->parentObject->getId())); $join->setJoinProperties($this->tablename, $this->valueFieldReflection->getAnnotation('table'), $this->valueType, $key->getStorageName()); $instance = $this->valueFieldReflection->newInstanceArgs(); $this->data = $instance->getAll($join); } return $this->data; } protected function getStorage() { return $this->parentObject->getDbContext(); } /** * * @param \Foundation\Object\DBStored $object * @return DbSet */ public function add(\Foundation\Object\DataObject $object) { $this->getStorage()->query("INSERT IGNORE INTO %n %v", $this->tablename, array($this->valueType => $object->getId(), $this->parentFieldName => $this->parentObject->getId())); return $this; } public function contains(\Foundation\Object\DataObject $object) { return !!$this->getStorage()->select("%n", $this->valueType)->from($this->tablename) ->where('%and', array($this->valueType => $object->getId(), $this->parentFieldName => $this->parentObject->getId()))->fetchSingle(); } /** * * @param type $object */ public function remove(\Foundation\Object\DataObject $object) { $this->getStorage()->delete($this->tablename) ->where('%and', array($this->valueType => $object->getId(), $this->parentFieldName => $this->parentObject->getId()))->execute(); return $this; } public function current() { return $this->getResult()->current(); } public function key() { return $this->getResult()->key(); } public function next() { return $this->getResult()->next(); } public function rewind() { return $this->getResult()->rewind(); } public function valid() { return $this->getResult()->valid(); } public function getDistinct($key, $value) { return $this->getResult()->getDistinct($key, $value); } public function count() { return $this->getResult()->count(); } /** * !! NENI APLIKOVAN COUNT ALL * @return type */ public function countAll() { return $this->getResult()->count(); } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Utils; use \Foundation\Predicate, \Foundation\Interfaces\IIterableDataObjectSet; /** * Description of Filter * * @author <NAME> */ class Filter extends \Nette\Object { /** * * @param type string * @return type string */ public static function webalizeClassName($value){ return str_replace(" ", "", ucwords(preg_replace("/\-/", " ", \Nette\Utils\Strings::webalize($value)))); } /** * * @param \Foundation\Predicates\Base $predicate * @param IIterableDataObjectSet $set * @return \Foundation\Set\Set */ public static function filterSetWithPredicate(\Foundation\Predicates\Base $predicate, IIterableDataObjectSet $set) { $ret = new \Foundation\Set\Set(); foreach ($set as $value) { if ($predicate->isMatching($value)) { $ret->add($value); } } return $ret; } /** * * @param type $phone * @return type */ public static function sanitizePhone($phone) { $num = preg_replace("/[^0-9]/", "", $phone->getValue()); return intval(substr($num, strlen($num)-9, 9)); } public static function encodeNumber($number, $short = false) { if (strlen($number) > ($short ? 11 : 16) || $number < 1) throw new \Nette\Application\ApplicationException("Potencial overflow"); $mod = $number%36; $res = base_convert(($number+($short ? 73 : 9876543)) * ($short ? 3 : (73-$mod)), 10, $short ? 36 : 30); while (strlen($res)%3 != 0) { $res = "0".$res; } if ($short) { return base64_encode($res); } else { return base_convert($mod, 10, 36) . base64_encode($res); } } public static function decodeNumber($number, $short = false) { if (!$short) { $mod = base_convert(substr($number, 0, 1), 36, 10); $number = substr($number, 1); } $n = (base_convert(base64_decode($number), $short ? 36 : 30, 10) / ($short ? 3 : (73-$mod))) - ($short ? 73 : 9876543); if (round($n) != $n) throw new \Nette\Application\ApplicationException('Neplatný kód'); return $n; } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\DBCache; /** * Description of SelectCache * * @storage memCachedDb * //@storage cacheStorage * @table _select_cache * @key className */ class SelectCache extends \Foundation\Object\CachedStorage { /** * * @var string * @key */ public $className; /** * * @var string */ public $ownSelect; /** * * @var StorageDictionary */ public $joins; /** * * @var string */ public $hash; /** * * @param \Nette\Reflection\ClassType $reflection * @return SelectCache */ public static function getOrCreateWithObjectReflection(\Nette\Reflection\ClassType $reflection) { $obj = self::getById($reflection->getName()); $regenerate = false; if (!\Nette\Environment::isProduction() && $obj && $obj->hash != \Foundation\Object\DataObject::getTypeHash($reflection)) { $regenerate = true; } if (!\Nette\Environment::isProduction() && $obj) { //$fields = \Foundation\Object\DataObject::getFieldsWithReflection($reflection); foreach ($obj->joins as $classname => $value) { if ($value['hash'] != \Foundation\Object\DataObject::getTypeHash(new \Nette\Reflection\ClassType($classname))) { $regenerate = true; break; } } } if ($regenerate) { $obj->createOwnSelectWithReflection($reflection); $obj->generateJoinsWithReflection($reflection); $obj->hash = \Foundation\Object\DataObject::getTypeHash($reflection); $obj->update(); } else if (!$obj) { $obj = new SelectCache(); $obj->className = $reflection->getName(); $obj->createOwnSelectWithReflection($reflection); $obj->generateJoinsWithReflection($reflection); $obj->hash = \Foundation\Object\DataObject::getTypeHash($reflection); $obj->create(); } //\Nette\Diagnostics\Debugger::barDump(array('obj'=>$obj, 'reg'=>$regenerate), "haha?"); //$obj->joins = array(); //$obj->update(); return $obj; } public function createOwnSelectWithReflection(\Nette\Reflection\ClassType $reflection) { $fields = \Foundation\Object\DataObject::getFieldsWithReflection($reflection); $select = array(); foreach ($fields as $field) { /* @var $field Field */ if ($field->isSetOfData() && !$field->isLazy()) { /* @implement Lazy data sets in select statement */ throw new \Nette\NotImplementedException("Sets are not implemented"); } else if (!$field->isSetOfData()) { $select[] = "[".$reflection->getAnnotation('table'). "." .$field->getStorageName() . "]" . ($field->getName() == $field->getStorageName() ? "" : " as [".$field->getName()."]"); }; } $this->ownSelect = implode(", ", $select); } public function generateJoinsWithReflection(\Nette\Reflection\ClassType $reflection) { $fields = \Foundation\Object\DataObject::getFieldsWithReflection($reflection); $currentlyJoinedTables = array(); $this->joins = array(); foreach ($fields as $field) { /* @var $field Field */ if ($field->isJoined() && !$field->isLazy() && $field->getJoinedClassReflection()->getAnnotation('cached') !== TRUE ) { // && $field->isSetOfData() $joinreflection = $field->getJoinedClassReflection(); \Nette\Diagnostics\Debugger::barDump($field, "REF?"); $joinfields = \Foundation\Object\DataObject::getFieldsWithReflection($joinreflection); if ($joinreflection instanceof \Nette\Reflection\ClassType && $joinreflection->isSubclassOf("\\Foundation\\Object\\DBStored")) { $joinTabAlias = ($field->getName() == $joinreflection->getAnnotation('table') . '_id') ? $joinreflection->getAnnotation('table') : $field->getName()."_".$joinreflection->getAnnotation('table'); $table = "[".$joinreflection->getAnnotation('table')."] as [".$joinTabAlias."]"; $on = "[".$joinTabAlias.".". $field->getJoinStorageName() ."] = [".$reflection->getAnnotation('table').".".$field->getStorageName()."]"; $select = array(); $joinTrasnlation = array(); foreach ($joinfields as $joinfield) { /* @var $joinfield Field */ if ($field->isSetOfData() && !$field->isLazy()) { /* @implement Lazy data sets in join statement */ } else if (!$field->isSetOfData()) { $select[] = "[".$joinTabAlias. "." .$joinfield->getStorageName() . "] as [r_".$joinTabAlias."_".$joinfield->getName()."]"; } $joinTrasnlation[$joinfield->getName()] = "r_".$joinTabAlias."_".$joinfield->getName(); } $select = implode(", ", $select); $this->joins[$joinreflection->getName()] = array( 'table' => $table, 'on' => $on, 'select' => $select, 'translation' => $joinTrasnlation, 'hash' => \Foundation\Object\DataObject::getTypeHash($joinreflection) ); } } } } } <file_sep><?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Foundation\Set; /** * Description of SerializableDictionary * * @author <NAME> */ class SerializableDictionary extends Dictionary implements \Foundation\Interfaces\IStringStorable { public function jsonSerialize() { $ret = $this->iterator->getArrayCopy(); //$ret["_json_type_"] = \Nette\Reflection\ClassType::from($this)->getName(); return $ret; } public function jsonUnSerialize($decodedJsonArray) { $set = array(); foreach ($decodedJsonArray as $key => $value) { if (is_array($value)) { if (!iss) $obj = new SerializableDictionary(); $obj->jsonUnSerialize($value); $set[$key] = $obj; } else { $set[$key] = $value; } } $this->iterator = new \ArrayIterator($set); } public function serialize() { $array = array(); foreach ($this as $key => $value) { if ($value instanceof \Foundation\Interfaces\IStringStorable) { $value = $value->jsonSerialize(); } $array[$key] = $value; } return json_encode($array); } public function unserialize($serialized) { $array = json_decode($serialized, true); $this->jsonUnSerialize($array); } protected function validateInputValue($value, $key = null) { if (!in_array(gettype($value), \Foundation\CONS::$STATIC_TYPES)) { throw new \Foundation\BadInputException("Key shold be scalar type"); } if (!in_array(gettype($value), \Foundation\CONS::$STATIC_TYPES) && !$value instanceof SerializableDictionary) { throw new \Foundation\BadInputException("Value of '$key' should be scalar or SerializableDictionary"); } } }
d7d6f6678348146b1ab6af30870296947ff6d4ac
[ "Markdown", "PHP" ]
29
PHP
davidmenger/SimpleOrm
663b95179237b61a1fdce1fec647a17ee6c1091e
93f0dcfb4d0d2f224b06693983fe1c7f3d9bd554
refs/heads/master
<repo_name>pkuxmq/Automatic-Differentiation<file_sep>/Makefile all: g++ -O2 ADGraph.cpp Operator.cpp test.cpp -o test <file_sep>/Operator.h #ifndef __OPERATOR__ #define __OPERATOR__ #include "ADGraph.h" class Op_Add : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Sub : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Mul : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Div : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Sin : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Cos : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Tan : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Log : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; class Op_Exp : public ADOperator { public: vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); double computeOp(vector<ADNode *> *); }; #endif <file_sep>/test.cpp #include <iostream> #include <map> #include "ADGraph.h" #include "Operator.h" using namespace std; double f(double x1, double x2, double x3) { return (sin(x1+1)+cos(2*x2))*tan(log(x3)) + (sin(x2+1)+cos(2*x1))*exp(1+sin(x3)); } int main(int argc, char *argv[]) { if (argc != 4) { fprintf(stderr, "Too few arguments!\n"); exit(1); } int X1 = atoi(argv[1]), X2 = atoi(argv[2]), X3 = atoi(argv[3]); ADGraph ADG; ADNode *x1 = ADG.CreateInputNode(); ADNode *x2 = ADG.CreateInputNode(); ADNode *x3 = ADG.CreateInputNode(); ADNode *one = ADG.CreateConstNode(1); ADNode *two = ADG.CreateConstNode(2); ADNode *t1, *t2, *y; t1 = ADG.Add(x1, one); t1 = ADG.Sin(t1); t2 = ADG.Mul(two, x2); t2 = ADG.Cos(t2); t1 = ADG.Add(t1, t2); t2 = ADG.Log(x3); t2 = ADG.Tan(t2); y = ADG.Mul(t1, t2); t1 = ADG.Add(x2, one); t1 = ADG.Sin(t1); t2 = ADG.Mul(two, x1); t2 = ADG.Cos(t2); t1 = ADG.Add(t1, t2); t2 = ADG.Sin(x3); t2 = ADG.Add(one, t2); t2 = ADG.Exp(t2); t1 = ADG.Mul(t1, t2); y = ADG.Add(y, t1); ADG.BuildADGraph(); x1->SetVal(X1); x2->SetVal(X2); x3->SetVal(X3); ADG.Compute(); double d1 = ADG.GetDiff(x1), d2 = ADG.GetDiff(x2), d3 = ADG.GetDiff(x3); cout << "Automatic differentiation results:" << endl; cout << "Diff for x1: " << d1 << endl; cout << "Diff for x2: " << d2 << endl; cout << "Diff for x3: " << d3 << endl; cout << endl; cout << "Numerical differentiation results:" << endl; cout << "Diff for x1: " << (f(X1 + 1e-8, X2, X3) - f(X1, X2, X3)) / 1e-8 << endl; cout << "Diff for x2: " << (f(X1, X2 + 1e-8, X3) - f(X1, X2, X3)) / 1e-8 << endl; cout << "Diff for x3: " << (f(X1, X2, X3 + 1e-8) - f(X1, X2, X3)) / 1e-8 << endl; cout << endl; } <file_sep>/ADGraph.cpp #include "ADGraph.h" #include "Operator.h" #include <map> #include <queue> using std::map; using std::queue; extern Op_Add op_add; extern Op_Sub op_sub; extern Op_Mul op_mul; extern Op_Div op_div; extern Op_Sin op_sin; extern Op_Cos op_cos; extern Op_Tan op_tan; extern Op_Log op_log; extern Op_Exp op_exp; vector<ADNode *> ADOperator::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { vector<ADNode *> Diff; return Diff; } double ADOperator::computeOp(vector<ADNode *> *preNodes) { return 0; } ADNode::ADNode() { op = NULL; NodeDiff = NULL; val = 0; } ADNode::ADNode(ADOperator *o) { op = o; NodeDiff = NULL; val = 0; } ADNode::~ADNode() {} void ADNode::ConnectPreNode(ADNode *n) { preNodes.push_back(n); n->postNodes.push_back(this); } void ADNode::ConnectPostNode(ADNode *n) { postNodes.push_back(n); n->preNodes.push_back(this); } void ADNode::SetVal(double v) { val = v; } void ADNode::ComputeNode() { if (op != NULL) val = op->computeOp(&preNodes); } ADGraph::ADGraph() {} ADGraph::~ADGraph() { for (auto i : Nodes) delete i; } void ADGraph::ConnectNode(ADNode *pre, ADNode *post) { pre->ConnectPostNode(post); } void ADGraph::TopoSort() { map<ADNode *, int> NodeMap; int NodeNum = Nodes.size(); for (int i = 0; i < NodeNum; i++) NodeMap[Nodes[i]] = i; int *degree = new int[NodeNum]; memset(degree, 0, sizeof(int) * NodeNum); for (int i = 0; i < NodeNum; i++) { for (auto j : Nodes[i]->postNodes) degree[NodeMap[j]]++; } vector<ADNode *> OrderedNodes; queue<ADNode *> WaitingList; for (int i = 0; i < NodeNum; i++) if (degree[i] == 0) WaitingList.push(Nodes[i]); while (!WaitingList.empty()) { auto i = WaitingList.front(); WaitingList.pop(); OrderedNodes.push_back(i); for (auto j : i->postNodes) { degree[NodeMap[j]]--; if (degree[NodeMap[j]] == 0) WaitingList.push(j); } } Nodes = OrderedNodes; } void ADGraph::BuildADGraph() { TopoSort(); int NodeNum = Nodes.size(); for (int i = NodeNum - 1; i >= 0; i--) { if (Nodes[i]->postNodes.empty()) { Nodes[i]->NodeDiff = CreateConstNode(1); } else if (Nodes[i]->postNodes.size() == 1) { Nodes[i]->NodeDiff = Nodes[i]->postNodeDiff[0]; } else { ADNode *d = CreateOpNode(&op_add); for (auto k : Nodes[i]->postNodeDiff) ConnectNode(k, d); Nodes[i]->NodeDiff = d; } if (Nodes[i]->op == NULL) continue; vector<ADNode *> DiffNodes = Nodes[i]->op->computeDiff(&(Nodes[i]->preNodes), &(Nodes)); int n = DiffNodes.size(); for (int j = 0; j < n; j++) { ADNode *d = CreateOpNode(&op_mul); ConnectNode(Nodes[i]->NodeDiff, d); ConnectNode(DiffNodes[j], d); Nodes[i]->preNodes[j]->postNodeDiff.push_back(d); } } } void ADGraph::Compute() { TopoSort(); for (auto i : Nodes) i->ComputeNode(); } double ADGraph::GetDiff(ADNode *node) { return node->NodeDiff->val; } ADNode *ADGraph::CreateInputNode() { ADNode *node = new ADNode(NULL); Nodes.push_back(node); inputNodes.push_back(node); return node; } ADNode *ADGraph::CreateOpNode(ADOperator *o) { ADNode *node = new ADNode(o); Nodes.push_back(node); return node; } ADNode *ADGraph::CreateConstNode(double c) { ADNode *node = new ADNode(NULL); node->SetVal(c); Nodes.push_back(node); return node; } ADNode *ADGraph::Add(ADNode *n1, ADNode *n2) { ADNode *node = new ADNode(&op_add); ConnectNode(n1, node); ConnectNode(n2, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Sub(ADNode *n) { ADNode *node = new ADNode(&op_sub); ConnectNode(n, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Sub(ADNode *n1, ADNode *n2) { ADNode *node = new ADNode(&op_sub); ConnectNode(n1, node); ConnectNode(n2, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Mul(ADNode *n1, ADNode *n2) { ADNode *node = new ADNode(&op_mul); ConnectNode(n1, node); ConnectNode(n2, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Div(ADNode *n1, ADNode *n2) { ADNode *node = new ADNode(&op_div); ConnectNode(n1, node); ConnectNode(n2, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Sin(ADNode *n) { ADNode *node = new ADNode(&op_sin); ConnectNode(n, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Cos(ADNode *n) { ADNode *node = new ADNode(&op_cos); ConnectNode(n, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Tan(ADNode *n) { ADNode *node = new ADNode(&op_tan); ConnectNode(n, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Log(ADNode *n) { ADNode *node = new ADNode(&op_log); ConnectNode(n, node); Nodes.push_back(node); return node; } ADNode *ADGraph::Exp(ADNode *n) { ADNode *node = new ADNode(&op_exp); ConnectNode(n, node); Nodes.push_back(node); return node; } <file_sep>/README.md # Automatic-Differentiation Homework for Convex Analysis and Optimization Methods ## Function The program provides interface for building computational graph, building automatic differentiation computational graph and computing the results for a given expression DAG. The program also include a test sample for function y = (sin(x1 + 1) + cos(x2)) * tan(log(x3)) + (sin(x2 + 1) + cos(2x2) * exp(1 + sin(x3)) ## Environment Linux Test sample: run the excutable file 'test' with three arguments (x1, x2, x3), such as ./test 2 2 2. <file_sep>/Operator.cpp #include "Operator.h" using std::sin; using std::cos; using std::tan; using std::log; using std::exp; Op_Add op_add; Op_Sub op_sub; Op_Mul op_mul; Op_Div op_div; Op_Sin op_sin; Op_Cos op_cos; Op_Tan op_tan; Op_Log op_log; Op_Exp op_exp; vector<ADNode *> Op_Add::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); vector<ADNode *> Diffs; for (int i = 0; i < n; i++) { ADNode *d = new ADNode(NULL); d->SetVal(1); Diffs.push_back(d); GraphNodes->push_back(d); } return Diffs; } double Op_Add::computeOp(vector<ADNode *> *preNodes) { double val = 0; for (auto i : *preNodes) val += i->val; return val; } vector<ADNode *> Op_Sub::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); if (n != 2 && n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } vector<ADNode *> Diffs; if (n == 2) { ADNode *d1 = new ADNode(NULL); d1->SetVal(1); Diffs.push_back(d1); ADNode *d2 = new ADNode(NULL); d2->SetVal(-1); Diffs.push_back(d2); GraphNodes->push_back(d1); GraphNodes->push_back(d2); } else { ADNode *d1 = new ADNode(NULL); d1->SetVal(-1); Diffs.push_back(d1); GraphNodes->push_back(d1); } return Diffs; } double Op_Sub::computeOp(vector<ADNode *> *preNodes) { double val = 0; int n = preNodes->size(); if (n != 2 && n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } if (n == 2) val = (*preNodes)[0]->val - (*preNodes)[1]->val; else val = -(*preNodes)[0]->val; return val; } vector<ADNode *> Op_Mul::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); vector<ADNode *> Diffs; if (n == 2) { Diffs.push_back((*preNodes)[1]); Diffs.push_back((*preNodes)[0]); } else { for (int i = 0; i < n; i++) { ADNode *d = new ADNode(&op_mul); for (int j = 0; j < n; j++) { if (i == j) continue; d->ConnectPreNode((*preNodes)[j]); } Diffs.push_back(d); GraphNodes->push_back(d); } } return Diffs; } double Op_Mul::computeOp(vector<ADNode *> *preNodes) { double val = 1; for (auto i : *preNodes) val *= i->val; return val; } vector<ADNode *> Op_Div::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); if (n != 2) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } vector<ADNode *> Diffs; ADNode *d1 = new ADNode(NULL); d1->SetVal(1); ADNode *d2 = new ADNode(&op_div); d2->ConnectPreNode(d1); d2->ConnectPreNode((*preNodes)[1]); Diffs.push_back(d2); ADNode *d3 = new ADNode(&op_mul); d3->ConnectPreNode((*preNodes)[1]); d3->ConnectPreNode((*preNodes)[1]); ADNode *d4 = new ADNode(&op_div); d4->ConnectPreNode((*preNodes)[0]); d4->ConnectPreNode(d3); ADNode *d5 = new ADNode(&op_sub); d5->ConnectPreNode(d4); Diffs.push_back(d5); GraphNodes->push_back(d1); GraphNodes->push_back(d2); GraphNodes->push_back(d3); GraphNodes->push_back(d4); GraphNodes->push_back(d5); return Diffs; } double Op_Div::computeOp(vector<ADNode *> *preNodes) { double val = 0; int n = preNodes->size(); if (n != 2) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } val = (*preNodes)[0]->val / (*preNodes)[1]->val; return val; } vector<ADNode *> Op_Sin::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } vector<ADNode *> Diffs; ADNode *d = new ADNode(&op_cos); d->ConnectPreNode((*preNodes)[0]); Diffs.push_back(d); GraphNodes->push_back(d); return Diffs; } double Op_Sin::computeOp(vector<ADNode *> *preNodes) { double val = 0; int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } val = sin((*preNodes)[0]->val); return val; } vector<ADNode *> Op_Cos::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } vector<ADNode *> Diffs; ADNode *d1 = new ADNode(&op_sin); d1->ConnectPreNode((*preNodes)[0]); ADNode *d2 = new ADNode(&op_sub); d2->ConnectPreNode(d1); Diffs.push_back(d2); GraphNodes->push_back(d1); GraphNodes->push_back(d2); return Diffs; } double Op_Cos::computeOp(vector<ADNode *> *preNodes) { double val = 0; int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } val = cos((*preNodes)[0]->val); return val; } vector<ADNode *> Op_Tan::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } vector<ADNode *> Diffs; ADNode *d1 = new ADNode(&op_cos); d1->ConnectPreNode((*preNodes)[0]); ADNode *d2 = new ADNode(&op_mul); d2->ConnectPreNode(d1); d2->ConnectPreNode(d1); ADNode *d3 = new ADNode(NULL); d3->SetVal(1); ADNode *d4 = new ADNode(&op_div); d4->ConnectPreNode(d3); d4->ConnectPreNode(d2); Diffs.push_back(d4); GraphNodes->push_back(d1); GraphNodes->push_back(d2); GraphNodes->push_back(d3); GraphNodes->push_back(d4); return Diffs; } double Op_Tan::computeOp(vector<ADNode *> *preNodes) { double val = 0; int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } val = tan((*preNodes)[0]->val); return val; } vector<ADNode *> Op_Log::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } vector<ADNode *> Diffs; ADNode *d1 = new ADNode(NULL); d1->SetVal(1); ADNode *d2 = new ADNode(&op_div); d2->ConnectPreNode(d1); d2->ConnectPreNode((*preNodes)[0]); Diffs.push_back(d2); GraphNodes->push_back(d1); GraphNodes->push_back(d2); return Diffs; } double Op_Log::computeOp(vector<ADNode *> *preNodes) { double val = 0; int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } val = log((*preNodes)[0]->val); return val; } vector<ADNode *> Op_Exp::computeDiff(vector<ADNode *> *preNodes, vector<ADNode *> *GraphNodes) { int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } vector<ADNode *> Diffs; ADNode *d = new ADNode(&op_exp); d->ConnectPreNode((*preNodes)[0]); Diffs.push_back(d); GraphNodes->push_back(d); return Diffs; } double Op_Exp::computeOp(vector<ADNode *> *preNodes) { double val = 0; int n = preNodes->size(); if (n != 1) { fprintf(stderr, "Error node number %d for substraction!\n", n); exit(1); } val = exp((*preNodes)[0]->val); return val; } <file_sep>/ADGraph.h #ifndef __ADGRAPH__ #define __ADGRAPH__ #include <iostream> #include <math.h> #include <vector> #include <string.h> using std::vector; class ADNode; class ADGraph; class ADOperator { public: virtual vector<ADNode *> computeDiff(vector<ADNode *> *, vector<ADNode *> *); virtual double computeOp(vector<ADNode *> *); }; class ADNode { public: vector<ADNode *> preNodes, postNodes; ADOperator *op; vector<ADNode *> postNodeDiff; ADNode *NodeDiff; double val; void ConnectPreNode(ADNode *); void ConnectPostNode(ADNode *); void SetVal(double); void ComputeNode(); ADNode(); ADNode(ADOperator *); ~ADNode(); }; class ADGraph { public: vector<ADNode *> Nodes, inputNodes, outputNodes; ADNode *CreateInputNode(); ADNode *CreateOpNode(ADOperator *); ADNode *CreateConstNode(double); void ConnectNode(ADNode *, ADNode *); void TopoSort(); void BuildADGraph(); void Compute(); double GetDiff(ADNode *); ADNode *Add(ADNode *, ADNode *); ADNode *Sub(ADNode *); ADNode *Sub(ADNode *, ADNode *); ADNode *Mul(ADNode *, ADNode *); ADNode *Div(ADNode *, ADNode *); ADNode *Sin(ADNode *); ADNode *Cos(ADNode *); ADNode *Tan(ADNode *); ADNode *Log(ADNode *); ADNode *Exp(ADNode *); ADGraph(); ~ADGraph(); }; #endif
4789b458d2fa8c25cabf6ea1f0aea7def8596f09
[ "Markdown", "Makefile", "C++" ]
7
Makefile
pkuxmq/Automatic-Differentiation
b39963d7cea4facad3c2a2b14e934cd780e19569
890bcadc4c2750b4fa7be924b2fe4d71d3b83f69
refs/heads/master
<repo_name>rchisebu/paease-spring-api<file_sep>/src/main/java/com/starlabs/PaEase/repository/TransactionsRepository.java package com.starlabs.PaEase.repository; import com.starlabs.PaEase.model.Statement; import com.starlabs.PaEase.model.Transactions; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; /** * * @author <NAME> */ @Repository public interface TransactionsRepository extends JpaRepository<Transactions, Long> { @Query(value = "SELECT * FROM transactions where msisdn=:msisdn AND status_code=:statusCode AND MONTH(date_created) = MONTH(CURDATE()) AND YEAR(date_created) = YEAR(CURDATE()) ORDER BY date_created ASC", nativeQuery = true) List<Transactions> findByMsisdnAndStatusCode(@Param("msisdn") Long msisdn, @Param("statusCode") int statusCode); @Query(value = "SELECT s.service_name as service,SUM(t.amount) as amount,cp.percentage_charge as charge FROM customerprofiles cp INNER JOIN transactions t ON cp.msisdn=t.msisdn INNER JOIN services s ON t.serviceID=s.serviceID where t.msisdn=:msisdn AND t.status_code=:statusCode AND MONTH(t.date_created) = MONTH(CURDATE()) AND YEAR(t.date_created) = YEAR(CURDATE()) group by s.service_name", nativeQuery = true) public List<Statement> statement(@Param("msisdn") Long msisdn, @Param("statusCode") int statusCode); Transactions findByStatuscodeAndTransactionIDAndMsisdnAndAccountAndServiceID(int statuscode,Long transactionID, Long msisdn, Long account, Long serviceID); Transactions findByTransactionID(Long transactionID); } <file_sep>/src/main/java/com/starlabs/PaEase/model/RiskCategory.java package com.starlabs.PaEase.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.data.jpa.domain.support.AuditingEntityListener; /** * * @author <NAME> */ @Entity @Table(name = "riskcategory") @EntityListeners(AuditingEntityListener.class) @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class RiskCategory implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long riskID; private String name; private String description; private String max_amount; private int active; /** * @return the riskID */ public Long getRiskID() { return riskID; } /** * @param riskID the riskID to set */ public void setRiskID(Long riskID) { this.riskID = riskID; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the maximumAmount */ public String getMaximumAmount() { return max_amount; } /** * @param maximumAmount the maximumAmount to set */ public void setMaximumAmount(String maximumAmount) { this.max_amount = maximumAmount; } /** * @return the active */ public int getActive() { return active; } /** * @param active the active to set */ public void setActive(int active) { this.active = active; } } <file_sep>/src/main/java/com/starlabs/PaEase/model/CustomerProfile.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.starlabs.PaEase.model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; /** * * @author <NAME> */ @Entity @Table(name = "customerprofiles") @EntityListeners(AuditingEntityListener.class) @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class CustomerProfile implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long profileID; @Column(nullable = false, updatable = false) @Temporal(TemporalType.TIMESTAMP) @CreatedDate @JsonIgnore private Date date_created; @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) @LastModifiedDate @JsonIgnore private Date date_modified; @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) @OneToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "customerID", nullable = false) private Customer customer; public CustomerProfile() { } @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) @OneToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "risk_categoryID", nullable = false) private RiskCategory riskCategory; private Long msisdn; private Long alternative_msisdn; private String bank_account; private Double balance; private Double loan_amount; private Double min_amount; private String percentage_charge; @JsonIgnore private String PIN; private int status; private int wrong_pin_attempts; private String lastlogin; /** * @return the profileID */ public Long getProfileID() { return profileID; } /** * @param profileID the profileID to set */ public void setProfileID(Long profileID) { this.profileID = profileID; } /** * @return the date_created */ public Date getDate_created() { return date_created; } /** * @param date_created the date_created to set */ public void setDate_created(Date date_created) { this.date_created = date_created; } /** * @return the date_modified */ public Date getDate_modified() { return date_modified; } /** * @param date_modified the date_modified to set */ public void setDate_modified(Date date_modified) { this.date_modified = date_modified; } /** * @return the customer */ public Customer getCustomer() { return customer; } /** * @param customer the customer to set */ public void setCustomer(Customer customer) { this.customer = customer; } /** * @return the riskCategory */ public RiskCategory getRiskCategory() { return riskCategory; } /** * @param riskCategory the riskCategory to set */ public void setRiskCategory(RiskCategory riskCategory) { this.riskCategory = riskCategory; } /** * @return the msisdn */ public Long getMsisdn() { return msisdn; } /** * @param msisdn the msisdn to set */ public void setMsisdn(Long msisdn) { this.msisdn = msisdn; } /** * @return the alternative_msisdn */ public Long getAlternative_msisdn() { return alternative_msisdn; } /** * @param alternative_msisdn the alternative_msisdn to set */ public void setAlternative_msisdn(Long alternative_msisdn) { this.alternative_msisdn = alternative_msisdn; } /** * @return the bank_account */ public String getBank_account() { return bank_account; } /** * @param bank_account the bank_account to set */ public void setBank_account(String bank_account) { this.bank_account = bank_account; } /** * @return the balance */ public Double getBalance() { return balance; } /** * @param balance the balance to set */ public void setBalance(Double balance) { this.balance = balance; } /** * @return the loan_amount */ public Double getLoan_amount() { return loan_amount; } /** * @param loan_amount the loan_amount to set */ public void setLoan_amount(Double loan_amount) { this.loan_amount = loan_amount; } /** * @return the min_amount */ public Double getMin_amount() { return min_amount; } /** * @param min_amount the min_amount to set */ public void setMin_amount(Double min_amount) { this.min_amount = min_amount; } /** * @return the percentage_charge */ public String getPercentage_charge() { return percentage_charge; } /** * @param percentage_charge the percentage_charge to set */ public void setPercentage_charge(String percentage_charge) { this.percentage_charge = percentage_charge; } /** * @return the PIN */ public String getPIN() { return PIN; } /** * @param PIN the PIN to set */ public void setPIN(String PIN) { this.PIN = PIN; } /** * @return the status */ public int getStatus() { return status; } /** * @param status the status to set */ public void setStatus(int status) { this.status = status; } /** * @return the wrong_pin_attempts */ public int getWrong_pin_attempts() { return wrong_pin_attempts; } /** * @param wrong_pin_attempts the wrong_pin_attempts to set */ public void setWrong_pin_attempts(int wrong_pin_attempts) { this.wrong_pin_attempts = wrong_pin_attempts; } /** * @return the lastlogin */ public String getLastlogin() { return lastlogin; } /** * @param lastlogin the lastlogin to set */ public void setLastlogin(String lastlogin) { this.lastlogin = lastlogin; } } <file_sep>/src/main/java/com/starlabs/PaEase/model/Statement.java package com.starlabs.PaEase.model; /** * * @author chulu */ public interface Statement { String getService(); Double getAmount(); int getCharge(); } <file_sep>/src/main/java/com/starlabs/PaEase/controller/APIController.java package com.starlabs.PaEase.controller; import com.google.gson.Gson; import com.starlabs.PaEase.request.Request; import com.starlabs.PaEase.config.ApiSecurityConfig; import com.starlabs.PaEase.logger.APILogger; import com.starlabs.PaEase.model.Clients; import com.starlabs.PaEase.model.CustomerProfile; import com.starlabs.PaEase.model.Statement; import com.starlabs.PaEase.model.Transactions; import com.starlabs.PaEase.repository.ClientRepository; import com.starlabs.PaEase.repository.CustomerProfileRepository; import com.starlabs.PaEase.repository.TransactionsRepository; import com.starlabs.PaEase.service.APIService; import com.starlabs.PaEase.service.Response; import com.starlabs.PaEase.utils.Utils; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * * @author chulu */ @RestController @RequestMapping("/api") public class APIController { private APILogger log; private ApiSecurityConfig config; private Response resp; private Gson gson; private ArrayList response; private ArrayList validationResp; private Utils utils; @Autowired ClientRepository clientRepository; @Autowired TransactionsRepository transactionsRepository; @Autowired CustomerProfileRepository customerProfileRepository; @Autowired APIService apiService; public APIController() { this.validationResp = new ArrayList(); this.utils = new Utils(); this.config = new ApiSecurityConfig(); this.log = new APILogger(getClass()); this.resp = new Response(); this.gson = new Gson(); this.response = new ArrayList(); } @PreAuthorize("permitAll()") @GetMapping("/clients") public List<Clients> getAllclients() { return clientRepository.findAll(); } /* @GetMapping("/async") public ResponseEntity<Map<String, String>> async() { this.apiservice.process(); Map<String, String> result = new java.util.HashMap<>(); result.put("message", "Request is being processed"); return new ResponseEntity<>(result, HttpStatus.OK); } @PostMapping("/clients") public Clients createClient(@Valid @RequestBody Clients client) { return clientRepository.save(client); } @GetMapping("/customerProfiles") public List<CustomerProfile> getCustomerprofiles() { return customerProfileRepository.findAll(); }*/ @PostMapping("/v1/json") public ResponseEntity<Response> JsonRequest(@Valid @RequestBody Request request) { Request requestForLogs = request; requestForLogs.setPin(00000000000000000); log.info("|" + this.getClass().getSimpleName() + "|"+ Thread.currentThread().getStackTrace()[1].getMethodName() + "|" + request.getMsisdn() + " | Request is : " + gson.toJson(requestForLogs)); if (this.config.checkMethod(request.getMethod())) { //Lets validate mandatory fields first before proceeding this.validationResp = this.config.validateMethodMandatoryFields(request, log, gson); if (this.validationResp.isEmpty()) { this.resp = this.apiService.handleRequest(request); } else { //Missing mandatory fields this.resp.setData(response); this.resp.setStatus(Utils.status_missing_mandatory_parm); this.resp.setStatus_desc(Utils.status_missing_mandatory_parm_desc.replace("{params}", this.utils.ArrayListToString(this.validationResp))); log.info("| " + Thread.currentThread().getStackTrace()[1].getMethodName() + "|" + request.getMsisdn() + " | Mandatory parameter(s) {" + this.utils.ArrayListToString(this.validationResp) + "} are missing!"); } } else { //Method being requested is not allowed log.info("|" + this.getClass().getSimpleName() +"| " + Thread.currentThread().getStackTrace()[1].getMethodName() + "|" + request.getMsisdn() + " | Requested method : " + request.getMethod() + " is not allowed!"); this.resp.setData(response); this.resp.setStatus(Utils.status_invalid_method); this.resp.setStatus_desc(Utils.status_invalid_method_desc.replace("{method}", request.getMethod())); } return ResponseEntity.accepted().body(this.resp); } @GetMapping("/encode/{pin}") public ResponseEntity<String> encodePin(@PathVariable(value = "pin") String pin) { String response = ""; if (!pin.isEmpty()) { response = this.config.encodePin(pin); } return new ResponseEntity<String>(response, new HttpHeaders(), HttpStatus.OK); } @PostMapping("/decode") public ResponseEntity<Response> decodePin(@RequestBody Request request) { log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + "| Response status code is: " + request.toString()); this.resp.setStatus(101); if (request.getPin() > 0 && !request.getHash().isEmpty()) { this.resp.setStatus(100); } return ResponseEntity.ok(this.resp); } } <file_sep>/src/main/java/com/starlabs/PaEase/repository/CustomerProfileRepository.java package com.starlabs.PaEase.repository; import com.starlabs.PaEase.model.CustomerProfile; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * * @author <NAME> */ @Repository public interface CustomerProfileRepository extends JpaRepository<CustomerProfile, Long> { CustomerProfile findByMsisdn(Long msisdn); } <file_sep>/src/main/java/com/starlabs/PaEase/request/Request.java package com.starlabs.PaEase.request; import javax.validation.constraints.NotBlank; /** * * @author chulu */ public class Request { private Long msisdn; private Long b_msisdn; private int pin; private String extra_data; private int serviceID; private double amount; private Long account; private String transactionID; private int status_code; private String status_desc; private String external_transactionID; private String receipt_number; @NotBlank(message = "Method cannot be blank!") private String method; private String hash; /** * @return the hash */ public String getHash() { return hash; } /** * @param hash the hash to set */ public void setHash(String hash) { this.hash = hash; } /** * @return the method */ public String getMethod() { return method; } /** * @param method the method to set */ public void setMethod(String method) { this.method = method; } /** * @return the msisdn */ public Long getMsisdn() { return msisdn; } /** * @param msisdn the msisdn to set */ public void setMsisdn(Long msisdn) { this.msisdn = msisdn; } /** * @return the b_msisdn */ public Long getB_msisdn() { return b_msisdn; } /** * @param b_msisdn the b_msisdn to set */ public void setB_msisdn(Long b_msisdn) { this.b_msisdn = b_msisdn; } /** * @return the pin */ public int getPin() { return pin; } /** * @param pin the pin to set */ public void setPin(int pin) { this.pin = pin; } /** * @return the extra_data */ public String getExtra_data() { return extra_data; } /** * @param extra_data the extra_data to set */ public void setExtra_data(String extra_data) { this.extra_data = extra_data; } /** * @return the serviceID */ public int getServiceID() { return serviceID; } /** * @param serviceID the serviceID to set */ public void setServiceID(int serviceID) { this.serviceID = serviceID; } /** * @return the amount */ public double getAmount() { return amount; } /** * @param amount the amount to set */ public void setAmount(double amount) { this.amount = amount; } /** * @return the account */ public Long getAccount() { return account; } /** * @param account the account to set */ public void setAccount(Long account) { this.account = account; } /** * @return the transactionID */ public String getTransactionID() { return transactionID; } /** * @param transactionID the transactionID to set */ public void setTransactionID(String transactionID) { this.transactionID = transactionID; } /** * @return the status_code */ public int getStatus_code() { return status_code; } /** * @param status_code the status_code to set */ public void setStatus_code(int status_code) { this.status_code = status_code; } /** * @return the status_desc */ public String getStatus_desc() { return status_desc; } /** * @param status_desc the status_desc to set */ public void setStatus_desc(String status_desc) { this.status_desc = status_desc; } /** * @return the external_transactionID */ public String getExternal_transactionID() { return external_transactionID; } /** * @param external_transactionID the external_transactionID to set */ public void setExternal_transactionID(String external_transactionID) { this.external_transactionID = external_transactionID; } /** * @return the receipt_number */ public String getReceipt_number() { return receipt_number; } /** * @param receipt_number the receipt_number to set */ public void setReceipt_number(String receipt_number) { this.receipt_number = receipt_number; } } <file_sep>/src/main/java/com/starlabs/PaEase/request/ServiceRequest.java package com.starlabs.PaEase.request; /** * * @author chulu */ public class ServiceRequest { /** * @return the extra_data */ public String getExtra_data() { return extra_data; } /** * @param extra_data the extra_data to set */ public void setExtra_data(String extra_data) { this.extra_data = extra_data; } private Long msisdn; private int serviceID; private double amount; private Long account; private String transactionID; private String nrc; private double balance; private String percentageCharge; private String extra_data; /** * @return the msisdn */ public Long getMsisdn() { return msisdn; } /** * @param msisdn the msisdn to set */ public void setMsisdn(Long msisdn) { this.msisdn = msisdn; } /** * @return the serviceID */ public int getServiceID() { return serviceID; } /** * @param serviceID the serviceID to set */ public void setServiceID(int serviceID) { this.serviceID = serviceID; } /** * @return the amount */ public double getAmount() { return amount; } /** * @param amount the amount to set */ public void setAmount(double amount) { this.amount = amount; } /** * @return the account */ public Long getAccount() { return account; } /** * @param account the account to set */ public void setAccount(Long account) { this.account = account; } /** * @return the transactionID */ public String getTransactionID() { return transactionID; } /** * @param transactionID the transactionID to set */ public void setTransactionID(String transactionID) { this.transactionID = transactionID; } /** * @return the nrc */ public String getNrc() { return nrc; } /** * @param nrc the nrc to set */ public void setNrc(String nrc) { this.nrc = nrc; } /** * @return the balance */ public double getBalance() { return balance; } /** * @param balance the balance to set */ public void setBalance(double balance) { this.balance = balance; } /** * @return the percentageCharge */ public String getPercentageCharge() { return percentageCharge; } /** * @param percentageCharge the percentageCharge to set */ public void setPercentageCharge(String percentageCharge) { this.percentageCharge = percentageCharge; } }
931e10f8fd173cb7a848140d1f1e988cfefb27f6
[ "Java" ]
8
Java
rchisebu/paease-spring-api
fd26ade93f66152b487ab9c3e24d0b1bce125957
b41d212b8d709437ae236c43ecc481faed6318cd
refs/heads/main
<file_sep># Programa de Cadastro de Produtos Destinado à disciplina de Programação com Banco de Dados. <file_sep>import data import sqlite3 from PyQt5 import uic, QtWidgets #função de cadastro def menuCad(): #controle de tela tela.close() tela_cad.show() def cadastrar(): #conexao com o banco de dados conexao = data.connect() #data.create(conexao) #recebendo informações cod = tela_cad.lineEdit_Cod.text() nome = tela_cad.lineEdit_Nome.text() descricao = tela_cad.lineEdit_Desc.text() quantidade = tela_cad.lineEdit_Quant.text() #inserindo na base data.cadastrar(conexao, cod, nome, descricao, quantidade) #limpando os botões tela_cad.lineEdit_Cod.setText("") tela_cad.lineEdit_Nome.setText("") tela_cad.lineEdit_Desc.setText("") tela_cad.lineEdit_Quant.setText("") limpeza() #confirmando o cadastro através de uma mensagem def cadastrado(): tela_cad.label_Cadastrado.setText("Produto cadastrado com sucesso!") def limpeza(): banco = sqlite3.connect("produto.db") cursor = banco.cursor() cursor.execute(""" delete from produto where nome is NULL or nome = "" """) cursor.execute(""" delete from produto where cod is NULL or cod = "" """) banco.commit() banco.close() def produtos(): tela.close() tela_prod.show() banco = sqlite3.connect("produto.db") cursor = banco.cursor() cursor.execute("select * from produto order by nome;") lidos = cursor.fetchall() #criando a tabela na interface tela_prod.tableWidget.setRowCount(len(lidos)) tela_prod.tableWidget.setColumnCount(4) for i in range(0, len(lidos)): for j in range(0, 4): tela_prod.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(str(lidos[i][j]))) limpeza() def menuBusca(): tela.close() tela_busca.show() def busca_cod(): banco = sqlite3.connect("produto.db") cursor = banco.cursor() cod = tela_busca.lineEdit_Cod.text() cursor.execute("select * from produto where cod = ?", (cod, )) lidos = cursor.fetchall() tela_resultado.tableWidget.setRowCount(len(lidos)) tela_resultado.tableWidget.setColumnCount(4) for i in range(0, len(lidos)): for j in range(0, 4): tela_resultado.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(str(lidos[i][j]))) banco.close() def busca_nome(): banco = sqlite3.connect("produto.db") cursor = banco.cursor() nome = tela_busca.lineEdit_Nome.text() cursor.execute("select * from produto where nome = ?", (nome, )) lidos = cursor.fetchall() tela_resultado.tableWidget.setRowCount(len(lidos)) tela_resultado.tableWidget.setColumnCount(4) for i in range(0, len(lidos)): for j in range(0, 4): tela_resultado.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(str(lidos[i][j]))) banco.close() def resultado(): tela_resultado.show() tela_busca.lineEdit_Nome.setText("") tela_busca.lineEdit_Cod.setText("") def menuExcluir(): tela.close() tela_excluir.show() def excluir_cod(): banco = sqlite3.connect("produto.db") cursor = banco.cursor() cod = tela_excluir.lineEdit_Cod.text() cursor.execute("delete from produto where cod = ?", (cod, )) banco.commit() banco.close() def excluir_nome(): banco = sqlite3.connect("produto.db") cursor = banco.cursor() nome = tela_excluir.lineEdit_Nome.text() cursor.execute("delete from produto where nome = ?", (nome, )) banco.commit() banco.close() def excluido(): tela_excluir.label_Excluido.setText("Produto excluído com sucesso!") tela_excluir.lineEdit_Nome.setText("") tela_excluir.lineEdit_Cod.setText("") #função menu def menu(): #limpando para evitar lixo ao cancelar tela_cad.lineEdit_Cod.setText("") tela_cad.lineEdit_Nome.setText("") tela_cad.lineEdit_Desc.setText("") tela_cad.lineEdit_Quant.setText("") tela_busca.lineEdit_Nome.setText("") tela_busca.lineEdit_Cod.setText("") tela_excluir.lineEdit_Nome.setText("") tela_excluir.lineEdit_Cod.setText("") #fechando as telas que podem estar abertas tela_cad.close() tela_prod.close() tela_busca.close() tela_resultado.close() tela_excluir.close() #abrindo a tela principal tela.show() #excluindo dados vazios do banco limpeza() app = QtWidgets.QApplication([]) tela = uic.loadUi("menu.ui") tela_cad = uic.loadUi("cadastrar.ui") tela_prod = uic.loadUi("produtos.ui") tela_busca = uic.loadUi("busca.ui") tela_resultado = uic.loadUi("resultado.ui") tela_excluir = uic.loadUi("excluir.ui") #botões #tela menu tela.pushButton_MCad.clicked.connect(menuCad) tela.pushButton_MPro.clicked.connect(produtos) tela.pushButton_MBus.clicked.connect(menuBusca) tela.pushButton_MExc.clicked.connect(menuExcluir) #tela cadastro tela_cad.pushButton_Cadastrar.clicked.connect(cadastrar) tela_cad.pushButton_Cadastrar.clicked.connect(cadastrado) tela_cad.pushButton_Cancelar.clicked.connect(menu) #tela produtos tela_prod.pushButton_Cancelar.clicked.connect(menu) #tela busca tela_busca.pushButton_ProCod.clicked.connect(busca_cod) tela_busca.pushButton_ProCod.clicked.connect(resultado) tela_busca.pushButton_ProNome.clicked.connect(busca_nome) tela_busca.pushButton_ProNome.clicked.connect(resultado) tela_busca.pushButton_Cancelar.clicked.connect(menu) tela_resultado.pushButton_Cancelar.clicked.connect(menu) #tela de exclusão tela_excluir.pushButton_ExcCod.clicked.connect(excluir_cod) tela_excluir.pushButton_ExcCod.clicked.connect(excluido) tela_excluir.pushButton_ExcNome.clicked.connect(excluir_nome) tela_excluir.pushButton_ExcNome.clicked.connect(excluido) tela_excluir.pushButton_Cancelar.clicked.connect(menu) tela.show() app.exec()<file_sep>import sqlite3 CREATE_TABLE = "create table produto(cod integer, nome text, descricao text, quantidade integer)" INSERT_PRODUTO = "insert into produto (cod, nome, descricao, quantidade) values (?, ?, ?, ?);" BUSCA_PRODUTO_POR_NOME = "select * from produto where nome = ?;" def connect(): return sqlite3.connect("produto.db") #função cria tabela def create(conexao): with conexao: conexao.execute(CREATE_TABLE) #função inserir def cadastrar(conexao, cod, nome, descricao, quantidade): with conexao: conexao.execute(INSERT_PRODUTO,( cod, nome, descricao, quantidade)) #função busca por nome def busca_nome(conexao, nome): with conexao: return conexao.execute(BUSCA_PRODUTO_POR_NOME, (nome, )).fetchall()
bb903f649c3543ae62b366ad0182d51a4f1e67f8
[ "Markdown", "Python" ]
3
Markdown
italomsiqueira/pythoncomdb
4ef751fe6ff0abf1288e611bdf59a581c6e3c392
20a09a06cba8f2eb66021791e4da2710d48c9e89
refs/heads/master
<file_sep>package Basic; import java.util.Random; public class Neuron { private int layer; private int position; private double[] x; private double[] w; private double u; private double y; private byte func; // 1-sigmoidal private int in; private double beta; public Neuron(int layer,int pos,int in,byte func,double beta){ this.layer=layer; this.position=pos; this.func=func; this.beta=beta; this.u=0.00; this.y=0.00; this.setIn(in); this.w = new double[in+1]; this.x = new double[in+1]; initW(); } public int getLayer() { return layer; } public void setLayer(int layer) { this.layer = layer; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public double getX(int i) { return x[i]; } public void setX(double x,int i) { if(i>0 && i<=this.in){ this.x[i] = x; } } public double getW(int i) { return w[i]; } public void setW(double w,int i) { this.w[i] = w; } public double getY() { return y; } private void initW(){ Random generator = new Random(); this.x[0]=1; this.w[0]=-0.5; for(int i =1;i<this.in;i++){ this.w[i]=generator.nextDouble()*2-1; } } public int getIn() { return in; } public void setIn(int in) { this.in = in; } private double f(double x){ switch(this.func){ case 1 : return 1/(1+(Math.pow(Math.E,(-this.beta*x)))); default : return 0.00; } } public double d(double x){ switch(this.func){ case 1 : double f =f(x); return this.beta*(1-f)*f; default: return 0.00; } } private void sum(){ for(int i=0;i<this.in;i++){ this.u = this.u+(this.w[i]*this.x[i]); } } public void calculate(){ sum(); this.y= f(this.u); } }
3ec9eefc675621f896383394274228d1ca718b8e
[ "Java" ]
1
Java
lestath/Brain
76e3d0618604c7f9e089ae12309491c1d723f240
b870bc74de81ae5537b14cfd88d65ff1fa4d329e
refs/heads/main
<file_sep>// // ViewController.swift // SlideshowApp // // Created by koux2 on 2021/03/21. // import UIKit class ViewController: UIViewController { var timer: Timer! var imageNumber: Int! var imageList: [UIImage?]! @IBOutlet weak var image: UIButton! @IBOutlet weak var pauseButton: UIButton! @IBOutlet weak var prevButton: UIButton! @IBOutlet weak var fowardButton: UIButton! override func viewDidLoad() { super.viewDidLoad() imageList = [ UIImage(named:"image1"), UIImage(named:"image2"), UIImage(named:"image3"), UIImage(named:"image4"), UIImage(named:"image5"), UIImage(named:"image6") ] imageNumber = 0 showImage() image.imageView?.contentMode = .scaleAspectFit } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) pause() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let detailViewController = segue.destination as! DetailViewController detailViewController.image = image.image(for: .normal) } @IBAction func unwind(_ segue: UIStoryboardSegue) { } @IBAction func back(_ sender: Any) { prevImage() } @IBAction func foward(_ sender: Any) { nextImage() } @IBAction func pause(_ sender: Any) { pause() } func pause() { if timer == nil { setTimer() } else { timer.invalidate() timer = nil } setPauseTitile() setButtonEnable() } @objc func nextImageByTimer(_ timer: Timer) { nextImage() setTimer() } func nextImage() { imageNumber += 1 if imageNumber >= imageList.count { imageNumber = 0 } showImage() } func prevImage() { imageNumber -= 1 if imageNumber < 0 { imageNumber = imageList.count - 1 } showImage() } func showImage() { image.setImage(imageList[imageNumber], for: .normal) } func setTimer() { if timer != nil { timer.invalidate() } timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(nextImageByTimer(_:)), userInfo: nil, repeats: false) } func setPauseTitile() { let title = timer == nil ? "再生" : "停止" pauseButton.setTitle(title, for: .normal) } func setButtonEnable() { if timer != nil { prevButton.isEnabled = false fowardButton.isEnabled = false } else { prevButton.isEnabled = true fowardButton.isEnabled = true } } }
f523ea4ccbda73273ddf9621fc70ccffc83d50bc
[ "Swift" ]
1
Swift
koux2/TechacademyLesson5App
185fe5e49684028d1a9afe1ddeeb181e6bb9d8ae
1ff33c7204cbd660e0881096a9e1fb2a0eb11b0a
refs/heads/master
<repo_name>cbeserra/fsw-105<file_sep>/Week1/grocery-storeJS/index.js var shopper = { name: "Chris", wallet: 50, hasMoney: true, buy: function() { return this.name + "is buying something", }, groceryCart: ["milk","eggs","bacon", "tortillas"], console.log(shopper.buy())<file_sep>/Week3/loops_and_arrays/extracredit.js var lights = false; //var switches = [2, 5, 435, 4, 3]; // Light is On //var switches = [1, 1, 1, 1, 3]; // Light is on var toggles = [9, 3, 4, 2]; //Light is off for( var i = 0; i < toggles.length; i++ ) { for( var j = 0; j < toggles[i]; j++) { lights = !lights; } } if( lights ) { console.log("The lights are ON!"); } else { console.log("The lights are OFF!"); } <file_sep>/Week4/string&array_methods/arrayMethod.js var fruit = ["banana", "apple", "orange", "watermelon"]; var vegetables = ["carrot", "tomato", "pepper", "lettuce"]; vegetables.pop(); fruit.shift(); var basket = fruit.indexOf("orange"); fruit.push(basket); var vegLength = vegetables.length; vegetables.push(vegLength); food = fruit.concat(vegetables); let removed = food.splice(4, 2); const reversed = food.reverse(); console.log(food.toString());<file_sep>/Week4/string&array_methods/getting started.js function capitalizeAndLowercase(str){ var upperLower = str.toUpperCase() + str.toLowerCase(); return"Upper and Lower Case String is: " + upperLower; } console.log(capitalizeAndLowercase("Hello")); console.log("============"); function findMiddleIndex(str){ var middleOfString = Math.floor(str.length /2); return "Rounded down String's half is: " + middleOfString; } console.log(findMiddleIndex("Hello")); console.log(findMiddleIndex("Hello World")); console.log("==========="); function returnFirstHalf(str){ var middleOfWord = (str.length /2); return "Return the String's first half is: " + str.slice(0, middleOfWord); } console.log(returnFirstHalf("Hello")); console.log(returnFirstHalf("Hello World")); console.log("===========") function firstHalfCapSecondLower(str) { var midWord = (str.length / 2); var firstHalf = str.slice(0, midWord) var secHalf = str.slice(midWord) var result = firstHalf.toUpperCase() + secHalf.toLowerCase() return "Word split in half and first half upperscase is: " + result } console.log(firstHalfCapSecondLower("Hello")); console.log(firstHalfCapSecondLower("Hello World"));
f7702d910d73cdf0ca04a285272b4bf41e368519
[ "JavaScript" ]
4
JavaScript
cbeserra/fsw-105
a97576ecbee080ba0258c2ae4e84917f06e5d7dc
ab321bb1a73801101bd97ed47c88a8796f3c73c8
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class checkout : System.Web.UI.Page { //Uses smoothiename to get the smoothie image, and displays the quantity in the 2nd table data. private String smoothieRow(string smoothieName, int smoothieQuantitiy) { if (smoothieQuantitiy != 0) { String row = "<tr>" + "<td><img src=\"Smoothieimages/" + smoothieName +".jpg\" width=\"115\" height=\"140\"></td>" + "<td>" + smoothieQuantitiy.ToString() + "</td>" + "<td>18</td>" + "</tr>"; return row; } else { return ""; } } //Returns smoothie quantity. If the cookie value is null, then it returns 0. Helps to prevent crashes. private int smoothieQuantity(String cookieValue) { if (cookieValue != null) { return int.Parse(cookieValue); } else { return 0; } } protected void Page_Load(object sender, EventArgs e) { //If cookie does not exist, then redirect the user back to the homepage. if (Request.Cookies["drinkCookie"] == null) { Response.Redirect("Default.aspx"); } //read the values from the cookie HttpCookie drinkCookie = Request.Cookies["drinkCookie"]; int smoothie1 = smoothieQuantity(drinkCookie.Values["smoothie1"]); int smoothie2 = smoothieQuantity(drinkCookie.Values["smoothie2"]); int smoothie3 = smoothieQuantity(drinkCookie.Values["smoothie3"]); //If the user has not purchase any smoothie, then redirect him back to the homepage. if (smoothie1 == 0 && smoothie2 == 0 && smoothie3 == 0) { Response.Redirect("Default.aspx"); } //Calculates the total price. double totalPrice = (smoothie1 + smoothie2 + smoothie3) * 18; //Creates a table. String table = "<table style=\"width:100%\">" + "<tr>" + //Header row "<td><strong>Flavor</strong></td>" + "<td><strong>Quantitiy</strong></td>" + "<td><strong>Price</strong></td>" + "</tr>"; //Populates the table with smoothie rows if quantity is more than 0. table += smoothieRow("smoothie1", smoothie1); table += smoothieRow("smoothie2", smoothie2); table += smoothieRow("smoothie3", smoothie3); table += "<tr>" + "<td>Total</td>" + "<td></td>" + //Left empty intentionally. "<td>" + totalPrice + " AED</td>" + "</tr>"; //Closes the table tag. table += "</table>"; //Applies table. Label1.Text = table; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.Cookies["drinkCookie"] == null) { HttpCookie drinkCookie = new HttpCookie("drinkCookie"); drinkCookie.Expires = DateTime.Today.AddDays(3); Response.Cookies.Add(drinkCookie); } } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("checkout.aspx"); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class add : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // read the value of the query string passed from the home page String id = Request.QueryString["id"]; //save it into the cookie if (Request.Cookies["drinkCookie"] != null) { //Get cookie object. HttpCookie drinkCookie = Request.Cookies["drinkCookie"]; //Read value from cookie, if no value exists, then set initial value as 0. int smoothie1 = 0; int smoothie2 = 0; int smoothie3 = 0; //If the cookie value is not empty, then get the current value from the cookie. if (drinkCookie.Values["smoothie1"] != null) { smoothie1 = int.Parse(drinkCookie.Values["smoothie1"]); } if (drinkCookie.Values["smoothie2"] != null) { smoothie2 = int.Parse(drinkCookie.Values["smoothie2"]); } if (drinkCookie.Values["smoothie3"] != null) { smoothie3 = int.Parse(drinkCookie.Values["smoothie3"]); } //Increase the quantity based on the id. if (id == "1") { smoothie1++; } if (id == "2") { smoothie2++; } if (id == "3") { smoothie3++; } //Add to cookie values drinkCookie.Values["smoothie1"] = smoothie1.ToString(); drinkCookie.Values["smoothie2"] = smoothie2.ToString(); drinkCookie.Values["smoothie3"] = smoothie3.ToString(); //Confirm changes to cookie object. Response.Cookies.Add(drinkCookie); } //After saving the value in the cookie, the user should be redirected to the home page. Response.Redirect("Default.aspx"); } }
07e218bdbceec50c7082cc37ff4f6d0ede750d5c
[ "C#" ]
3
C#
overwatcheddude/cia4103_week4_state_management_revision
4deb6bd58eb36f6a34d27a7753f33e964af66f3c
67e3b13b958ebb810e10354ccdea4a47d42e2dec
refs/heads/master
<repo_name>shmchen/myJdbc-Demo<file_sep>/day06/src/com/shmchen/dao/impl/IStudentDaoImpl.java package com.shmchen.dao.impl; import java.util.List; import com.shmchen.dao.IResultSetHandle; import com.shmchen.dao.IStudentDao; import com.shmchen.domain.Student; import com.shmchen.jdbc.TemplateUtil; public class IStudentDaoImpl implements IStudentDao { @Override public void save(Student student) { String sql = "INSERT INTO t_student(`name`, age) VALUES(?, ?)"; TemplateUtil.excuteUpdate(sql, student.getName(), student.getAge()); } @Override public void delete(int id) { String sql = "DELETE FROM t_student WHERE id = ?"; TemplateUtil.excuteUpdate(sql, id); } @Override public void edit(Student student) { String sql = "UPDATE t_student SET `name` = ?, age = ? WHERE id = ?"; TemplateUtil.excuteUpdate(sql, student.getName(), student.getAge(), student.getId()); } @Override public Student get(int id) { String sql = "SELECT * FROM t_student WHERE id = ?"; IResultSetHandle<Student> handle = new StudentResultSetHandle<Student>(Student.class); List<Student> res = TemplateUtil.excuteQuery(handle, sql, id); return res != null ? res.get(0) : null; } @Override public List<Student> getAll() { String sql = "SELECT * FROM t_student"; IResultSetHandle<Student> handle = new StudentResultSetHandle<Student>(Student.class); List<Student> res = TemplateUtil.excuteQuery(handle, sql); return res != null ? res : null; } } <file_sep>/README.md Java JDBC操作数据库 数据库连接池使用阿里druid 做学生信息的增删改查 ![image](home.png) <file_sep>/day06/src/com/shmchen/server/StudentServlet.java package com.shmchen.server; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.shmchen.dao.IStudentDao; import com.shmchen.dao.impl.IStudentDaoImpl; import com.shmchen.domain.Student; @WebServlet("/student") public class StudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; IStudentDao dao = new IStudentDaoImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); // 获取操作指令 String cmd = req.getParameter("cmd"); if ("save".equals(cmd)) { saveOrUpdate(req, resp); }else if ("delete".equals(cmd)) { delete(req, resp); }else if ("edit".equals(cmd)) { this.edit(req, resp); }else { list(req, resp); } } private void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String stuID = req.getParameter("id"); if (stuID != null) { // 更新操作 int id = Integer.parseInt(stuID); String name = req.getParameter("name"); int age = Integer.parseInt(req.getParameter("age")); Student student = new Student(id, name, age); dao.edit(student); }else { // 新增操作 String name = req.getParameter("name"); int age = Integer.parseInt(req.getParameter("age")); Student student = new Student(name, age); dao.save(student); } resp.sendRedirect(getServletContext().getContextPath() + "/student"); } private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); Student student = dao.get(Integer.parseInt(id)); req.setAttribute("student", student); req.getRequestDispatcher("/views/edit.jsp").forward(req, resp); } private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = Integer.parseInt(req.getParameter("id")); dao.delete(id); resp.sendRedirect(getServletContext().getContextPath() + "/student"); } private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Student> all = dao.getAll(); req.setAttribute("list", all); req.getRequestDispatcher("/views/list.jsp").forward(req, resp); } }
98997dccdfdb1719640f9d1cc598b348b591a6a1
[ "Markdown", "Java" ]
3
Java
shmchen/myJdbc-Demo
46b5fa8571624dec8f45a7ff74cc531086b3285f
49288b498ddac781a1e1116220d8b56727aa018b
refs/heads/master
<repo_name>mspoonam/themoviedb<file_sep>/themoviedb/connection/MovieItemEntity.swift // // MovieItemEntity.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SwiftyJSON public class MovieItemEntity: NSObject, JSONInitializable { // MARK: - Properties let id: Int let posterPathString: String? let adult: Bool let overview: String let releaseDate: Date let genreIds: [Int] let originalTitle: String let originalLanguage: String let title: String let backdropPathString: String? let popularity: Double let voteCount: Int let video: Bool let voteAverage: Double let favourite: Bool // MARK: - Computed properties var fullTitle: String { return self.title } var posterPath: ImgPath? { guard let posterPathString = self.posterPathString else { return nil } return ImgPath.poster(path: posterPathString) } var backdropPath: ImgPath? { guard let backdropPathString = self.backdropPathString else { return nil } return ImgPath.backdrop(path: backdropPathString) } // MARK: - JSONInitializable initializer public required init(json: JSON) { self.id = json["id"].intValue self.posterPathString = json["poster_path"].string self.adult = json["adult"].boolValue self.overview = json["overview"].stringValue self.releaseDate = json["release_date"].dateValue self.genreIds = json["genre_ids"].arrayValue.flatMap({ $0.int }) self.originalTitle = json["original_title"].stringValue self.originalLanguage = json["original_language"].stringValue self.title = json["title"].stringValue self.backdropPathString = json["backdrop_path"].string self.popularity = json["popularity"].doubleValue self.voteCount = json["popularity"].intValue self.video = json["video"].boolValue self.voteAverage = json["vote_average"].doubleValue self.favourite = false super.init() } } // MARK: - extension MovieItemEntity { // MARK: - Description public override var description: String { let dateString: String = DtHandler.SharedFormatter.string(from: self.releaseDate) return "\(self.originalTitle) (\(dateString))" } public override var debugDescription: String { return self.description } } // MARK: - extension Array where Element: MovieItemEntity { var withoutDuplicates: [MovieItemEntity] { var exists: [Int: Bool] = [:] return self.filter { exists.updateValue(true, forKey: $0.id) == nil } } } <file_sep>/themoviedb/connection/ApiHelper.swift // // ApiHelper.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import Alamofire import RxSwift import SwiftyJSON public final class ApiHelper { // MARK: - singleton static let instance: ApiHelper = ApiHelper() // MARK: - Properties fileprivate let disposeBag: DisposeBag = DisposeBag() fileprivate(set) var imgHandler: ImageHandler? = nil // MARK: - Initializer (private) fileprivate init() {} // MARK: - public func start() { // Start updating the API configuration (Every four days) // FIXME: - Improve this by performing background fetch let days: RxTimeInterval = 4.0 * 60.0 * 60.0 * 24.0 Observable<Int> .timer(0, period: days, scheduler: MainScheduler.instance) .flatMap { (_) -> Observable<ApiJson> in return self.configuration() }.map { (apiConfiguration) -> ImageHandler in return ImageHandler(apiData: apiConfiguration) }.subscribe(onNext: { (imgHandler) in self.imgHandler = imgHandler }).addDisposableTo(self.disposeBag) } // MARK: - Configuration fileprivate func configuration() -> Observable<ApiJson> { return Observable.create { (observer) -> Disposable in let request = Alamofire .request(Router.configuration) .validate() .responseJSON { (response) in switch response.result { case .success(let data): let apiConfiguration = ApiJson(json: JSON(data)) observer.onNext(apiConfiguration) observer.onCompleted() case .failure(let error): observer.onError(error) } } return Disposables.create { request.cancel() } } } // MARK: - Search films public func films(withTitle title: String, startingAtPage page: Int = 0, loadNextPageTrigger trigger: Observable<Void> = Observable.empty()) -> Observable<[MovieItemEntity]> { let parameters: FilmSearchParameters = FilmSearchParameters(query: title, atPage: page) return ApiHelper.instance.films(fromList: [], with: parameters, loadNextPageTrigger: trigger) } fileprivate func films(fromList currentList: [MovieItemEntity], with parameters: FilmSearchParameters, loadNextPageTrigger trigger: Observable<Void>) -> Observable<[MovieItemEntity]> { return self.films(with: parameters).flatMap { (Paginator) -> Observable<[MovieItemEntity]> in let newList = currentList + Paginator.results if let _ = Paginator.nextPage { return Observable.concat([ Observable.just(newList), Observable.never().takeUntil(trigger), self.films(fromList: newList, with: parameters.nextPage, loadNextPageTrigger: trigger) ]) } else { return Observable.just(newList) } } } fileprivate func films(with parameters: FilmSearchParameters) -> Observable<Paginator<MovieItemEntity>> { guard !parameters.query.isEmpty else { return Observable.just(Paginator.Empty()) } return Observable<Paginator<MovieItemEntity>>.create { (observer) -> Disposable in let request = Alamofire .request(Router.searchFilms(parameters: parameters)) .validate() .responsePaginatedFilms(queue: nil, completionHandler: { (response) in switch response.result { case .success(let Paginator): observer.onNext(Paginator) observer.onCompleted() case .failure(let error): observer.onError(error) } }) return Disposables.create { request.cancel() } } } // MARK: - Popular films public func popularFilms(startingAtPage page: Int = 0, loadNextPageTrigger trigger: Observable<Void> = Observable.empty()) -> Observable<[MovieItemEntity]> { return ApiHelper.instance.popularFilms(fromList: [], atPage: page, loadNextPageTrigger: trigger) } fileprivate func popularFilms(fromList currentList: [MovieItemEntity], atPage page: Int, loadNextPageTrigger trigger: Observable<Void>) -> Observable<[MovieItemEntity]> { return self.popularFilms(atPage: page).flatMap { (Paginator) -> Observable<[MovieItemEntity]> in let newList = currentList + Paginator.results if let nextPage = Paginator.nextPage { return Observable.concat([ Observable.just(newList), Observable.never().takeUntil(trigger), self.popularFilms(fromList: newList, atPage: nextPage, loadNextPageTrigger: trigger) ]) } else { return Observable.just(newList) } } } fileprivate func popularFilms(atPage page: Int = 0) -> Observable<Paginator<MovieItemEntity>> { return Observable<Paginator<MovieItemEntity>>.create { (observer) -> Disposable in let request = Alamofire .request(Router.popularFilms(page: page)) .validate() .responsePaginatedFilms(queue: nil, completionHandler: { (response) in switch response.result { case .success(let Paginator): observer.onNext(Paginator) observer.onCompleted() case .failure(let error): observer.onError(error) } }) return Disposables.create { request.cancel() } } } // MARK: - Film detail public func filmDetail(fromId filmId: Int) -> Observable<MovieDetailItemEntity> { return Observable<MovieDetailItemEntity>.create { (observer) -> Disposable in let request = Alamofire .request(Router.filmDetail(filmId: filmId)) .validate() .responseFilmDetail { (response) in switch response.result { case .success(let filmDetail): observer.onNext(filmDetail) observer.onCompleted() case .failure(let error): observer.onError(error) } } return Disposables.create { request.cancel() } } } // // MARK: - Person // // public func person(forId id: Int) -> Observable<PersonDetail> { // return Observable<PersonDetail>.create { (observer) -> Disposable in // let request = Alamofire // .request(Router.person(id: id)) // .validate() // .responsePersonDetail { (response) in // switch response.result { // case .success(let personDetail): // observer.onNext(personDetail) // observer.onCompleted() // case .failure(let error): // observer.onError(error) // } // } // return Disposables.create { request.cancel() } // } // } // // public func filmsCredited(forPersonId id: Int) -> Observable<FilmsCredited> { // return Observable<FilmsCredited>.create { (observer) -> Disposable in // let request = Alamofire // .request(Router.personCredits(id: id)) // .validate() // .responseCreditedFilms { (response) in // switch response.result { // case .success(let creditedFilms): // observer.onNext(creditedFilms) // observer.onCompleted() // case .failure(let error): // observer.onError(error) // } // } // return Disposables.create { request.cancel() } // } // } } // MARK: - extension Alamofire.DataRequest { // MARK: - Films response serializer static func filmsResponseSerializer() -> DataResponseSerializer<[MovieItemEntity]> { return DataResponseSerializer { (request, response, data, error) in if let error = error { return .failure(error) } else { guard let data = data else { return .success([]) } let jsonArray = JSON(data: data)["results"].arrayValue return .success(jsonArray.map({ MovieItemEntity(json: $0) })) } } } @discardableResult func responseFilms(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<[MovieItemEntity]>) -> Void) -> Self { return response(queue: queue, responseSerializer: DataRequest.filmsResponseSerializer(), completionHandler: completionHandler) } // MARK: - Paginated list of films response serializer static func paginatedFilmsResponseSerializer() -> DataResponseSerializer<Paginator<MovieItemEntity>> { return DataResponseSerializer { (request, response, data, error) in if let error = error { return .failure(error) } else { guard let data = data else { return .success(Paginator.Empty()) } let json = JSON(data: data) guard let page = json["page"].int, let totalResults = json["total_results"].int, let totalPages = json["total_pages"].int else { return .success(Paginator.Empty()) } let films = json["results"].arrayValue.map({ MovieItemEntity(json: $0) }) let paginator = Paginator(page: page - 1, totalResults: totalResults, totalPages: totalPages, results: films) return .success(paginator) } } } @discardableResult func responsePaginatedFilms(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Paginator<MovieItemEntity>>) -> Void) -> Self { return response(queue: queue, responseSerializer: DataRequest.paginatedFilmsResponseSerializer(), completionHandler: completionHandler) } // MARK: - Film detail response serializer static func filmDetailResponseSerializer() -> DataResponseSerializer<MovieDetailItemEntity> { return DataResponseSerializer { (request, response, data, error) in if let error = error { return .failure(error) } else { guard let data = data else { return .failure(DataError.noData) } let json = JSON(data: data) let filmDetail = MovieDetailItemEntity(json: json) return .success(filmDetail) } } } @discardableResult func responseFilmDetail(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<MovieDetailItemEntity>) -> Void) -> Self { return response(queue: queue, responseSerializer: DataRequest.filmDetailResponseSerializer(), completionHandler: completionHandler) } } <file_sep>/themoviedb/connection/MovieDetailItemEntity.swift // // MovieDetailItemEntity.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SwiftyJSON public final class MovieDetailItemEntity: MovieItemEntity { // MARK: - Properties let homepage: URL? let detailId: Int? let filmOverview: String? let runtime: Int? // MARK: - JSONInitializable initializer public required init(json: JSON) { self.homepage = json["homepage"].URL self.detailId = json["imdb_id"].int self.filmOverview = json["overview"].string self.runtime = json["runtime"].int super.init(json: json) } } <file_sep>/themoviedb/connection/PopularModel.swift // // PopularModel.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import RxSwift import RxCocoa import Alamofire import SwiftyJSON final class PopularModel: NSObject { // MARK: - Properties let disposaBag: DisposeBag = DisposeBag() // Input let reloadTrigger: PublishSubject<Void> = PublishSubject() let nextPageTrigger: PublishSubject<Void> = PublishSubject() // Output lazy private(set) var films: Observable<[MovieItemEntity]> = self.setupFilms() // MARK: - Reactive Setup fileprivate func setupFilms() -> Observable<[MovieItemEntity]> { let trigger = self.nextPageTrigger.asObservable().debounce(0.2, scheduler: MainScheduler.instance) return self.reloadTrigger .asObservable() .debounce(0.3, scheduler: MainScheduler.instance) .flatMapLatest { (_) -> Observable<[MovieItemEntity]> in return ApiHelper.instance.popularFilms(startingAtPage: 0, loadNextPageTrigger: trigger) } .shareReplay(1) } } <file_sep>/themoviedb/DetailedViewController.swift // // DetailedViewController.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import RxSwift import RxCocoa import SDWebImage import CoreData // MARK: - public final class DetailedViewController: UIViewController, ReactiveDisposable { // MARK: - Properties let disposeBag: DisposeBag = DisposeBag() var viewModel: PopularDetailModel? var backgroundImagePath: Observable<ImgPath?> = Observable.empty() // MARK: - IBOutlet properties @IBOutlet weak var markFav: UIView! @IBOutlet weak var blurredImageView: UIImageView! @IBOutlet weak var fakeNavigationBar: UIView! @IBOutlet weak var fakeNavigationBarHeight: NSLayoutConstraint! @IBOutlet weak var backdropImageView: UIImageView! @IBOutlet weak var backdropImageViewHeight: NSLayoutConstraint! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var scrollContentView: UIView! @IBOutlet weak var filmTitleLabel: UILabel! @IBOutlet weak var filmOverviewLabel: UILabel! @IBOutlet weak var filmSubDetailsView: UIView! @IBOutlet weak var filmRuntimeImageView: UIImageView! @IBOutlet weak var filmRuntimeLabel: UILabel! @IBOutlet weak var filmRatingImageView: UIImageView! @IBOutlet weak var filmRatingLabel: UILabel! // MARK: - UIViewController life cycle override public func viewDidLoad() { super.viewDidLoad() self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) self.setupUI() if let viewModel = self.viewModel { self.setupBindings(forViewModel: viewModel) } } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.fakeNavigationBarHeight.constant = 89 // Adjust scrollview insets based on film title let height: CGFloat = self.view.bounds.width / ImgSize.backdropRatio self.scrollView.contentInset = UIEdgeInsets(top: height, left: 0, bottom: 0, right: 0) self.scrollView.scrollIndicatorInsets = UIEdgeInsets(top: height, left: 0, bottom: 0, right: 0) } // MARK: - UI Setup fileprivate func setupUI() { self.fakeNavigationBar.backgroundColor = UIColor(commonColor: .offBlack).withAlphaComponent(0.2) self.filmTitleLabel.apply(style: .filmDetailTitle) self.filmSubDetailsView.alpha = 0.0 self.filmSubDetailsView.backgroundColor = UIColor(commonColor: .offBlack).withAlphaComponent(0.2) self.filmRuntimeImageView.tintColor = UIColor(commonColor: .lightY) self.filmRuntimeLabel.apply(style: .filmRating) self.filmRatingLabel.apply(style: .filmRating) self.filmOverviewLabel.apply(style: .body) } fileprivate func setupCollectionViews() { } fileprivate func updateBackdropImageViewHeight(forScrollOffset offset: CGPoint?) { if let height = offset?.y { self.backdropImageViewHeight.constant = max(0.0, -height) } else { let height: CGFloat = self.view.bounds.width / ImgSize.backdropRatio self.backdropImageViewHeight.constant = max(0.0, height) } } // MARK: - Populate fileprivate func populate(forFilmDetail filmDetail: MovieDetailItemEntity) { UIView.animate(withDuration: 0.2) { self.filmSubDetailsView.alpha = 1.0 } self.filmRuntimeLabel.text = "Rating - \(filmDetail.voteAverage)/10" self.blurredImageView.contentMode = .scaleAspectFill if let backdropPath = filmDetail.backdropPath { if let posterPath = filmDetail.posterPath { self.blurredImageView.setImage(fromDBPath: posterPath, withSize: .medium) } self.backdropImageView.contentMode = .scaleAspectFill self.backdropImageView.setImage(fromDBPath: backdropPath, withSize: .medium, animatedOnce: true) self.backdropImageView.backgroundColor = UIColor.clear } else if let posterPath = filmDetail.posterPath { self.blurredImageView.setImage(fromDBPath: posterPath, withSize: .medium) self.backdropImageView.contentMode = .scaleAspectFill self.backdropImageView.setImage(fromDBPath: posterPath, withSize: .medium) self.backdropImageView.backgroundColor = UIColor.clear } else { self.blurredImageView.image = nil self.backdropImageView.contentMode = .scaleAspectFit self.backdropImageView.image = #imageLiteral(resourceName: "Logo_Icon") self.backdropImageView.backgroundColor = UIColor.groupTableViewBackground } self.filmTitleLabel.text = filmDetail.fullTitle.uppercased() self.filmOverviewLabel.text = filmDetail.overview } public func prePopulate(forFilm film: MovieItemEntity) { if let posterPath = film.posterPath { self.blurredImageView.setImage(fromDBPath: posterPath, withSize: .medium, animatedOnce: true) } self.filmTitleLabel.text = film.fullTitle.uppercased() self.filmOverviewLabel.text = film.overview } // MARK: - Reactive setup fileprivate func setupBindings(forViewModel viewModel: PopularDetailModel) { viewModel .filmDetail .subscribe(onNext: { [weak self] (filmDetail) in self?.populate(forFilmDetail: filmDetail) }).addDisposableTo(self.disposeBag) self.backgroundImagePath = viewModel.filmDetail.map { (filmDetail) -> ImgPath? in return filmDetail.posterPath ?? filmDetail.backdropPath } self.scrollView.rx.contentOffset.subscribe { [weak self] (contentOffset) in self?.updateBackdropImageViewHeight(forScrollOffset: contentOffset.element) }.addDisposableTo(self.disposeBag) self.unMarkFavourite() if self.fetchIdAndCheck(id: viewModel.filmId) { self.markFavourite() } let gestureFavourite = UITapGestureRecognizer() gestureFavourite.rx.event.bindNext{ recognizer in self.save(id: viewModel.filmId) }.addDisposableTo(self.disposeBag) self.markFav.addGestureRecognizer(gestureFavourite) } override public func prepare(for segue: UIStoryboardSegue, sender: Any?) { } func save(id:Int) { guard self.filmRatingImageView.tag == 0 else { self.unMarkFavourite() self.deleteIt(id: id) return } let idEntity = NSEntityDescription.entity(forEntityName: "PopluarEntity", in: getManagedContext())! let user = NSManagedObject(entity: idEntity, insertInto: getManagedContext()) user.setValue(id, forKeyPath: "filmid") do { try getManagedContext().save() self.markFavourite() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } func fetchIdAndCheck(id: Int)->Bool{ let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "PopluarEntity") do { fetchRequest.predicate = NSPredicate(format: "filmid == %d", id) let fetchedResults = try getManagedContext().fetch(fetchRequest) if fetchedResults.count>0 { print("found PopluarEntity") return true } } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } return false } func deleteIt(id: Int) { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "PopluarEntity") do { fetchRequest.predicate = NSPredicate(format: "filmid == %d", id) let fetchedResults = try getManagedContext().fetch(fetchRequest) if fetchedResults.count>0 { for entity in fetchedResults { getManagedContext().delete(entity) } try getManagedContext().save() } } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } } fileprivate func getManagedContext()->NSManagedObjectContext{ return ((UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext)! } fileprivate func markFavourite(){ self.filmRatingImageView.image = UIImage(named: "marked_stars") self.filmRatingImageView.tag = 1 } fileprivate func unMarkFavourite(){ self.filmRatingImageView.image = UIImage(named: "unmark_stars") self.filmRatingImageView.tag = 0 } } <file_sep>/themoviedb/connection/PopularDetailModel.swift // // PopularDetailModel.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import RxCocoa import RxSwift public final class PopularDetailModel: NSObject { // MARK: - Properties let filmId: Int let filmDetail: Observable<MovieDetailItemEntity> // MARK: - Initializer init(withFilmId id: Int) { self.filmId = id self.filmDetail = Observable .just(()) .flatMapLatest { (_) -> Observable<MovieDetailItemEntity> in return ApiHelper.instance.filmDetail(fromId: id) }.shareReplay(1) super.init() } } <file_sep>/themoviedb/CollectionOfMovies.swift // // CollectionOfMovies.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public class CollectionOfMovies: UIViewController { // MARK: - IBOutlet properties @IBOutlet weak var collectionView: UICollectionView! // MARK: - UIViewController handling public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.collectionViewItemsPerRow = self.itemsPerRow(for: UIScreen.main.bounds.size) } // MARK: - Rotation handling public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) guard self.isViewLoaded else { return } self.collectionViewItemsPerRow = self.itemsPerRow(for: size) self.collectionView.collectionViewLayout.invalidateLayout() } fileprivate func itemsPerRow(for size: CGSize) -> Int { return 1 } // MARK: - UICollectionViewCell layout properties fileprivate var collectionViewItemsPerRow: Int = 2 fileprivate let collectionViewMargin: CGFloat = 15.0 fileprivate let collectionViewItemSizeRatio: CGFloat = ImgSize.posterRatio fileprivate var collectionViewItemWidth: CGFloat { return (self.collectionView.bounds.width - (CGFloat(self.collectionViewItemsPerRow + 1) * self.collectionViewMargin)) / CGFloat(self.collectionViewItemsPerRow) } fileprivate var collectionViewItemHeight: CGFloat { return self.collectionViewItemWidth / self.collectionViewItemSizeRatio } } // MARK: - extension CollectionOfMovies: UICollectionViewDelegateFlowLayout { // MARK: - UICollectionViewDelegateFlowLayout public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.collectionViewItemWidth, height: self.collectionViewItemHeight) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: self.collectionViewMargin, left: self.collectionViewMargin, bottom: self.collectionViewMargin, right: self.collectionViewMargin) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return self.collectionViewMargin } } <file_sep>/themoviedb/ViewController.swift // // ViewController.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import RxSwift import RxCocoa final class ViewController: CollectionOfMovies, ReactiveDisposable { // MARK: - IBOutlet Properties @IBOutlet weak var placeholderView: UIView! fileprivate let refreshControl: UIRefreshControl = UIRefreshControl() // MARK: - Properties fileprivate let popularView: PopularModel = PopularModel() let disposeBag: DisposeBag = DisposeBag() override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.setupUI() self.setupCollectionView() self.setupBindings() self.popularView.reloadTrigger.onNext(()) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } // MARK: - Reactive bindings setup fileprivate func setupBindings() { // Bind refresh control to data reload self.refreshControl.rx .controlEvent(.valueChanged) .filter({ self.refreshControl.isRefreshing }) .bindTo(self.popularView.reloadTrigger) .addDisposableTo(self.disposeBag) // Bind view model films to the table view self.popularView .films .bindTo(self.collectionView.rx.items(cellIdentifier: MovieCell.DefaultReuseIdentifier, cellType: MovieCell.self)) { (row, film, cell) in cell.populate(withPosterPath: film.posterPath, andTitle: film.fullTitle) }.addDisposableTo(self.disposeBag) // Bind view model films to the refresh control self.popularView.films .subscribe { _ in self.refreshControl.endRefreshing() }.addDisposableTo(self.disposeBag) // Bind table view bottom reached event to loading the next page self.collectionView.rx .reachedBottom .bindTo(self.popularView.nextPageTrigger) .addDisposableTo(self.disposeBag) } // MARK: - UI Setup fileprivate func setupUI() { } fileprivate func setupCollectionView() { self.collectionView.registerReusableCell(MovieCell.self) self.collectionView.rx.setDelegate(self).addDisposableTo(self.disposeBag) self.collectionView.addSubview(self.refreshControl) } fileprivate func setupScrollViewViewInset(forBottom bottom: CGFloat, animationDuration duration: Double? = nil) { let inset = UIEdgeInsets(top: 0, left: 0, bottom: bottom, right: 0) if let duration = duration { UIView.animate(withDuration: duration, animations: { self.collectionView.contentInset = inset self.collectionView.scrollIndicatorInsets = inset }) } else { self.collectionView.contentInset = inset self.collectionView.scrollIndicatorInsets = inset } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let filmDetailsViewController = segue.destination as? DetailedViewController, let customSegue = segue as? PushDetailViewSequeHandler, let indexPath = sender as? IndexPath, let cell = self.collectionView.cellForItem(at: indexPath) as? MovieCell { do { let film: MovieItemEntity = try collectionView.rx.model(at: indexPath) self.preparePushTransition(to: filmDetailsViewController, with: film, fromCell: cell, via: customSegue) } catch { fatalError(error.localizedDescription) } } } } extension ViewController: UITableViewDelegate { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.performSegue(withIdentifier: "DetailedViewControllerSeque", sender: indexPath) } } extension ViewController: CellTransitionCustom { public func preparePushTransition(to viewController: DetailedViewController, with film: MovieItemEntity, fromCell cell: MovieCell, via segue: PushDetailViewSequeHandler) { let detailViewModel = PopularDetailModel(withFilmId: film.id) viewController.viewModel = detailViewModel viewController.rx.viewDidLoad.subscribe(onNext: { _ in viewController.prePopulate(forFilm: film) }).addDisposableTo(disposeBag) // Setup the segue for transition segue.startingFrame = cell.convert(cell.bounds, to: self.view) segue.posterImage = cell.filmPosterImageView.image } } <file_sep>/themoviedb/DtHandler.swift // // DtHandler.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit public final class DtHandler: NSObject { // MARK: - Properties static var SharedFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter }() // MARK: - Initializer fileprivate override init() { super.init() } } <file_sep>/themoviedb/MovieCell.swift // // MovieCell.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public final class MovieCell: UICollectionViewCell { // MARK: - IBOutlet properties // @IBOutlet weak var filmTitleLabel: UILabel! @IBOutlet weak var filmPosterImageView: UIImageView! // MARK: - UICollectionViewCell life cycle override public func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor(white: 0.0, alpha: 0.15) // self.filmTitleLabel.font = UIFont.systemFont(ofSize: 12.0) } // MARK: - func populate(withPosterPath posterPath: ImgPath?, andTitle title: String) { // self.filmTitleLabel.text = title self.filmPosterImageView.image = nil if let posterPath = posterPath { self.filmPosterImageView.setImage(fromDBPath: posterPath, withSize: .medium, animatedOnce: true) } } } extension MovieCell: NibLoadableView { } extension MovieCell: ReusableView { } <file_sep>/themoviedb/PushDetailViewSequeHandler.swift // // PushDetailViewSequeHandler.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public protocol CellTransitionCustom: class { func preparePushTransition(to viewController: DetailedViewController, with film: MovieItemEntity, fromCell cell: MovieCell, via segue: PushDetailViewSequeHandler) } // MARK: - public final class PushDetailViewSequeHandler: UIStoryboardSegue { // MARK: - Properties var startingFrame: CGRect = CGRect.zero var posterImage: UIImage? public static var identifier: String { return "DetailedViewControllerSeque" } // MARK: - UIStoryboardSegue public override func perform() { guard let sourceView = self.source.view else { fatalError() } // Create overlaying poster image for animated transition let posterImageView: UIImageView = UIImageView(frame: self.startingFrame) posterImageView.backgroundColor = UIColor.groupTableViewBackground posterImageView.image = self.posterImage let blurView: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) blurView.frame = posterImageView.bounds blurView.alpha = 0.0 blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight] UIApplication.window?.insertSubview(posterImageView, aboveSubview: sourceView) posterImageView.addSubview(blurView) var finalFrame = sourceView.bounds finalFrame.size.height = finalFrame.height - 25 self.source.navigationController?.pushViewController(self.destination, animated: false) UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: .curveLinear, animations: { posterImageView.frame = finalFrame blurView.alpha = 1.0 }, completion: { (_) in }) UIView.animate(withDuration: 0.1, delay: 0.3, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveLinear, animations: { posterImageView.alpha = 0.0 }, completion: { (_) in posterImageView.removeFromSuperview() }) } } <file_sep>/themoviedb/connection/Router.swift // // Router.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import Alamofire // MARK: - OrderingCriteria enum public enum OrderingCriteria { // MARK: - Properties var stringPath: String { switch self { case .ascending: return ".asc" case .descending: return ".desc" } } // MARK: - Cases case ascending case descending } // MARK: - FilmSortingCriteria enum public enum FilmSortingCriterion { // MARK: - Properties var URLParameter: String { switch self { case .popularity(let order): return "popularity" + order.stringPath case .releaseDate(let order): return "release_date" + order.stringPath case .revenue(let order): return "revenue" + order.stringPath case .primaryReleaseDate(let order): return "primary_release_date" + order.stringPath case .originalTitle(let order): return "original_title" + order.stringPath case .voteAverageCount(let order): return "vote_average" + order.stringPath case .voteCount(let order): return "vote_count" + order.stringPath } } // MARK: - Cases case popularity(order: OrderingCriteria) case releaseDate(order: OrderingCriteria) case revenue(order: OrderingCriteria) case primaryReleaseDate(order: OrderingCriteria) case originalTitle(order: OrderingCriteria) case voteAverageCount(order: OrderingCriteria) case voteCount(order: OrderingCriteria) } // MARK: public struct DiscoverParameters { // MARK: - Properties let sortBy: FilmSortingCriterion let page: Int? // MARK: - Initializers init(sortBy sortingCriterion: FilmSortingCriterion, atPage page: Int? = nil) { self.sortBy = sortingCriterion self.page = page } } // MARK: - extension DiscoverParameters: URLParametersListSerializable { // MARK: - URLParametersListSerializable var URLParametersList: ParametersList { var parameters: ParametersList = ParametersList() parameters["sort_by"] = self.sortBy.URLParameter if let page = self.page { parameters["page"] = "\(page + 1)" } return parameters } } // MARK: public struct FilmSearchParameters { // MARK: - Properties let query: String let page: Int? let language: String? let includeAdult: Bool? let year: Int? let primaryReleaseYear: Int? var nextPage: FilmSearchParameters { guard let page = self.page else { return self } return FilmSearchParameters(query: self.query, page: page + 1, language: self.language, includeAdult: self.includeAdult, year: self.year, primaryReleaseYear: self.primaryReleaseYear) } // MARK: - Initializers init(query: String, page: Int?, language: String?, includeAdult: Bool?, year: Int?, primaryReleaseYear: Int?) { self.query = query self.page = page self.language = language self.includeAdult = includeAdult self.year = year self.primaryReleaseYear = primaryReleaseYear } init(query: String) { self.query = query self.page = nil self.language = nil self.includeAdult = nil self.year = nil self.primaryReleaseYear = nil } init(query: String, atPage page: Int) { self.query = query self.page = page self.language = nil self.includeAdult = nil self.year = nil self.primaryReleaseYear = nil } } // MARK: - extension FilmSearchParameters: URLParametersListSerializable { // MARK: - URLParametersListSerializable var URLParametersList: ParametersList { var parameters: ParametersList = Dictionary() parameters["query"] = self.query if let page = self.page { parameters["page"] = "\(page + 1)" } if let language = self.language { parameters["language"] = language } if let includeAdult = self.includeAdult , includeAdult == true { parameters["include_adult"] = "true" } if let year = self.year { parameters["year"] = "\(year)" } if let primaryReleaseYear = self.primaryReleaseYear { parameters["primary_release_year"] = "\(primaryReleaseYear)" } return parameters } } // MARK: - URLRequestConvertible enum public enum Router: URLRequestConvertible { // MARK: - Properties static let BaseURL: URL = URL(string: "https://api.themoviedb.org/3")! static let DBApiKey: String = "b66ffea8276ce576d60df52600822c88" var path: String { switch self { case .configuration: return "/configuration" case .searchFilms(_): return "/search/movie" case .popularFilms(_): return "/movie/popular" case .upcomingFilms(_): return "/movie/upcoming" case .discoverFilms(_): return "/discover/movie" case .filmDetail(let filmId): return "/movie/\(filmId)" case .filmCredits(let filmId): return "/movie/\(filmId)/credits" case .person(let id): return "/person/\(id)" case .personCredits(let id): return "/person/\(id)/movie_credits" } } var httpMethod: Alamofire.HTTPMethod { switch self { case .configuration: return .get case .searchFilms(_): return .get case .popularFilms(_): return .get case .upcomingFilms(_): return .get case .discoverFilms(_): return .get case .filmDetail(_): return .get case .filmCredits(_): return .get case .person(_): return .get case .personCredits(_): return .get } } // MARK: - Cases case configuration case searchFilms(parameters: FilmSearchParameters) case popularFilms(page: Int?) case upcomingFilms(page: Int?) case discoverFilms(parameters: DiscoverParameters) case filmDetail(filmId: Int) case filmCredits(filmId: Int) case person(id: Int) case personCredits(id: Int) // MARK: - URLRequestConvertible overriden properties / functions public func asURLRequest() throws -> URLRequest { let url: URL = Router.BaseURL.appendingPathComponent(self.path) var request: URLRequest = URLRequest(url: url) request.httpMethod = self.httpMethod.rawValue let finalRequest: URLRequest = try { switch self { case .configuration: var urlParameters = ParametersList() urlParameters["api_key"] = Router.DBApiKey return try URLEncoding.queryString.encode(request, with: urlParameters) case .searchFilms(let parameters): var urlParameters = parameters.URLParametersList urlParameters["api_key"] = Router.DBApiKey return try URLEncoding.queryString.encode(request, with: urlParameters) case .popularFilms(let page): var urlParameters = ParametersList() urlParameters["api_key"] = Router.DBApiKey if let page = page { urlParameters["page"] = "\(page + 1)" } return try URLEncoding.queryString.encode(request, with: urlParameters) case .upcomingFilms(let page): var urlParameters = ParametersList() urlParameters["api_key"] = Router.DBApiKey if let page = page { urlParameters["page"] = "\(page + 1)" } return try URLEncoding.queryString.encode(request, with: urlParameters) case .discoverFilms(let parameters): var urlParameters = parameters.URLParametersList urlParameters["api_key"] = Router.DBApiKey return try URLEncoding.queryString.encode(request, with: urlParameters) case .filmDetail(_): var urlParameters = ParametersList() urlParameters["api_key"] = Router.DBApiKey urlParameters["append_to_response"] = "videos" return try URLEncoding.queryString.encode(request, with: urlParameters) case .filmCredits(_): var urlParameters = ParametersList() urlParameters["api_key"] = Router.DBApiKey return try URLEncoding.queryString.encode(request, with: urlParameters) case .person(_): var urlParameters = ParametersList() urlParameters["api_key"] = Router.DBApiKey urlParameters["append_to_response"] = "images" return try URLEncoding.queryString.encode(request, with: urlParameters) case .personCredits(_): var urlParameters = ParametersList() urlParameters["api_key"] = Router.DBApiKey return try URLEncoding.queryString.encode(request, with: urlParameters) } }() return finalRequest } } <file_sep>/themoviedb/ImageHandler.swift // // ImageHandler.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SwiftyJSON public enum ImgSize { case small case medium case big case original static var posterRatio: CGFloat = (2.0 / 3.0) static var backdropRatio: CGFloat = (300.0 / 169.0) } public enum ImgPath { case backdrop(path: String) case logo(path: String) case poster(path: String) case profile(path: String) case still(path: String) var path: String { switch self { case .backdrop(let path): return path case .logo(let path): return path case .poster(let path): return path case .profile(let path): return path case .still(let path): return path } } } public final class ImageHandler: NSObject { // MARK: - Properties fileprivate let apiData: ApiJson // MARK: - Initializer public init(apiData: ApiJson) { self.apiData = apiData } // MARK: - Helper functions private func pathComponent(forSize size: ImgSize, andPath imagePath: ImgPath) -> String { let array: [String] = { switch imagePath { case .backdrop: return self.apiData.backdropSizes case .logo: return self.apiData.logoSizes case .poster: return self.apiData.posterSizes case .profile: return self.apiData.profileSizes case .still: return self.apiData.stillSizes } }() let sizeComponentIndex: Int = { switch size { case .small: return 0 case .medium: return array.count / 2 case .big: return array.count - 2 case .original: return array.count - 1 } }() let sizeComponent: String = array[sizeComponentIndex] return "\(sizeComponent)/\(imagePath.path)" } func url(fromDBPath imagePath: ImgPath, withSize size: ImgSize) -> URL? { let pathComponent = self.pathComponent(forSize: size, andPath: imagePath) let url = URL(string: self.apiData.imagesSecureBaseURLString)?.appendingPathComponent(pathComponent) return url } } <file_sep>/themoviedb/connection/Paginator.swift // // Paginator.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit public struct Paginator<T> { // MARK: - Properties let page: Int let totalResults: Int let totalPages: Int let results: [T] // MARK: - Initializer init(page: Int, totalResults: Int, totalPages: Int, results: [T]) { self.page = page self.totalResults = totalResults self.totalPages = totalPages self.results = results } // MARK: - Helper functions / properties var count: Int { return self.results.count } var nextPage: Int? { let nextPage = self.page + 1 guard nextPage < self.totalPages else { return nil } return nextPage } static func Empty() -> Paginator { return Paginator(page: 0, totalResults: 0, totalPages: 0, results: []) } } extension Paginator { // MARK: - Subscript subscript(index: Int) -> T { return self.results[index] } } <file_sep>/themoviedb/connection/ApiJson.swift // // ApiJson.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import SwiftyJSON public struct ApiJson: JSONInitializable { // MARK: - Properties let imagesBaseURLString: String let imagesSecureBaseURLString: String let backdropSizes: [String] let logoSizes: [String] let posterSizes: [String] let profileSizes: [String] let stillSizes: [String] // MARK: - JSONInitializable initializer init(json: JSON) { self.imagesBaseURLString = json["images"]["base_url"].stringValue self.imagesSecureBaseURLString = json["images"]["secure_base_url"].stringValue self.backdropSizes = json["images"]["backdrop_sizes"].arrayValue.map({ $0.stringValue }) self.logoSizes = json["images"]["logo_sizes"].arrayValue.map({ $0.stringValue }) self.posterSizes = json["images"]["poster_sizes"].arrayValue.map({ $0.stringValue }) self.profileSizes = json["images"]["profile_sizes"].arrayValue.map({ $0.stringValue }) self.stillSizes = json["images"]["still_sizes"].arrayValue.map({ $0.stringValue }) } } <file_sep>/README.md https://www.themoviedb.org/?language=en Have you visited this and you have been a fan of this. This is one of my best projects as a learning towards RxSwift and RxCocoa while using TMDB apis ![](https://github.com/mspoonam/themoviedb/blob/master/appvideo.gif)<file_sep>/themoviedb/GroupExtensionsSampleApp.swift // // GroupExtensionsSampleApp.swift // // Created by <NAME> on 28/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import SwiftyJSON import RxSwift import RxCocoa import SDWebImage import Alamofire public typealias ParametersList = [String: String] // MARK: - public struct CollectionViewSelection { let collectionView: UICollectionView let indexPath: IndexPath } // MARK: - URLParametersListSerializable protocol protocol URLParametersListSerializable { var URLParametersList: ParametersList { get } } // MARK: - JSONInitializable protocol protocol JSONInitializable { init(json: JSON) } protocol JSONFailableInitializable { init?(json: JSON) } // MARK: - NSUserDefault extension UserDefaults { class func performOnce(forKey key: String, perform: () -> Void, elsePerform: (() -> Void)? = nil) { let once = self.standard.object(forKey: key) self.standard.set(true, forKey: key) self.standard.synchronize() if once == nil { perform() } else { elsePerform?() } } } // MARK: - JSON extension JSON { public var date: Date? { get { switch self.type { case .string: guard let dateString = self.object as? String else { return nil } return DtHandler.SharedFormatter.date(from: dateString) default: return nil } } set { if let newValue = newValue { self.object = DtHandler.SharedFormatter.string(from: newValue) } else { self.object = NSNull() } } } public var dateValue: Date { get { guard let date = self.date else { return Date() } return date } set { self.date = newValue } } } // MARK: - ReusableView protocol protocol ReusableView: class { static var DefaultReuseIdentifier: String { get } } extension ReusableView where Self: UIView { static var DefaultReuseIdentifier: String { return NSStringFromClass(self) } } // MARK: - NibLoadableView protocol protocol NibLoadableView: class { static var nibName: String { get } } extension NibLoadableView where Self: UIView { static var nibName: String { return NSStringFromClass(self).components(separatedBy: ".").last! } } // MARK: - UITableView extension extension UITableView { func registerReusableCell<T: UITableViewCell>(_: T.Type) where T: ReusableView { self.register(T.self, forCellReuseIdentifier: T.DefaultReuseIdentifier) } func registerReusableCell<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) self.register(nib, forCellReuseIdentifier: T.DefaultReuseIdentifier) } func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView { guard let cell = self.dequeueReusableCell(withIdentifier: T.DefaultReuseIdentifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.DefaultReuseIdentifier)") } return cell } } // MARK: - UICollectionView extension extension UICollectionView { func registerReusableCell<T: UICollectionViewCell>(_: T.Type) where T: ReusableView { self.register(T.self, forCellWithReuseIdentifier: T.DefaultReuseIdentifier) } func registerReusableCell<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) self.register(nib, forCellWithReuseIdentifier: T.DefaultReuseIdentifier) } func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView { guard let cell = dequeueReusableCell(withReuseIdentifier: T.DefaultReuseIdentifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.DefaultReuseIdentifier)") } return cell } } // MARK: - Reactive protocol protocol ReactiveDisposable { var disposeBag: DisposeBag { get } } // MARK: - Reactive extensions extension Reactive where Base: UIScrollView { // MARK: - UIScrollView reactive extension public var reachedBottom: Observable<Void> { let scrollView = self.base as UIScrollView return self.contentOffset.flatMap{ [weak scrollView] (contentOffset) -> Observable<Void> in guard let scrollView = scrollView else { return Observable.empty() } let visibleHeight = scrollView.frame.height - self.base.contentInset.top - scrollView.contentInset.bottom let y = contentOffset.y + scrollView.contentInset.top let threshold = max(0.0, scrollView.contentSize.height - visibleHeight) return (y > threshold) ? Observable.just(()) : Observable.empty() } } public var startedDragging: Observable<Void> { let scrollView = self.base as UIScrollView return scrollView.panGestureRecognizer.rx .event .filter({ $0.state == .began }) .map({ _ in () }) } } extension Reactive where Base: UIViewController { // MARK: - UIViewController reactive extension public var viewDidLoad: Observable<Void> { return self.sentMessage(#selector(UIViewController.viewDidLoad)).map({ _ in return () }) } public var viewWillAppear: Observable<Bool> { return self.sentMessage(#selector(UIViewController.viewWillAppear(_:))).map({ $0.first as! Bool }) } public var viewDidAppear: Observable<Bool> { return self.sentMessage(#selector(UIViewController.viewDidAppear(_:))).map({ $0.first as! Bool }) } public var viewWillDisappear: Observable<Bool> { return self.sentMessage(#selector(UIViewController.viewWillDisappear(_:))).map({ $0.first as! Bool }) } public var viewDidDisappear: Observable<Bool> { return self.sentMessage(#selector(UIViewController.viewDidDisappear(_:))).map({ $0.first as! Bool }) } } // MARK: - UIImageView extension extension UIImageView { func setImage(fromDBPath path: ImgPath, withSize size: ImgSize, animatedOnce: Bool = true, withPlaceholder placeholder: UIImage? = nil) { guard let imageURL = ApiHelper.instance.imgHandler?.url(fromDBPath: path, withSize: size) else { return } let hasImage: Bool = (self.image != nil) self.sd_setImage(with: imageURL, placeholderImage: nil, options: .avoidAutoSetImage) { [weak self] (image, error, cacheType, url) in if animatedOnce && !hasImage && cacheType == .none { self?.alpha = 0.0 UIView.animate(withDuration: 0.5) { self?.alpha = 1.0 } } self?.image = image } } } // MARK: - SegueReachable protocol protocol SegueReachable: class { static var segueIdentifier: String { get } } // MARK: - TextStyle extension extension TextStyle { var attributes: [String: AnyObject] { return [NSAttributedStringKey.font.rawValue: self.font, NSAttributedStringKey.foregroundColor.rawValue: self.color] } } // MARK: - UILabel extension extension UILabel { func apply(style: TextStyle) { self.font = style.font self.textColor = style.color } } // MARK: - Custom errors public enum DataError: Error { case noData } // MARK: - Key window extension UIApplication { static var window: UIWindow? { guard let delegate = self.shared.delegate else { return nil } return delegate.window ?? nil } } func unique<S: Sequence, E: Hashable>(source: S) -> [E] where E==S.Iterator.Element { var seen: [E:Bool] = [:] return source.filter { seen.updateValue(true, forKey: $0) == nil } }
365b088fd3a4a384a2aef245dfb919c71c6ac5b8
[ "Swift", "Markdown" ]
17
Swift
mspoonam/themoviedb
dd145d499757de2b47ddffc8b834216d86c04c63
a0119984e35596c577890ee0450c6e062baf78ed
refs/heads/master
<repo_name>PrajeeshBalasubramani/Mail-Automation<file_sep>/Structureemail.py from __future__ import print_function import smtplib from tkinter import * import numpy as np from tkinter import ttk import tkinter import tkinter as tk import pandas as pd import time import datetime import urllib import urllib.request as ur import sys import os import logging import logging.config import threading import tkinter.messagebox import random try: import Tkinter as tk import Queue as qu except ImportError: import tkinter as tk import queue as qu now = datetime.datetime.now() l=now.strftime("%Y ") l=l+now.strftime("%m ") l=l+now.strftime("%d ") logging.basicConfig(filename='{0}_logfile.log'.format(l),level=logging.DEBUG) from email.mime.text import MIMEText APP_TITLE = "Mail Automation" APP_XPOS = 100 APP_YPOS = 100 APP_WIDTH = 800 APP_HEIGHT = 300 UPDATE_TIME = 1000 # Milliseconds QUEUE_SIZE = 500 POLLING_TIME = 1000 p=[] a=[] b=[] p1=[] a1=[] b1=[] prop=[] class mainwindow(object): ls=[] lt=[] xs=[] ys=[] lg=[] lh=[] vs=[] ar=0 imr=0 br=0 cr=0 def __init__(self): global lg global lh global ar global im global imr global b global br global vs global ls global cr global xs self.g=open('EnterSampleEmails.txt','r') self.gr=self.g.read() mainwindow.lg = self.gr.split(",") time.sleep(3) self.h=open("EnterSampleNames.txt",'r') self.th=self.h.read() mainwindow.lh=self.th.split(",") time.sleep(3) self.v=open('EnterIDs.txt','r')#inquotes self.vr=self.v.read() mainwindow.vs =self.vr.split(",") self.x=open('prajeesh.txt','r')#inquotes self.xr=self.x.read() mainwindow.xs = self.xr.split(",") self.y=open('prajeeshpass.txt','r')#inquotes self.yr=self.y.read() mainwindow.ys =self.yr.split(",") self.s= open('clgmail.txt','r') self.sr=self.s.read() mainwindow.ls = self.sr.split(",") time.sleep(3) self.t=open("EnterRecevierNames.txt",'r') self.tr=self.t.read() mainwindow.lt=self.tr.split(",") time.sleep(3) self.c= open('Entersubject.txt','r') mainwindow.cr=self.c.read()#inquotes self.a = open('EntertheHTMLPart-I.txt','r') mainwindow.ar=self.a.read() self.im= open('EnterImagePart.txt','r') mainwindow.imr=self.im.read() self.b= open('EntertheHTMLPart-II.txt','r') mainwindow.br=self.b.read() secondmain() def internetcheck(self): try: ur.urlopen('https://www.google.co.in/?gfe_rd=cr&dcr=0&ei=aNA8WtaQBayIX7Dop5gGm', timeout=1) #to check internet return True except ur.URLError as err: return False def first(self,parent): self.parent=parent parent.title=("Mail Automation Application" ) self.welcome=Label(parent,text="Welcome to Mail Automation Application") self.welcome.grid(sticky=E) self.Sample= Button(parent, text='Scheduled') self.Sample.grid(row=8) self.Actual= Button(parent, text='Regular',command=secondmain) self.Actual.grid(row=6, column=0,sticky=N) class secondwindow(mainwindow): def __init__(self,master): global lg global lh global ar global im global imr global b global br global vs global ls global cr global xs global ment self.g=open('quotesone.txt','r',encoding="utf8") self.gr=self.g.read() prop = self.gr.split("||") quote=random.choice(prop) self.master = master self.intruction = Label(self.master, text='<NAME>',font='Italic 25 bold',fg="green") self.intruction.grid(row=0, column=1, sticky=W) #self.image = tk.PhotoImage(file="image.jpg") self.image = tk.PhotoImage(file="image.gif") self.label = tk.Label(image=self.image) self.label.grid(row=0,column=0) self.title = Label(self.master, text='Mail Automation',font='Italic 15 bold',fg="black") self.title.grid(row=1, column=2, sticky=W) self.name = Label(self.master, text='Select:',font='Helvetica 13 bold') self.name.grid(row=3,column=1,sticky=E) self.Sample= Button(self.master, text='Sample',command=self.sample,bg="blue",fg="white",) self.Sample.grid(row=5,column=2,sticky=W) self.name1 = Label(self.master, text=' ',font='Helvetica 13 bold') self.name1.grid(row=4,column=2) self.Actual= Button(self.master, text='Regular',command=self.receviernumber,bg="blue",fg="white",) self.Actual.grid(row=3, column=2,sticky=W) self.name1 = Label(self.master, text=' ',font='Helvetica 13 bold') self.name1.grid(row=6,column=2) #self.bottom_frm = tk.Frame(self.master) self.btn_frm_r = tk.Frame(self.master, background='yellow', width=600, height=50) self.btn_frm_r.grid(column=0, row=8 , columnspan= 10) self.name1 = Label(self.btn_frm_r, text=quote,font='Helvetica 13 bold') self.name1.grid() #elf.bottom_frm.grid(side="bottom",fill="x",expand=False) def error(self): roots=Tk() self.k = 300 self.s = 100 self.wk = roots.winfo_screenwidth() self.hw = roots.winfo_screenheight() self.z = (self.wk/2) - (self.k/2) self.u = (self.hw/2) - (self.s/2) self.text=Entry(self.master) self.text.grid(row=3) roots.geometry('%dx%d+%d+%d' % (self.k, self.s, self.z, self.u)) roots.mainloop() def sample(self): global lg global lh global ar global im global imr global b global br global vs global ls global cr global xs logging.debug('Selected Sample Option') for i in range(0, len(self.lg)): logging.debug('enterd interation No:%d'%i) title = self.lh[i] msg_00content = '<p><span style="font-size: 14pt;font-family: arial,helvetica,sans-serif; ">Namaste {title},<br /></p>'.format( title=title) msg_01content = self.ar msg_02content = self.imr msg_03content = self.br msg = msg_00content + msg_01content + msg_02content + msg_03content message = MIMEText(msg, 'html') message['From'] =self.vs[i] message['To'] = self.ls[0] message['Subject'] = self.cr msg_full = message.as_string() if i <= 10: try: if self.internetcheck() == False: tkinter.messagebox.showwarning('Warning','Network Failure,waiting for connections') logging.error(str(now)) logging.error("Internet Connection Not Established") for u in range(0,1000000): if self.internetcheck() == False: time.sleep(1) tkinter.messagebox.showwarning('Warning',"Sleeping until internet connects...Trying %d times" % u) sys.stdout.flush() if self.internetcheck() == True: break else: tkinter.messagebox.showinfo('Information','Awake from sleep, Got connection...') logging.debug(str(now)) logging.debug("Internet Connection Established") sys.stdout.flush() break else: server = smtplib.SMTP('smtp.gmail.com:587') # setting up service provider name : port number server.starttls() # asking server to start server.login(self.xs[0], self.ys[0]) # Sender Mail, Sender Mail Password server.sendmail(self.xs[0], [self.lg[i]], msg_full) p.append(self.xs[0]) a.append(self.lg[i]) b.append(self.cr) logging.debug('Sending to : %s'%self.lh[i]) except smtplib.SMTPException: if self.internetcheck() == False: tkinter.messagebox.showinfo('Information','Network Failure,waiting for connections') logging.error(str(now)) logging.error("Internet Connection Not Established") for u in range(0, 1000000): if self.internetcheck() == False: time.sleep(1) tkinter.messagebox.showinfo('Information','Sleeping until internet connects...Trying %d times' % u) sys.stdout.flush() if self.internetcheck() == True: break else: logging.debug(str(now)) logging.debug("Internet Connection Established") sys.stdout.flush() else: roots=Tk() self.k = 300 self.s = 100 self.wk = roots.winfo_screenwidth() self.hw = roots.winfo_screenheight() self.z = (self.wk/2) - (self.k/2) self.u = (self.hw/2) - (self.s/2) self.text=Text(roots) self.text.grid(row=3) roots.geometry('%dx%d+%d+%d' % (self.k, self.s, self.z, self.u)) file = open("Errorlog.txt", "w") file.write("Date Time:{}".format(str(now))) file.write("Error: MailerID {} /n".format(self.xs[0])) file.write("Error: MailerID {} /n".format(i)) file.close() self.d1="Date Time:{}".format(str(now)) tkinter.messagebox.showinfo('Information',"Date Time:{}".format(str(now))) tkinter.messagebox.showinfo('Information',"Error: MailID {}".format(self.xs[0])) tkinter.messagebox.showinfo('Information',"Error: Sent upto {}".format(i)) self.text.insert(END,"Date Time:{} \n".format(str(now))) self.text.insert(END,"Error: MailID {} \n".format(xs[0])) self.text.insert(END,"Error: Sent upto {} \n".format(i)) logging.error("Unexpected Error Occured") logging.error(str(now)) logging.error("Sent upto:%d"%i) roots.geometry('%dx%d+%d+%d' % (self.k, self.s, self.z, self.u)) roots.mainloop() break else: logging.debug('Contact Developer...Needs Renovation.') print("Contact Developer...Needs Renovation.") main() def receviernumber(self): global numberentry global codeentry global lg global lh global ar global im global imr global b global br global vs global ls global cr global xs roots=Tk() self.k = 300 self.s = 100 self.wk = roots.winfo_screenwidth() self.hw = roots.winfo_screenheight() self.z = (self.wk/2) - (self.k/2) self.u = (self.hw/2) - (self.s/2) roots.title("Mail Automation") self.receviernumber = Label(roots, text='Recevier Number:') self.receviernumber.grid(row=2) self.code = Label(roots, text='Specific Code') self.code.grid(row=3) self.numberentry= tk.Entry(roots) self.numberentry.grid(row=2, column=1) self.codeentry= tk.Entry(roots) self.codeentry.grid(row=3, column=1) self.B1=Button(roots, text=" Start ",bg="blue",fg="white",command=self.actual ).grid(row=5,column=1) roots.geometry('%dx%d+%d+%d' % (self.k, self.s, self.z, self.u)) roots.mainloop() def actual(self): global numberentry global codeentry global ment #ment=StringVar() logging.debug('Selected Actual Customers Option') j=0 k=1 df=self.codeentry.get() self.uo=self.numberentry.get() self.uo=int(self.uo) print(self.uo) for i in range(self.uo, len(mainwindow.ls)): logging.debug('enterd interation No:%d'%i) title = self.lt[i] msg_00content = '<p><span style="font-size: 14pt;font-family: arial,helvetica,sans-serif; ">Namaste {title},<br /></p>'.format( title=title) msg_01content = self.ar msg_02content = self.imr msg_03content = self.br msg = msg_00content + msg_01content + msg_02content + msg_03content message = MIMEText(msg, 'html') message['From'] =self.vs[j] message['To'] = self.ls[0] bk=',Feedback-ID:{df}:{fd}:01:01'.format(df=df,fd=i) message['Subject'] = self.cr+bk msg_full = message.as_string() if i <= 500: try: if self.internetcheck() == False: tkinter.messagebox.showwarning('Warning',"Network Failue,waiting for connections") logging.error(str(now)) logging.error("Internet Connection Not Established") for u in range(0,1000000): if self.internetcheck() == False: time.sleep(1) tkinter.messagebox.showwarning('Warning',"Sleeping until internet connects...Trying %d times" % u) sys.stdout.flush() if self.internetcheck() == True: break else: tkinter.messagebox.showwarning('Warning',"Awake from sleep, Got connection...") #print("Awake from sleep, Got connection...", end='\r') logging.debug(str(now)) logging.debug("Internet Connection Established") sys.stdout.flush() else: server = smtplib.SMTP('smtp.gmail.com:587') # setting up service provider name : port number server.starttls() # asking server to start server.login(self.xs[0], self.ys[0]) # Sender Mail, Sender Mail Password server.sendmail(self.xs[0], [self.ls[0]], msg_full) p1.append(self.xs[0]) a1.append(self.ls[0]) b1.append(self.cr) #print(" \n Sent to ", i, self.lt[i]) server.quit() # asking server to quit time.sleep(10) logging.debug('Sending to : %s'%self.lt[i]) if k!=0: if j<30: j=1 elif j>30 and j<60: j=2 elif j>60 and j<90: j=3 elif j>90 and j<120: j=4 elif j>120 and j<150: j=5 elif j>150 and j<180: j=6 elif j>180 and j<210: j=7 elif j>210 and j<240: j=8 elif j>240 and j<270: j=9 elif j>300 and j<330: j=10 elif j>330 and j<360: j=11 elif j>360 and j<390: j=12 elif j>390 and j<420: j=13 elif j>420 and j<450: j=14 elif j>450 and j<480: j=15 elif j>480 and j<510: j=16 elif j>510 and j<540: j=17 elif j>540 and j<580: j=18 except smtplib.SMTPException: if self.internetcheck() == False: ment="Network Failue,waiting for connections" self.text.insert(END,ment) logging.error(str(now)) logging.error("Internet Connection Not Established") for u in range(0, 1000000): if self.internetcheck() == False: time.sleep(1) tkinter.messagebox.showwarning('Warning',"Sleeping until internet connects...Trying %d times" % u) sys.stdout.flush() if self.internetcheck() == True: break else: tkinter.messagebox.showwarning('Warning',"Awake from sleep, Got connection...") sys.stdout.flush() logging.debug(str(now)) logging.debug("Internet Connection Established") sys.stdout.flush() break else: roots=Tk() self.k = 300 self.s = 100 self.wk = roots.winfo_screenwidth() self.hw = roots.winfo_screenheight() self.z = (self.wk/2) - (self.k/2) self.u = (self.hw/2) - (self.s/2) self.text=Text(roots) self.text.grid(row=3) roots.geometry('%dx%d+%d+%d' % (self.k, self.s, self.z, self.u)) file = open("Errorlog.txt", "w") file.write("Date Time:{}".format(str(now))) file.write("Error: MailerID {} /n".format(self.xs[j])) file.write("Error: MailerID {} /n".format(i)) file.close() self.text.insert(END,"Date Time:{} \n".format(str(now))) self.text.insert(END,"Error: MailID {} \n".format(self.xs[0])) self.text.insert(END,"Error: Sent upto {} \n".format(i)) self.text.insert(END,"Error section j=",j) logging.error("Unexpected Error Occured") logging.error(str(now)) logging.error("Sent upto: %d"%i) logging.error("Sent with: %d"%j) j=j+1 k=0 roots.geometry('%dx%d+%d+%d' % (self.k, self.s, self.z, self.u)) roots.mainloop() continue elif i>=500: logging.debug('Contact Developer...Needs Renovation.') print("Contact Developer.... Needs Renovation.") main1() #-------------sample--------------------------------------------------------------------# class appThread(threading.Thread): def __init__(self, queue1=None,queue2=None,queue3=None): self.queue1 = queue1 self.queue2 = queue2 self.queue3 = queue3 threading.Thread.__init__(self,target=self.run1) threading.Thread.__init__(self,target=self.run) self.start() def run(self): msg=b[0] self.update_queue3(msg) self.run1() def run1(self): #for i in range(0,len(p)): num_count=p[0] self.update_queue1(num_count) self.run2() #print("4",v) def run2(self): for i in range(0,len(a)): num=a[i] self.update_queue2(num) def update_queue1(self,num_count): self.queue1.put(num_count) self.queue1.join() def update_queue2(self,num): self.queue2.put(num) self.queue2.join() def update_queue3(self,msg): self.queue3.put(msg) self.queue3.join() class application(tk.Frame): def __init__(self, master): self.master = master self.master.protocol("WM_DELETE_WINDOW", self.close) tk.Frame.__init__(self, master) self.app_thread = None self.frame_head = tk.Frame(self, width=600, height=50) self.frame_head.grid(column=0, row=0 , columnspan= 10) self.title = Label(self.frame_head, text='Mail Automation',font='Italic 15 bold',fg="black") self.title.grid(row=0, column=0, sticky=W) self.frame_body = tk.Frame(self, width=600, height=500) self.frame_body.grid(column=0, row=1 , columnspan= 10) tk.Label(self.frame_body, text=b[0],font='Italic 13 bold',fg="green").grid(column=0, row=2, stick='W') #self.name1 = Label(self.control_frame, text=b1[0],font='Helvetica 13 bold') #self.name1.grid() #self.subject = Label(self.control_frame, text='Sending Subject:') self.frame_body2 = tk.Frame(self, width=600, height=500) self.frame_body2.grid(column=0, row=5 , columnspan= 10) self.sender = Label(self.frame_body2, text='From:') self.recevier = Label(self.frame_body2, text='To:') self.sender.grid(row=2, sticky=W) self.recevier.grid(row=3, sticky=W) #self.subjectentry= Entry(self.control_frame ) self.senderentry= Entry(self.frame_body2) self.recevierentry= Entry(self.frame_body2) #self.subjectentry.grid(row=1, column=1) self.senderentry.grid(row=2, column=1) self.recevierentry.grid(row=3, column=1) self.B1=Button(self.frame_body2, text=" Start ",bg="purple",fg="white", command=self.start_thread).grid(row=5,column=1) self.queue1 = qu.Queue(QUEUE_SIZE) self.queue2 = qu.Queue(QUEUE_SIZE) self.queue3 = qu.Queue(QUEUE_SIZE) self.queue_polling() def start_thread(self): if self.app_thread == None: self.app_thread = appThread( self.queue1,self.queue2,self.queue3) else: if not self.app_thread.isAlive(): self.app_thread = appThread( self.queue1,self.queue2,self.queue3) def queue_polling(self): if self.queue3.qsize() : try: data3 = self.queue3.get() #self.subjectentry.delete(0,'end') #self.subjectentry.insert(0,data3) self.queue3.task_done() except qu.Empty: pass print("hai") if self.queue1.qsize() : try: data1 = self.queue1.get() #print("37",self.max_number) self.senderentry.delete(0,'end') self.senderentry.insert(0,data1) self.queue1.task_done() except qu.Empty: pass print("hai") if self.queue2.qsize(): try: data2 = self.queue2.get() self.recevierentry.delete(0,'end') self.recevierentry.insert(0,data2) self.queue2.task_done() except qu.Empty: pass print("hai") self.after(POLLING_TIME, self.queue_polling) def close(self): print("Application-Shutdown") self.app_thread.join() self.master.destroy() #--------------------error---------------------------------------------------------------------------# #------------------------------------------actual----------------------------------------------------# class AppThread(threading.Thread): def __init__(self, queue1=None,queue2=None,queue3=None): self.queue1 = queue1 self.queue2 = queue2 self.queue3 = queue3 threading.Thread.__init__(self,target=self.run1) threading.Thread.__init__(self,target=self.run) self.start() def run(self): msg=b1[0] self.update_queue3(msg) self.run1() def run1(self): #for i in range(0,len(p)): num_count=p1[0] self.update_queue1(num_count) self.run2() #print("4",v) def run2(self): for i in range(0,len(a1)): num=a1[0] self.update_queue2(num) def update_queue1(self,num_count): self.queue1.put(num_count) self.queue1.join() def update_queue2(self,num): self.queue2.put(num) self.queue2.join() def update_queue3(self,msg): self.queue3.put(msg) self.queue3.join() class Application(tk.Frame): def __init__(self, master): self.master = master self.master.protocol("WM_DELETE_WINDOW", self.close) tk.Frame.__init__(self, master) self.app_thread = None self.frame_head = tk.Frame(self, width=600, height=50) self.frame_head.grid(column=0, row=0 , columnspan= 10) self.title = Label(self.frame_head, text='Mail Automation',font='Italic 15 bold',fg="black") self.title.grid(row=0, column=0, sticky=W) self.frame_body = tk.Frame(self, width=600, height=500) self.frame_body.grid(column=0, row=1 , columnspan= 10) tk.Label(self.frame_body, text=b1[0],font='Italic 13 bold',fg="green").grid(column=0, row=2, stick='W') #self.name1 = Label(self.control_frame, text=b1[0],font='Helvetica 13 bold') #self.name1.grid() #self.subject = Label(self.control_frame, text='Sending Subject:') self.frame_body2 = tk.Frame(self, width=600, height=500) self.frame_body2.grid(column=0, row=5 , columnspan= 10) self.sender = Label(self.frame_body2, text='From:') self.recevier = Label(self.frame_body2, text='To:') self.sender.grid(row=2, sticky=W) self.recevier.grid(row=3, sticky=W) #self.subjectentry= Entry(self.control_frame ) self.senderentry= Entry(self.frame_body2) self.recevierentry= Entry(self.frame_body2) #self.subjectentry.grid(row=1, column=1) self.senderentry.grid(row=2, column=1) self.recevierentry.grid(row=3, column=1) self.B1=Button(self.frame_body2, text=" Start ",bg="purple",fg="white", command=self.start_thread).grid(row=5,column=1) self.queue1 = qu.Queue(QUEUE_SIZE) self.queue2 = qu.Queue(QUEUE_SIZE) self.queue3 = qu.Queue(QUEUE_SIZE) self.queue_polling() def start_thread(self): if self.app_thread == None: self.app_thread = AppThread( self.queue1,self.queue2,self.queue3) else: if not self.app_thread.isAlive(): self.app_thread = AppThread( self.queue1,self.queue2,self.queue3) def queue_polling(self): if self.queue3.qsize() : try: data3 = self.queue3.get() #self.subjectentry.delete(0,'end') #self.subjectentry.insert(0,data3) self.queue3.task_done() except qu.Empty: pass print("hai") if self.queue1.qsize() : try: data1 = self.queue1.get() self.senderentry.delete(0,'end') self.senderentry.insert(0,data1) self.queue1.task_done() except qu.Empty: pass print("hai") if self.queue2.qsize(): try: data2 = self.queue2.get() self.recevierentry.delete(0,'end') self.recevierentry.insert(0,data2) self.queue2.task_done() except qu.Empty: pass print("hai") self.after(POLLING_TIME, self.queue_polling) def close(self): print("Application-Shutdown") self.app_thread.join() self.master.destroy() def main1(): app_win = tk.Tk() app_win.title(APP_TITLE) app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS)) app_win.geometry("{}x{}".format(APP_WIDTH, APP_HEIGHT)) app = Application(app_win).pack(fill='both', expand=True) app_win.mainloop() def main(): app_win = tk.Tk() app_win.title(APP_TITLE) app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS)) app_win.geometry("{}x{}".format(APP_WIDTH, APP_HEIGHT)) app = application(app_win).pack(fill='both', expand=True) app_win.mainloop() #--------------------------------------------------------------------------------------------------------# def secondmain(): app_win = tk.Tk() app_win.title("Mail Automation") #app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS)) app_win.geometry("{}x{}".format(APP_WIDTH, APP_HEIGHT)) #app_win.geometry('%dx%d+%d+%d' % (self.k, self.s, self.z, self.u)) #roots.mainloop() app = secondwindow(app_win) app_win.mainloop() mainwindow()
e0c5a06083fb23b2fecdfea0ceced71b0289b1f0
[ "Python" ]
1
Python
PrajeeshBalasubramani/Mail-Automation
9c1ff7e34cf81a6b0e7ba11e8a51efbea4909dda
76bbce6b856f88ac45c7a1cd6752c87cc00e0ed1
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Text; namespace Tetris { class Shape { public int shapeType; public int rootPosition = Game.width + (Game.width/2); public int rotation = 0; public int colorInt; public static List<ConsoleColor> colorScheme = new List<ConsoleColor>() { ConsoleColor.Green, ConsoleColor.Red, ConsoleColor.Yellow, ConsoleColor.White, ConsoleColor.DarkBlue, }; public static List<List<int>> shapeTypes = new List<List<int>> { new List<int>(){1, Game.width, Game.width+1}, new List<int>(){-1, -Game.width, 1}, new List<int>(){-Game.width, Game.width, Game.width*2}, new List<int>(){1, 2, -Game.width}, new List<int>(){-1, -2, -Game.width}, new List<int>(){1, Game.width, Game.width-1}, new List<int>(){-1, Game.width, Game.width+1}, }; public ConsoleColor color; public List<int> boxes = new List<int>(); public Shape() { Random rnd = new Random(); colorInt = rnd.Next(0, colorScheme.Count); color = colorScheme[colorInt]; shapeType = rnd.Next(1, shapeTypes.Count +1); GenerateShape(); } void GenerateShape() { if (shapeTypes.Count > shapeType-1) { var shapeTypeList = shapeTypes[shapeType - 1]; for (int i = 0; i < shapeTypeList.Count; i++) { boxes.Add(shapeTypeList[i]); } } } } } <file_sep>using System; using System.Timers; namespace Tetris { // // This class is more or less lifted verbatim from a personal game // project and you probably shouldn't have to make any changes here. // public class ScheduleTimer : IDisposable { public bool Aborted { get; private set; } bool _active = true; long _start; long _time; Timer _timer; readonly Action _action; public ScheduleTimer(int time, Action action) { _time = time; _action = () => { _active = false; action(); }; Resume(); } public void Abort() { Aborted = true; Invalidate(); } public void Pause() { if (_active && !Aborted) { Invalidate(); _time = Math.Max(1, _time - (DateTimeOffset.Now.ToUnixTimeMilliseconds() - _start)); } } public void Resume() { if (_active && !Aborted) { _start = DateTimeOffset.Now.ToUnixTimeMilliseconds(); _timer = new Timer(_time); _timer.Elapsed += (sender, arg) => _action(); _timer.AutoReset = false; _timer.Start(); } } void Invalidate() { if (_timer != null) { _timer.Enabled = false; _timer.Close(); _timer = null; } } public void Dispose() => Invalidate(); } } <file_sep># Tetris Tetris game made using c#. <file_sep>using System; namespace Tetris { class Program { static void Main(string[] args) { var game = new Game(); game.Start(); // game loop while (true) { // listen to key presses if (Console.KeyAvailable) { var input = Console.ReadKey(true); switch (input.Key) { // pause and resume the game with P case ConsoleKey.P: if (game.Paused) game.Resume(); else game.Pause(); break; // send key presses to the game if it's not paused case ConsoleKey.UpArrow: case ConsoleKey.DownArrow: case ConsoleKey.LeftArrow: case ConsoleKey.RightArrow: if (!game.Paused) game.Input(input.Key); break; // end the game with ESC case ConsoleKey.Escape: game.Stop(); return; } } } } } } <file_sep>using System; using System.Threading; using System.Collections.Generic; using System.Text; namespace Tetris { class Game { ScheduleTimer _timer; int tickDelay = 500; public static int width = 15; public static int height = 29; bool finished = true; bool gameOver = false; int score; List<int> boxes = new List<int>(); Shape currentShape; public bool Paused { get; private set; } public void Start() { Console.CursorVisible = false; GenerateMap(); RenderMap(); NewShape(); ScheduleNextTick(); } public void Pause() { Paused = true; _timer.Pause(); } public void Resume() { Paused = false; _timer.Resume(); } public void Stop() { _timer.Pause(); gameOver = true; Console.SetCursorPosition(width + width, Console.WindowHeight / 5); Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine($"GAME OVER"); } void ScheduleNextTick() { _timer = new ScheduleTimer(tickDelay, Tick); } void NewShape() { if (!gameOver) { currentShape = new Shape(); //Checks for GameOver if (boxes[currentShape.rootPosition] != 0) { DrawShape(); Stop(); return; } DrawShape(); } } void UndrawShape() { int root = currentShape.rootPosition; var x = root % width; var y = (int)root / width; boxes[root] = 0; Console.SetCursorPosition(x+x, y); Console.BackgroundColor = ConsoleColor.Blue; Console.Write(" "); for (int i = 0; i < currentShape.boxes.Count; i++) { var boxInt = root + currentShape.boxes[i]; if (boxInt > boxes.Count) break; var boxX = boxInt % width; var boxY = (int)boxInt / width; boxes[boxInt] = 0; Console.SetCursorPosition(boxX + boxX, boxY); Console.BackgroundColor = ConsoleColor.Blue; Console.Write(" "); } } void DrawShape() { int root = currentShape.rootPosition; var x = root % width; var y = (int)root / width; boxes[root] = currentShape.colorInt +2; Console.SetCursorPosition(x+x, y); Console.BackgroundColor = currentShape.color; Console.Write(" "); for (int i = 0; i < currentShape.boxes.Count; i++) { var boxInt = root + currentShape.boxes[i]; if (boxInt > boxes.Count) break; var boxX = boxInt % width; var boxY = (int)boxInt / width; boxes[boxInt] = currentShape.colorInt + 2; Console.SetCursorPosition(boxX + boxX, boxY); Console.BackgroundColor = currentShape.color; Console.Write(" "); } } bool MoveShapeDown() { int root = currentShape.rootPosition; if (root + width > boxes.Count) return false; if (boxes[root + width] == 0) { for (int i = 0; i < currentShape.boxes.Count; i++) { var boxInt = root + currentShape.boxes[i]; if (boxes[boxInt + width] != 0) { return false; } } currentShape.rootPosition += width; return true; } return false; } bool MoveShapeRight() { if (finished) { finished = false; int root = currentShape.rootPosition; if (boxes[root + 1] == 0) { for (int i = 0; i < currentShape.boxes.Count; i++) { var boxInt = root + currentShape.boxes[i]; if (boxes[boxInt + 1] != 0) { finished = true; return false; } } currentShape.rootPosition += 1; finished = true; return true; } finished = true; return false; } return false; } bool MoveShapeLeft() { if (finished) { finished = false; int root = currentShape.rootPosition; if (boxes[root - 1] == 0) { for (int i = 0; i < currentShape.boxes.Count; i++) { var boxInt = root + currentShape.boxes[i]; if (boxes[boxInt - 1] != 0) { finished = true; return false; } } currentShape.rootPosition -= 1; finished = true; return true; } finished = true; return false; } return false; } void RotateShapeRight() { if (finished) { finished = false; int root = currentShape.rootPosition; //Check if shape can rotate else returns for (int i = 0; i < currentShape.boxes.Count; i++) { var boxInt = root + currentShape.boxes[i]; int newBoxInt = RotateBox(boxInt, root); bool boxIntIsInShape = false; for (int j = 0; j < currentShape.boxes.Count; j++) { var box = root + currentShape.boxes[j]; if (root + newBoxInt == box) { boxIntIsInShape = true; } } if (boxes[root + newBoxInt] != 0 && !boxIntIsInShape) { finished = true; return; } } UndrawShape(); for (int i = 0; i < currentShape.boxes.Count; i++) //Loops through all boxes { var boxInt = root + currentShape.boxes[i]; int newBoxInt = RotateBox(boxInt, root); currentShape.boxes[i] = newBoxInt; } DrawShape(); finished = true; } } static int RotateBox(int boxInt, int root) { if (boxInt == root - width) { return 1; } else if (boxInt == root + 1) { return width; } else if (boxInt == root + width) { return -1; } else if (boxInt == root - 1) { return -width; } else if (boxInt == root - width * 2) { return 2; } else if (boxInt == root + 2) { return width * 2; } else if (boxInt == root + width * 2) { return -2; } else if (boxInt == root - 2) { return -width * 2; } if (boxInt == root - width + 1) { return 1 + width; } else if (boxInt == root + 1 + width) { return width - 1; } else if (boxInt == root + width - 1) { return -1 - width; } else if (boxInt == root - 1 - width) { return -width + 1; } return 0; } void ManageShape() { if (finished) { finished = false; UndrawShape(); // Clears last iteration of the current shape. //Tries to move the shape down 1 step (root += width). bool canMoveDown = MoveShapeDown(); DrawShape(); // Draws Shape if (!canMoveDown) //Checks if shape is at the bottom { RowCheck(); //Checks for a full row NewShape(); } finished = true; } } void DrawBox(int boxInt, int boxColor) { var x = boxInt % width; var y = (int)boxInt / width; boxes[boxInt] = boxColor; Console.SetCursorPosition(x+x, y); Console.BackgroundColor = Shape.colorScheme[boxColor -2]; Console.Write(" "); } void ClearBox(int boxInt) { var x = boxInt % width; var y = (int)boxInt / width; boxes[boxInt] = 0; Console.SetCursorPosition(x+x, y); Console.BackgroundColor = ConsoleColor.Blue; Console.Write(" "); } void RightKeyPress() { UndrawShape(); // Clears last iteration of the current shape. //Tries to move the shape to the right 1 step (root += width). bool canMoveRight = MoveShapeRight(); DrawShape(); // Draws Shape } void LeftKeyPress() { UndrawShape(); // Clears last iteration of the current shape. //Tries to move the shape to the left 1 step (root += width). bool canMoveLeft = MoveShapeLeft(); DrawShape(); // Draws Shape } void RenderMap() { int boxInt = 0; for(int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (boxes[boxInt] == 0) Console.BackgroundColor = ConsoleColor.Blue; else if (boxes[boxInt] == 1) Console.BackgroundColor = ConsoleColor.DarkGray; else if (boxes[boxInt] == 2) Console.BackgroundColor = ConsoleColor.Red; Console.SetCursorPosition(x+x, y); Console.Write(" "); boxInt++; } Console.WriteLine(""); } Console.BackgroundColor = ConsoleColor.Black; } void RowCleared(int height) // Move all rows down { score++; for (int y = height; y > 0; y -= width) { for (int x = 1; x < width - 1; x++) { int boxInt = y + x; if (boxes[boxInt] != 0) { var colorInt = boxes[boxInt]; //Move box down ClearBox(boxInt); boxInt += width; DrawBox(boxInt, colorInt); } } } } void RowCheck() { for (int y = width; y < height * width -width; y += width) { bool fullRow = true; for (int x = 1; x < width -1; x++) { int boxInt = y + x; if (boxes[boxInt] == 0) { fullRow = false; } } if (fullRow) { for (int x = 1; x < width - 1; x++) { int boxInt = y + x; ClearBox(boxInt); } RowCleared(y); } } } void Iteration() { if (finished && !gameOver) { finished = false; Console.SetCursorPosition(width + width, Console.WindowHeight / 4); Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine($"Score: {score}"); finished = true; } ManageShape(); } void GenerateMap() // Adds walls around the map { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (y == height-1) { boxes.Add(1); } else if (x == 0 || x == width-1) { boxes.Add(1); } else { boxes.Add(0); } } } } void Tick() { Iteration(); ScheduleNextTick(); } public void Input(ConsoleKey key) { if (!gameOver) { if (key.ToString() == "RightArrow") { RightKeyPress(); } else if (key.ToString() == "LeftArrow") { LeftKeyPress(); } else if (key.ToString() == "DownArrow") { ManageShape(); } else if (key.ToString() == "UpArrow") { RotateShapeRight(); } } } } }
ca26dce444549db1528ef24b6d8552a8a65bc2ad
[ "Markdown", "C#" ]
5
C#
JoakimSjogren/Tetris
bcc4d8b3afa3d8b60398069f9a35a749caeb67c1
8451f3abf7bea316eb954c3285803878d729c967
refs/heads/master
<file_sep><p align="center"> <a href="" rel="noopener"> </p> <h3 align="center">PPL Python Process Launch</h3> <div align="center"> </div> ## 🧐 About <a name = "about"></a> **it's a simple utility to do things the way I like to do them ... BAD and rapid** **Have you ever had to kill a subprocess or a process launched by a script as a daemon?** **with ppl you do it easy, greep process && kill. the end.** ## 🏁 Getting Started <a name = "getting_started"></a> ### Installing `python setup.py` ## 🔧 Running the tests <a name = "tests"></a> `python main.py` ## 🎈 Usage <a name="usage"></a> ``` python #!/usr/bin/env python """ example file main.py """ from ppl import start, stop import time # start process name processo processo = start('python demone.py') """ if the script takes parameters, processo = start(f'python demone.py {parameters}') """ time.sleep(10) # kill process name processo stop(processo) ``` <file_sep>#!/usr/bin/env python import os import subprocess def pypocessgrep(): args = ["pgrep", 'python'] out = os.popen(" ".join(args)).read().strip() return list(map(int, out.splitlines())) def start(command): first = pypocessgrep() subprocess.Popen(command, shell=True) after = pypocessgrep() for k in after: if k not in first: return k def stop(process): command = f'kill {process}' os.system(command) <file_sep>#!/usr/bin/env python import time while True: print('coccodio') time.sleep(1)<file_sep>#!/usr/bin/env python from ppl import start, stop import time processo = start('python demone.py') time.sleep(10) stop(processo) <file_sep>#!/usr/bin/env python from .ppl import start, stop
7ae9e4a64c678152fde2f1d4da5115acea1ed627
[ "Markdown", "Python" ]
5
Markdown
Pinperepette/ppl
10785a55cf9fc695672e91ae8512694e89040c06
6ba47b98ab099a37cce8fc5368bfff6918555478
refs/heads/master
<repo_name>Bhanoosingh/PythonExample<file_sep>/decoraterExp.py def helper(func): def check(a,b): if b==0: return 'Infinite' else: return func(a,b) return check @helper def div(a,b): return a/b #div=helper(div) print('Division=>',div(5,0)) <file_sep>/Devloper.py from MyModule import Employee as emp class Devloper(emp.Employee): raise_up=1.10 def __init__(self,fname,lname,pay,plang): #Employee.__init__(fname,lname,pay) super().__init__(fname,lname,pay) self.plang=plang def display(self): super().display() print('Plang:-',self.plang) fname=input('Enter your first name:-') lname=input('Enter your last name:-') pay=int(input('Enter Employee pay:-')) plang=input('Enter your programming lang:-') obj=Devloper(fname,lname,pay,plang); obj.display() <file_sep>/README.md # PythonExample PythonExample To use Employee.py as module in devloper create MyModule Folder and keep file in it and also create __init__.py (blank file in MyModule folder) <file_sep>/AbstractExp.py from abc import ABC,abstractmethod class animal(ABC): @abstractmethod def move(self): pass class human(animal): def move(self): print('I can walk') class snake(animal): def move(self): print('I can crawal') obj1=human(); obj2=snake(); obj3=animal(); obj1.move(); obj2.move(); <file_sep>/Employee.py class Employee: raise_up=1.04 def __init__(self,fname,lname,pay): self.fname=fname self.lname=lname self.email=<EMAIL>+lname+'@<EMAIL>' self.pay=pay def display(self): print('Name:',self.fname+' '+self.lname) print('Email:',self.email) print('Pay :',self.pay) def apply_raise(self): self.pay=int(self.pay*self.raise_up)
9f99df9f228553575986acf59844186cdc749641
[ "Markdown", "Python" ]
5
Python
Bhanoosingh/PythonExample
0aceb56b0847470173e2a833f61b5f2ff528a508
44033244c860702d887155b5027d91dc6ce28a26
refs/heads/master
<file_sep>module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), karma: { unit: { configFile: 'public/tests/karma.conf.js', background: true, browsers: ['PhantomJS'], autoWatch: true, port: 9876 } }, coffee: { compile: { expand: true, cwd: "public/assets/coffee/", src: ['**/*.coffee'], dest: 'public/javascripts/', ext: '.js' } }, eco: { app: { options: { amd: true, basePath:"public/assets/coffee/App" }, files: { 'public/javascripts/App/templates.js': 'public/assets/coffee/App/templates/*.eco' } } }, watch: { //run unit tests with karma (server needs to be already running) karma: { files: ['public/tests/**/*.js', 'public/tests/**/*.coffee'], tasks: ['karma:unit:run'] }, scripts: { files: 'public/assets/coffee/App/**/*.coffee', tasks: ['coffee'] }, eco: { files: 'public/assets/coffee/App/templates/**/*.eco', tasks: ['eco'] } } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-eco'); grunt.loadNpmTasks('grunt-contrib-requirejs'); // Default task(s). grunt.registerTask('default', ['']); //to start tru karma:unit watch grunt.registerTask('devandtest', ['karma:unit', 'watch']); }; <file_sep>(function() { require.config({ baseUrl: 'javascripts/', paths: { jquery: 'libs/jquery-2.1.0.min', backbone: 'libs/backbone-min', underscore: 'libs/underscore-min', marionette: 'libs/backbone.marionette.min', models: 'App/models', collections: 'App/collections', views: 'App/views', templates: 'App/templates' }, shim: { underscore: { exports: '_' }, backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' }, marionette: { deps: ['backbone', 'underscore', 'jquery'], exports: 'Backbone.Marionette' } } }); require(['models/MovieModel', 'templates'], function(MovieModel, JST) { var movie; console.warn(JST({ num: 293648 })); movie = new MovieModel; return movie.fetch(); }); }).call(this); <file_sep>CoffeeEx ======== Ex. - Grunt - Coffeescript - Backbone - Backbone.Marionette - Underscore - ECO - jQuery - Karma - Mocha - Chai - Sinon
2d18823b83e53d5942e6ec9c0a3beeff5532be8b
[ "JavaScript", "Markdown" ]
3
JavaScript
Razum/CoffeeEx
8cdc0de0e3b00c67a03eaced4d3ec9a2c0371d8d
97582a1e06775334b56028190c69e8c4582946e4
refs/heads/main
<repo_name>mikehaben69/boost<file_sep>/asio/demo_rep_timer/Makefile # THESE PATHS WILL NEED TO BE EDITED TO MATCH THE INSTALL PATHS ON YOUR PC... # Path to Boost libraries: BOOST_PATH := /home/mike/boost/boost_1_77_0 CXX = g++ CPPFLAGS = -I.. -I$(BOOST_PATH) # put pre-processor settings (-I, -D, etc) here CXXFLAGS = -Wall # put compiler settings here LDFLAGS = -L$(BOOST_PATH)/stage/lib -lpthread # put linker settings here LDFLAGS_EXTRA = -lpthread # put linker settings here rep_timer_demo: rep_timer_demo.o $(CXX) -o $@ $(CXXFLAGS) $(LDFLAGS) rep_timer_demo.o $(LDFLAGS_EXTRA) .cpp.o: $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< rep_timer_demo.cpp: ../basic_repeating_timer.hpp clean: $(RM) rep_timer_demo.o rep_timer_demo <file_sep>/asio/demo_rep_timer/rep_timer_demo.cpp #include <iostream> #include <basic_repeating_timer.hpp> void OnRepTimer(boost::system::error_code const& error) { if (!error) { std::cout << "Tick" << std::endl; } } void OnTimer1(boost::system::error_code const& error) { if (!error) { std::cout << "Bong1" << std::endl; } } void OnTimer2(boost::system::error_code const& error) { if (!error) { std::cout << "Bong2" << std::endl; } } void OnTimer3(boost::system::error_code const& error) { if (!error) { std::cout << "Bong3" << std::endl; } } int main(void) { boost::asio::io_context io_ctx; boost::asio::deadline_timer test_timer_1(make_strand(io_ctx)); boost::asio::any_io_executor ex = test_timer_1.get_executor(); boost::asio::any_io_executor ex2 = make_strand(io_ctx); boost::asio::deadline_timer test_timer_2(ex); boost::asio::deadline_timer test_timer_3(ex2); boost::asio::any_io_executor ex3 = make_strand(io_ctx); boost::asio::repeating_timer rep_timer_1(ex3); std::cout << "Starting some timers..." << std::endl; test_timer_1.expires_from_now( boost::posix_time::milliseconds(2900) ); test_timer_1.async_wait(OnTimer1); test_timer_2.expires_from_now( boost::posix_time::milliseconds(900) ); test_timer_2.async_wait(OnTimer2); test_timer_3.expires_from_now( boost::posix_time::milliseconds(1900) ); test_timer_3.async_wait(OnTimer3); rep_timer_1.start( boost::posix_time::milliseconds(1000), OnRepTimer ); boost::asio::io_service::work work(io_ctx); // force io_ctx to keep running until explicitly stopped io_ctx.run(); std::cout << "Timers are running" << std::endl; for(;;) {} } <file_sep>/README.md # boost (Hopefully) useful additions to the Boost libraries, starting with one for Boost ASIO - a repeating timer with similar API to the existing basic_deadline_timer.
e30c4b39459ed63520475d6d5800b893ff863612
[ "Markdown", "Makefile", "C++" ]
3
Makefile
mikehaben69/boost
db432815ddd411dab80aefc590498bba675b64fa
f894052bb9b86f4025e57f8d49586ebea72e0804
refs/heads/main
<repo_name>Evgeni67/M3-D2<file_sep>/M3-D2/backEnd.js var unirest = require("unirest"); var req = unirest("GET", "https://rapidapi.p.rapidapi.com/playlist/%7Bid%7D"); req.headers({ "x-rapidapi-key": "<KEY>", "x-rapidapi-host": "deezerdevs-deezer.p.rapidapi.com", "useQueryString": true } ); req.end(function (res) { if (res.error) throw new Error(res.error); console.log(res.body); } );
46633d7e1cb6470559a3a565af4f1399995ffa75
[ "JavaScript" ]
1
JavaScript
Evgeni67/M3-D2
ffb5c80e3dd91735a17b779b7747e79882fea77d
f802114b5947017d9e8671d841e04c3e57ec04e3
refs/heads/master
<repo_name>AmineBoudaoud/MinesweeperForJava<file_sep>/Minesweeper/Minesweeper.java /**TO DO * 0. Don't Let player lose on first click * 1. Add Reset Button * 2. Game Lost, Game Won sign * 3. Real Flag and Bomb symbols * 4. Time Calculator * 5. High score table * 6. Number of bomb setting option - custom mode * 7. Difficulty mode option * 8. Fix Flagging non-Pushable scores */ import acm.graphics.*; import acm.program.*; import acm.util.*; import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Minesweeper extends GraphicsProgram implements MouseMotionListener { /** Number of bricks per row */ public static int TILE_COLUMNS= 10; /** Number of rows of bricks, in range 1..10. */ public static int TILE_ROWS= 10; /** Width of a brick */ public static int TILE_SIDE=40; /** Width of the game display (al coordinates are in pixels) */ public static final int GAME_WIDTH= TILE_COLUMNS*TILE_SIDE; /** Height of the game display */ public static final int GAME_HEIGHT= TILE_ROWS*TILE_SIDE; public static char Mines[][]=new char [TILE_COLUMNS] [TILE_ROWS]; public static boolean TILE_BLOCK=false; public static boolean GAME_LOSS, GAME_WIN; /** Mine Number. Default setting - 10% of squares */ public static final int MINE_NUMBER= (int) (TILE_COLUMNS*TILE_ROWS/10); /** rowColors[i] is the color of row i of bricks */ private static final Color[] TileColors= {Color.white, Color.blue, Color.green, Color.red, new Color (128,0,128),Color.black, new Color (128,0,0), new Color (64, 224, 208), new Color (128,128,128)}; /** random number generator */ private RandomGenerator rgen= new RandomGenerator(); /** Run the program as an application. */ public static void main(String[] args) { String[] sizeArgs= {"width=" + GAME_WIDTH, "height=" + GAME_HEIGHT}; new Minesweeper().start(sizeArgs); } /** Run the Minesweeper program. */ public void run() { setup(); } /** Set Up all the components of Minesweeper */ public void setup () { createBricks(); MineGenerator(); NumberGenerator(); addMouseListeners(); } /** Creates the set of Bricks for the Minesweeper board */ private void createBricks () { for (int i=0;i<TILE_COLUMNS;i++) { for (int j=0;j<TILE_ROWS;j++) { Tile tile=new Tile (i*TILE_SIDE, j*TILE_SIDE, TILE_SIDE,TILE_SIDE); tile.setColor (new Color (100,100,100)); tile.setRaised (true); tile.setFilled (true); add(tile); } } } /** Randomly generate mines throughtout the board */ private void MineGenerator () { int i=0; while (i<MINE_NUMBER) { int x=rgen.nextInt(0,TILE_COLUMNS-1); int y=rgen.nextInt(0,TILE_ROWS-1); if (Mines[x][y]!='x') { Mines[x][y]='x'; i++; } } } /** Generates the numbers on each of the tiles throughout the board. Each number denoted the number of mines surrounding * the tile. 0 is not displayed. */ private void NumberGenerator () { for (int i=0;i<TILE_COLUMNS;i++) { for (int j=0;j<TILE_ROWS;j++) { if (Mines[i][j]!='x') Mines [i][j]=(char) (CountSurround (i,j)+48); if (Mines[i][j]=='0') Mines[i][j]=' '; } } } /** Counts the mines surrounding the Tile at [i,j] */ private int CountSurround (int i, int j) { int count=0; if (i+1!=TILE_COLUMNS && Mines [i+1][j]=='x') count++; if (i+1!=TILE_COLUMNS && j+1!=TILE_ROWS && Mines [i+1][j+1]=='x') count++; if (i-1!=-1 && j+1!=TILE_ROWS && Mines [i-1][j+1]=='x') count++; if (i+1!=TILE_COLUMNS && j-1!=-1 && Mines [i+1][j-1]=='x') count++; if (i-1!=-1 && j-1!=-1 && Mines [i-1][j-1]=='x') count++; if (i-1!=-1 && Mines [i-1][j]=='x') count++; if (j+1!=TILE_ROWS && Mines [i][j+1]=='x') count++; if (j-1!=-1 && Mines [i][j-1]=='x') count++; return count; } /** Procedure that is run when mouse is clicked */ public void mouseClicked(MouseEvent e) { if (GAME_LOSS==false && GAME_WIN==false) { GPoint p= new GPoint(e.getPoint()); if (SwingUtilities.isRightMouseButton(e)) { FlagTile (getTileAt (p)); } else if (SwingUtilities.isLeftMouseButton(e)) { GLabel label=getLabelAt(p); if (label!=null && label.getLabel()==""+'#') remove (label); PressTile (getTileAt(p), true); } } } /** Flag the Tile t */ public void FlagTile (Tile t) { if (t.flagged==false) { t.flagged=true; t.setColor (new Color (220,220,220)); GLabel label=new GLabel (""+'#', t.getLocation().getX(),t.getLocation().getY()+TILE_SIDE); label.setFont(new Font("Lucida Grande", Font.BOLD, 3*TILE_SIDE/4)); label.move((TILE_SIDE-label.getWidth())/2 , -2*(TILE_SIDE-label.getHeight())); label.setColor (Color.red); add (label); } else { t.flagged=false; t.setColor (new Color (100,100,100)); remove (getLabelAt(t.getLocation())); } } /** Press the Tile t */ public void PressTile (Tile t, boolean clearblanks) { t.setColor (new Color (200,200,200)); char c=LabelPrinter (t.getLocation()); if (c=='x') { t.setColor (Color.red); BlockAllTiles(); } if (c==' ' && clearblanks==true) clearBlanks ((int) t.getLocation().getX()/TILE_SIDE,(int)t.getLocation().getY()/TILE_SIDE); t.setRaised(false); if (isRemaining()==false) WinSign(); } /** Blocks all tiles when Mine is hit */ public void BlockAllTiles() { GAME_LOSS=true; for (int i=0;i<TILE_COLUMNS;i++) { for (int j=0;j<TILE_ROWS;j++) { Tile t= getTileAt(i,j); t.setColor (Color.red); } } } /** Clear surrounding blank tile if a blank tile is pressed */ public void clearBlanks(int i, int j) { if (i==-1 || i==TILE_COLUMNS || j==-1 || j==TILE_ROWS || getTileAt(i,j).isRaised()==false) return; if (Mines [i][j]!=' ') { PressTile (getTileAt(i,j), false); return; } PressTile (getTileAt(i,j), false); for (int p=-1;p<=1;p++) { for (int q=-1;q<=1;q++) { clearBlanks (i+p,j+q); } } } /** Prints the appropriate Tile label at Gpoint p and returns the character printed */ public char LabelPrinter (GPoint p) { int x=(int) (p.getX()/TILE_SIDE); int y=(int) (p.getY()/TILE_SIDE); GLabel label=new GLabel (""+Mines[x][y], x*TILE_SIDE,(y+1)*TILE_SIDE); label.setFont(new Font("Lucida Grande", Font.BOLD, 3*TILE_SIDE/4)); label.move((TILE_SIDE-label.getWidth())/2 , -2*(TILE_SIDE-label.getHeight())); if (49<=Mines [x][y] && 57>=Mines[x][y]) label.setColor (TileColors[Mines[x][y]-48]); add (label); return Mines[x][y]; } /** Prints the Win Symbol*/ public void WinSign() { for (int i=0;i<TILE_COLUMNS;i++) { for (int j=0;j< TILE_ROWS;j++) { Tile t=getTileAt (i,j); t.setColor(Color.green); if (t.isRaised()) { GLabel g=getLabelAt (t.getLocation()); if (g!=null) g.setLabel ("W"); else { g=new GLabel ("W",t.getLocation().getX(),t.getLocation().getY()+TILE_SIDE); g.setFont(new Font("Lucida Grande", Font.BOLD, 3*TILE_SIDE/4)); g.move((TILE_SIDE-g.getWidth())/2 , -2*(TILE_SIDE-g.getHeight())); add (g); } g.setColor (Color.black); } } } } /** Returns true if there are pressable tiles remaining and false otherwise */ public boolean isRemaining() { for (int i=0;i<TILE_COLUMNS;i++) { for (int j=0;j< TILE_ROWS;j++) { Tile t=getTileAt(i,j); if (t.isRaised()==true) { if (Mines [i][j]=='x') continue; else return true; } } } GAME_WIN=true; return false; } /** Returns the tile at GPoint p */ public Tile getTileAt (GPoint p) { int x=((int)(p.getX()/TILE_SIDE))*TILE_SIDE+1; int y=((int)(p.getY()/TILE_SIDE))*TILE_SIDE+1; GObject g=getElementAt (x,y); return (Tile)g; } /** Returns the tile at the coordinate i,j */ public Tile getTileAt (int i, int j) { int x=i*TILE_SIDE+1; int y=j*TILE_SIDE+1; GObject g=getElementAt (x,y); return (Tile)g; } /** Returns the label at the coordinate i,j.Null, if there is none */ public GLabel getLabelAt (int i, int j) { int x=i*TILE_SIDE+(TILE_SIDE/2); int y=j*TILE_SIDE+(TILE_SIDE/2); GObject g=getElementAt (x,y); if (g instanceof GLabel) return (GLabel)g; return null; } /** Returns the label at the Point p.Null, if there is none */ public GLabel getLabelAt (GPoint p) { int x=((int)(p.getX()/TILE_SIDE))*TILE_SIDE+(TILE_SIDE/2); int y=((int)(p.getY()/TILE_SIDE))*TILE_SIDE+(TILE_SIDE/2); GObject g=getElementAt (x,y); if (g instanceof GLabel) return (GLabel)g; return null; } } /** An instance is a Brick */ class Tile extends G3DRect { public boolean flagged; /** Constructor: a new brick with width w and height h*/ public Tile(double w, double h) { super (w,h); flagged=false; } /** Constructor: a new brick at (x,y) with width w and height h*/ public Tile(double x, double y, double w, double h) { super (x,y,w,h); flagged=false; } }<file_sep>/README.md MinesweeperForJava ================== A quirky little Minesweeper implementation on Java
c52a699606787b22d941a07dd192706ba1e80122
[ "Markdown", "Java" ]
2
Java
AmineBoudaoud/MinesweeperForJava
54cebbe9ec1366433dfe938ba00c79918efc3fb7
f30fc986468ad697bae99b684498ab403d29219d
refs/heads/master
<file_sep># Blacklight Ansible Container *NOTE:* This is used to provision a CENTOS 7 container for use with Blacklight application development ## Instuctions (Substitute BLACKLIGHT_APP with the name of the Blacklight app you wish to use. The app username is the name of your Blacklight app.) If you are working from an existing Git repository, first clone the project: `git clone PROJECT_GIT_URL BLACKLIGHT_APP`, otherwise create the project directory: `mkdir BLACKLIGHT_APP`. To provision the server: - Change your directory to the project directory `cd /PATH/TO/BLACKLIGHT_APP` - Install [ansible-container](https://www.ansible.com/ansible-container). - Clone the blackligh-ansible-container ansible files `git clone https://github.com/skng5/blacklight-ansible-container.git BLACKLIGHT_APP` - `cd BLACKLIGHT_APP` - Change the name of your application in `ansible/container.yml`, `main.yml`, and `playbook.yml`. - Build the container: `ansible-container build` - Run the container: `ansible-container run` - In a separate terminal, log onto the container `docker exec -it ansible_BLACKLIGHT_APP_1 su - BLACKLIGHT_APP` To create a new Blacklight application: - Go to the application directory: `cd /var/www/BLACKLIGHT_APP`. - Create a rails app: `rails new .` - Add the Blacklight and and any other gems you need to the Gemfile. - Build the application: `bundle install`. - Migrate the database: `rake db:migrate` If this is from a cloned repository: - Install the required gems: `bundle install` For both new and cloned projects: - In one terminal or session, start Solr: `solr_wrapper` - In another terminal or session, start the blacklight application: `rails server -b 0.0.0.0` Solr should be accessible at http://localhost:8983 The application should be accessible at http://localhost:3000 <file_sep>#!/bin/bash echo "Press [CTRL+C] to stop.." while : do sleep 60 done
0dbeefffde26441b207c055122b0684213fed985
[ "Markdown", "Shell" ]
2
Markdown
skng5/provision
c751561c0643e374f89fc76787c77b4f6c7db426
5d067702a31ec5418b42bdaa2fea2ed8e8ea3b4c
refs/heads/master
<repo_name>Beteasy/wechat-miniprogram<file_sep>/app_server/hello.py from flask import Flask, request import control import json app = Flask(__name__) @app.route('/predict/', methods=['GET', 'POST']) def predict(): return 'Hello World!' @app.route('/xunlian/', methods=['GET', 'POST']) def xunlian(): return 'Hello World!' if __name__ == '__main__': app.run()<file_sep>/app_server/control/init.py import predict import xunlian <file_sep>/douBanMovies/pages/movies/moviesMore/moviesMore.js // pages/movies/moviesMore/moviesMore.js var app = getApp(); var utils = require("../../../utils/util.js"); Page({ /** * 页面的初始数据 */ data: { movies:[], totalMovies:[], nextIndex:0, isEmpty:true }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { var categoryName = options.categoryName; var publicUrl = app.globalUrl.doubanUrl; var url = ""; this.setData({ categoryName: categoryName }) switch (options.categoryName) { case "正在热映": var url = publicUrl + "/v2/movie/in_theaters"; break; case "即将上映": var url = publicUrl + "/v2/movie/coming_soon"; break; case "TOP250": var url = publicUrl + "/v2/movie/top250"; break; } this.setData({ url: url }) utils.getMovieInfo(url, this.callback); wx.showNavigationBarLoading(); }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { //上啦加载。url的起始位置需要变化 var nextUrl = this.data.url+"?start="+this.data.nextIndex+"&count=20"; utils.getMovieInfo(nextUrl,this.callback); wx.showNavigationBarLoading(); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { var refreshUrl = this.data.url; this.data.totalMovies = []; this.data.isEmpty = true; utils.getMovieInfo(refreshUrl, this.callback); }, callback: function(res) { //处理数据 var movies = []; var totalMovies = []; for (var index in res.subjects) { var subjectItem = res.subjects[index]; var title = subjectItem.title; if (title.length > 6) { title = title.substring(0, 6) + "..."; } var temp = { title: title, movieImage: subjectItem.images.large, id: subjectItem.id, } movies.push(temp); } if(!this.data.isEmpty){ totalMovies = this.data.movies.concat(movies); } else{ totalMovies = movies; this.data.isEmpty = false; } this.setData({ movies: totalMovies }); this.data.nextIndex += 20; wx.hideNavigationBarLoading(); console.log(movies); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { wx.setNavigationBarTitle({ title: this.data.categoryName }) }, movieDetailEvent:function(event){ var id = event.currentTarget.id; wx.navigateTo({ url: '../../moviesDetail/moviesDetail?id='+id }) }, /** * 生命周期函数--监听页面显示 */ onShow: function() { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { } })<file_sep>/cloudDlp/miniprogram/pages/myPage/myNews/myNewsDetail/myNewsDetail.js // pages/myPage/myNews/myNewsDetail/myNewsDetail.js const db = wx.cloud.database(); Page({ /** * 页面的初始数据 */ data: { userName: '', publishDate: '', newsTitle: '', newsContent: '', userHead: '', newsImage: '', id:'' }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { db.collection("userMessage").where({ _id: options.newsId }).get() .then(res => { console.log(res) this.setData({ newsContent: res.data[0].content, newsImage: res.data[0].fileID, newsTitle: res.data[0].title, userHead: res.data[0].userHead, publishDate: res.data[0].publishDate, userName: res.data[0].userName, id:options.newsId }) console.log(this.data.id) }) .catch(err => { console.log(err); }) wx.setNavigationBarTitle({ title: this.data.newsTitle }) }, deleteButtonEvent:function(event){ var that = this; wx.showModal({ title: '提示', content: '删除后此消息将不会被展示', success(res) { if (res.confirm) { // console.log('用户点击确定') // console.log(that.data.id) db.collection("userMessage").doc(that.data.id).remove({ success: res => { wx.showToast({ title: '删除成功', }) }, fail: err => { wx.showToast({ icon: 'none', title: '删除失败', }) } }) //删除图片 wx.cloud.deleteFile({ fileList: [that.data.newsImage] }).then(res => { // handle success console.log(res.fileList) }).catch(error => { // handle error console.log("fialed") }) } else if (res.cancel) { console.log('用户点击取消') } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/pachong/pachong/app-server/color.py def checkcolor(): return [255, 240, 255] def newcolor(): return 255<file_sep>/cloudDlp/miniprogram/pages/fill/fill.js // pages/fill/fill.js const db = wx.cloud.database(); Page({ /** * 页面的初始数据 */ data: { tempFilePaths: '', title:"", content:"", fileID:"", userHeadAndNickname:[], }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { // console.log(options) this.setData({ userHeadAndNickname:options.userInfo.split(",") }) }, inputEvent:function(event){ }, formSubmit:function(event){ // console.log(event); var date = new Date(); var publishDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDate() db.collection('userMessage').add({ data: { publishDate: publishDate, userHead: this.data.userHeadAndNickname[0], userName: this.data.userHeadAndNickname[1], title:event.detail.value.title, content:event.detail.value.content, contentPreview: event.detail.value.content.substring(0,20), fileID: this.data.fileID } }).then(res => { // console.log(res); wx.showToast({ title: '提交成功', }) }).catch(err => { // console.log(err); wx.showToast({ icon: 'none', title: '提交失败', }) }) }, uploadImage: function(event) { var that = this; wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success(res) { // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFilePaths that.setData({ tempFilePaths: tempFilePaths[0] }) // console.log(that.data.tempFilePaths) wx.cloud.uploadFile({ cloudPath: new Date().getTime() + '.png', filePath: that.data.tempFilePaths, // 文件路径 }).then(res => { // get resource ID // console.log(res.fileID) that.setData({ fileID:res.fileID }) }).catch(error => { // handle error console.log(error); }) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { } })<file_sep>/cloudDlp/miniprogram/pages/lostAndFound/lostAndFoundDetail/lostAndFoundDetail.js // pages/lostAndFound/lostAndFoundDetail/lostAndFoundDetail.js const db = wx.cloud.database(); Page({ /** * 页面的初始数据 */ data: { newsData: null, userName: '', publishDate: '', newsTitle: '', newsContent: '', userHead: '', newsImage: '' }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { // var that = this; // console.log("newsId") // console.log(options.newsId) db.collection("userMessage").where({ _id: options.newsId }).get() .then(res => { // console.log(res) // console.log("get information") // console.log(res.data[0]); // var that = this this.setData({ newsContent: res.data[0].content, newsImage:res.data[0].fileID, newsTitle: res.data[0].title, userHead: res.data[0].userHead, publishDate: res.data[0].publishDate, userName: res.data[0].userName, // newsData:res.data[0] }) wx.setNavigationBarTitle({ title: this.data.newsTitle }) }) .catch(err => { console.log(err); }) // console.log("newsData") // console.log(this.data.newsData) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { } })<file_sep>/School/pages/newsData/newsData.js var newsData = [ { "newsId":0, "userHead":"../images/userHead.jpg", "userName":"MR.JOHN", "publishDate": "publishDate", "newsTitle":"消息的标题", "newsImage":"../images/newsImage.jpg", "newsContent":"​网页开发渲染线程和脚本线程是互斥的,这也是为什么长时间的脚本运行可能会导致页面失去响应,而在小程序中,二者是分开的,分别运行在不同的线程中。网页开发者可以使用到各种浏览器暴露出来的 DOM API,进行 DOM 选中和操作。而如上文所述,小程序的逻辑层和渲染层是分开的,逻辑层运行在 JSCore 中,并没有一个完整浏览器对象,因而缺少相关的DOM API和BOM API。这一区别导致了前端开发非常熟悉的一些库,例如 jQuery、 Zepto 等,在小程序中是无法运行的。同时 JSCore 的环境同 NodeJS 环境也是不尽相同,所以一些 NPM 的包在小程序中也是无法运行的", "newsPreview":"网页开发渲染线程和脚本线程是互斥的" }, { "newsId": 1, "userHead": "../images/userHead.jpg", "userName": "MR.JOHN", "publishDate": "publishDate", "newsTitle": "消息的标题", "newsImage": "../images/newsImage.jpg", "newsContent": "​JS-SDK 解决了移动网页能力不足的问题,通过暴露微信的接口使得 Web 开发者能够拥有更多的能力,然而在更多的能力之外,JS-SDK 的模式并没有解决使用移动网页遇到的体验不良的问题。用户在访问网页的时候,在浏览器开始显示之前都会有一个的白屏过程,在移动端,受限于设备性能和网络速度,白屏会更加明显。我们团队把很多技术精力放置在如何帮助平台上的Web开发者解决这个问题。因此我们设计了一个 JS-SDK 的增强版本,其中有一个重要的功能,称之为“微信 Web 资源离线存储", "newsPreview": "JS-SDK 解决了移动网页能力不足的问题" }, ] // 导出模板 module.exports = { newsData:newsData }
80b0c678ae9201009b63514379a92b317f9461c4
[ "JavaScript", "Python" ]
8
Python
Beteasy/wechat-miniprogram
c8e86fb341baa40a70c93648d47ba1267522f3b4
cf6a58377db810c6e8bab9d9b89a5c00ecb8d23f
refs/heads/master
<file_sep>// INSERISCO LA VARIABILE PER IL NOME var nome = prompt('Scrivi il tuo nome'); // INSERISCO LA VARIABILE PER IL COGNOME var cognome = prompt('Scrivi il tuo cognome'); // INSERISCO LA VARIABILE PER IL COLORE var colore = prompt('Scrivi il tuo colore preferito'); //PASSWORD GENERATOR var password = <PASSWORD> + <PASSWORD> + colore + "19"; document.getElementById('password').innerHTML = password; alert('ciao Eli, ciao Enri')
115b48aa571f08455036caac768299e0c303b313
[ "JavaScript" ]
1
JavaScript
FedericaC03/js-pwdgen-wannabe
33986e59e0f97a899f1c8f7d06337c17a71dee15
0370203296e2321e4d30a3ac2aac031dc05ea70c
refs/heads/main
<file_sep> const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; const Render = Matter.Render; const Constraint=Matter.Constraint; var treeObject,groundObject, launcherObject; var mango1,mango2,mango3,mango4,mango5,mango6,mango7,mango8,mango9,mango10; var world,boy; var stoneObject; function preload(){ boy=loadImage("boy.png"); } function setup() { createCanvas(1300, 600); engine = Engine.create(); world = engine.world; stoneObject = new Stone(200,700,10,10); mango1 = new Mango(1080,50,44); mango2 = new Mango(1000,100,44); mango3 = new Mango(1150,110,44); mango4 = new Mango(1200,170,44); mango5 = new Mango(1080,150,44); mango6 = new Mango(900,200,44); mango7 = new Mango(1000,200,44); mango8 = new Mango(1140,200,44); mango9 = new Mango(1250,230,44); mango10 = new Mango(1070,250,44); treeObject=new tree(1050,580); groundObject=new ground(width/2,600,width,20); launcherObject = new Launcher(stoneObject.body,{x:240,y:410}); Engine.run(engine); } function draw() { background(230); textSize(25); text("Press 'Space key' to get a second Chance to Play",50 ,50); image(boy ,200,340,200,300); treeObject.display(); mango1.display(); mango2.display(); mango3.display(); mango4.display(); mango5.display(); mango6.display(); mango7.display(); mango8.display(); mango9.display(); mango10.display(); stoneObject.display(); groundObject.display(); launcherObject.display(); detectollision(stoneObject,mango1); detectollision(stoneObject,mango2); detectollision(stoneObject,mango3); detectollision(stoneObject,mango4); detectollision(stoneObject,mango5); detectollision(stoneObject,mango6); detectollision(stoneObject,mango7); detectollision(stoneObject,mango8); detectollision(stoneObject,mango9); detectollision(stoneObject,mango10); } function mouseDragged() { Matter.Body.setPosition(stoneObject.body,{x:mouseX,y:mouseY}); } function mouseReleased() { launcherObject.fly(); } function detectollision(lstone,lmango){ mangoBodyPosition=lmango.body.position stoneBodyPosition=lstone.body.position var distance=dist(stoneBodyPosition.x, stoneBodyPosition.y, mangoBodyPosition.x, mangoBodyPosition.y) if(distance<=lmango.r+lstone.r) { Matter.Body.setStatic(lmango.body,false); } } function keyPressed(){ if(keyCode === 32){ Matter.Body.setPosition(stoneObject.body,{x:235,y:420}) launcherObject.attach(stoneObject.body); } } <file_sep>class Launcher{ constructor(bodyA,pointB){ var options = { bodyA: bodyA, pointB: pointB, stiffness: 0.004, length: 10 } this.bodyA=bodyA; this.pointB=pointB; this.launcher= Constraint.create(options); World.add(world, this.launcher); } fly(){ this.launcher.bodyA = null; } attach(body) { this.launcher.bodyA = body; } display(){ if(this.launcher.bodyA){ var pointA = this.bodyA.position; var pointB = this.pointB; strokeWeight(4); line(pointA.x, pointA.y, pointB.x, pointB.y); } } };
bf4d4d7d6ce655acc2d9768ec93ece81f4761cb1
[ "JavaScript" ]
2
JavaScript
rag-02/project-28
484f94eb02e0c3764fac8b67f055e55ef01084a8
4a376c4a69adfe4e6bf80d06e652002afc39160e
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Models\Slider; use Illuminate\Database\Events\SchemaLoaded; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Image; class HomeController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $sliders = Slider::paginate(5); return view('admin.slider.index', compact('sliders')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view('admin.slider.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $data = $request->validate([ 'title' => 'required', 'description' => 'required', 'image_path' => 'image|required' ]); $file = $request->file('image_path'); $extension = $file->getClientOriginalExtension(); $uniqueId = hexdec(uniqid()) . '.' . $extension; $imagePath = "sliders/$uniqueId"; Image::make($file)->resize(1920, 1088)->save(storage_path('app/public/' . $imagePath)); // $path = $request->file('image_path')->storeAs('brands',$uniqueId); $slider = new Slider(); $slider->title = $request->title; $slider->description = $request->description; $slider->image_path = $imagePath; $slider->save(); return redirect()->back()->with('success', 'Slider was created successfully!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // $slider = Slider::findOrFail($id); return view('admin.slider.edit', compact('slider')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $data = $request->validate([ 'title' => 'required', 'description' => 'required', ]); $slider = Slider::findOrFail($id); if ($request->hasFile('image_path')) { if (Storage::exists($slider->image_path)) { unlink(public_path('storage/') . $slider->image_path); // Storage::delete($slider->image_path); } $file = $request->file('image_path'); $extension = $file->getClientOriginalExtension(); $uniqueId = hexdec(uniqid()) . '.' . $extension; // $path = $request->file('image_path')->storeAs('brands',$uniqueId); $imagePath = "sliders/$uniqueId"; Image::make($file)->resize(1920, 1800)->save(storage_path('app/public/' . $imagePath)); $slider->title = $request->title; $slider->description = $request->description; $slider->image_path = $imagePath; $slider->save(); return redirect()->back()->with('success', 'Slider was updated successfully!'); } else { $slider->title = $request->title; $slider->description = $request->description; $slider->save(); return redirect()->back()->with('success', 'Slider was updated successfully!'); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // // $slider = Slider::findOrFail($id); // if(Storage::exists($slider->image_path)) // { // Storage::delete($slider->image_path); // } $slider->delete(); return redirect()->back()->with('success', 'Slider was deleted successfully!'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; class PasswordController extends Controller { public function edit() { return view('admin.change_password'); } /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function update(Request $request) { // $validator = Validator::make($request->all(),[ 'old_password' => '<PASSWORD>', 'password' => '<PASSWORD>' ]); $user = Auth::user(); $validator->after(function($validator) use($request, $user){ if(!Hash::check($request->old_password, $user->password)) { $validator->errors()->add('old_password', 'The old password is incorrect'); } }); if($validator->fails()) { return redirect()->back()->withErrors($validator); } else { $user->fill([ 'password' => <PASSWORD>($request->password) ]); $user->save(); return redirect()->back()->with('success', 'Your password has been update successfully!'); } } public function getProfile() { $user = Auth::user(); return view('admin.profile', compact('user')); } public function updateP(Request $request) { $data = $request->validate([ 'name' => 'required', ]); $user = Auth::user(); $user->name = $request->name; $user->save(); $notification = [ 'alert-type' => 'success', 'message' => 'Your profile has been update successfully!' ]; return redirect()->back()->with($notification); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Category; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class CategoryController extends Controller { // public function __construct() { $this->middleware(['verified', 'auth']); } public function index() { $categories = Category::latest()->with('user')->paginate(5); $currentPage = $categories->currentPage(); $trashCategories = Category::onlyTrashed()->latest()->paginate(5); return view('admin.category.index', compact('categories', 'currentPage', 'trashCategories')); } public function store(Request $request) { $data = $request->validate([ 'category' => 'required' ]); $category = Category::make($data); $category->user_id = Auth::id(); $category->save(); return redirect()->back()->with('success', 'Category was added successfully!'); } public function edit(Category $category) { return view('admin.category.edit', compact('category')); } public function update(Request $request, Category $category) { $data = $request->validate([ 'category' => 'required' ]); $category->category = $request->category; $category->save(); return redirect()->back()->with('success', 'Category was updated successfully!'); } public function restore($id) { $category = Category::withTrashed()->findOrFail($id); $category->restore(); return redirect()->back()->with('success', 'Category was restore successfully!'); } public function forceDelete($id) { $category = Category::withTrashed()->findOrFail($id); $category->forceDelete(); return redirect()->back()->with('success', 'Category was delete permantely successfully!'); } public function destroy(Category $category) { $category->delete(); return redirect()->back()->with('success', 'Category was delete successfully!'); } } <file_sep><?php use App\Http\Controllers\AboutController; use App\Http\Controllers\HomeController; use Illuminate\Foundation\Auth\EmailVerificationRequest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Models\User; use App\Http\Controllers\CategoryController; use App\Http\Controllers\BrandController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { $brands = \App\Models\Brand::latest()->get(); $sliders = \App\Models\Slider::all(); $countAbout = \App\Models\HomeAbout::count(); $countAbout = $countAbout == 0 ? 1 : $countAbout; $about = \App\Models\HomeAbout::find(random_int(1,$countAbout)); return view('home', compact('brands', 'sliders', 'about')); }); Route::get('portfolio', function (){ $images = \App\Models\Multipic::all(); return view('portfolio', compact('images')); })->name('portfolio'); Route::get('categories',[CategoryController::class, 'index'])->name('category.index'); Route::post('categories',[CategoryController::class, 'store'])->name('category.store'); Route::get('categories/{category}',[CategoryController::class, 'edit'])->name('category.edit'); Route::patch('categories/{category}',[CategoryController::class, 'update'])->name('category.update'); Route::get('categories/delete/{category}',[CategoryController::class, 'destroy'])->name('category.delete'); Route::get('categories/restore/{category}',[CategoryController::class, 'restore'])->name('category.restore'); Route::get('categories/force-delete/{category}',[CategoryController::class, 'forceDelete'])->name('category.forceDelete'); Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () { $users = User::all(); return view('admin.index', compact('users')); })->name('dashboard'); Route::get('brands/destroy/{id}', [BrandController::class, 'destroy'])->name('brands.destroy'); Route::get('sliders/destroy/{id}', [HomeController::class, 'destroy'])->name('sliders.destroy'); //Route::get('abouts/destroy/{id}', [AboutController::class, 'destroy'])->name('abouts.destroy'); Route::resource('brands',BrandController::class)->except(['destroy']); Route::resource('sliders',HomeController::class)->except(['destroy']); Route::resource('abouts',AboutController::class)->except('destroy'); //Route::resources([ // 'brands' => BrandController::class, // 'sliders' => HomeController::class //]); Route::get('multipics', [BrandController::class, 'getAllImages'])->name('multipic.index'); Route::post('multipics', [BrandController::class, 'storeImages'])->name('multipic.store'); Route::get('/email/verify', function () { return view('auth.verify-email'); })->middleware('auth')->name('verification.notice'); Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) { $request->fulfill(); return redirect('/dashboard'); })->middleware(['auth', 'signed'])->name('verification.verify'); Route::post('/email/verification-notification', function (Request $request) { $request->user()->sendEmailVerificationNotification(); return back()->with('status', 'verification-link-sent'); })->middleware(['auth', 'throttle:6,1'])->name('verification.send'); Route::get('edit-password', [\App\Http\Controllers\PasswordController::class, 'edit'])->name('password.edit'); Route::put('update-password', [\App\Http\Controllers\PasswordController::class, 'update'])->name('password.update'); Route::get('user/profile', [\App\Http\Controllers\PasswordController::class, 'getProfile'])->name('profile.show'); Route::put('user/profile', [\App\Http\Controllers\PasswordController::class, 'updateP'])->name('profile.update'); <file_sep><?php namespace App\Http\Controllers; use App\Models\HomeAbout; use Illuminate\Http\Request; class AboutController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $abouts = HomeAbout::latest()->paginate(5); return view('admin.about.index', compact('abouts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view('admin.about.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $request->validate([ 'title' => 'required', 'short_dis' => 'required', 'long_dis' => 'required' ]); $about = new HomeAbout(); $about->title = $request->title; $about->short_dis = $request->short_dis; $about->long_dis = $request->long_dis; $about->save(); return redirect()->route('abouts.index')->with('success', 'About page was created successfully!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // $about = HomeAbout::findOrFail($id); return view('admin.about.edit', compact('about')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $request->validate([ 'title' => 'required', 'short_dis' => 'required', 'long_dis' => 'required' ]); $about = HomeAbout::findOrFail($id); $about->title = $request->title; $about->short_dis = $request->short_dis; $about->long_dis = $request->long_dis; $about->save(); return redirect()->route('abouts.index')->with('success', 'About page was updated successfully!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Brand; use App\Models\Multipic; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; use Image; class BrandController extends Controller { public function __construct() { $this->middleware(['verified', 'auth']); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $brands = Brand::latest()->paginate(5); return view('admin.brand.index', compact('brands')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $data = $request->validate([ 'image_path' => 'required|image', 'name' => 'required' ]); $file = $request->file('image_path'); $extension = $file->getClientOriginalExtension(); $uniqueId = hexdec(uniqid()).'.'.$extension; $imagePath = "brands/$uniqueId"; Image::make($file)->resize(300, 200)->save(storage_path('app/public/'.$imagePath)); // $path = $request->file('image_path')->storeAs('brands',$uniqueId); $brand = new Brand(); $brand->name = $request->name; $brand->image_path = $imagePath; $brand->save(); return redirect()->back()->with('success', 'Brand was created successfully!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // $brand = Brand::find($id); return view('admin.brand.edit', compact('brand')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $data = $request->validate([ 'name' => 'required' ]); $brand = Brand::find($id); if($request->hasFile('image_path')) { if(Storage::exists($brand->image_path)) { unlink(public_path('storage/').$brand->image_path); // Storage::delete($brand->image_path); } $file = $request->file('image_path'); $extension = $file->getClientOriginalExtension(); $uniqueId = hexdec(uniqid()).'.'.$extension; // $path = $request->file('image_path')->storeAs('brands',$uniqueId); $imagePath = "brands/$uniqueId"; Image::make($file)->resize(300, 200)->save(storage_path('app/public/'.$imagePath)); $brand->name = $request->name; $brand->image_path = $imagePath; $brand->save(); return redirect()->back()->with('success', 'Brand was updated successfully!'); } else { $brand->name = $request->name; $brand->save(); return redirect()->back()->with('success', 'Brand was updated successfully!'); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // $brand = Brand::findOrFail($id); // if(Storage::exists($brand->image_path)) // { // Storage::delete($brand->image_path); // } $brand->delete(); return redirect()->back()->with('success', 'Brand was deleted successfully!'); } public function getAllImages() { $images = Multipic::latest()->paginate(5); return view('admin.multipic.index', compact('images')); } public function storeImages(Request $request) { // dd($request->file('image_path')); $request->validate([ 'image_path' => 'required' ]); $images = $request->file('image_path'); foreach ($images as $image) { $extension = $image->getClientOriginalExtension(); $uniqueId = hexdec(uniqid()).'.'.$extension; $imagePath = "multipic/$uniqueId"; Image::make($image)->resize(300, 200)->save(storage_path('app/public/'.$imagePath)); // $path = $request->file('image_path')->storeAs('brands',$uniqueId); $pic = new Multipic(); $pic->image_path = $imagePath; $pic->save(); } return redirect()->back()->with('success', 'Multipic was created successfully!'); } }
20d6f509aad965c98d31d3736959761483dc9377
[ "PHP" ]
6
PHP
HuyNguyen206/laravel8-training
eeb439c32533bdb4a6a92bc09e4f5d071ee5ba5d
1f46e94b63036c8337d388c0b803484fd172af00
refs/heads/master
<file_sep>/** * Created by donghoon on 2016. 7. 5.. */ import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; @Component({ selector: 'profile', templateUrl: 'build/pages/my-page/profile/profile.html' }) export class ProfilePage { constructor(private navController:NavController) { }; } <file_sep>/** * Created by donghoon on 2016. 7. 9.. */ import {Component} from "@angular/core"; import {TodoService} from "./todo-service"; @Component({ selector: 'todo-input', template: `<div> <input type=""text #myInput/> <button (click)="onClick(myInput.value)">Click me</button> </div>` }) export class TodoInput { constructor(public todoSerivice:TodoService) { } onClick(value) { this.todoSerivice.todos.push(value); console.log(this.todoSerivice.todos); } } <file_sep>/** * Created by donghoon on 2016. 7. 4.. */ import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; import {CardToothpastePage} from './toothpaste/card-toothpaste'; import {CardBabyPowderPage} from './baby-powder/card-baby-powder'; @Component({ selector: "main-card", directives: [CardToothpastePage, CardBabyPowderPage], templateUrl: "build/pages/home/cards/main-card.html" }) export class MainCardPage { constructor(private navController:NavController) { } } <file_sep># watchbaby 1. npm install -g ionic@beta 2. npm install 3. ionic platform add android 4. ionic platform add ios 5. ionic serve -lcs <file_sep>import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; import {HeaderPage} from '../commons/header/header'; @Component({ directives: [HeaderPage], templateUrl: 'build/pages/set-interest/set-interest.html' }) export class SetInterestPage { constructor(private navController: NavController) { } } <file_sep>/** * Created by donghoon on 2016. 7. 4.. */ import {Component} from "@angular/core"; import {Platform} from 'ionic-angular'; @Component({ templateUrl: "build/pages/commons/search/main-search.html" }) export class MainSearchPage { items; isAndroid:boolean = false; constructor(platform:Platform) { this.isAndroid = platform.is('android'); this.initializeItems(); } initializeItems() { this.items = [ "기저귀", "로션", "물티슈", "목욕용품", "베이비 파우더", "분유", "샴푸", "선케어", "유모차", "치약" ]; } getItems(ev) { // Reset items back to all of the items this.initializeItems(); // set val to the value of the ev target var val = ev.target.value; // if the value is an empty string don't filter the items if (val && val.trim() != '') { this.items = this.items.filter((item) => { return (item.toLowerCase().indexOf(val.toLowerCase()) > -1); }) } } } <file_sep>/** * Created by donghoon on 2016. 7. 4.. */ import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; @Component({ selector: "card-baby-powder", templateUrl: "build/pages/home/cards/baby-powder/card-baby-powder.html" }) export class CardBabyPowderPage { private cards; constructor(private navController:NavController) { this.initializeCard(); } initializeCard() { this.cards = [ { title: "<NAME>", date: "November 5, 1955", image: "images/advance-card-bttf.png", description: "Wait a minute. Wait a minute, Doc. Uhhh... Are you telling me that you built a time machine...out of aDeLorean?! Whoa. This is heavy." }, { title: "<NAME>", date: "November 5, 1955", image: "images/advance-card-bttf.png", description: "Wait a minute. Wait a minute, Doc. Uhhh... Are you telling me that you built a time machine...out of aDeLorean?! Whoa. This is heavy." }, { title: "<NAME>", date: "November 5, 1955", image: "images/advance-card-bttf.png", description: "Wait a minute. Wait a minute, Doc. Uhhh... Are you telling me that you built a time machine...out of aDeLorean?! Whoa. This is heavy." }, { title: "<NAME>", date: "November 5, 1955", image: "images/advance-card-bttf.png", description: "Wait a minute. Wait a minute, Doc. Uhhh... Are you telling me that you built a time machine...out of aDeLorean?! Whoa. This is heavy." } ]; } } <file_sep>/** * Created by donghoon on 2016. 7. 5.. */ import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; import {MainSearchPage} from '../search/main-search'; @Component({ selector: 'commons-header', templateUrl: 'build/pages/commons/header/header.html' }) export class HeaderPage { constructor(private navController:NavController) { }; moveSearchPage() { this.navController.push(MainSearchPage); }; } <file_sep>import {Component} from '@angular/core'; import {Platform, ionicBootstrap, MenuController} from 'ionic-angular'; import {StatusBar} from 'ionic-native'; import {HomeTabMenu} from './pages/home/tabs/tabs'; import {MyPage} from './pages/my-page/my-page'; import {LoginPage} from './pages/login/login'; import {SignupPage} from './pages/signup/signup'; import {TodoService} from "./service/todo-service"; @Component({ templateUrl: 'build/app.html' }) export class MyApp { private rootPage:any = HomeTabMenu; private homePage = HomeTabMenu; private myPage = MyPage; private loginPage = LoginPage; private signupPage = SignupPage; constructor(private platform:Platform, private menu:MenuController) { menu.enable(true); platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); }); } openPage(page) { console.log("clicked!" + page); // Reset the nav controller to have just this page // we wouldn't want the back button to show in this scenario this.rootPage = page; // close the menu when clicking a link from the menu this.menu.close(); } } ionicBootstrap(MyApp, [TodoService]); <file_sep>import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; import {MainSlidePage} from './slides/main-slide'; import {MainCardPage} from './cards/main-card'; import {HeaderPage} from '../commons/header/header'; import {TodoInput} from '../../service/todo-input'; @Component({ directives: [HeaderPage, MainSlidePage, MainCardPage, TodoInput], templateUrl: 'build/pages/home/home.html' }) export class HomePage { constructor(private navController:NavController) { }; } <file_sep>/** * Created by donghoon on 2016. 7. 4.. */ import {Component} from "@angular/core"; import {NavController} from 'ionic-angular'; @Component({ selector: "main-slide", templateUrl: "build/pages/home/slides/main-slide.html" }) export class MainSlidePage { private slides; private slideOptions = { initialSlide: 0, autoplay: 3000, pager: true, loop: true }; constructor(private navController:NavController) { this.initializeSlides(); } initializeSlides() { this.slides = [ { title: "Welcome to the Docs!", description: "The <b>Ionic Component Documentation</b> showcases a number of useful components that are included out of the box with Ionic.", image: "images/thumbnail-duckling-1.jpg", }, { title: "What is Ionic?", description: "<b>Ionic Framework</b> is an open source SDK that enables developers to build high quality mobile apps with web technologies like HTML, CSS, and JavaScript.", image: "images/thumbnail-duckling-2.jpg", }, { title: "What is Ionic Platform?", description: "The <b>Ionic Platform</b> is a cloud platform for managing and scaling Ionic apps with integrated services like push notifications, native builds, user auth, and live updating.", image: "images/thumbnail-duckling-3.jpg", } ]; }; } <file_sep>/** * Created by donghoon on 2016. 7. 3.. */ import {Component} from '@angular/core'; import {NavController, NavParams} from 'ionic-angular'; import {ViewController, Platform} from 'ionic-angular'; import {HomePage} from "../../home/home"; import {SetInterestPage} from "../../set-interest/set-interest"; import {LoginPage} from "../../login/login"; import {CategoriesPage} from "../../categories/categories"; import {StoryPage} from "../../story/story"; @Component({ template: ` <ion-tabs class="tabs-basic"> <ion-tab tabTitle="홈" [root]="tabOne"></ion-tab> <ion-tab tabTitle="리뷰" [root]="tabTwo"></ion-tab> <ion-tab tabTitle="카테고리" [root]="tabThree"></ion-tab> <ion-tab tabTitle="스토리" [root]="tabFour"></ion-tab> </ion-tabs> ` }) export class HomeTabMenu { tabOne = HomePage; tabTwo = SetInterestPage; tabThree = CategoriesPage; tabFour = StoryPage; } <file_sep>/** * Created by donghoon on 2016. 7. 5.. */ import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; @Component({ selector: 'review', templateUrl: 'build/pages/my-page/review/review.html' }) export class ReviewPage { constructor(private navController:NavController) { }; } <file_sep>import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; import {HeaderPage} from '../commons/header/header'; import {CardToothpastePage} from '../home/cards/toothpaste/card-toothpaste'; import {CardBabyPowderPage} from '../home/cards/baby-powder/card-baby-powder'; /* Generated class for the CategoriesPage page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ directives: [HeaderPage, CardToothpastePage, CardBabyPowderPage], templateUrl: 'build/pages/categories/categories.html', }) export class CategoriesPage { filter:string = "product"; isAndroid:boolean = false; constructor(platform:Platform) { this.isAndroid = platform.is('android'); } } <file_sep>/** * Created by donghoon on 2016. 7. 4.. */ import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; import {ProfilePage} from './profile/profile'; import {ReviewPage} from './review/review'; @Component({ directives: [ProfilePage, ReviewPage], templateUrl: "build/pages/my-page/my-page.html" }) export class MyPage { review:string = "my"; isAndroid:boolean = false; constructor(platform:Platform) { this.isAndroid = platform.is('android'); } } <file_sep>/** * Created by donghoon on 2016. 7. 9.. */ import {Injectable} from "@angular/core"; @Injectable() export class TodoService{ todos = []; }
06efe13b58c494687b85dac43c708362cb6c3b44
[ "Markdown", "TypeScript" ]
16
TypeScript
devarchi33/watchbaby
9de81ab72df43aa81fd37e8684de86e585416636
9860e0d2145238fb5425d0fec1a0529be231dfef
refs/heads/master
<file_sep># Application to pull streaming data from twitter and determine the sentiment of them. from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import json import sys import webbrowser import codecs import csv from string import punctuation import matplotlib.pyplot as plt import time class tweetlistener(StreamListener): def on_status(self,status): global counter,Total_tweet_count,outfile,search_words_list,indiv,outfile counter += 1 if counter >= Total_tweet_count: search_words_list.pop(0) outfile.close() senti1 = Sentiment() senti1.sentiment_analysis() #time.sleep(15) search_tweets() try: print "----------NEW TWEET ARRIVED!-----------" print "Tweet Text : %s" % status.text outfile.write(status.text) outfile.write(str("\n")) print "Author's Screen name : %s" % status.author.screen_name print "Time of creation : %s" % status.created_at print "Source of Tweet : %s" % status.source except UnicodeEncodeError: print "Skipping a tweet" def on_error(self, status): drawing() print "Too soon reconnected . Will terminate the program" print status sys.exit() class Sentiment(): def sentiment_analysis(self): global file2,indiv,outfile,labels,colors,all_figs pos_sent = open("positive_words.txt").read() positive_words = pos_sent.split('\n') positive_counts = [] neg_sent = open('negative_words.txt').read() negative_words = neg_sent.split('\n') outfile.close() negative_counts = [] conclusion = [] tweets_list = [] tot_pos = 0 tot_neu = 0 tot_neg = 0 all_total = 0 #print file2 tweets = codecs.open(file2, 'r', "utf-8").read() tweet_list_dup = [] tweets_list = tweets.split('\n') #print tweets_list for tweet in tweets_list: positive_counter = 0 negative_counter = 0 tweet = tweet.encode("utf-8") tweet_list_dup.append(tweet) tweet_processed = tweet.lower() for p in list(punctuation): tweet_processed = tweet_processed.replace(p, '') words = tweet_processed.split(' ') word_count = len(words) for word in words: if word in positive_words: positive_counter = positive_counter + 1 elif word in negative_words: negative_counter = negative_counter + 1 positive_counts.append(positive_counter) negative_counts.append(negative_counter) if positive_counter > negative_counter: conclusion.append("Positive") tot_pos += 1 elif positive_counter == negative_counter: conclusion.append("Neutral") tot_neu += 0.5 else: conclusion.append("Negative") tot_neg +=1 #print len(positive_counts) output = zip(tweet_list_dup, positive_counts, negative_counts,conclusion) #output = output.encode('utf-8') print "******** Overall Analysis **************" if tot_pos > tot_neg and tot_pos > tot_neu: print "Overall Sentiment - Positive" elif tot_neg > tot_pos and tot_neg > tot_neu: print "Overall Sentiment - Negative" elif tot_neg == tot_neu and tot_neg > tot_pos: print "Overall Sentiment - Negative" elif tot_pos + tot_neg < tot_neu: print "Overall Sentiment - Semi Positive " else: print "Overall Sentiment - Neutral" print "%%%%%%%%%%%% End of stream - " + indiv + " %%%%%%%%%%%%%%%%%%%%%" file1 = 'tweet_sentiment_' + indiv + '.csv' writer = csv.writer(open(file1, 'wb')) writer.writerows(output) draw_helper = [] draw_helper.append(tot_pos) draw_helper.append(tot_neg) draw_helper.append(tot_neu) draw_helper.append(indiv) all_figs.append(draw_helper) #figs.append(drawing()) def drawing(): global all_figs for one_fig in all_figs: all_total = 0 sentiments = {} sentiments["Positive"] = one_fig[0] sentiments["Negative"] = one_fig[1] sentiments["Neutral"] = one_fig[2] all_total = one_fig[0] + one_fig[1] + one_fig[2] sizes = [] sizes = [sentiments['Positive']/float(all_total), sentiments['Negative']/float(all_total), sentiments['Neutral']/float(all_total)] plt.pie(sizes,labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) plt.axis('equal') plt.title('sentiment for the word - ' + str(one_fig[3])) fig_name = "fig_" + str(one_fig[3]) + ".png" # Save the figures plt.savefig(fig_name) plt.close() plt.show() def main(): global Total_tweet_count,outfile,file,search_words_list,auth,labels,colors,all_figs consumer_key = 'O9KXKiFmfzTNgF0eevXXXX' consumer_secret = '<KEY>' access_token = '<KEY>' access_secret = '<KEY>' search_words = str(raw_input("Enter Search words - separate them by comma: ")) Total_tweet_count = int(raw_input("Enter tweets to be pulled for each search word: ")) #print search_words search_words_list = search_words.split(",") Total_tweet_count = 10 auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) labels = ['Positive','Negative','Neutral'] colors = ['yellowgreen','lightcoral','gold'] all_figs= [] search_tweets() outfile = codecs.open("F:\\test_tweets1.txt", 'w', "utf-8")#iphone def search_tweets(): global search_words_list,counter,auth,indiv,outfile,file2,plt,access consumer_key = 'ZkIxjbsPacixuhTg7aclkQ' consumer_secret = '<KEY>' access_token = '<KEY>' access_secret = '<KEY>' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) #auth.set_access_token(access_token, access_secret) print search_words_list for indiv in search_words_list: #indiv = indiv.split() print "Search Word - " + indiv + " - is being processed" counter = 0 file2 = "test_" + str(indiv[0]) + ".txt" outfile = codecs.open(file2, 'w', "utf-8") twitterStream = Stream(auth, tweetlistener()) one_list = [] one_list.append(indiv) print one_list twitterStream.filter(track=one_list,languages = ["en"]) #for i in range(len(figs)): drawing() sys.exit() main() <file_sep># Twitter_Sentiment_Analysis Application to pull streaming data from twitter and determine the sentiment of them
5b5b6a1b4758539bda29784ac407aa3205894962
[ "Markdown", "Python" ]
2
Python
SevaMahapatra/Twitter_Sentiment_Analysis
4249d80c04ed0f99ad4c62a4333d092433b97dd8
23c4cb5b22de7ec36fc388ecbf089091a4eb84ac
refs/heads/master
<repo_name>icprog/CTRL_IKUN<file_sep>/优课堂/优课堂/Form1.cs using System; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using CCWin; namespace 优课堂 { public partial class Form1 : Form { Sunisoft.IrisSkin.SkinEngine skinEngine = new Sunisoft.IrisSkin.SkinEngine(); List<string> skins; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //加载所有皮肤列表 skins = System.IO.Directory.GetFiles(Application.StartupPath + @"\界面ssk", "*.ssk").ToList(); skins.ForEach(x => { skinDataGridView1.Rows.Add(Path.GetFileNameWithoutExtension(x)); }); skinEngine.SkinFile = skins[38]; skinEngine.Active = true; } private void skinDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (skinDataGridView1.CurrentRow != null) { //加载皮肤 skinEngine.SkinFile = skins[skinDataGridView1.CurrentRow.Index]; skinEngine.Active = true; } } private void skinButton_t_MouseClick(object sender, MouseEventArgs e) { Form form = new Teacher(); this.Hide(); form.ShowDialog(); Application.ExitThread(); } private void skinButton1_Click(object sender, EventArgs e) { DialogResult t = MessageBox.Show("确认退出程序", "提示", MessageBoxButtons.YesNo); if(DialogResult.Yes==t) Application.Exit(); } private void skinButton_S_Click(object sender, EventArgs e) { Form form = new Student(); this.Hide(); form.ShowDialog(); Application.ExitThread(); } private void skinBotton_TF_Click(object sender, EventArgs e) { TFlog tF = new TFlog(); this.Hide(); tF.ShowDialog(); Application.ExitThread(); } } } <file_sep>/优课堂/优课堂/selectData.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; namespace 优课堂 { class selectData { public static DataTable table(string tablename) { string con = PubConstant.ConnectionString; string sql = string.Format("select * from {0}", tablename); SqlConnection connection = new SqlConnection(con); SqlDataAdapter cmd = new SqlDataAdapter(sql, connection); DataSet dataSet = new DataSet(); connection.Open(); cmd.Fill(dataSet); connection.Close(); DataTable dataTable = new DataTable(); dataTable = dataSet.Tables[0]; return dataTable; } public static DataTable table1(string table,string name) { string con = PubConstant.ConnectionString; string sql = string.Format("select * from {0} where 姓名='{1}'", table,name); SqlConnection connection = new SqlConnection(con); SqlDataAdapter cmd = new SqlDataAdapter(sql, connection); DataSet dataSet = new DataSet(); connection.Open(); cmd.Fill(dataSet); connection.Close(); DataTable dataTable = new DataTable(); dataTable = dataSet.Tables[0]; return dataTable; } public static DataTable table2(string sql) { string con = PubConstant.ConnectionString; SqlConnection connection = new SqlConnection(con); SqlDataAdapter cmd = new SqlDataAdapter(sql, connection); DataSet dataSet = new DataSet(); connection.Open(); cmd.Fill(dataSet); connection.Close(); DataTable dataTable = new DataTable(); dataTable = dataSet.Tables[0]; return dataTable; } } } <file_sep>/优课堂/Backup7/Attend_list.cs using System; namespace Maticsoft.Model { /// <summary> /// Attend_list:实体类(属性说明自动提取数据库字段的描述信息) /// </summary> [Serializable] public partial class Attend_list { public Attend_list() {} #region Model private string _stuno; private string _stuname; private string _teacher_name; private string _cousename; private string _attend; /// <summary> /// /// </summary> public string StuNo { set{ _stuno=value;} get{return _stuno;} } /// <summary> /// /// </summary> public string StuName { set{ _stuname=value;} get{return _stuname;} } /// <summary> /// /// </summary> public string Teacher_name { set{ _teacher_name=value;} get{return _teacher_name;} } /// <summary> /// /// </summary> public string CouseName { set{ _cousename=value;} get{return _cousename;} } /// <summary> /// /// </summary> public string Attend { set{ _attend=value;} get{return _attend;} } #endregion Model } } <file_sep>/优课堂/优课堂/Student_user.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; using System.Windows.Forms; namespace 优课堂 { public partial class Student_user : Form { public Student_user() { InitializeComponent(); } string user; public Student_user(string user) { InitializeComponent(); this.user = user; } private void Student_user_Load(object sender, EventArgs e) { string tablename = string.Format("学生用户{0}基本信息", user); if (Class1.ExistsTable(tablename)) { DataTable table = 优课堂.selectData.table(tablename); skinLabel2.Text = table.Rows[0][0].ToString(); skinLabel3.Text = table.Rows[0][1].ToString(); skinLabel4.Text = table.Rows[0][2].ToString(); skinLabel5.Text = table.Rows[0][3].ToString(); skinLabel1.Text = "选择教师及课程、学生姓名查看考勤信息"; } if (skinLabel1.Text == "点击添加个人信息") { Add add = new Add(user); this.Close(); add.ShowDialog(); } } private void skinButton1_Click(object sender, EventArgs e) { try { string tablename = string.Format("{0}{1}{2}课程考勤表", skinWaterTextBox1.Text.ToString(), skinWaterTextBox2.Text.ToString(), skinWaterTextBox4.Text.ToString()); string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); string sql = "select name from sysobjects where xtype='u' order by name"; SqlCommand cmd = new SqlCommand(sql, con); SqlDataReader dr = null; con.Open(); dr = cmd.ExecuteReader(); bool test = false; ; while (dr.Read()) { string str = dr["name"].ToString(); if (str.Contains(string.Format("{0}", skinWaterTextBox1.Text.ToString())) && str.Contains("课程考勤表") && str.Contains(skinWaterTextBox2.Text.ToString())) { test = true; } } if (test == false) { MessageBox.Show("无该教师考勤表"); } if (test == true) { string con1 = PubConstant.ConnectionString; string sql1 = string.Format("select * from {0} where 姓名='{1}'", tablename, skinWaterTextBox3.Text.ToString()); SqlConnection connection = new SqlConnection(con1); SqlDataAdapter cmd1 = new SqlDataAdapter(sql1, connection); DataSet dataSet = new DataSet(); connection.Open(); cmd1.Fill(dataSet); connection.Close(); DataTable dataTable = new DataTable(); dataTable = dataSet.Tables[0]; skinDataGridView1.DataSource = dataTable; } } catch (Exception ex) { MessageBox.Show("请输入完整的学生课程信息"); } } private void skinButton3_Click(object sender, EventArgs e) { DialogResult t = MessageBox.Show("确认退出程序", "提示", MessageBoxButtons.YesNo); if (DialogResult.Yes == t) Application.Exit(); } private void skinButton2_Click(object sender, EventArgs e) { Form form = new Form1(); this.Hide(); form.ShowDialog(); Application.ExitThread(); } } } <file_sep>/优课堂/优课堂/Add_course.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; using System.Windows.Forms; namespace 优课堂 { public partial class Add_course : Form { public Add_course() { InitializeComponent(); } private void skinButton1_Click(object sender, EventArgs e) { try { OpenFileDialog op = new OpenFileDialog(); op.Filter = "Excel(97-2003)文件|*.xls|所有文件|*.*"; op.Title = "打开文件夹"; string path = null; op.InitialDirectory = "d:\\";//最初从D盘开始查找文件,测试文件放置于本文件夹。 op.FilterIndex = 1; if (op.ShowDialog() == DialogResult.OK)//判断路径是否正确 { path = op.FileName; } string name = GetExcelFile.GetFile(path);//获取Excel文件。 string Tsql = "SELECT * FROM [" + name + "]"; DataTable table = ExcelToDataTable.Redatatable(path, Tsql).Tables[0];//将Excel转换为dataset类型并赋值于table Class1 class1 = new Class1(); Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("姓名", "varchar(20)"); dic.Add("课程名", "varchar(20)"); dic.Add("辅导员", "varchar(50)"); string tablename = string.Format("{0}{1}{2}课程考勤表", skinWaterTextBox1.Text.ToString(), skinWaterTextBox2.Text.ToString(), skinWaterTextBox3.Text.ToString()); class1.CreateDataTable("优课堂", tablename, dic, "学号"); string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); con.Open(); for (int i = 1; i < table.Rows.Count; i++) { string sql = string.Format("insert into {4}{5}{6}课程考勤表(学号,姓名,课程名,辅导员) values ('{0}','{1}','{2}','{3}')", table.Rows[i][0], table.Rows[i][1], table.Rows[i][2], table.Rows[i][3], skinWaterTextBox1.Text.ToString(), skinWaterTextBox2.Text.ToString(), skinWaterTextBox3.Text.ToString()); SqlCommand cmd1 = new SqlCommand(sql, con); cmd1.ExecuteNonQuery(); } con.Close(); skinDataGridView1.DataSource = selectData.table(tablename); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void skinButton2_Click(object sender, EventArgs e) { this.Hide(); } private void skinButton3_Click(object sender, EventArgs e) { DialogResult t = MessageBox.Show("确认退出程序", "提示", MessageBoxButtons.YesNo); if (DialogResult.Yes == t) Application.Exit(); } } } <file_sep>/优课堂/优课堂/Teacher.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 优课堂 { public partial class Teacher : Form { int t = 0; public Teacher() { InitializeComponent(); } private void skinButton1_Click(object sender, EventArgs e) { string sql = string.Format("select * from User_Teacher where userName='{0}' and userPassword='{1}'", user.Text.ToString(), password.Text.ToString()); if (skinCode1.CodeStr == skinWaterTextBox1.Text.ToString()) { if (selectData.table2(sql).Rows.Count > 0) { Teacher_zone User = new Teacher_zone(user.Text.ToString()); this.Hide(); User.ShowDialog(); Application.ExitThread(); } else { t++; MessageBox.Show("用户名或密码错误!", "提示"); user.Text = ""; password.Text = ""; if(t > 5) { MessageBox.Show("多次登录失败,可能不存在该用户"); } } } else { MessageBox.Show("验证码错误!", "提示"); skinWaterTextBox1.Text = ""; } } private void skinButton2_Click(object sender, EventArgs e) { Teacher_ZC _ZC = new Teacher_ZC(); this.Hide(); _ZC.ShowDialog(); } } } <file_sep>/优课堂/优课堂/Student.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace 优课堂 { public partial class Student : Form { int t=0; public Student() { InitializeComponent(); } private void skinButton1_Click(object sender, EventArgs e) { User_list user_List = new User_list(); string sql = string.Format("userName='{0}' and userPassword='{1}'", user.Text.ToString(), password.Text.ToString()); int t=user_List.GetRecordCount(sql); if (skinCode1.CodeStr == skinWaterTextBox1.Text.ToString()) { if (t > 0) { Student_user student_User = new Student_user(user.Text.ToString()); this.Hide(); student_User.ShowDialog(); Application.ExitThread(); } else { t++; MessageBox.Show("用户名或密码错误!", "提示"); user.Text = ""; password.Text = ""; if (t > 5) { MessageBox.Show("多次登录失败,可能不存在该用户"); } } } else { MessageBox.Show("验证码错误!", "提示"); skinWaterTextBox1.Text = ""; } } private void skinButton2_Click(object sender, EventArgs e) { Student_ZC _ZC = new Student_ZC(); this.Hide(); _ZC.ShowDialog(); } } } <file_sep>/优课堂/优课堂/Add_teacher.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; using System.Windows.Forms; namespace 优课堂 { public partial class Add_teacher : Form { string user; public Add_teacher(string user) { InitializeComponent(); this.user = user; } private void skinButton1_Click(object sender, EventArgs e) { Class1 class1 = new Class1(); //用一个dictionary类型,来保存 数据库表的字段 和 数据类型 Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("姓名", "varchar(20)"); dic.Add("学院", "varchar(20)"); string tablename = string.Format("教师用户{0}基本信息", user); class1.CreateDataTable("优课堂", tablename, dic, "教工号"); string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); string sql = string.Format("insert into {3}(教工号,姓名,学院) values('{0}','{1}','{2}')", skinWaterTextBox1.Text.ToString(), skinWaterTextBox5.Text.ToString(), skinWaterTextBox4.Text.ToString(), tablename); SqlCommand cmd1 = new SqlCommand(sql, con); con.Open(); int i=cmd1.ExecuteNonQuery(); con.Close(); MessageBox.Show("信息录入成功,请重新登录。"); Teacher teacher = new Teacher(); this.Close(); teacher.ShowDialog(); } } } <file_sep>/优课堂/Backup7/User_list.cs using System; namespace Maticsoft.Model { /// <summary> /// User_list:实体类(属性说明自动提取数据库字段的描述信息) /// </summary> [Serializable] public partial class User_list { public User_list() {} #region Model private string _username; private string _userpassword; /// <summary> /// /// </summary> public string userName { set{ _username=value;} get{return _username;} } /// <summary> /// /// </summary> public string userPassword { set{ _userpassword=value;} get{return _userpassword;} } #endregion Model } } <file_sep>/优课堂/优课堂/TF_ZC.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 优课堂 { public partial class TF_ZC : Form { public TF_ZC() { InitializeComponent(); } private void skinButton2_Click(object sender, EventArgs e) { string sql = string.Format("insert into User_TF(userName,userPassword) values ('{0}','{1}')", user.Text.ToString(), password.Text.ToString()); if (skinWaterTextBox1.Text.ToString() == skinCode1.CodeStr) { if (password.Text.ToString() == skinWaterTextBox2.Text.ToString()) { if (Updatedata.Update1(sql)>0) MessageBox.Show("注册成功!", "提示"); } else { MessageBox.Show("两次密码输入不一致!", "提示"); skinWaterTextBox2.Text = ""; } } else { MessageBox.Show("验证码错误!", "提示"); skinWaterTextBox1.Text = ""; } } private void skinButton1_Click(object sender, EventArgs e) { TFlog tF = new TFlog(); this.Hide(); tF.ShowDialog(); Application.ExitThread(); } } } <file_sep>/优课堂/优课堂/Add.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; using System.Windows.Forms; namespace 优课堂 { public partial class Add : Form { string user; public Add(string user) { InitializeComponent(); this.user = user; } private void skinButton1_Click(object sender, EventArgs e) { Class1 class1 = new Class1(); //用一个dictionary类型,来保存 数据库表的字段 和 数据类型 Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("姓名", "varchar(20)"); dic.Add("专业年级", "varchar(20)"); dic.Add("辅导员", "varchar(20)"); string tablename = string.Format("学生用户{0}基本信息",user); class1.CreateDataTable("优课堂", tablename, dic,"学号"); string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); string sql = string.Format("insert into {4}(学号,姓名,专业年级,辅导员) values('{0}','{1}','{2}','{3}')", skinWaterTextBox1.Text.ToString(), skinWaterTextBox5.Text.ToString(), skinWaterTextBox4.Text.ToString(), skinWaterTextBox2.Text.ToString(),tablename); SqlCommand cmd1 = new SqlCommand(sql, con); con.Open(); cmd1.ExecuteNonQuery(); con.Close(); MessageBox.Show("信息录入成功,请重新登录。"); Student student = new Student(); this.Close(); student.ShowDialog(); } } } <file_sep>/优课堂/Backup3/Teacher_Flist.cs using System; namespace Maticsoft.Model { /// <summary> /// Teacher_Flist:实体类(属性说明自动提取数据库字段的描述信息) /// </summary> [Serializable] public partial class Teacher_Flist { public Teacher_Flist() {} #region Model private string _stuno; private string _stuname; private string _teacher_f; /// <summary> /// /// </summary> public string StuNo { set{ _stuno=value;} get{return _stuno;} } /// <summary> /// /// </summary> public string StuName { set{ _stuname=value;} get{return _stuname;} } /// <summary> /// /// </summary> public string Teacher_F { set{ _teacher_f=value;} get{return _teacher_f;} } #endregion Model } } <file_sep>/优课堂/优课堂/Teacher_ZC.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 优课堂 { public partial class Teacher_ZC : Form { public Teacher_ZC() { InitializeComponent(); } private void skinButton2_Click(object sender, EventArgs e) { string sql = string.Format("insert into User_Teacher(userName,userPassword) values ('{0}','{1}')", user.Text.ToString(), password.Text.ToString()); if (skinWaterTextBox1.Text.ToString() == skinCode1.CodeStr) { if (password.Text.ToString() == skinWaterTextBox2.Text.ToString()) { if (Updatedata.Update1(sql) > 0) MessageBox.Show("注册成功!", "提示"); } else { MessageBox.Show("两次密码输入不一致!", "提示"); skinWaterTextBox2.Text = ""; } } else { MessageBox.Show("验证码错误!", "提示"); skinWaterTextBox1.Text = ""; } } private void skinButton1_Click(object sender, EventArgs e) { Form form = new Teacher(); this.Hide(); form.ShowDialog(); Application.ExitThread(); } } } <file_sep>/优课堂/优课堂/updata_attend.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 优课堂 { public partial class updata_attend : Form { string tablename; public updata_attend(string tablename) { InitializeComponent(); this.tablename = tablename; } private void updata_attend_Load(object sender, EventArgs e) { DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } private void skinButton1_Click(object sender, EventArgs e) { string time = "考勤时间" + skinWaterTextBox2.Text.ToString(); if (skinCheckBox1.Checked == true && skinCheckBox3.Checked == true && skinCheckBox4.Checked==true) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox1.Checked == true && skinCheckBox3.Checked == true ) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox1.Checked == true && skinCheckBox4.Checked == true) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox3.Checked == true && skinCheckBox4.Checked == true) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox1.Checked == true && skinCheckBox3.Checked==false && skinCheckBox4.Checked==false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox1.Text.ToString(), skinWaterTextBox1.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } } if (skinCheckBox3.Checked == true && skinCheckBox1.Checked == false && skinCheckBox4.Checked == false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox3.Text.ToString(), skinWaterTextBox1.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } } if (skinCheckBox4.Checked == true && skinCheckBox1.Checked == false && skinCheckBox3.Checked == false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox4.Text.ToString(), skinWaterTextBox1.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } } } private void skinButton9_Click(object sender, EventArgs e) { this.Hide(); } private void skinButton10_Click(object sender, EventArgs e) { DialogResult t = MessageBox.Show("确认退出程序", "提示", MessageBoxButtons.YesNo); if (DialogResult.Yes == t) Application.Exit(); } } } <file_sep>/优课堂/优课堂/TF.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; using System.Windows.Forms; namespace 优课堂 { public partial class TF : Form { string tablename; public TF() { InitializeComponent(); } private void skinButton1_Click(object sender, EventArgs e) { try { tablename = string.Format("{0}{1}{2}课程考勤表", skinWaterTextBox1.Text.ToString(), skinWaterTextBox2.Text.ToString(), skinWaterTextBox4.Text.ToString()); string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); string sql = "select name from sysobjects where xtype='u' order by name"; SqlCommand cmd = new SqlCommand(sql, con); SqlDataReader dr = null; con.Open(); dr = cmd.ExecuteReader(); bool test = false; ; while (dr.Read()) { string str = dr["name"].ToString(); if (str.Contains(string.Format("{0}", skinWaterTextBox1.Text.ToString())) && str.Contains("课程考勤表") && str.Contains(skinWaterTextBox2.Text.ToString())) { test = true; } } if (test == false) { MessageBox.Show("无该教师考勤表"); } if (test == true) { string con1 = PubConstant.ConnectionString; string sql1 = string.Format("select * from {0} where 姓名='{1}'", tablename, skinWaterTextBox3.Text.ToString()); SqlConnection connection = new SqlConnection(con1); SqlDataAdapter cmd1 = new SqlDataAdapter(sql1, connection); DataSet dataSet = new DataSet(); connection.Open(); cmd1.Fill(dataSet); connection.Close(); DataTable dataTable = new DataTable(); dataTable = dataSet.Tables[0]; skinDataGridView1.DataSource = dataTable; } } catch (Exception ex) { MessageBox.Show("请输入完整的学生课程信息"); } } private void skinButton2_Click(object sender, EventArgs e) { string time = "考勤时间" + skinWaterTextBox5.Text.ToString(); if (skinCheckBox1.Checked == true && skinCheckBox3.Checked == true && skinCheckBox4.Checked == true) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox1.Checked == true && skinCheckBox3.Checked == true) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox1.Checked == true && skinCheckBox4.Checked == true) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox3.Checked == true && skinCheckBox4.Checked == true) { MessageBox.Show("请不要勾选多项"); } if (skinCheckBox1.Checked == true && skinCheckBox3.Checked == false && skinCheckBox4.Checked == false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox1.Text.ToString(), skinWaterTextBox3.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table1(tablename,skinWaterTextBox3.Text.ToString()); skinDataGridView1.DataSource = dataTable; } } if (skinCheckBox3.Checked == true && skinCheckBox1.Checked == false && skinCheckBox4.Checked == false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox3.Text.ToString(), skinWaterTextBox3.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table1(tablename, skinWaterTextBox3.Text.ToString()); skinDataGridView1.DataSource = dataTable; } } if (skinCheckBox4.Checked == true && skinCheckBox1.Checked == false && skinCheckBox3.Checked == false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox4.Text.ToString(), skinWaterTextBox3.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table1(tablename, skinWaterTextBox3.Text.ToString()); skinDataGridView1.DataSource = dataTable; } } } private void skinButton6_Click(object sender, EventArgs e) { Form form = new Form1(); this.Hide(); form.ShowDialog(); Application.ExitThread(); } private void skinButton5_Click(object sender, EventArgs e) { DialogResult t = MessageBox.Show("确认退出程序", "提示", MessageBoxButtons.YesNo); if (DialogResult.Yes == t) Application.Exit(); } } } <file_sep>/优课堂/优课堂/attend_main.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; using System.Windows.Forms; namespace 优课堂 { public partial class attend_main : Form { int i = 0; string tablename = null; string time = null; public attend_main(string tablename,string time) { InitializeComponent(); this.tablename = tablename; this.time = time; } private void attend_main_Load(object sender, EventArgs e) { try { skinButton1.Visible=false; skinButton2.Visible = false; skinButton3.Visible = false; skinButton4.Visible = false; skinLabelallname.Visible = false; skinCheckBox1.Visible = false; skinCheckBox2.Visible = false; skinButton5.Visible = false; skinButton6.Visible = false; skinButton7.Visible = false; skinButton8.Visible = false; time = "考勤时间" + time + "时"; string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); string sql = string.Format("alter table {0} add {1} varchar(50)", tablename, time); SqlCommand cmd = new SqlCommand(sql, con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } catch(Exception ex) { if (ex.ToString().Contains("唯一")) { DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } else { MessageBox.Show(ex.ToString()); } } } private void skinButtonall_Click(object sender, EventArgs e) { skinButton1.Visible = true; skinButton2.Visible = true; skinButton3.Visible = true; skinButton4.Visible = true; skinLabelallname.Visible = true; skinCheckBox1.Visible = true; skinCheckBox2.Visible = true; } private void skinButton1_Click(object sender, EventArgs e) { if (i == 0) { skinLabelallname.Text = skinDataGridView1.Rows[i].Cells["姓名"].Value.ToString(); } if (i >=1 && i != skinDataGridView1.RowCount - 1) { skinLabelallname.Text = skinDataGridView1.Rows[i].Cells["姓名"].Value.ToString(); i--; } if(i== skinDataGridView1.RowCount - 1) { i--; skinLabelallname.Text = skinDataGridView1.Rows[i].Cells["姓名"].Value.ToString(); } } private void skinButton2_Click(object sender, EventArgs e) { if (i < skinDataGridView1.RowCount - 1&& i>=0) { skinLabelallname.Text = skinDataGridView1.Rows[i].Cells["姓名"].Value.ToString(); i++; } else { MessageBox.Show("点名结束"); } } private void skinButton4_Click(object sender, EventArgs e) { if(skinCheckBox1.Checked == true && skinCheckBox2.Checked == true) { MessageBox.Show("请不要勾选两项"); } if (skinCheckBox1.Checked==true) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox1.Text.ToString(), skinLabelallname.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } } if (skinCheckBox2.Checked==true) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox2.Text.ToString(), skinLabelallname.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } } } private void skinButton3_Click(object sender, EventArgs e) { DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; skinButton1.Visible = false; skinButton2.Visible = false; skinButton3.Visible = false; skinButton4.Visible = false; skinLabelallname.Visible = false; skinCheckBox1.Visible = false; skinCheckBox2.Visible = false; skinButton5.Visible = false; skinButton6.Visible = false; skinButton7.Visible = false; skinButton8.Visible = false; } private void skinButtonSJ_Click(object sender, EventArgs e) { skinButton5.Visible = true; skinButton6.Visible = true; skinButton7.Visible = true; skinButton8.Visible = true; skinLabelallname.Visible = true; skinCheckBox1.Visible = true; skinCheckBox2.Visible = true; } private void timer_(object sender, EventArgs e) { Random random = new Random(); int l = random.Next(0, skinDataGridView1.RowCount - 1); skinLabelallname.Text= skinDataGridView1.Rows[l].Cells["姓名"].Value.ToString(); } private void skinButton8_Click(object sender, EventArgs e) { timer1.Start(); } private void skinButton7_Click(object sender, EventArgs e) { timer1.Stop(); } private void skinButton5_Click(object sender, EventArgs e) { if (skinCheckBox1.Checked == true && skinCheckBox2.Checked == true) { MessageBox.Show("请不要勾选两项"); } if (skinCheckBox1.Checked == true && skinCheckBox2.Checked == false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox1.Text.ToString(), skinLabelallname.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } } if (skinCheckBox2.Checked == true && skinCheckBox1.Checked == false) { string sql = string.Format("update {0} set {1}='{2}' where 姓名='{3}'", tablename, time, skinCheckBox2.Text.ToString(), skinLabelallname.Text.ToString()); if (Updatedata.Update1(sql) > 0) { MessageBox.Show("修改成功"); DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; } } } private void skinButton6_Click(object sender, EventArgs e) { DataTable dataTable = selectData.table(tablename); skinDataGridView1.DataSource = dataTable; skinButton1.Visible = false; skinButton2.Visible = false; skinButton3.Visible = false; skinButton4.Visible = false; skinLabelallname.Visible = false; skinCheckBox1.Visible = false; skinCheckBox2.Visible = false; skinButton5.Visible = false; skinButton6.Visible = false; skinButton7.Visible = false; skinButton8.Visible = false; } private void skinButton9_Click(object sender, EventArgs e) { this.Hide(); } private void skinButton10_Click(object sender, EventArgs e) { DialogResult t = MessageBox.Show("确认退出程序", "提示", MessageBoxButtons.YesNo); if (DialogResult.Yes == t) Application.Exit(); } } } <file_sep>/优课堂/优课堂/TFlog.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 优课堂 { public partial class TFlog : Form { int t = 0; public TFlog() { InitializeComponent(); } private void skinButton1_Click(object sender, EventArgs e) { string sql = string.Format("select * from User_TF where userName='{0}' and userPassword='{1}'", user.Text.ToString(), password.Text.ToString()); if (skinCode1.CodeStr == skinWaterTextBox1.Text.ToString()) { if (selectData.table2(sql).Rows.Count > 0) { TF tF = new TF(); this.Hide(); tF.ShowDialog(); Application.ExitThread(); } else { t++; MessageBox.Show("用户名或密码错误!", "提示"); user.Text = ""; password.Text = ""; if (t > 5) { MessageBox.Show("多次登录失败,可能不存在该用户"); } } } else { MessageBox.Show("验证码错误!", "提示"); skinWaterTextBox1.Text = ""; } } private void skinButton2_Click(object sender, EventArgs e) { TF_ZC _ZC = new TF_ZC(); this.Hide(); _ZC.ShowDialog(); } } } <file_sep>/优课堂/优课堂/update.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; namespace 优课堂 { class Updatedata { public static int Update1(string sql) { string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); SqlCommand cmd = new SqlCommand(sql, con); con.Open(); int t = cmd.ExecuteNonQuery(); con.Close(); return t; } public static int Update2(string sql) { string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); SqlCommand cmd = new SqlCommand(sql, con); con.Open(); int t = cmd.ExecuteNonQuery(); con.Close(); return t; } } } <file_sep>/优课堂/setDatabase/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; namespace 优课堂 { public class Class1 { public static bool ExistsTable(string tablename) { /// <summary> /// 判断数据库表是否存在,返回页头,通过指定专用的连接字符串,执行一个不需要返回值的SqlCommand命令。 /// </summary> /// <param name="tablename">bhtsoft表</param> /// <returns></returns> string ConnectionString = PubConstant.ConnectionString; string tableNameStr = "select count(1) from sysobjects where name = '" + tablename + "'"; using (SqlConnection con = new SqlConnection(ConnectionString)) { con.Open(); SqlCommand cmd = new SqlCommand(tableNameStr, con); int result = Convert.ToInt32(cmd.ExecuteScalar()); if (result == 0) { return false; } else { return true; } } } public void CreateDataTable(string db, string dt, Dictionary<string, string> dic,string Key) { string connToMaster = PubConstant.ConnectionString; //如果数据库表存在,则抛出错误 if (ExistsTable(dt) == true) { throw new Exception("数据库表已经存在!"); } else//数据表不存在,创建数据表 { //拼接字符串,(该串为创建内容) string content = string.Format("{0} varchar(20) primary key ",Key); //取出dic中的内容,进行拼接 List<string> test = new List<string>(dic.Keys); for (int i = 0; i < dic.Count(); i++) { content = content + " , " + test[i] + " " + dic[test[i]]; } //其后判断数据表是否存在,然后创建数据表 string createTableStr = "use " + db + " create table " + dt + " (" + content + ")"; SqlConnection con = new SqlConnection(connToMaster); SqlCommand cmd = new SqlCommand(createTableStr, con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } } <file_sep>/优课堂/优课堂/Student_ZC.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Maticsoft.Model; namespace 优课堂 { public partial class Student_ZC : Form { public Student_ZC() { InitializeComponent(); } private void skinButton2_Click(object sender, EventArgs e) { User_list user_List = new User_list(); Maticsoft.Model.User_list _List = new Maticsoft.Model.User_list(); _List.userName = user.Text.ToString(); _List.userPassword = <PASSWORD>(); if (skinWaterTextBox1.Text.ToString() == skinCode1.CodeStr) { if (password.Text.ToString() == skinWaterTextBox2.Text.ToString()) { if (user_List.Add(_List)) MessageBox.Show("注册成功!", "提示"); } else { MessageBox.Show("两次密码输入不一致!", "提示"); skinWaterTextBox2.Text = ""; } } else { MessageBox.Show("验证码错误!", "提示"); skinWaterTextBox1.Text = ""; } } private void skinButton1_Click(object sender, EventArgs e) { Form form = new Student(); this.Hide(); form.ShowDialog(); Application.ExitThread(); } } } <file_sep>/优课堂/优课堂/Teacher_zone.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility; using System.Data; using System.Windows.Forms; namespace 优课堂 { public partial class Teacher_zone : Form { public Teacher_zone() { InitializeComponent(); } string user; public Teacher_zone(string user) { InitializeComponent(); this.user = user; } private void Teacher_zone_Load(object sender, EventArgs e) { string tablename = string.Format("教师用户{0}基本信息", user); if (Class1.ExistsTable(tablename)) { DataTable table = 优课堂.selectData.table(tablename); skinLabel2.Text = table.Rows[0][0].ToString(); skinLabel3.Text = table.Rows[0][1].ToString(); skinLabel4.Text = table.Rows[0][2].ToString(); skinLabel1.Text = "CTRL_IKUN团队"; } if (skinLabel1.Text == "点击添加个人信息") { Add_teacher add = new Add_teacher(user); this.Close(); add.ShowDialog(); } } private void skinButton1_Click(object sender, EventArgs e) { Add_course add_Course = new Add_course(); add_Course.Show(); } private void skinButton2_Click(object sender, EventArgs e) { skinComboBox1.Items.Clear(); string cons = PubConstant.ConnectionString; SqlConnection con = new SqlConnection(cons); string sql = "select name from sysobjects where xtype='u' order by name"; SqlCommand cmd = new SqlCommand(sql, con); SqlDataReader dr = null; con.Open(); dr = cmd.ExecuteReader(); bool test = false; ; while (dr.Read()) { string str = dr["name"].ToString(); if (str.Contains(string.Format("{0}", skinLabel3.Text.ToString())) && str.Contains("课程考勤表")) { int index = this.skinDataGridView1.Rows.Add(); skinDataGridView1.Rows[index].Cells["Column1"].Value = str; test = true; skinComboBox1.Items.Add(str.ToString()); } } if(test==false) { MessageBox.Show("请导入课程表"); } } private void skinButton3_Click(object sender, EventArgs e) { if (skinComboBox1.Text.ToString().Contains("考勤表")) { string time = dateTimePicker1.Text.ToString() + dateTimePicker1.Value.Hour.ToString(); attend_main _Main = new attend_main(skinComboBox1.Text.ToString(),time); _Main.ShowDialog(); } else { MessageBox.Show("请选择课程。"); } } private void skinButton4_Click(object sender, EventArgs e) { if (skinComboBox1.Text.ToString().Contains("考勤表")) { updata_attend updata_Attend = new updata_attend(skinComboBox1.Text.ToString()); updata_Attend.ShowDialog(); } else { MessageBox.Show("请选择课程。"); } } private void skinButton6_Click(object sender, EventArgs e) { Form form = new Form1(); this.Hide(); form.ShowDialog(); Application.ExitThread(); } private void skinButton5_Click(object sender, EventArgs e) { DialogResult t = MessageBox.Show("确认退出程序", "提示", MessageBoxButtons.YesNo); if (DialogResult.Yes == t) Application.Exit(); } } }
6464bc42cbe1e990ca90ed825840f06d16e89275
[ "C#" ]
21
C#
icprog/CTRL_IKUN
8c0ed256519c8d65c6e2c451a33712ab5143f61f
ed3608171fcf9ec90f514f317fd585d464983b58
refs/heads/master
<file_sep>from argparse import ArgumentParser from uuid import uuid4 from flask import Flask, jsonify, request from myBlockChain import BlockChain app = Flask(__name__) blockchain = BlockChain() node_identifier = str(uuid4()).replace('-', '') @app.route('/index', methods=['GET']) def index(): return "Hello BlockChain" @app.route('/transactions/new', methods=['POST']) def new_transaction(): values = request.get_json() print(values) require = ["sender", "recipient", "amount"] if values is None: return "Missing values", 400 if not all(k in values for k in require): return "Missing values", 400 index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {"message": f'Transaction added to Block {index}'} return jsonify(response), 201 @app.route('/mine', methods=['GET']) def mine(): last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) blockchain.new_transaction(sender="0", recipient=node_identifier, amount=1) block = blockchain.new_block(proof, None) response = { "message": "new block forged", 'index': block['index'], 'transactions': block['transactions'], 'proof': block['proof'], 'previous_hash': block['previous_hash'] } print(response) return jsonify(response), 200 @app.route('/chain', methods=['GET']) def full_chain(): response = { 'chain': blockchain.chain, 'length': len(blockchain.chain) } return jsonify(response), 200 @app.route('/nodes/register', methods=['POST']) def register_nodes(): values = request.get_json() nodes = values.get("nodes") if nodes is None: return "error: not a valid nodes", 400 for node in nodes: blockchain.register_node(node) response = { "message": "new nodes have been added", "total_node": list(blockchain.nodes) } return jsonify(response), 200 @app.route('/nodes/resolve', methods=['GET']) def consensus(): replaced = blockchain.resolve_conflicts() response = { 'new_chain': blockchain.chain, 'replaced': replaced } return jsonify(response), 200 if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on') args = parser.parse_args() port = args.port app.run(host='127.0.0.1', port=port, debug=True)
e3cc2cbd7893622be06c6d73a19c70421aeb823f
[ "Python" ]
1
Python
travis-joe/immoc-blockchain
fb724e6b029cdbf19c666b524e5226ed020fa145
82cdaa93a78150ae6f86939acc0997955c66bea6
refs/heads/master
<repo_name>JonasXPX/Projeto-AJKN<file_sep>/README.md "# Projeto-AJKN" <file_sep>/leitor_firebase.ino #include <Adafruit_Fingerprint.h> #include <ESP8266HTTPClient.h> #include <ESP8266WiFi.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> SoftwareSerial serial(14, 12); //D5 D6 Adafruit_Fingerprint finger = Adafruit_Fingerprint(&serial); const String address = "192.168.43.78"; LiquidCrystal_I2C lcd(0x27, 16, 2); String msgDeErro; String bemVindoMsg; void setup() { Serial.begin(9600); finger.begin(57600); lcd.init(); lcd.backlight(); while (1) { if (finger.verifyPassword()) { setMensagem(0,0, "Leitor biometrico encontrado"); break; } else { Serial.println("Leitor Biometrico nao encontrado"); } } WiFi.begin("AJKN", "hackme"); setMensagem(0,0, "Conectando..."); Serial.println("Conectando à rede"); while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } String ip = WiFi.localIP().toString(); setMensagem(0,0, "Conectado! IP: " + ip); Serial.print("Conectado! Seu IP é:"); Serial.println(WiFi.localIP()); bemVindoMsg = getMensagemFromServer("bemvindo"); // cadastrar = getMensagemFromServer("cadastrar"); } void loop() { int saida = aguardarIdParaRegistro(); if (saida == -1) { } Serial.print("> " + String(saida)); if (saida >= 1) { int error; int out = registrar(saida); Serial.print("Registro concluido: "); Serial.println((error = getErrorByCode(out))); if(msgDeErro != ""){ setMensagem(0,0, msgDeErro); delay(2000); } msgDeErro = ""; if (error == 0) { enviarRegistro(saida); setMensagem(0, 0, "CADASTRO CONCLUIDO"); Serial.println("Registro enviado."); delay(1000); } } int fingerID = getFinger(); if (fingerID != -1) { sendReadFinger(fingerID); } setMensagem(0, 0, bemVindoMsg); delay(500); } int getFinger() { uint8_t p = finger.getImage(); if (p != FINGERPRINT_OK) return -1; p = finger.image2Tz(); if (p != FINGERPRINT_OK) return -1; p = finger.fingerFastSearch(); if (p != FINGERPRINT_OK) return -1; return finger.fingerID; } /** * Caso leia uma digital, * Enviar o ID capturado para * o servidor. * Para fazer logs, e registrar * a entrada do aluno */ int sendReadFinger(int id) { HTTPClient http; http.begin("http://" + String(address) + "/api/senddata/" + String(id)); http.addHeader("Content-Type", "application/json"); int httpCode = http.POST("{\"id\": \"" + String(id) + "\"}"); http.end(); return httpCode; } /** * Enviar o cadastro do ID da digital * Para o servidor */ String enviarRegistro(int id) { HTTPClient http; http.begin("http://" + String(address) + "/api/registrar/" + String(id)); http.addHeader("Content-Type", "application/json"); http.POST(""); return http.getString(); } /** * Fica escutando o servidor, * Caso o adminstrador envie uma requisição para * cadastrar uma nova digital. */ int aguardarIdParaRegistro() { String saida = "-1"; HTTPClient http; http.begin("http://" + String(address) + "/api/registrar"); int code = http.GET(); if (code < 0) { return -1; } String retorno = http.getString(); http.end(); return retorno.toInt(); } int registrar(int saida) { setMensagem(0, 0, "COLOQUE SUA DIGITAL NO LEITOR"); Serial.print("Registrando Digital na ID "); Serial.println(saida); int p = -1; while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: break; } } p = finger.image2Tz(1); switch (p) { case FINGERPRINT_OK: break; default: Serial.println("Erro image2Tz(1)"); return p; } Serial.println("Retire o dedo"); setMensagem(0,0, "RETIRE O DEDO"); delay(3000); p = 0; while (p != FINGERPRINT_NOFINGER) { p = finger.getImage(); } p = -1; Serial.println("Coloque o mesmo dedo novamente"); setMensagem(0,0, "INSIRA O DEDO"); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: break; case FINGERPRINT_NOFINGER: break; default: Serial.println("Error getImage(2)"); break; } } p = finger.image2Tz(2); switch (p) { case FINGERPRINT_OK: break; default: Serial.println("Error image2Tz(2)"); return p; } p = finger.createModel(); if (p != FINGERPRINT_OK) { Serial.println("Error on createModel()"); return p; } p = finger.storeModel(saida); if (p != FINGERPRINT_OK) { Serial.println("Error on storeModel()"); return p; } } int getErrorByCode(int code) { int error = 0; switch (code) { case FINGERPRINT_IMAGEMESS: Serial.println("Imagem muito confusa"); msgDeErro = "Imagem muito confusa"; error = 1; break; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Erro ao se comunicar"); msgDeErro = "Erro ao se comunicar"; error = 1; break; case FINGERPRINT_FEATUREFAIL | FINGERPRINT_INVALIDIMAGE: Serial.println("Nao foi possível encontrar características da impressao digital"); msgDeErro = "Digital sem nao encontrada."; error = 1; break; case FINGERPRINT_ENROLLMISMATCH: Serial.println("Digital nao corresponde"); msgDeErro = "Digital nao corresponde"; error = 1; break; case FINGERPRINT_BADLOCATION: Serial.println("Impossível Armazenar dados"); msgDeErro = "Impossível Armazenar dados"; error = 1; break; case FINGERPRINT_FLASHERR: Serial.println("Erro ao salvar na memoria"); msgDeErro = "Erro ao salvar na memoria"; error = 1; break; case FINGERPRINT_IMAGEFAIL: Serial.println("Erro ao capturar imagem"); msgDeErro = "Erro ao capturar imagem"; error = 1; break; } return error; } String getMensagemFromServer(String param) { HTTPClient http; http.begin("http://" + String(address) + "/api/getmensagem/" + String(param)); http.GET(); String msg = http.getString(); http.end(); return msg; } void setMensagem(int pos1, int pos2, String msg) { limparLcd(); String msg1, msg2; if(msg.length() >= 16) { msg1 = msg.substring(0, 15); msg2 = msg.substring(15, msg.length()); } else { msg1 = msg; } lcd.setCursor(pos1,pos2); lcd.print(msg1); if(msg.length() >= 16) { lcd.setCursor(0, 1); lcd.print(msg2); } } void limparLcd(){ lcd.setCursor(0,0); lcd.print(" "); delay(25); lcd.setCursor(0,1); lcd.print(" "); delay(25); }
5d128a65f5f91febf9c74db7e6678c130024c3d8
[ "Markdown", "C++" ]
2
Markdown
JonasXPX/Projeto-AJKN
a3e3a9a3bdfdff595f8c80a9b4c24e08f835312a
92f734d8f86c4023b9aa6939c631e72126197052
refs/heads/master
<file_sep> import java.io.FileInputStream; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class Repository { private Member member; private Staff staff; private Properties p = new Properties(); public Repository() { try { p.load(new FileInputStream("src/bgetesting/Settings.properties")); Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { e.printStackTrace(); } } public void insertNote(String notes, int memberId, int staffId) { String query = "insert into notes(notes, dateNotes, memberId, staffId) values (?, ?, ?, ?)"; try (Connection con = DriverManager.getConnection(p.getProperty("connectionString"), p.getProperty("name"), p.getProperty("password")); PreparedStatement insertNotes = con.prepareStatement(query)) { insertNotes.setString(1, notes); insertNotes.setTimestamp(2, new Timestamp(System.currentTimeMillis())); insertNotes.setInt(3, memberId); insertNotes.setInt(4, staffId); insertNotes.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public List<Staff> getStaffMembers() { List<Staff> staff = new ArrayList<>(); try (Connection con = DriverManager.getConnection(p.getProperty("connectionString"), p.getProperty("name"), p.getProperty("password")); PreparedStatement memberStmt = con.prepareStatement("select * from staff")) { ResultSet rs = memberStmt.executeQuery(); while (rs.next()) { Staff temp = new Staff(); temp.setForename(rs.getString("forename")); temp.setSurname(rs.getString("surname")); temp.setIdNumber(rs.getString("idNumber")); temp.setId(rs.getInt("id")); staff.add(temp); } } catch (SQLException e) { e.printStackTrace(); } return staff; } public List<Member> getMembers() { List<Member> members = new ArrayList<>(); try (Connection con = DriverManager.getConnection(p.getProperty("connectionString"), p.getProperty("name"), p.getProperty("password")); PreparedStatement memberStmt = con.prepareStatement("select * from member")) { ResultSet rs = memberStmt.executeQuery(); while (rs.next()) { Member temp = new Member(); temp.setForename(rs.getString("forename")); temp.setSurname(rs.getString("surname")); temp.setIdNumber(rs.getString("idNumber")); temp.setId(rs.getInt("id")); members.add(temp); } } catch (SQLException e) { e.printStackTrace(); } return members; } public void displayPass() { String query = "select member.forename, workOutSession.startTime, hall.hallName, activity.activity\n" + "from member\n" + "right join attendance\n" + "on attendance.memberId = member.Id\n" + "inner join workOutSession\n" + "on workOutSession.id = attendance.workOutSessionId\n" + "inner join hall\n" + "on hall.id = workOutSession.hallId\n" + "inner join activity\n" + "on activity.id = workOutSession.activityid;"; try (Connection con = DriverManager.getConnection(p.getProperty("connectionString"), p.getProperty("name"), p.getProperty("password")); PreparedStatement memberStmt = con.prepareStatement(query)) { ResultSet rs = memberStmt.executeQuery(); System.out.printf("%-8s | %-21s | %-11s | %s\n", "Namn", "Starttid", "Hall", "Aktivitet"); createLine(); while (rs.next()) { String name = rs.getString("forename"); String startTime = rs.getString("startTime"); String hall = rs.getString("hallName"); String activity = rs.getString("activity"); System.out.printf("%-8s | %-21s | %-11s | %s\n", name, startTime, hall, activity); } createLine(); } catch (SQLException e) { e.printStackTrace(); } } public void displayNotes() { String query = "select member.forename as Medlem, notes, staff.forename as Personlig_Tränare from member" + "\ninner join notes" + "\non notes.memberId = member.id" + "\ninner join staff" + "\non notes.staffId = staff.id;"; try (Connection con = DriverManager.getConnection(p.getProperty("connectionString"), p.getProperty("name"), p.getProperty("password")); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query)) { System.out.printf("%-7s | %-32s | %s\n", "Namn", "Notering", "Tränare"); createLine(); while (rs.next()) { String member = rs.getString("Medlem"); String notes = rs.getString("notes"); String staff = rs.getString("Personlig_Tränare"); System.out.printf("%-7s | %-32s | %s\n", member, notes, staff); } createLine(); } catch (Exception e) { e.printStackTrace(); } } public void setMember(Member member) { this.member = member; } public Member getMember() { return member; } public void setStaff(Staff staff) { this.staff = staff; } public Staff getStaff() { return staff; } private void createLine() { System.out.println("---------------------------------------------------------"); } }
2ca0f63663f4b3e7aafd0ee0aa5be29ef6c40311
[ "Java" ]
1
Java
RichardHags/SQLBestGymEver
b79cd5ba2d68d6ea5af450a390c22cae4b866a1c
e41e93a27e8aff88a265874346c692ae164f5b25
refs/heads/master
<file_sep>import { AuthState, BurgerBuilderState, OrderState, } from '@nx-react-burger-app/shared/interfaces'; export interface State { burgerBuilder: BurgerBuilderState; order: OrderState; auth: AuthState; } <file_sep>import axios from 'axios'; export const loadIngredients = () => { return axios.get( 'https://react-burger-app-b0d49.firebaseio.com/ingredients.json' ); }; <file_sep>export * from './lib/burger-builder-data-access'; export * from './lib/burger-builder.reducer'; export * from './lib/burger-builder.sagas'; export * from './lib/burger-builder.actions'; <file_sep>export interface BurgerBuilderState { ingredients: Ingredient; totalPrice: number; error: Error; building: boolean; } export type Ingredient = { [key in Ingredients]: number; }; export enum Ingredients { SALAD = 'salad', CHEESE = 'cheese', MEAT = 'meat', BACON = 'bacon', } export enum BurgerBuilderActions { ADD_INGREDIENT = '[Burger Builder] Add Ingredient', REMOVE_INGREDIENT = '[Burger Builder] Remove Ingredient', LOAD_INGREDIENTS = '[Burger Builder] Load Ingredients', LOAD_INGREDIENTS_SUCCESS = '[Burger Builder] Load Ingredients Success', LOAD_INGREDIENTS_FAILURE = '[Burger Builder] Load Ingredients Failure', } export interface AddIngredient { type: typeof BurgerBuilderActions.ADD_INGREDIENT; ingredientName: Ingredients; } export interface RemoveIngredient { type: typeof BurgerBuilderActions.REMOVE_INGREDIENT; ingredientName: Ingredients; } export interface LoadIngredients { type: typeof BurgerBuilderActions.LOAD_INGREDIENTS; } export interface LoadIngredientsSuccess { type: typeof BurgerBuilderActions.LOAD_INGREDIENTS_SUCCESS; ingredients: Ingredient; } export interface LoadIngredientsFailure { type: typeof BurgerBuilderActions.LOAD_INGREDIENTS_FAILURE; error: Error; } export type BurgerBuilderActionTypes = | AddIngredient | RemoveIngredient | LoadIngredients | LoadIngredientsSuccess | LoadIngredientsFailure; <file_sep>import { OrderState } from '@nx-react-burger-app/shared/interfaces'; import produce from 'immer'; const initialState: OrderState = { orders: [], loaded: false, purchased: false, }; export const OrderReducer = produce((state = initialState, action) => { return state; }); <file_sep>export * from './lib/auth-feature-auth'; <file_sep>import { NavLink } from 'react-router-dom'; import styled from 'styled-components'; export const NavigationItem = styled.li` margin: 10px 0; box-sizing: border-box; display: block; width: 100%; `; const activeClassName = 'nav-item-active'; export const StyledNavLink = styled(NavLink).attrs({ activeClassName, })` color: #8f5c2c; text-decoration: none; width: 100%; box-sizing: border-box; display: block; &.${activeClassName} { color: #40a4c8; } &:hover { color: #40a4c8; } `; <file_sep>export * from './lib/burger-builder.interfaces'; export * from './lib/store.interfaces'; export * from './lib/order.interfaces'; export * from './lib/auth.interfaces'; <file_sep>import styled from 'styled-components'; export const ButtonContainer = styled.button` background-color: transparent; border: none; color: white; outline: none; cursor: pointer; font: inherit; padding: 10px; margin: 10px; font-weight: bold; &:first-of-type { margin-left: 0; padding-left: 0; } `; export const ButtonSuccess = styled(ButtonContainer)` color: #5c9210; `; export const ButtonDanger = styled(ButtonContainer)` color: #944317; `; <file_sep>import { watchBurgerBuilder } from '@nx-react-burger-app/burger-builder/data-access'; import { watchOrders } from '@nx-react-burger-app/order/data-access'; import { all, fork } from 'redux-saga/effects'; export const rootSaga = function* root() { yield all([fork(watchBurgerBuilder), fork(watchOrders)]); }; <file_sep>export * from './lib/order-feature-order'; <file_sep>export interface AuthState { token: string; userId: string; error: Error; loaded: boolean; } <file_sep>import { LoadOrders, LoadOrdersFailure, LoadOrdersSuccess, Order, OrderActions, PurchaseBurger, PurchaseBurgerFailure, PurchaseBurgerSuccess, } from '@nx-react-burger-app/shared/interfaces'; export const purchaseBurger = (): PurchaseBurger => { return { type: OrderActions.PURCHASE_BURGER, }; }; export const purchaseBurgerSuccess = ( orderId: number, orders: [] ): PurchaseBurgerSuccess => { return { type: OrderActions.PURCHASE_BURGER_SUCCESS, orders, orderId, }; }; export const purchaseBurgerFailure = (error: Error): PurchaseBurgerFailure => { return { type: OrderActions.PURCHASE_BURGER_FAILURE, error, }; }; export const loadOrders = (token: string, userId: string): LoadOrders => { return { type: OrderActions.LOAD_ORDERS, token, userId, }; }; export const loadOrdersSuccess = (orders: Order[]): LoadOrdersSuccess => { return { type: OrderActions.LOAD_ORDERS_SUCCESS, orders, }; }; export const loadOrdersFailure = (error: Error): LoadOrdersFailure => { return { type: OrderActions.LOAD_ORDERS_FAILURE, error, }; }; <file_sep>import { State } from '@nx-react-burger-app/shared/interfaces'; import { applyMiddleware, combineReducers, compose, createStore } from 'redux'; import createSagaMiddleware from 'redux-saga'; import { BurgerBuilderReducer } from '@nx-react-burger-app/burger-builder/data-access'; import { OrderReducer } from '@nx-react-burger-app/order/data-access'; import { AuthReducer } from '@nx-react-burger-app/auth/data-access'; import { rootSaga } from './root.sagas'; export const rootReducers = combineReducers<State>({ burgerBuilder: BurgerBuilderReducer, order: OrderReducer, auth: AuthReducer, }); const sagaMiddleware = createSagaMiddleware(); const composeEnhancer = (process.env.NODE_ENV !== 'production' && window['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__']) || compose; export const store = createStore( rootReducers, {}, composeEnhancer(applyMiddleware(sagaMiddleware)) ); sagaMiddleware.run(rootSaga); <file_sep>import styled from 'styled-components'; export const DrawerToggleContainer = styled.div` width: 40px; height: 100%; display: flex; flex-flow: column; justify-content: space-between; align-items: center; padding: 10px 0; box-sizing: border-box; cursor: pointer; background-color: white; @media (min-width: 500px) { display: none; } `; <file_sep>import styled from 'styled-components'; export const LogoContainer = styled.div` background-color: white; padding: 8px; height: 100%; box-sizing: border-box; border-radius: 5px; `; export const LogoImg = styled.img` height: 100%; `; <file_sep>export { FeatureBurgerBuilder } from './lib/feature-burger-builder'; <file_sep>import styled from 'styled-components'; export const BuildControlContainer = styled.div` display: flex; justify-content: space-between; align-items: center; margin: 5px 0; `; export const BuildControlBtn = styled.button` display: block; font: inherit; padding: 5px; margin: 0 5px; width: 80px; border: 1px solid #aa6817; cursor: pointer; outline: none; &:disabled { background-color: #ac9980; border: 1px solid #7e7365; color: #ccc; cursor: default; } &:hover:disabled { background-color: #ac9980; color: #ccc; cursor: not-allowed; } `; export const BuildControlLabel = styled.div` padding: 10px; font-weight: bold; width: 80px; `; export const BuildControlBtnLess = styled(BuildControlBtn)` background-color: #d39952; color: white; `; export const BuildControlBtnMore = styled(BuildControlBtn)` background-color: #8f5e1e; color: white; `; <file_sep>import axios from 'axios'; export const loadOrders = (queryParams: string) => { return axios.get(`/orders.json${queryParams}`); }; <file_sep>import { call, put, takeEvery } from 'redux-saga/effects'; import { OrderActions } from '@nx-react-burger-app/shared/interfaces'; import { loadOrdersFailure, loadOrdersSuccess } from './order.actions'; import { loadOrders } from './order.service'; export function* watchOrders() { yield takeEvery(OrderActions.LOAD_ORDERS, loadOrders$); } function* loadOrders$(action) { const { token, userId } = action; try { const queryParams = '?auth=' + token + '&orderBy="userId"&equalTo="' + userId + '"'; const { data } = yield call(() => loadOrders(queryParams)); const fetchedOrders = []; console.log('[ActionOrder] res: ', data); for (const key in data.data) { fetchedOrders.push({ ...data.data[key], id: key, }); } yield put(loadOrdersSuccess(fetchedOrders)); } catch (error) { yield put(loadOrdersFailure(error)); } } <file_sep>import { Ingredient } from './burger-builder.interfaces'; export interface OrderState { orders: Order[]; loaded: boolean; purchased: boolean; } export enum OrderActions { PURCHASE_BURGER = '[Order] Purchase Burger', PURCHASE_BURGER_SUCCESS = '[Order] Purchase Burger Success', PURCHASE_BURGER_FAILURE = '[Order] Purchase Burger Failure', LOAD_ORDERS = '[Order] Load Orders', LOAD_ORDERS_SUCCESS = '[Order] Load Orders Success', LOAD_ORDERS_FAILURE = '[Order] Load Orders Failure', } export interface PurchaseBurger { type: typeof OrderActions.PURCHASE_BURGER; } export interface PurchaseBurgerSuccess { type: typeof OrderActions.PURCHASE_BURGER_SUCCESS; orderId: number; orders: Order[]; } export interface PurchaseBurgerFailure { type: typeof OrderActions.PURCHASE_BURGER_FAILURE; error: Error; } export interface LoadOrders { type: typeof OrderActions.LOAD_ORDERS; token: string; userId: string; } export interface LoadOrdersSuccess { type: typeof OrderActions.LOAD_ORDERS_SUCCESS; orders: Order[]; } export interface LoadOrdersFailure { type: typeof OrderActions.LOAD_ORDERS_FAILURE; error: Error; } export interface Client { country: string; deliveryMethod: 'cheapest' | 'fastest'; email: string; name: string; street: string; zipCode: string; } export interface Order { ingredients: Ingredient[]; client: Client; price: number; userId: string; } <file_sep>import { AuthState } from '@nx-react-burger-app/shared/interfaces'; import produce from 'immer'; const initialState: AuthState = { token: null, userId: null, error: null, loaded: false, }; export const AuthReducer = produce((state = initialState, action) => { return state; }); <file_sep>module.exports = { projects: [ '<rootDir>/apps/burger-app', '<rootDir>/libs/burger-builder/feature-burger-builder', '<rootDir>/libs/burger-builder/data-access', '<rootDir>/libs/shared/interfaces', '<rootDir>/libs/shared/ui', '<rootDir>/libs/order/data-access', '<rootDir>/libs/order/feature-order', '<rootDir>/libs/auth/data-access', '<rootDir>/libs/auth/feature-auth', ], }; <file_sep>export * from './lib/shared-ui'; export * from './lib/layout/layout.component'; <file_sep>export * from './lib/auth-data-access'; export * from './lib/auth.reducer'; <file_sep>import styled from 'styled-components'; export const ToolbarHeader = styled.header` height: 56px; width: 100%; position: fixed; top: 0; left: 0; background-color: #703b09; display: flex; justify-content: space-between; align-items: center; padding: 0 20px; box-sizing: border-box; z-index: 90; `; export const ToolbarNav = styled.nav` height: 100%; @media (max-width: 499px) { display: none; } `; export const ToolbarLogo = styled.div` height: 80%; `; export const ToolbarNavigation = styled.ul` margin: 0; padding: 0; list-style: none; display: flex; flex-flow: column; align-items: center; height: 100%; @media (min-width: 500px) { flex-flow: row; } `; <file_sep>export * from './lib/order-data-access'; export * from './lib/order.reducer'; export * from './lib/order.sagas'; <file_sep>import { AddIngredient, BurgerBuilderActions, BurgerBuilderActionTypes, BurgerBuilderState, Ingredient, Ingredients, LoadIngredientsSuccess, RemoveIngredient, } from '@nx-react-burger-app/shared/interfaces'; import produce from 'immer'; const initialState: BurgerBuilderState = { building: false, error: null, ingredients: { [Ingredients.BACON]: 0, [Ingredients.CHEESE]: 0, [Ingredients.MEAT]: 0, [Ingredients.SALAD]: 0, }, totalPrice: 4, }; const INGREDIENT_PRICES = { salad: 0.5, cheese: 0.4, meat: 1.3, bacon: 0.7, }; const addIngredient = ( draft: BurgerBuilderState, { ingredientName }: AddIngredient ) => { const updateIngredient: Ingredient = { ...draft.ingredients, [ingredientName]: draft.ingredients[ingredientName] + 1, }; return { ...draft, ingredients: updateIngredient, totalPrice: draft.totalPrice + INGREDIENT_PRICES[ingredientName], building: true, }; }; const removeIngredient = ( draft: BurgerBuilderState, { ingredientName }: RemoveIngredient ) => { const updateIngredient: Ingredient = { ...draft.ingredients, [ingredientName]: draft.ingredients[ingredientName] - 1, }; return { ...draft, ingredients: updateIngredient, totalPrice: draft.totalPrice - INGREDIENT_PRICES[ingredientName], building: true, }; }; const loadIngredientsSuccess = ( draft: BurgerBuilderState, { ingredients }: LoadIngredientsSuccess ) => { if (!ingredients) { ingredients = initialState.ingredients; } return { ...draft, ingredients, }; }; export const BurgerBuilderReducer = ( state = initialState, action: BurgerBuilderActionTypes ) => { return produce(state, (draft) => { switch (action.type) { case BurgerBuilderActions.ADD_INGREDIENT: { return addIngredient(draft, action); } case BurgerBuilderActions.REMOVE_INGREDIENT: { return removeIngredient(draft, action); } case BurgerBuilderActions.LOAD_INGREDIENTS_SUCCESS: { return loadIngredientsSuccess(draft, action); } default: { return state; } } }); }; <file_sep>import { AddIngredient, BurgerBuilderActions, Ingredient, Ingredients, LoadIngredients, LoadIngredientsFailure, LoadIngredientsSuccess, RemoveIngredient, } from '@nx-react-burger-app/shared/interfaces'; export const addIngredient = (ingredientName: Ingredients): AddIngredient => { return { type: BurgerBuilderActions.ADD_INGREDIENT, ingredientName, }; }; export const removeIngredient = ( ingredientName: Ingredients ): RemoveIngredient => { return { type: BurgerBuilderActions.REMOVE_INGREDIENT, ingredientName, }; }; export const loadIngredients = (): LoadIngredients => { return { type: BurgerBuilderActions.LOAD_INGREDIENTS, }; }; export const loadIngredientsSuccess = ( ingredients: Ingredient ): LoadIngredientsSuccess => { return { type: BurgerBuilderActions.LOAD_INGREDIENTS_SUCCESS, ingredients, }; }; export const loadIngredientsFailure = ( error: Error ): LoadIngredientsFailure => { return { type: BurgerBuilderActions.LOAD_INGREDIENTS_FAILURE, error, }; }; <file_sep>import { BurgerBuilderActions } from '@nx-react-burger-app/shared/interfaces'; import { call, put, takeEvery } from 'redux-saga/effects'; import { loadIngredientsFailure, loadIngredientsSuccess, } from './burger-builder.actions'; import { loadIngredients } from './burger-builder.service'; export function* watchBurgerBuilder() { yield takeEvery(BurgerBuilderActions.LOAD_INGREDIENTS, loadIngredients$); } function* loadIngredients$() { try { const { data } = yield call(loadIngredients); yield put(loadIngredientsSuccess(data)); } catch (error) { yield put(loadIngredientsFailure(error)); } } <file_sep>import styled from 'styled-components'; export const LayoutContent = styled.main` margin-top: 72px; `;
6e00255736db9420f6ce1cfc38981aafac0c6e6a
[ "JavaScript", "TypeScript" ]
31
TypeScript
LukeSwierlik/nx-react-burger-app
4065b0db6d3cbe7ba472479e602d9a5c7dca0026
5d722517907604bfec5f86d5de13f66b2dbf8473
refs/heads/master
<repo_name>allmeida/logistica-api<file_sep>/src/main/resources/db/migration/V001__cria-tabela-cliente.sql create table cliente ( id bigint not null auto_increment, nome varchar(50) not null, email varchar(250) not null, telefone varchar(20) not null, primary key (id) );
749b1ace59cca6f5f33dfd46ecda4b334862ac84
[ "SQL" ]
1
SQL
allmeida/logistica-api
331482b5c1cbbe19c26a87a468f6f5b0d75023a4
f2cb3dabb7324205d5200ba64980cc7cfa7dbb11
refs/heads/master
<file_sep><?php require_once 'vendor/autoload.php'; use AyeAye\Api\Api; use Dotenv\Dotenv; use Riverwash\UsersController; use Psr\Log\AbstractLogger; $dotenv = new Dotenv(__DIR__); $dotenv->load(); header('Access-Control-Allow-Origin: '. getenv('ACCESS_CONTROL_ALLOW_ORIGIN')); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); header('Access-Control-Allow-Headers: origin, content-type, accept'); date_default_timezone_set('Europe/Warsaw'); if (!getenv('LUNO_KEY') || !getenv('LUNO_SECRET') || !getenv('SLACK_WEBHOOK') || !getenv('SLACK_CHANNEL') || !getenv('SESSION_NAME')) { header('HTTP/1.1 500 Internal Server Error'); echo json_encode([ 'data' => [ 'error' => 'Please configure environment variables.' ] ]); exit(0); } session_name(getenv('SESSION_NAME')); session_start(); class EchoLogger extends AbstractLogger { public function log($level, $message, array $context = array()) { echo $message . PHP_EOL; $this->logArray($context); } public function logArray($array, $indent = ' ') { foreach ($array as $key => $value) { if (!is_scalar($value)) { echo $indent . $key . ':' . PHP_EOL; $this->logArray($value, $indent . ' '); continue; } echo $indent . $key . ': ' . $value; } } } $initialController = new UsersController(); $api = new Api($initialController); $api->setLogger(new EchoLogger); $api->go()->respond(); <file_sep><?php namespace Riverwash; use AyeAye\Api\Controller; use Duffleman\Luno\LunoRequester; use Maknz\Slack\Client; class RiverwashController extends Controller { /** * Holds the Luno Requester. * * @var LunoRequester */ protected $lunoRequester; /** * @var */ protected $slack; /** * RiverwashController constructor. */ public function __construct() { $this->lunoRequester = new LunoRequester([ 'sandbox' => getenv('LUNO_SANDBOX') === 'true', 'key' => getenv('LUNO_KEY'), 'secret' => getenv('LUNO_SECRET'), 'timeout' => 10000, ]); $this->slack = new Client(getenv('SLACK_WEBHOOK'), [ 'username' => 'Pralka Rzeczna', 'channel' => getenv('SLACK_CHANNEL'), 'icon' => ':washing:', 'link_names' => true ]); } }<file_sep><?php namespace Riverwash; use Maknz\Slack\Attachment; use Maknz\Slack\Message; use MHlavac\DiacriticsRemover\DiacriticsRemover; use Riverwash\Model\User; use Riverwash\Model\Session; use AyeAye\Api\Exception; use Duffleman\Luno\Exceptions\LunoApiException; class UserController extends RiverwashController { /** * Register new user * * @param string $handle Nickname * @param string $group Group(s) * @param string $country Country * @param string $email E-mail * @param string $password <PASSWORD> * @param string $language Language * * @return array * * @throws Exception */ public function postRegisterEndpoint($handle, $group, $country, $email, $password, $language) { $language = filter_var(trim($language), FILTER_SANITIZE_STRING); $handle = filter_var(trim($handle), FILTER_SANITIZE_STRING); $group = filter_var(trim($group), FILTER_SANITIZE_STRING); $country = filter_var(trim($country), FILTER_SANITIZE_STRING); $email = filter_var(trim($email), FILTER_SANITIZE_EMAIL); $remover = new DiacriticsRemover(); $handle = $remover->parse($handle); $group = $remover->parse($group); if ($handle == '') { $text = ($language == 'pl' ? 'Pole Ksywa nie może być puste!' : 'Handle field cannot be empty!'); return new Exception($text, 500); } if ($email == '') { $text = ($language == 'pl' ? 'Musisz podać adres e-mail!' : 'E-mail field cannot be empty!'); return new Exception($text, 500); } if ($password == '') { $text = ($language == 'pl' ? 'Hasło nie może być puste!' : 'Password field cannot be empty!'); return new Exception($text, 500); } try { $lunoUser = $this->lunoRequester->users->create([ 'username' => $email, 'email' => $email, 'password' => $<PASSWORD>, 'profile' => [ 'handle' => $handle, 'group' => $group, 'country' => $country ] ]); $user = new User(); $user->fromLunoUser($lunoUser); } catch (LunoApiException $exception) { $text = ($language == 'pl' ? 'Nieudana komunikacja z API:' . print_r($exception->getAll(), true) : $exception->getMessage()); $e = new Exception($text, 500); return $e->jsonSerialize(); } try { $this->sendSlackRegistration($user); } catch (Exception $exception) { $text = $exception->getMessage(); $e = new Exception($text, 500); return $e->jsonSerialize(); } return $user; } /** * Sign-in existing user * * @param string $email E-mail * @param string $password <PASSWORD> * @param string $language Language * * @return array * * @throws Exception */ public function postSignInEndpoint($email, $password, $language) { $language = filter_var(trim($language), FILTER_SANITIZE_STRING); $email = filter_var(trim($email), FILTER_SANITIZE_EMAIL); if ($email == '') { $text = ($language == 'pl' ? 'Musisz podać adres e-mail!' : 'E-mail field cannot be empty!'); return new Exception($text, 500); } if ($password == '') { $text = ($language == 'pl' ? 'Hasło nie może być puste!' : 'Password field cannot be empty!'); return new Exception($text, 500); } try { $response = $this->lunoRequester->users->login($email, $password); $session = new Session(); $session->fromResponse($response); } catch (LunoApiException $exception) { $status = 500; if ($exception->getLunoCode() === 'incorrect_password') { $text = ($language == 'pl' ? 'Nieprawidłowe hasło' : $exception->getLunoDescription()); $status = $exception->getLunoStatus(); } else { $text = ($language == 'pl' ? 'Nieudana komunikacja z API' . print_r($exception, true) : $exception->getMessage()); } $e = new Exception($text, $status); return $e->jsonSerialize(); } $_SESSION['session'] = $session; $user = new User(); $user->fromLunoUser($session->user); return [ 'success' => true, 'nominationCasted' => $user->nominationCasted ]; } /** * Nominate demoscener * * @param string $nickname Nickname * @param string $description Description * @param string $language Language * * @return array * * @throws Exception */ public function postNominateEndpoint($nickname, $description, $language) { $language = filter_var(trim($language), FILTER_SANITIZE_STRING); $session = null; $sessionError = $this->getSessionError($language); if ($sessionError !== false) { return $sessionError; } else { $session = $this->getSession(); } $nickname = filter_var(trim($nickname), FILTER_SANITIZE_STRING); $description = filter_var(trim($description), FILTER_SANITIZE_STRING); if ($nickname == '') { $text = ($language == 'pl' ? 'Musisz podać nickname!' : 'Nickname field cannot be empty!'); return new Exception($text, 500); } if ($description == '') { $text = ($language == 'pl' ? 'Uzasadnienie nie może być puste!' : 'Reason field cannot be empty!'); return new Exception($text, 500); } $user = new User(); $user->fromLunoUser($session->user); if ($this->getUserNominationCasted($user)) { $text = ($language == 'pl' ? 'Można tylko raz nominować kandydata!' : 'You can nominate a candidate only once!'); return new Exception($text, 500); } try { $this->setUserNominationCasted($user); } catch (LunoApiException $exception) { $status = 500; if ($exception->getLunoCode() === 'incorrect_password') { $text = ($language == 'pl' ? 'Nieprawidłowe hasło' : $exception->getLunoDescription()); $status = $exception->getLunoStatus(); } else { $text = $exception->getMessage(); } $e = new Exception($text, $status); return $e->jsonSerialize(); } try { $this->sendSlackNomination($user, $nickname, $description); } catch (Exception $exception) { $text = $exception->getMessage(); $e = new Exception($text, 500); return $e->jsonSerialize(); } return [ 'success' => true ]; } private function sendSlackRegistration(User $user) { $message = $this->slack->createMessage(); $message->setText('Na stronie zarejestrował się nowy użytkownik:'); $this->slackAttachUserDataToMessage($message, $user); $this->slack->sendMessage($message); } private function sendSlackNomination(User $user, $nickname, $description) { $message = $this->slack->createMessage(); $message->setText('Nowa nominacja:'); $this->slackAttachNomineeDataToMessage($nickname, $description, $message); $this->slackAttachUserDataToMessage($message, $user); $this->slack->sendMessage($message); } /** * Check if session exists * * @return mixed */ private function getSessionError($language) { if (!isset($_SESSION['session'])) { $status = 401; $text = ($language == 'pl' ? 'Musisz być zalogowany(-a), aby nominować!' : 'Must be authenticated to nominate!'); $e = new Exception($text, $status); return $e->jsonSerialize(); } else { return false; } } /** * Get stored session * * @return Session */ private function getSession() { return $_SESSION['session']; } private function slackAttachUserDataToMessage(Message $message, User $user) { $attachment = new Attachment([ 'title' => 'Ksywa / Grupa', 'text' => $user->getNicknameAndGroupAsString(), 'color' => 'good' ]); $message->attach($attachment); $attachment = new Attachment([ 'title' => 'E-mail, kraj', 'text' => $user->getEmailAndCountryAsString(), 'color' => 'good' ]); $message->attach($attachment); } /** * @param string $nickname * @param string $description * @param Message $message */ private function slackAttachNomineeDataToMessage($nickname, $description, Message $message) { $attachment = new Attachment([ 'title' => 'Kandydatura', 'text' => $nickname, 'color' => '#3AA3E3' ]); $message->attach($attachment); $attachment = new Attachment([ 'title' => 'Uzasadnienie', 'text' => $description, 'color' => '#2a76a5' ]); $message->attach($attachment); } private function setUserNominationCasted(User $user) { $this->lunoRequester->users->append($user->id, [ 'profile' => [ 'nominationCasted' => true ] ]); } private function getUserNominationCasted(User $user) { $lunoUser = $this->lunoRequester->users->find($user->id); $user->fromLunoUser($lunoUser); return $user->nominationCasted; } } <file_sep><?php namespace Riverwash\Model; class User { public $handle; public $group; public $country; public $image; public $email; public $id; public $nominationCasted; public function fromLunoUser($lunoUser) { $profile = $lunoUser['profile']; $this->id = $lunoUser['id']; $this->email = $lunoUser['email']; $this->country = $profile['country']; $this->handle = $profile['handle']; $this->group = $profile['group']; $this->nominationCasted = isset($profile['nominationCasted']) && $profile['nominationCasted'] === true; $this->image = $this->getGravatarUrlFromEmail($lunoUser['email']); } private function getGravatarUrlFromEmail($email, $size = 0) { $default = 'wavatar'; $sizeLimiter = ($size > 0 ? '&s=' . $size : ''); return 'http://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?d=' . urlencode($default) . $sizeLimiter; } public function getNicknameAndGroupAsString() { return $this->handle . ($this->group != '' ? ' / ' . $this->group : ''); } public function getEmailAndCountryAsString() { return sprintf("%s (%s)", $this->email, $this->country); } }<file_sep># Riverwash API [![PHP >= 5.6](https://img.shields.io/badge/php-%3E%3D%205.5-8892BF.svg)] (https://php.net/) <file_sep><?php namespace Riverwash; use Riverwash\Model\User; class UsersController extends RiverwashController { /** * List registered users * @return array */ public function getUsersEndpoint() { $users = []; $lunoUsersIterator = $this->lunoRequester->users->all(); foreach ($lunoUsersIterator as $lunoUser) { $user = new User(); $user->fromLunoUser($lunoUser); array_push($users, [ 'handle' => $user->handle, 'group' => $user->group, 'country' => $user->country, 'image' => $user->image ]); }; return $users; } /** * lol... * @return $this */ public function userController() { return new UserController(); } } <file_sep><?php namespace Riverwash\Model; class Session { private $type; private $id; private $url; private $key; private $created; private $expires; private $lastAccess; private $accessCount; private $ip; private $userAgent; private $details; public $user; public function fromResponse($response) { $session = $response['session']; $user = $response['user']; $this->type = $session['type']; $this->id = $session['id']; $this->url = $session['url']; $this->key = $session['key']; $this->created = $session['created']; $this->expires = $session['expires']; $this->lastAccess = $session['last_access']; $this->accessCount = $session['access_count']; $this->ip = $session['ip']; $this->userAgent = $session['user_agent']; $this->details = $session['details']; $this->user = $user; } }
e0933c2c68e07e2e7ae2e47a0df73b519286ca35
[ "Markdown", "PHP" ]
7
PHP
argasek/riverwash-api
651c9059d781dfd2847d7c2f875d406f35599e95
80643b18faceb2ee738d16f02410fd1d80a42b25
refs/heads/master
<file_sep>import turtle, random t = turtle.Turtle() t.speed("fastest") t.home() randint = random.randint var1 = 0 turtle.colormode(255) for x in range (70): r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) t.color(r, g, b) t.circle(60) t.forward(170) t.backward(170) t.setheading(var1) var1 = var1 + 5<file_sep>import turtle, random t = turtle.Turtle() ran = random.randint turtle.colormode(255) t.home() turtle.bgcolor("black") t.speed("fastest") for x in range (0, 180): r = ran(0, 255) g = ran(0, 255) b = ran(0, 255) t.color(r, g, b) length = ran(10,350) t.forward(length) t.backward(length) t.left(2) <file_sep> import turtle, random turtle.colormode(255) t = turtle.Turtle() t.home() randint = random.randint var1 = 0 t.speed("fastest") for x in range(50): r = randint(0,255) g = randint(0,255) b = randint(0,255) t.pencolor(r, g, b) var1 += 10 t.circle(var1,180) t.width(var1/20) <file_sep>import turtle, random colors = ["red","orange","yellow","green","blue","purple","yellow"] turtle.setup(500,500,0,0) turtle.bgcolor("black") t = turtle.Turtle() t.home() t.color("white") for x in range(100): mycolor = random.randint(0,6) xpos = random.randint(-250,250) ypos = random.randint(-250,250) t.goto(xpos,ypos) t.dot(20,colors[mycolor]) t.invisible() <file_sep>import turtle, random t = turtle.Turtle() randint = random.randint t.home() turtle.bgcolor("black") turtle.colormode(255) t.speed("fastest") for x in range(35): r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) t.color(r, g, b) t.circle(50) t.forward(100) t.circle(50) t.backward(100) t.left(10)
61672faa6676875b15430ee81723d24896e7592a
[ "Python" ]
5
Python
jaqlai/python_turtle_art
85b035908665ab6db260b9176c45d4202875d359
aac6661c560d5709d326ae3e385428056e4b2c65
refs/heads/master
<repo_name>FluentDOM/YAML-Dipper<file_sep>/src/Serializer.php <?php /** * Serialize an (XHTML) DOM into a HTML5 string. * * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @copyright Copyright (c) 2009-2014 <NAME>, <NAME> */ namespace FluentDOM\YAML\Dipper { use secondparty\Dipper\Dipper as Dipper; /** * Serialize an (XHTML) DOM into a HTML5 string. * * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @copyright Copyright (c) 2009-2014 <NAME>, <NAME> */ class Serializer { /** * @var \DOMDocument */ private $_document = NULL; /** * @var array */ private $_options = []; public function __construct(\DOMDocument $document, array $options = []) { $this->_document = $document; $this->_options = $options; } public function __toString() { try { return $this->asString(); } catch (\Exception $e) { return ''; } } public function asString() { $jsondom = new \FluentDOM\Serializer\Json($this->_document); $yaml = Dipper::make($jsondom->jsonSerialize()); return (string)$yaml; } } } <file_sep>/README.md FluentDOM-YAML-Dipper ===================== [![License](https://poser.pugx.org/fluentdom/yaml-dipper/license.svg)](http://www.opensource.org/licenses/mit-license.php) [![Build Status](https://travis-ci.org/FluentDOM/YAML-Dipper.svg?branch=master)](https://travis-ci.org/FluentDOM/YAML-Dipper) [![Total Downloads](https://poser.pugx.org/fluentdom/yaml-dipper/downloads.svg)](https://packagist.org/packages/fluentdom/yaml-dipper) [![Latest Stable Version](https://poser.pugx.org/fluentdom/yaml-dipper/v/stable.svg)](https://packagist.org/packages/fluentdom/yaml-dipper) [![Latest Unstable Version](https://poser.pugx.org/fluentdom/yaml-dipper/v/unstable.svg)](https://packagist.org/packages/fluentdom/yaml-dipper) Adds support for YAML to FluentDOM. It adds a loader and a serializer. It uses the [Dipper](https://github.com/secondparty/dipper) library. NOTE: At the moment a [fork of Dipper](https://github.com/FluentDOM/dipper) is used. This plugin needs FluentDOM 5.2.1 aka the current development version. Installation ------------ ```text composer require fluentdom/yaml-dipper ``` Loader ------ The loader registers automatically. You can trigger it with the types `yaml` and `text/yaml`. ```php $document = FluentDOM::load($yaml, 'text/yaml'); $query = FluentDOM($yaml, 'text/yaml'); ``` Serializer ---------- The serializer needs to be created with for document and can be casted into a string. ```php echo new FluentDOM\YAML\Dipper\Serializer($document); ``` <file_sep>/tests/SerializerTest.php <?php namespace FluentDOM\YAML\Dipper { use FluentDOM\Document; use PHPUnit\Framework\TestCase; require_once __DIR__.'/../vendor/autoload.php'; class SerializerTest extends TestCase { /** * @covers \FluentDOM\YAML\Dipper\Serializer */ public function testLoadReturnsImportedDocument() { $xml = '<?xml version="1.0" encoding="UTF-8"?> <json:json xmlns:json="urn:carica-json-dom.2013"> <regular_map> <one>first</one> <two>second</two> </regular_map> <shorthand_map> <one>first</one> <two>second</two> </shorthand_map> </json:json>'; $dom = new Document(); $dom->preserveWhiteSpace = FALSE; $dom->loadXml($xml); $serializer = new Serializer($dom); $yaml = "---\n". "regular_map:\n". " one: first\n". " two: second\n". "shorthand_map:\n". " one: first\n". " two: second"; $this->assertEquals( $yaml, (string)$serializer ); } /** * @covers \FluentDOM\YAML\Dipper\Serializer */ public function testToStringCatchesExceptionAndReturnEmptyString() { $serializer = new Serializer_TestProxy(new Document()); $this->assertEquals( '', (string)$serializer ); } } class Serializer_TestProxy extends Serializer { public function asString() { throw new \LogicException('Catch It.'); } } }<file_sep>/src/Loader.php <?php /** * Load a DOM document from a HTML5 string or file * * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @copyright Copyright (c) 2009-2014 <NAME>, <NAME> */ namespace FluentDOM\YAML\Dipper { use FluentDOM\Document; use FluentDOM\DocumentFragment; use FluentDOM\Loadable; use FluentDOM\Loader\Options; use FluentDOM\Loader\Supports; use secondparty\Dipper\Dipper as Dipper; /** * Load a DOM document from a HTML5 string or file */ class Loader extends \FluentDOM\Loader\Json\JsonDOM { use Supports; /** * @return string[] */ public function getSupported() { return ['yaml', 'text/yaml']; } /** * Load the YAML string into an DOMDocument * * @param mixed $source * @param string $contentType * @param array|\Traversable|Options $options * @return Document|NULL */ public function load($source, $contentType, $options = []) { if ($this->supports($contentType)) { $settings = $this->getOptions($options); $settings->isAllowed($sourceType = $settings->getSourceType($source)); switch ($sourceType) { case Options::IS_FILE : $source = file_get_contents($source); case Options::IS_STRING : default : $yaml = Dipper::parse($source); if (!empty($yaml) || is_array($yaml)) { $document = new Document('1.0', 'UTF-8'); $document->appendChild( $root = $document->createElementNS(self::XMLNS, 'json:json') ); $this->transferTo($root, $yaml); return $document; } } } return NULL; } /** * Load the YAML string into an DOMDocumentFragment * * @param mixed $source * @param string $contentType * @param array|\Traversable|Options $options * @return DocumentFragment|NULL */ public function loadFragment($source, $contentType, $options = []) { if ($this->supports($contentType)) { $yaml = Dipper::parse($source); if (!empty($yaml) || is_array($yaml)) { $document = new Document('1.0', 'UTF-8'); $fragment = $document->createDocumentFragment(); $this->transferTo($fragment, $yaml); return $fragment; } } return NULL; } /** * @param array|Options|\Traversable $options * @return Options */ public function getOptions($options) { $result = new Options( $options, [ Options::CB_IDENTIFY_STRING_SOURCE => function($source) { return (FALSE !== strpos($source, "\n")); } ] ); return $result; } } }<file_sep>/CHANGELOG.md Version 1.0.0 ------------- - Added: FluentDOM\YAML\Dipper\Loader - integrates as loader for 'yaml' and 'text/yaml' - Added: FluentDOM\YAML\Dipper\Serializer - saves a DOM (JsonDOM) document as YAML (can be cast to string)
8bd3b3e9bdd42f1a476b47fcb94396d3d09a2484
[ "Markdown", "PHP" ]
5
PHP
FluentDOM/YAML-Dipper
c9970cdc3d619f74f3341ebdc1a9c2b23eebce5f
739ace7ad03a38e72e738025b00d3f85cadd0a00
refs/heads/master
<repo_name>dmitru/redux-bootstrap-starter-kit<file_sep>/app/components/FormFields/Loading.js import React from 'react' import classNames from 'classnames' import { Glyphicon } from 'react-bootstrap' import styles from './Loading.css' export default class Loading extends React.Component { static propTypes = { delay: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.number, ]), inline: React.PropTypes.bool, text: React.PropTypes.string, } getDefaultProps() { return { delay: 500, inline: false, } } getInitialState() { return { delaying: !!this.props.delay, } } componentDidMount() { if (this.props.delay) { this.timeout = setTimeout(this.handleDisplay, this.props.delay) } } componentWillUnmount() { if (this.timeout) { clearTimeout(this.timeout) } } handleDisplay() { this.timeout = null this.setState({ delaying: false }) } render() { const { delay, inline, text } = this.props const { delaying } = this.state const classNamesConfig = {} classNamesConfig[styles.loadingDelayed] = delaying classNamesConfig[styles.loadingDisplayed] = delay && !delaying classNamesConfig[styles.loadingInline] = inline const className = classNames('Loading', classNamesConfig) return ( <div className={className}> <Glyphicon glyph="refresh" /> {text && <div className={styles.loadingText}>{text}&hellip;</div>} </div> ) } } <file_sep>/server/routes/auth.js 'use strict' const express = require('express') const router = express.Router() const ReCaptcha = require('recaptcha2') const recaptcha = new ReCaptcha({ siteKey: '<KEY>', secretKey: '<KEY>', }) const TOKEN_ID = 'a-secret-token-string' const USER = { email: '<EMAIL>', } const config = require('../config') const BACKEND_API_URL = `${config.backendApi.host}:${config.backendApi.port}` const request = require('superagent') const utils = require('../utils') router.get('/profile', (req, res) => { setTimeout(() => { res.json(USER) }, 800) }) router.post('/login', (req, res) => { request.post(`${BACKEND_API_URL}/api/Users/login`) .send({ email: req.body.email, password: <PASSWORD>, }).end((error, response) => { if (error) { if (error.status && error.status === 401) { res.status(401) .json({ errorCode: 'WRONG_CREDENTIALS', message: 'Wrong username or password.', }) } else { res.status(500) .json({ errorCode: 'SERVER_ERROR', message: 'Server unavailable.', }) } } else { res.json({ token: response.body.id, }) } }) }) router.post('/signup', (req, res) => { recaptcha.validate(req.body.captchaResponse) .then(() => { setTimeout(() => { if (req.body.email !== USER.email) { res.status(401) .json({ errorCode: 'WRONG_CREDENTIALS', message: 'Wrong username or password.', }) } else { res.json({ token: TOKEN_ID, }) } }, 800) }).catch(() => { res.status(403) .json({ errorCode: 'ACCESS_DENIED', message: 'Captcha is not verified.', }) }) }) module.exports = router <file_sep>/app/constants.js export const AUTH_LOGIN_REQUEST = 'AUTH/LOGIN_REQUEST' export const AUTH_LOGIN_ERROR = 'AUTH/LOGIN_ERROR' export const AUTH_LOGGED_IN = 'AUTH/LOGGED_IN' export const AUTH_LOGGED_OUT = 'AUTH/LOGGED_OUT' export const AUTH_SIGNUP_REQUEST = 'AUTH/SIGNUP_REQUEST' export const AUTH_SIGNUP_ERROR = 'AUTH/SIGNUP_ERROR' export const PROFILE_FETCH_REQUEST = 'PROFILE/FETCH_REQUEST' export const PROFILE_FETCH_SUCCESS = 'PROFILE/FETCH_SUCCESS' export const PROFILE_FETCH_FAILURE = 'PROFILE/FETCH_FAILURE' export const CURRENCIES_FETCH_REQUEST = 'CURRENCIES/FETCH_REQUEST' export const CURRENCIES_FETCH_SUCCESS = 'CURRENCIES/FETCH_SUCCESS' export const CURRENCIES_FETCH_FAILURE = 'CURRENCIES/FETCH_FAILURE' export const ENTRIES_FETCH_REQUEST = 'ENTRIES/FETCH_REQUEST' export const ENTRIES_FETCH_SUCCESS = 'ENTRIES/FETCH_SUCCESS' export const ENTRIES_FETCH_FAILURE = 'ENTRIES/FETCH_FAILURE' export const ENTRIES_ADD_REQUEST = 'ENTRIES/ADD_REQUEST' export const ENTRIES_ADD_SUCCESS = 'ENTRIES/ADD_SUCCESS' export const ENTRIES_ADD_FAILURE = 'ENTRIES/ADD_FAILURE' export const ENTRIES_TOGGLE_SELECTION = 'ENTRIES/TOGGLE_SELECTION' export const ENTRIES_UPDATE = 'ENTRIES/UPDATE' export const ENTRIES_UPDATE_FAILURE = 'ENTRIES/UPDATE_FAILURE' export const ENTRIES_DELETE = 'ENTRIES/DELETE' export const CATEGORIES_FETCH_REQUEST = 'CATEGORIES/FETCH_REQUEST' export const CATEGORIES_FETCH_SUCCESS = 'CATEGORIES/FETCH_SUCCESS' export const CATEGORIES_FETCH_FAILURE = 'CATEGORIES/FETCH_FAILURE' export const CATEGORIES_ADD_REQUEST = 'CATEGORIES/ADD_REQUEST' export const CATEGORIES_ADD_SUCCESS = 'CATEGORIES/ADD_SUCCESS' export const CATEGORIES_ADD_FAILURE = 'CATEGORIES/ADD_FAILURE' export const CATEGORIES_TOGGLE_SELECTION = 'CATEGORIES/TOGGLE_SELECTION' export const CATEGORIES_UPDATE = 'CATEGORIES/UPDATE' export const CATEGORIES_UPDATE_FAILURE = 'CATEGORIES/UPDATE_FAILURE' export const CATEGORIES_DELETE = 'CATEGORIES/DELETE' export const ERROR_CLIENT = 'ERROR_CLIENT' export const ERROR_SERVER = 'ERROR_SERVER' <file_sep>/app/containers/AddCategoryForm/AddCategoryForm.js import React, { Component } from 'react' import _ from 'lodash' import classNames from 'classnames' import { Row, Col, Button, } from 'react-bootstrap' import { reduxForm } from 'redux-form' import { TextInput } from '../../components/FormFields' import { getCategories } from '../../reducers/categories' export const fields = ['name'] const validate = (values, props) => { const errors = {} const name = _.trim(values.name) const { categories } = props if (_.includes(_.map(categories, (c) => c.name), name)) { errors.name = 'This name is already used by another category' } return errors } class AddCategory extends Component { static propTypes = { categories: React.PropTypes.array.isRequired, fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired, onSubmit: React.PropTypes.func, } constructor(props) { super(props) this.state = {} } render() { const { fields: { name }, handleSubmit } = this.props return ( <form className={classNames('form-horizontal')} onSubmit={handleSubmit} > <Row> <Col xs={9} sm={6} smOffset={2} style={{ paddingRight: '5px' }}> <TextInput autoFocus autocomplete="off" placeholder="Name of category" field={name} id="name" /> </Col> <Col xs={3} sm={2} style={{ paddingLeft: '5px' }}> <Button type="submit" bsStyle="default" > ADD </Button> </Col> </Row> </form> ) } } const formConfig = { form: 'addCategory', fields, validate, } const mapStateToProps = (state) => ({ categories: getCategories(state), }) export default reduxForm(formConfig, mapStateToProps)(AddCategory) <file_sep>/app/reducers/index.js import auth from './auth' import profile from './profile' import currencies from './currencies' import entries from './entries' import categories from './categories' module.exports = { auth, profile, currencies, entries, categories, } <file_sep>/app/api/entries.js import client from '../utils/apiClient' export const getAll = () => ( client.get('/api/Entries') ) export const create = ({ entry }) => ( client.post('/api/Entries').send(entry) ) export const update = ({ entry }) => ( client.put(`/api/Entries/${entry.id}`).send(entry) ) export const del = ({ ids }) => { if (Array.isArray(ids)) { return client.delete('/api/Entries').send({ ids }) } return client.delete(`/api/Entries/${ids}`) } <file_sep>/app/components/PaginatedList/index.js import PaginatedList from './PaginatedList' export default PaginatedList <file_sep>/app/utils/testUtils.js import chai from 'chai' chai.config.truncateThreshold = 0 export const expect = chai.expect import client from './apiClient' import MockAdapter from 'axios-mock-adapter' export const mockApi = new MockAdapter(client) <file_sep>/app/containers/EditEntryForm/EditEntryForm.js import React, { Component } from 'react' import classNames from 'classnames' import { Button, Label, } from 'react-bootstrap' import { reduxForm } from 'redux-form' import { TextInput, TypeaheadInput, Switch, } from '../../components/FormFields' import { getCategories } from '../../reducers/categories' export const fields = ['amount', 'category', 'isIncome'] const validate = (values) => { const errors = {} if (values.category && !Array.isArray(values.category)) { errors.category = 'Unknown category' } if (!/^[-+]?\d+(,\d+)*(\.\d+(e\d+)?)?$/.test(values.amount)) { errors.amount = 'A number is required' } return errors } const EditEntryForm = ({ fields: { amount, category, isIncome }, categories, handleSubmit, onCancel, }) => ( <form className={classNames('form-horizontal')} onSubmit={handleSubmit}> <TypeaheadInput field={category} placeholder="Category" labelKey="name" options={categories} renderMenuItemChildren={(props, option) => ( <Label>{option.name}</Label> )} /> <TextInput autocomplete="off" placeholder="Amount" field={amount} id="amount" /> <Switch field={isIncome} labels={{ on: 'INCOME', off: 'EXPENSE', }} switchStyles={{ width: 50, }} /> <Button bsStyle="default" onClick={onCancel}>Cancel</Button> <Button type="submit" bsStyle="default">Save</Button> </form> ) EditEntryForm.propTypes = { initialValues: React.PropTypes.object, categories: React.PropTypes.array.isRequired, fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, } const formConfig = { form: 'editEntry', fields, validate, } const mapStateToProps = (state) => ({ categories: getCategories(state), }) const EditEntryFormComponent = reduxForm(formConfig, mapStateToProps)(EditEntryForm) class EditEntryFormWrapper extends Component { static propTypes = { entry: React.PropTypes.object, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, } constructor(props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) } getFieldsFromEntry(entry) { if (!entry) { return {} } return { isIncome: entry.type === 'i', amount: entry.amount, category: entry.category ? [entry.category] : null, } } handleSubmit(data) { const { entry, onSubmit } = this.props onSubmit({ entry: { ...entry, amount: parseFloat(data.amount), type: data.isIncome ? 'i' : 'e', categoryId: data.category ? data.category[0].id : null, }, }) } render() { const { onCancel, entry } = this.props return ( <EditEntryFormComponent onSubmit={this.handleSubmit} onCancel={onCancel} initialValues={this.getFieldsFromEntry(entry)} /> ) } } export default EditEntryFormWrapper <file_sep>/app/api/index.js /** * Created by dmitru on 6/4/16. */ import * as auth from './auth' import * as profile from './profile' import * as currencies from './currencies' import * as entries from './entries' import * as categories from './categories' const api = { auth, profile, currencies, entries, categories, } export default api <file_sep>/app/components/FormFields/Help.js import React from 'react' import { Glyphicon, OverlayTrigger, Tooltip } from 'react-bootstrap' import styles from './Help.css' const Help = ({ text }) => { const tooltip = <Tooltip>{text}</Tooltip> return ( <OverlayTrigger overlay={tooltip} delayShow={300} delayHide={150}> <Glyphicon className={styles.help} glyph="question-sign" /> </OverlayTrigger> ) } Help.propTypes = { text: React.PropTypes.string.isRequired, } export default Help <file_sep>/app/components/PaginatedList/PaginatedList.js /** * Created by dmitru on 6/5/16. */ import React from 'react' import _ from 'lodash' import { Pagination } from 'react-bootstrap' class ScrolledList extends React.Component { static propTypes = { items: React.PropTypes.array, itemRenderer: React.PropTypes.func.isRequired, } constructor(props) { super(props) this.handlePaginationSelect = this.handlePaginationSelect.bind(this) const { items } = props const numPages = Math.floor((items.length - 1) / 10) + 1 this.state = { itemsPerPage: 10, curPage: Math.min(1, numPages), pages: numPages, } } componentWillReceiveProps(props) { this.updatePaginationState(props) } updatePaginationState(props) { const { items } = props const { itemsPerPage, curPage } = this.state const newNumPages = Math.floor((items.length - 1) / itemsPerPage) + 1 const newCurPage = Math.min(Math.max(1, curPage), newNumPages) this.setState({ pages: newNumPages, curPage: newCurPage, }) } handlePaginationSelect(eventKey) { this.setState({ curPage: eventKey, }) } render() { const { items, itemRenderer } = this.props const { pages, itemsPerPage, curPage } = this.state const itemsNotEmpty = items.length > 0 const visibleItems = _.slice(items, itemsPerPage * (curPage - 1), Math.min(items.length, itemsPerPage * curPage) ) const content = _.map(visibleItems, (item, id) => ( <div key={id}> {itemRenderer({ item })} </div> )) return ( <div style={{ textAlign: 'center' }}> {itemsNotEmpty ? content : <span>No items to show.</span>} {pages > 1 ? <Pagination items={pages} activePage={curPage} onSelect={this.handlePaginationSelect} boundaryLinks prev next first last ellipsis boundaryLinks maxButtons={4} /> : null } </div> ) } } export default ScrolledList <file_sep>/app/components/CategoryList/CategoryList.js /** * Created by dmitru on 6/5/16. */ import React from 'react' import Category from '../Category' const CategoryList = ({ categories = [] }) => { const categoriesNotEmpty = categories.length > 0 let content = [] if (categoriesNotEmpty) { content = categories.map((category) => ( <Category key={category.id} {...category} /> )) } return ( <div> {categoriesNotEmpty ? content : <span>No items to show.</span>} </div> ) } CategoryList.propTypes = { categories: React.PropTypes.array, } export default CategoryList <file_sep>/app/reducers/auth.js import { createSelector } from 'reselect' import _ from 'lodash' import * as constants from '../constants' import cookie from '../utils/cookie' const initialState = { isLoggingIn: false, isSigningUp: false, token: null, errorLogin: null, errorSignup: null, } const authToken = cookie.get('token') if (authToken) { initialState.token = authToken } export const getAuthToken = (state) => state.auth.token const getLoginError = (state) => state.auth.errorLogin const getSignupError = (state) => state.auth.errorSignup export const getIsLoggingIn = (state) => state.auth.isLoggingIn export const getIsSigningUp = (state) => state.auth.isSigningUp export const getIsAuthenticated = createSelector( [getAuthToken], (token) => !_.isNull(token) ) export const getSignupErrorMessage = createSelector( [getSignupError], (error) => ((error && error.message) ? error.message : null) ) export const getLoginErrorMessage = createSelector( [getLoginError], (error) => ((error && error.message) ? error.message : null) ) export default function userUpdate(state = initialState, { type, payload }) { switch (type) { case constants.AUTH_LOGIN_REQUEST: return { ...state, isLoggingIn: true } case constants.AUTH_SIGNUP_REQUEST: return { ...state, isSigningUp: true } case constants.AUTH_LOGGED_IN: return { ...state, token: payload.token, isLoggingIn: false, isSigningUp: false, errorLogin: false, errorSignup: false, } case constants.AUTH_LOGGED_OUT: return { ...initialState, token: null } case constants.AUTH_LOGIN_ERROR: return { ...state, errorLogin: payload, isLoggingIn: false } case constants.AUTH_SIGNUP_ERROR: return { ...state, errorSignup: payload, isSigningUp: false } default: return state } } <file_sep>/app/containers/AddEntryForm/index.js /** * Created by dmitru on 6/12/16. */ import AddEntryForm from './AddEntryForm' export default AddEntryForm <file_sep>/app/components/Loader/Loader.js /** * Created by dmitru on 6/5/16. */ import React from 'react' import styles from './Loader.scss' export default () => ( <div className={styles.loader}> Loading... </div> ) <file_sep>/app/reducers/entries.js import _ from 'lodash' import * as constants from '../constants' const initialState = { isLoading: false, items: null, error: null, selectedItems: [], } export default function entriesUpdate(state = initialState, { type, payload }) { switch (type) { case constants.ENTRIES_FETCH_REQUEST: return { ...state, isLoading: true } case constants.ENTRIES_FETCH_SUCCESS: return { ...state, isLoading: false, items: payload } case constants.ENTRIES_FETCH_FAILURE: return { ...state, error: payload } case constants.ENTRIES_ADD_REQUEST: return { ...state, items: [...state.items, payload.entry] } case constants.ENTRIES_ADD_SUCCESS: { const newEntries = _.map(state.items, (item) => { if (item.id === payload.temporaryId) { return payload.entry } return item }) return { ...state, items: newEntries } } case constants.ENTRIES_UPDATE: { const updatedEntry = payload.entry const newEntries = _.map(state.items, (e) => ( e.id === updatedEntry.id ? updatedEntry : e )) return { ...state, items: newEntries } } case constants.ENTRIES_DELETE: { const newEntries = _.filter(state.items, (e) => ( !_.includes(payload.ids, e.id) )) return { ...state, items: newEntries, selectedItems: [] } } case constants.ENTRIES_TOGGLE_SELECTION: { const selectedToToggle = _.intersection(state.selectedItems, payload.ids) const unselectedToToggle = _.difference(payload.ids, selectedToToggle) const newSelectedItems = _.union(unselectedToToggle, _.difference(state.selectedItems, selectedToToggle)) return { ...state, selectedItems: newSelectedItems } } case constants.AUTH_LOGGED_OUT: return { ...initialState } default: return state } } export const getEntries = (state) => state.entries.items export const getSelectedEntriesIds = (state) => state.entries.selectedItems <file_sep>/app/actions/categories.js import _ from 'lodash' import * as constants from '../constants' import api from '../api' export function fetchCategories() { return (dispatch, getState) => { const { auth: { token } } = getState() dispatch({ type: constants.CATEGORIES_FETCH_REQUEST, }) api.categories.getAll({ token }) .then((res) => { const data = res.body dispatch({ type: constants.CATEGORIES_FETCH_SUCCESS, payload: data, }) }) .catch((err) => { dispatch({ type: constants.CATEGORIES_FETCH_FAILURE, payload: err.data, }) }) } } export function fetchCategoriesIfNeeded() { return (dispatch, getState) => { const { categories } = getState() if (_.isNull(categories.items) && !categories.isLoading) { dispatch(fetchCategories()) } } } export function addCategory({ category }) { return (dispatch) => { // Optimistically add the new category to the list of categories // Generate temporary id for the category, which later will be replaced with real id // when the server returns response const temporaryId = `tmp_id_${(new Date).getTime()}_${Math.random() * 100000000}` dispatch({ type: constants.CATEGORIES_ADD_REQUEST, payload: { category: { ...category, id: temporaryId, isSaving: true, }, }, }) api.categories.create({ category }) .then((res) => { dispatch({ type: constants.CATEGORIES_ADD_SUCCESS, payload: { temporaryId, category: res.body, }, }) }) .catch((err) => { dispatch({ type: constants.CATEGORIES_ADD_FAILURE, payload: { temporaryId, category: err, }, }) }) } } export function toggleSelection({ id, ids }) { if (!_.isUndefined(ids)) { return { type: constants.CATEGORIES_TOGGLE_SELECTION, payload: { ids, }, } } return { type: constants.CATEGORIES_TOGGLE_SELECTION, payload: { ids: [id], }, } } export function updateCategory({ category }) { return (dispatch) => { dispatch({ type: constants.CATEGORIES_UPDATE, payload: { category: { ...category, isSaving: true, }, }, }) api.categories.update({ category }) .then(() => { dispatch({ type: constants.CATEGORIES_UPDATE, payload: { category, }, }) }) .catch((err) => { dispatch({ type: constants.CATEGORIES_UPDATE_FAILURE, payload: { error: err, }, }) }) } } export function deleteCategories({ ids }) { return (dispatch) => { dispatch({ type: constants.CATEGORIES_DELETE, payload: { ids, }, }) api.categories.del({ ids }).end() } } <file_sep>/server/routes/index.js const api = require('./auth') const routes = { api, } module.exports = routes <file_sep>/app/actions/auth/tests/auth.test.js import configureMockStore from 'redux-mock-store' import thunk from 'redux-thunk' import _ from 'lodash' import { login, logout } from '../auth' import { expect, mockApi } from '../../../utils/testUtils' import authLoggedInStub from './stubs/authLoggedIn.stub.json' import authErrorWrongCredentialsStub from './stubs/authErrorWrongCredentials.stub.json' import * as constants from '../../../constants' const middlewares = [thunk] const mockStore = configureMockStore(middlewares) describe('async actions', () => { afterEach(() => { mockApi.reset() }) it('creates AUTH_LOGGED_IN when successfully signed in', (done) => { mockApi.onPost('/api/login') .replyOnce(authLoggedInStub.status, authLoggedInStub.body) const expectedActions = [ { type: constants.AUTH_LOGIN_REQUEST }, { type: constants.AUTH_LOGGED_IN, payload: { token: 'a-token-string' } }, ] const store = mockStore({}) return store.dispatch(login({ email: '<EMAIL>', password: '<PASSWORD>' })) .then(() => { expect(store.getActions()).to.deep.equal(expectedActions) done() }) }) it('creates AUTH_LOGIN_ERROR when cannot sign in (server error)', (done) => { mockApi.onPost('/api/login') .replyOnce(500) const expectedActions = [ { type: constants.AUTH_LOGIN_REQUEST }, { type: constants.AUTH_LOGIN_ERROR, payload: { errorCode: constants.ERROR_SERVER, status: 500, message: 'Server error', }, }, ] const store = mockStore({}) return store.dispatch(login({ email: '<EMAIL>', password: '<PASSWORD>' })) .then(() => { expect(store.getActions()).to.deep.equal(expectedActions) done() }) }) it('creates AUTH_LOGIN_ERROR when cannot sign in (wrong credentials)', (done) => { mockApi.onPost('/api/login') .replyOnce(authErrorWrongCredentialsStub.status, authErrorWrongCredentialsStub.body) const expectedActions = [ { type: constants.AUTH_LOGIN_REQUEST }, { type: constants.AUTH_LOGIN_ERROR, payload: { errorCode: 'WRONG_CREDENTIALS', status: authErrorWrongCredentialsStub.status, }, }, ] const store = mockStore({}) store.dispatch(login({ email: '<EMAIL>', password: '<PASSWORD>' })) .then(() => { const actions = store.getActions() expect(actions).to.have.lengthOf(2) actions[1].payload = _.omit(actions[1].payload, 'message') expect(actions).to.deep.equal(expectedActions) done() }) }) it('creates AUTH_LOGGED_OUT when logged out', () => { const expectedAction = { type: constants.AUTH_LOGGED_OUT } expect(logout()).to.deep.equal(expectedAction) }) }) <file_sep>/app/containers/Entries/index.js import Entries from './Entries' export default Entries <file_sep>/app/actions/currencies.js import _ from 'lodash' import * as constants from '../constants' import api from '../api' export function fetchCurrencies() { return (dispatch) => { dispatch({ type: constants.CURRENCIES_FETCH_REQUEST, }) api.currencies.get() .then((res) => { const data = res.body dispatch({ type: constants.CURRENCIES_FETCH_SUCCESS, payload: data, }) }) .catch((err) => { dispatch({ type: constants.CURRENCIES_FETCH_FAILURE, payload: err.data, }) }) } } export function fetchCurrenciesIfNeeded() { return (dispatch, getState) => { const { currencies } = getState() if (_.isNull(currencies.items) && !currencies.isLoading) { dispatch(fetchCurrencies()) } } } <file_sep>/app/containers/App.js import React, { Component } from 'react' import { connect } from 'react-redux' import _ from 'lodash' import NotificationSystem from 'react-notification-system' import { getIsAuthenticated } from '../reducers/auth' import { getUserProfile } from '../reducers/profile' import { fetchUserProfileIfNeeded } from '../actions/profile' import { fetchCurrenciesIfNeeded } from '../actions/currencies' import { fetchEntriesIfNeeded } from '../actions/entries' import { fetchCategoriesIfNeeded } from '../actions/categories' import Layout from './Layout' import Loader from '../components/Loader' class App extends Component { static propTypes = { children: React.PropTypes.element, readyToShowUi: React.PropTypes.bool.isRequired, isAuthenticated: React.PropTypes.bool.isRequired, } static childContextTypes = { notificationCenter: React.PropTypes.object, } constructor(props) { super(props) this.notificationCenter = null } getChildContext() { return { notificationCenter: this.notificationCenter } } componentWillMount() { this.fetchInitialDataIfNeeded(this.props) } componentWillReceiveProps(props) { this.fetchInitialDataIfNeeded(props) } fetchInitialDataIfNeeded(props) { const { isAuthenticated, dispatch } = props if (!isAuthenticated) { return } dispatch(fetchUserProfileIfNeeded()) dispatch(fetchCurrenciesIfNeeded()) dispatch(fetchEntriesIfNeeded()) dispatch(fetchCategoriesIfNeeded()) } render() { const { children, readyToShowUi } = this.props return ( <Layout> <NotificationSystem ref={(c) => { this.notificationCenter = c }} /> <div> {readyToShowUi ? children : <Loader />} </div> </Layout> ) } } const mapStateToProps = (state) => { const isAuthenticated = getIsAuthenticated(state) return { readyToShowUi: isAuthenticated ? !_.isNull(getUserProfile(state)) : true, isAuthenticated, } } export default connect(mapStateToProps)(App) <file_sep>/app/api/categories.js import client from '../utils/apiClient' export const getAll = () => ( client.get('/api/Categories') ) export const create = ({ category }) => ( client.post('/api/Categories').send(category) ) export const update = ({ category }) => ( client.put(`/api/Categories/${category.id}`).send(category) ) export const del = ({ ids }) => { if (Array.isArray(ids)) { return client.delete('/api/Categories').send({ ids }) } return client.delete(`/api/Categories/${ids}`) } <file_sep>/app/actions/entries.js import _ from 'lodash' import * as constants from '../constants' import api from '../api' export function fetchEntries() { return (dispatch) => { dispatch({ type: constants.ENTRIES_FETCH_REQUEST }) api.entries.getAll() .then((res) => { const data = res.body dispatch({ type: constants.ENTRIES_FETCH_SUCCESS, payload: data, }) }) .catch((err) => { dispatch({ type: constants.ENTRIES_FETCH_FAILURE, payload: err, }) }) } } export function fetchEntriesIfNeeded() { return (dispatch, getState) => { const { entries } = getState() if (_.isNull(entries.items) && !entries.isLoading) { dispatch(fetchEntries()) } } } export function addEntry({ entry }) { return (dispatch) => { // Optimistically add the new entry to the list of entries // Generate temporary id for the entry, which later will be replaced with real id // when the server returns response const temporaryId = `tmp_id_${(new Date).getTime()}_${Math.random() * 100000000}` dispatch({ type: constants.ENTRIES_ADD_REQUEST, payload: { entry: { ...entry, id: temporaryId, isSaving: true, }, }, }) api.entries.create({ entry }) .then((res) => { dispatch({ type: constants.ENTRIES_ADD_SUCCESS, payload: { temporaryId, entry: res.body, }, }) }) .catch((err) => { dispatch({ type: constants.ENTRIES_ADD_FAILURE, payload: { temporaryId, error: err, }, }) }) } } export function toggleSelection({ id, ids }) { if (!_.isUndefined(ids)) { return { type: constants.ENTRIES_TOGGLE_SELECTION, payload: { ids, }, } } return { type: constants.ENTRIES_TOGGLE_SELECTION, payload: { ids: [id], }, } } export function updateEntry({ entry }) { return (dispatch) => { dispatch({ type: constants.ENTRIES_UPDATE, payload: { entry: { ...entry, isSaving: true, }, }, }) api.entries.update({ entry }) .then(() => { dispatch({ type: constants.ENTRIES_UPDATE, payload: { entry, }, }) }) .catch((err) => { dispatch({ type: constants.ENTRIES_UPDATE_FAILURE, payload: { error: err, }, }) }) } } export function deleteEntries({ ids }) { return (dispatch) => { dispatch({ type: constants.ENTRIES_DELETE, payload: { ids, }, }) api.entries.del({ ids }).end() } } <file_sep>/app/utils/apiClient.js /** * Created by dmitriybor on 08.06.16. */ import superagentPromisePlugin from 'superagent-promise-plugin' import superagentDefaults from 'superagent-defaults' import superagent from 'superagent' const superagent2 = superagentPromisePlugin.patch(superagent) const superagent3 = superagentDefaults(superagent2) export default superagent3 <file_sep>/app/containers/EditCategoryForm/index.js import EditCategoryForm from './EditCategoryForm' export default EditCategoryForm <file_sep>/app/containers/Categories/Categories.js import React, { Component } from 'react' import { connect } from 'react-redux' import { Row, Col, Modal, Button } from 'react-bootstrap' import { reset as resetForm } from 'redux-form' import _ from 'lodash' import { createSelector } from 'reselect' import { getCategories, getSelectedCategories } from '../../reducers/categories' import { fetchCategoriesIfNeeded, addCategory, updateCategory, toggleSelection, deleteCategories, } from '../../actions/categories' import Category from '../../components/Category' import Loader from '../../components/Loader' import PaginatedList from '../../components/PaginatedList' import ListToolbar from '../../components/ListToolbar' import EditCategoryForm from '../EditCategoryForm' import AddCategoryForm from '../AddCategoryForm' class Categories extends Component { static propTypes = { children: React.PropTypes.element, readyToShowUi: React.PropTypes.bool.isRequired, categories: React.PropTypes.array, selectedCategories: React.PropTypes.array.isRequired, } static contextTypes = { notificationCenter: React.PropTypes.object, } constructor(props) { super(props) this.handleAddCategory = this.handleAddCategory.bind(this) this.handleCategoryClick = this.handleCategoryClick.bind(this) this.handleEditModalSubmit = this.handleEditModalSubmit.bind(this) this.deleteCategories = this.deleteCategories.bind(this) this.closeEditModal = this.closeEditModal.bind(this) this.closeDeleteModal = this.closeDeleteModal.bind(this) this.toggleSelection = this.toggleSelection.bind(this) this.showDeleteModal = this.showDeleteModal.bind(this) this.showEditModal = this.showEditModal.bind(this) this.state = { showEditModal: false, showDeleteModal: false, } } componentWillMount() { this.fetchInitialDataIfNeeded() } handleAddCategory(values) { const { notificationCenter } = this.context const { dispatch } = this.props return new Promise((resolve, reject) => { const name = _.trim(values.name) if (_.isEmpty(name)) { reject({ name: 'A name is required', _error: 'Failed to add category' }) } else { dispatch(addCategory({ category: { name, }, })) dispatch(resetForm('addCategory')) notificationCenter.addNotification({ message: `Created category ${name}`, level: 'success', autoDismiss: 2, position: 'bl', dismissible: false, }) resolve() } }) } handleCategoryClick(entry) { if (entry.isSaving) { return } const { dispatch } = this.props dispatch(toggleSelection({ id: entry.id })) } showEditModal() { this.setState({ showEditModal: true }) } closeEditModal() { this.setState({ showEditModal: false }) } handleEditModalSubmit({ category }) { const { dispatch } = this.props dispatch(updateCategory({ category })) this.closeEditModal() } deleteCategories() { const { dispatch, selectedCategories } = this.props const selectedCategoriesIds = _.map(selectedCategories, (e) => e.id) dispatch(deleteCategories({ ids: selectedCategoriesIds })) this.closeDeleteModal() const { notificationCenter } = this.context const notificationText = selectedCategoriesIds.length > 1 ? `Deleted ${selectedCategoriesIds.length} categories` : `Deleted category ${name}` notificationCenter.addNotification({ message: notificationText, level: 'success', autoDismiss: 2, position: 'bl', dismissible: false, }) } showDeleteModal() { this.setState({ showDeleteModal: true }) } closeDeleteModal() { this.setState({ showDeleteModal: false }) } toggleSelection() { const { categories, selectedCategories, dispatch } = this.props if (_.isEmpty(selectedCategories)) { const allIdsNotSaving = _.map( _.filter(categories, (e) => !e.isSaving), (e) => e.id ) dispatch(toggleSelection({ ids: allIdsNotSaving })) } else { dispatch(toggleSelection({ ids: _.map(selectedCategories, (e) => e.id) })) } } fetchInitialDataIfNeeded() { const { dispatch } = this.props dispatch(fetchCategoriesIfNeeded()) } render() { const { children, readyToShowUi, categories, selectedCategories } = this.props if (!readyToShowUi) { return <Loader /> } const editModal = ( <Modal show={this.state.showEditModal} onHide={this.closeEditModal}> <Modal.Body> <h4>Edit categories</h4> </Modal.Body> <Modal.Footer> <EditCategoryForm category={_.isEmpty(selectedCategories) ? null : selectedCategories[0]} categories={categories} onCancel={this.closeEditModal} onSubmit={this.handleEditModalSubmit} /> </Modal.Footer> </Modal> ) const deleteModal = ( <Modal show={this.state.showDeleteModal} onHide={this.closeDeleteModal}> <Modal.Body> <h4>Are you sure?</h4> This action is irreversible. </Modal.Body> <Modal.Footer> <Button onClick={this.closeDeleteModal} autoFocus>No</Button> <Button bsStyle="danger" onClick={this.deleteCategories}>Yes</Button> </Modal.Footer> </Modal> ) return ( <Row> <Col xs={12} sm={8} smOffset={2} lg={6} lgOffset={3}> {editModal} {deleteModal} <AddCategoryForm onSubmit={this.handleAddCategory} /> <div style={{ height: '40px', paddingTop: '15px' }}> <ListToolbar editButtonEnabled={selectedCategories.length === 1} deleteButtonEnabled={selectedCategories.length > 0} toggleSelectionEnabled={selectedCategories.length > 0} onEditClick={this.showEditModal} onDeleteClick={this.showDeleteModal} onToggleSelectionClick={this.toggleSelection} /> </div> <div> <PaginatedList items={categories} itemRenderer={({ item }) => ( <Category {...item} onClick={() => this.handleCategoryClick(item)} /> )} /> </div> <div style={{ marginTop: '15px' }}>Number of categories: {categories.length}</div> <div> {children} </div> </Col> </Row> ) } } const categoriesViewSelector = createSelector( [getCategories], (categories) => ( _.sortBy(categories, (c) => c.name.toLowerCase()) ) ) const mapStateToProps = (state) => ({ readyToShowUi: !_.isNull(getCategories(state)), categories: categoriesViewSelector(state), selectedCategories: getSelectedCategories(state), }) export default connect(mapStateToProps)(Categories) <file_sep>/app/components/ListToolbar/ListToolbar.js import React from 'react' import { Glyphicon } from 'react-bootstrap' const ListToolbar = (props) => { // TODO: move the styles to a SASS file const styles = { activeToolbarLink: { fontWeight: 'bold', color: '#337ab7', transition: 'all 0.3s ease' }, inactiveToolbarLink: { fontWeight: 'bold', color: '#ccc', transition: 'all 0.3s ease' }, } const { editButtonEnabled, deleteButtonEnabled, toggleSelectionEnabled, onEditClick, onDeleteClick, onToggleSelectionClick, } = props const editButton = ( <a href="#" onClick={(e) => { e.preventDefault() if (editButtonEnabled && onEditClick) { onEditClick() } }} style={editButtonEnabled ? styles.activeToolbarLink : styles.inactiveToolbarLink} key="1" > <Glyphicon glyph="edit" />&nbsp;EDIT </a> ) const deleteButton = ( <a href="#" onClick={(e) => { e.preventDefault() if (deleteButtonEnabled && onDeleteClick) { onDeleteClick() } }} style={{ ...(deleteButtonEnabled ? styles.activeToolbarLink : styles.inactiveToolbarLink), marginLeft: '15px', }} key="2" > <Glyphicon glyph="trash" />&nbsp;DELETE </a> ) const toggleSelectionButton = ( <a href="#" onClick={(e) => { e.preventDefault() if (onToggleSelectionClick) { onToggleSelectionClick() } }} style={toggleSelectionEnabled ? styles.activeToolbarLink : styles.inactiveToolbarLink} key="3" > {toggleSelectionEnabled ? 'CLEAR' : 'ALL'} </a> ) const toolbarButtons = ( <div> {toggleSelectionButton} <div className="pull-right"> {editButton}{deleteButton} </div> </div> ) return ( <div> {toolbarButtons} </div> ) } ListToolbar.propTypes = { editButtonEnabled: React.PropTypes.bool.isRequired, deleteButtonEnabled: React.PropTypes.bool.isRequired, toggleSelectionEnabled: React.PropTypes.bool.isRequired, onEditClick: React.PropTypes.func, onDeleteClick: React.PropTypes.func, onToggleSelectionClick: React.PropTypes.func, } export default ListToolbar <file_sep>/app/containers/EditEntryForm/index.js import EditEntryForm from './EditEntryForm' export default EditEntryForm <file_sep>/app/containers/AddEntryForm/AddEntryForm.js /** * Created by dmitru on 6/12/16. */ /* * Taken from https://github.com/mjrussell/redux-auth-wrapper/blob/master/examples/basic/components/Login.js * */ import React, { Component } from 'react' import classNames from 'classnames' import _ from 'lodash' import { Row, Col, Button, Label, } from 'react-bootstrap' import { reduxForm } from 'redux-form' import { TextInput, TypeaheadInput, Switch, } from '../../components/FormFields' import { getCategories } from '../../reducers/categories' export const fields = ['amount', 'category', 'isIncome'] const validate = (values) => { const errors = {} if (values.category && !Array.isArray(values.category)) { errors.category = 'Unknown category' } if (!_.isEmpty(values.amount) && !/^[-+]?\d+(,\d+)*(\.\d+(e\d+)?)?$/.test(values.amount)) { errors.amount = 'A number is required' } return errors } class AddEntry extends Component { static propTypes = { categories: React.PropTypes.array.isRequired, fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired, onSubmit: React.PropTypes.func, } constructor(props) { super(props) this.state = {} } render() { const { fields: { amount, category, isIncome }, categories, handleSubmit } = this.props return ( <form className={classNames('form-horizontal')} onSubmit={handleSubmit}> <Row> <Col xs={6} sm={4} lg={4} xl={6} style={{ paddingRight: '5px' }} > <TypeaheadInput field={category} placeholder="Category" labelKey="name" options={categories} renderMenuItemChildren={(props, option) => ( <Label>{option.name}</Label> )} /> </Col> <Col xs={6} sm={4} lg={4} xl={6} style={{ paddingLeft: '5px' }} > <TextInput autoFocus autocomplete="off" placeholder="Amount" field={amount} id="amount" /> </Col> <Col xs={12} sm={4} lg={4} > <Col xs={6} sm={4} lg={4} style={{ paddingRight: '5px', textAlign: 'right' }} > <div className="pull-right"> <Switch field={isIncome} labels={{ on: 'INCOME', off: 'EXPENSE', }} switchStyles={{ width: 50, }} /> </div> </Col> <Col xs={6} style={{ paddingLeft: '5px', textAlign: 'left' }}> <Button type="submit" bsStyle="default" > ADD </Button> </Col> </Col> </Row> </form> ) } } const formConfig = { form: 'addEntry', fields, validate, initialValues: { isIncome: false, }, } const mapStateToProps = (state) => ({ categories: getCategories(state), }) export default reduxForm(formConfig, mapStateToProps)(AddEntry) <file_sep>/app/containers/Signup/Signup.js /* * Taken from https://github.com/mjrussell/redux-auth-wrapper/blob/master/examples/basic/components/Login.js * */ import { connect } from 'react-redux' import React, { Component } from 'react' import classNames from 'classnames' import { routerActions } from 'react-router-redux' import { Col, Row, Alert, Button, } from 'react-bootstrap' import { reduxForm } from 'redux-form' import Recaptcha from 'react-recaptcha' import _ from 'lodash' import Loader from '../../components/Loader' import { TextInput, PasswordInput, } from '../../components/FormFields' import { signup } from '../../actions/auth/auth' import { getIsSigningUp, getSignupErrorMessage, getIsAuthenticated } from '../../reducers/auth' import styles from './Signup.css' export const fields = ['email', 'password'] const validateForm = values => { const errors = {} if (!values.email) { errors.email = 'Required' } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address' } if (!values.password) { errors.password = '<PASSWORD>' } else if (values.password.length < 6) { errors.password = 'Should be longer <PASSWORD>' } return errors } class SignupContainer extends Component { static propTypes = { fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired, isSigningUp: React.PropTypes.bool.isRequired, isAuthenticated: React.PropTypes.bool.isRequired, signupError: React.PropTypes.string, redirect: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.func]), } constructor(props) { super(props) this.handleCaptchaResponse = this.handleCaptchaResponse.bind(this) this.state = { captchaResponse: null, } } componentWillMount() { this.ensureNotLoggedIn(this.props) } componentWillReceiveProps(props) { this.ensureNotLoggedIn(props) } handleSubmit = (values) => { const { dispatch } = this.props const { captchaResponse } = this.state dispatch(signup({ email: values.email, password: values.password, captchaResponse, })) } ensureNotLoggedIn = (props) => { const { dispatch, redirect, isAuthenticated } = props if (isAuthenticated) { dispatch(routerActions.replace(redirect)) } } handleCaptchaResponse = (response) => { console.log(response) this.setState({ captchaResponse: response }) } render() { const { fields: { email, password }, signupError, isSigningUp } = this.props const spinner = isSigningUp ? <Loader /> : null return ( <div> <Col xs={6} xsOffset={3} style={{ textAlign: 'center' }}> <h2>Sign up</h2> <form className={classNames(styles.loginForm, 'form-horizontal')} onSubmit={this.props.handleSubmit(this.handleSubmit)} > <Row> <Alert bsStyle="info"> <strong>Hint</strong>: use the following email: <code>"<EMAIL>"</code> </Alert> </Row> <Row> <TextInput field={email} id="email" label="Email:" /> </Row> <Row> <PasswordInput field={password} id="password" label="Password:" /> </Row> <Row> <div className="pull-right" style={{ marginBottom: '15px' }}> <Recaptcha sitekey="<KEY>" render="explicit" onloadCallback={(arg) => console.log(arg)} verifyCallback={this.handleCaptchaResponse} /> </div> </Row> <Row> <Button type="submit" disabled={isSigningUp || _.isNull(this.captchaResponse)}> Sign up </Button> </Row> <Row style={{ marginTop: '15px' }}> {signupError ? ( <Alert bsStyle="danger"> <strong>Can't sign up:</strong> {signupError} </Alert>) : null} </Row> <Row> {spinner} </Row> </form> </Col> </div> ) } } const SignupFormContainer = reduxForm({ form: 'signup', fields, validateForm, })(SignupContainer) const mapStateToProps = (state, ownProps) => { const redirect = ownProps.location.query.redirect || '/' return { redirect, signupError: getSignupErrorMessage(state), isAuthenticated: getIsAuthenticated(state), isSigningUp: getIsSigningUp(state), } } export default connect(mapStateToProps)(SignupFormContainer) <file_sep>/app/components/FormFields/TypeaheadInput.js import React, { PropTypes } from 'react' import _ from 'lodash' import Typeahead from 'react-bootstrap-typeahead' import FormField from './FormField' export default class Select extends FormField { static propTypes = { field: PropTypes.object.isRequired, } constructor(props) { super(props) this.handleBlur = this.handleBlur.bind(this) this.handleKeydown = this.handleKeydown.bind(this) } handleBlur(ev) { const { options, field } = this.props const value = ev.nativeEvent.target.value const matchedOption = _.find(options, (o) => o.name === value) if (matchedOption) { field.onChange([matchedOption]) } else { field.onBlur(ev) } } handleKeydown(e) { const keyCode = e.keyCode || e.which if (keyCode === 13) { e.preventDefault() } } render() { const { field, help, label, options, ...inputProps } = this.props return ( <div onKeyDown={this.handleKeydown}> <FormField field={field} help={help} inputProps={inputProps} label={label}> <Typeahead selected={Array.isArray(field.value) ? field.value : []} {...inputProps} options={options} onBlur={this.handleBlur} onChange={field.onChange} /> </FormField> </div> ) } } <file_sep>/app/reducers/profile.js import * as constants from '../constants' const initialState = { isLoading: false, user: null, error: null, } export default function profileUpdate(state = initialState, { type, payload }) { switch (type) { case constants.PROFILE_FETCH_REQUEST: return { ...state, isLoading: true } case constants.PROFILE_FETCH_SUCCESS: return { ...state, isLoading: false, user: payload } case constants.AUTH_LOGGED_OUT: return { ...initialState } default: return state } } export const getUserProfile = (state) => state.profile.user <file_sep>/README.md # (Yet Another) Redux Starter Kit [![Dependency Status](https://david-dm.org/dmitru/redux-bootstrap-starter-kit.svg)](https://david-dm.org/dmitru/redux-bootstrap-starter-kit) [![Build Status](https://travis-ci.org/dmitru/redux-bootstrap-starter-kit.svg?branch=master)](https://travis-ci.org/dmitru/redux-bootstrap-starter-kit) ## What is it? This is my try at creating a boilerplate project for React webapps. That said, **this boilerplate shouldn't probably be used in production - there are far better alternatives.** It's best to see it as my own educational adventure - I did learn a great deal about modern web tools while putting them all together in this project. In it's essense, it's a front-end part of a **simple CRUD application for tracking personal incomes/expenses**. Among other things, it showcases: - authentication (mocked on backend) - signing up form protected with [Recaptcha](https://www.google.com/recaptcha/intro/index.html) - client-side routing with [react-router-redux](https://github.com/reactjs/react-router-redux) - building with [webpack](https://webpack.github.io/) with hotreloading - [CSS modules](http://glenmaddern.com/articles/css-modules) with [SASS](http://sass-lang.com/) - ...and more! The backend is a mock: most of AJAX API calls are emulated on client and no real data is saved on the server. ## How to run it Install dependencies: ``npm i`` then run the dev server with hot-reloading: ``npm dev`` Or build a production bundle: ``npm build`` and run the Express.js server to serve it, render templates and mock an API: ``npm start`` ## Roadmap - [ ] describe the project structure in this README ## Credits The project was initially inspired by [this excellent tutorial](http://spapas.github.io/2016/03/02/react-redux-tutorial/). <file_sep>/app/components/FormFields/index.js /** * Created by dmitru on 6/11/16. */ import TextInput from './TextInput' import PasswordInput from './PasswordInput' import TypeaheadInput from './TypeaheadInput' import Switch from './Switch' export { TextInput, PasswordInput, TypeaheadInput, Switch, } <file_sep>/app/containers/Login/Login.js /* * Taken from https://github.com/mjrussell/redux-auth-wrapper/blob/master/examples/basic/components/Login.js * */ import React, { Component } from 'react' import classNames from 'classnames' import { routerActions } from 'react-router-redux' import { Col, Row, Alert, Button, } from 'react-bootstrap' import { reduxForm } from 'redux-form' import Loader from '../../components/Loader' import { TextInput, PasswordInput, } from '../../components/FormFields' import { login } from '../../actions/auth/auth' import { getIsAuthenticated, getIsLoggingIn, getLoginErrorMessage } from '../../reducers/auth' import styles from './Login.css' export const fields = ['email', 'password'] const validate = values => { const errors = {} if (!values.email) { errors.email = 'Required' } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address' } if (!values.password) { errors.password = '<PASSWORD>' } else if (values.password.length < 6) { errors.password = 'Should be longer than 6 characters' } return errors } class LoginContainer extends Component { static propTypes = { fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired, isAuthenticating: React.PropTypes.bool.isRequired, isAuthenticated: React.PropTypes.bool.isRequired, loginError: React.PropTypes.string, redirect: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.func]), } componentWillMount() { this.ensureNotLoggedIn(this.props) } componentWillReceiveProps(props) { this.ensureNotLoggedIn(props) } handleSubmit = (values) => { const { dispatch } = this.props dispatch(login({ email: values.email, password: values.password, })) } ensureNotLoggedIn = (props) => { const { dispatch, redirect, isAuthenticated } = props if (isAuthenticated) { dispatch(routerActions.replace(redirect)) } } render() { const { fields: { email, password }, loginError, isAuthenticating } = this.props const spinner = isAuthenticating ? <Loader /> : null return ( <div> <Col xs={6} xsOffset={3} style={{ textAlign: 'center' }}> <h2>Log in to the app</h2> <form className={classNames(styles.loginForm, 'form-horizontal')} onSubmit={this.props.handleSubmit(this.handleSubmit)} > <Row> <Alert bsStyle="info"> <strong>Hint</strong>: use the following email: <code>"<EMAIL>"</code> and <strong> any password</strong> </Alert> </Row> <Row> <TextInput field={email} id="email" label="Email:" /> </Row> <Row> <PasswordInput field={password} id="password" label="Password:" /> </Row> <Row> <Button type="submit" disabled={isAuthenticating}> Log in </Button> <Button onClick={() => this.props.dispatch(routerActions.replace('/signup'))} disabled={isAuthenticating} style={{ marginLeft: '15px' }} > Sign up </Button> </Row> <Row style={{ marginTop: '15px' }}> {loginError ? ( <Alert bsStyle="danger"> <strong>Can't login: </strong>{loginError} </Alert>) : null} </Row> <Row> {spinner} </Row> </form> </Col> </div> ) } } const formConfig = { form: 'login', fields, validate, } const mapStateToProps = (state, ownProps) => { const redirect = ownProps.location.query.redirect || '/' return { redirect, loginError: getLoginErrorMessage(state), isLoggingIn: getIsLoggingIn(state), isAuthenticated: getIsAuthenticated(state), } } export default reduxForm(formConfig, mapStateToProps)(LoginContainer) <file_sep>/app/api/auth.js import client from '../utils/apiClient' export const login = ({ email, password }) => ( client.post('/auth/login').send({ email, password }) ) export const signup = ({ email, password, captchaResponse }) => ( client.post('/auth/signup').send({ email, password, captchaResponse }) ) <file_sep>/app/components/FormFields/TextInput.js // Source: // https://gist.github.com/insin/bbf116e8ea10ef38447b import React, { PropTypes } from 'react' import FormField from './FormField' export default class TextInput extends FormField { static propTypes = { field: PropTypes.object.isRequired, } render() { const { field, help, label, placeholder, ...inputProps } = this.props return ( <FormField field={field} help={help} inputProps={inputProps} label={label}> <input value={field.value} {...inputProps} placeholder={placeholder} className="form-control" name={field.name} onBlur={field.onBlur} onChange={field.onChange} /> </FormField> ) } } <file_sep>/app/containers/EditCategoryForm/EditCategoryForm.js import React, { Component } from 'react' import _ from 'lodash' import classNames from 'classnames' import { Button, } from 'react-bootstrap' import { reduxForm } from 'redux-form' import { TextInput, } from '../../components/FormFields' export const fields = ['name'] const validate = (values, props) => { const errors = {} const name = _.trim(values.name) if (_.isEmpty(name)) { errors.name = 'A name is required' } const { otherCategories } = props if (_.includes(_.map(otherCategories, (c) => c.name), name)) { errors.name = 'This name is already used by another category' } return errors } const EditCategoryForm = ({ fields: { name }, handleSubmit, onCancel, }) => ( <form className={classNames('form-horizontal')} onSubmit={handleSubmit}> <TextInput placeholder="Name of category" field={name} id="name" /> <Button bsStyle="default" onClick={onCancel}>Cancel</Button> <Button type="submit" bsStyle="default">Save</Button> </form> ) EditCategoryForm.propTypes = { initialValues: React.PropTypes.object, fields: React.PropTypes.object.isRequired, handleSubmit: React.PropTypes.func.isRequired, otherCategories: React.PropTypes.array.isRequired, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, } const formConfig = { form: 'editCategory', fields, validate, } const EditCategoryFormComponent = reduxForm(formConfig)(EditCategoryForm) class EditCategoryFormWrapper extends Component { static propTypes = { category: React.PropTypes.object, categories: React.PropTypes.array.isRequired, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, } constructor(props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) } getFieldsFromCategory(category) { if (!category) { return {} } return { name: category.name, } } handleSubmit(data) { const { category, onSubmit } = this.props onSubmit({ category: { ...category, name: _.trim(data.name), }, }) } render() { const { onCancel, category, categories } = this.props const otherCategories = _.filter(categories, (c) => c.id !== category.id) console.log([otherCategories, categories, category]) return ( <EditCategoryFormComponent onSubmit={this.handleSubmit} onCancel={onCancel} otherCategories={otherCategories} initialValues={this.getFieldsFromCategory(category)} /> ) } } export default EditCategoryFormWrapper
2b3015defb3fdae3bbe061ae6eab73bab1f22482
[ "JavaScript", "Markdown" ]
40
JavaScript
dmitru/redux-bootstrap-starter-kit
d8c13bd6f9b8ef8d749e3944f5de9db1561d91e0
6b9f6fc702704269531531399fd386c49ddad29c
refs/heads/master
<repo_name>sborrazas/static_app_template<file_sep>/config.ru map "/" do use(Rack::Static, { :urls => ["/javascripts", "/images", "/stylesheets"], :root => File.join(Dir.pwd, "public") }) app = lambda do |env| headers = { "Content-Type" => "text/html", "Cache-Control" => "public, max-age=86400" } if env["PATH_INFO"] == "/" && env["REQUEST_METHOD"] == "GET" [ 200, headers, File.open("public/index.html", File::RDONLY) ] else [404, { "Content-Type" => "text/html" }, ["Not Found"]] end end run app end <file_sep>/public/javascripts/index.js console.log("CHANGEME");
e77b88b9707787bd2b2bcf5baa52bf42093e8171
[ "JavaScript", "Ruby" ]
2
Ruby
sborrazas/static_app_template
5e1044e9e9d1643804be41b27592e79291473a7e
b001db77fc7aef2fc4e70682352fd64e5cb7d39c
refs/heads/master
<repo_name>emilia-renner/virtual-bookstore<file_sep>/catalog/application.py # Import packages import os from flask import (Flask, render_template, request, redirect, url_for, jsonify, flash) from sqlalchemy import create_engine, asc from sqlalchemy.orm import sessionmaker from database_setup import User, Base, Category, Book from flask import session as login_session from flask import make_response, send_from_directory from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from werkzeug.utils import secure_filename import random import string import httplib2 import json import requests app = Flask(__name__, template_folder='templates') # Import client ID information for Gplus signin CLIENT_ID = json.loads( open('client_secrets.json', 'r').read())['web']['client_id'] APPLICATION_NAME = "Virtual Bookstore" engine = create_engine('sqlite:///virtual_bookstore.db?check_same_thread=False') # noqa E501 Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Create anti-forgery state token @app.route('/login') def showLogin(): state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32)) login_session['state'] = state return render_template('login.html', STATE=state) # Connect to Google @app.route('/gconnect', methods=['POST']) def gconnect(): # Validate state token if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response # Obtain authorization code code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) # Submit request, parse response h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1].decode('utf-8')) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is used for the intended user. gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response( json.dumps("Token's user ID doesn't match given user ID."), 401) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: response = make_response( json.dumps("Token's client ID does not match app's."), 401) response.headers['Content-Type'] = 'application/json' return response stored_access_token = login_session.get('access_token') stored_gplus_id = login_session.get('gplus_id') if stored_access_token is not None and gplus_id == stored_gplus_id: response = make_response( json.dumps('Current user is already connected.'), 200) response.headers['Content-Type'] = 'application/json' return response # Store the access token in the session for later use. login_session['access_token'] = credentials.access_token login_session['gplus_id'] = gplus_id print(login_session['gplus_id']) # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() print(data) login_session['username'] = data.get('name', False) login_session['picture'] = data['picture'] login_session['email'] = data['email'] # ADD PROVIDER TO LOGIN SESSION login_session['provider'] = 'google' # see if user exists, if it doesn't make a new one user_id = getUserID(data['email']) if not user_id: user_id = createUser(login_session) login_session['user_id'] = user_id output = '' output += '<h1>Welcome ' if login_session['username']: output += login_session['username'] output += '!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 300px; '\ 'height: 300px;' \ 'border-radius: 150px;' \ '-webkit-border-radius: 150px;' \ '-moz-border-radius: 150px;"> ' if login_session['username']: flash("You are now logged in as %s." % login_session['username']) print("done!") return output # User Helper Functions def createUser(login_session): newUser = User(name=login_session['username'], email=login_session['email'], picture=login_session['picture']) # noqa E501 session.add(newUser) session.commit() user = session.query(User).filter_by(email=login_session['email']).one() return user.id def getUserInfo(user_id): user = session.query(User).filter_by(id=user_id).one() return user def getUserID(email): user = session.query(User).filter_by(email=email).one() return user.id # Disconnect from Google - Revoke a current user's token # and reset their login_session @app.route('/gdisconnect') def gdisconnect(): access_token = login_session.get('access_token') if access_token is None: print('Access Token is None') response = make_response(json.dumps('Current user not connected.'), 401) response.headers['Content-Type'] = 'application/json' return response print('In gdisconnect access token is %s', access_token) print('User name is: ') print(login_session['username']) url = ('https://accounts.google.com/o/oauth2/revoke?token=%s' % login_session['access_token']) h = httplib2.Http() result = h.request(url, 'GET')[0] print('result is ') print(result) if result['status'] == '200': response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return response else: response = make_response( json.dumps('Failed to revoke token for given user.', 400)) response.headers['Content-Type'] = 'application/json' return response # JSON Endpoints @app.route('/categories/<int:category_id>/JSON') def categoriesJSON(category_id): books = session.query(Book).filter_by(category_id=category_id).all() return jsonify(Books=[i.serialize for i in books]) @app.route('/categories/<int:category_id>/<int:book_id>/JSON') def bookJSON(category_id, book_id): book = session.query(Book).filter_by(id=book_id).all() return jsonify(BookInfo=[i.serialize for i in book]) # Initial routing function which queries the categories database- main page @app.route('/', methods=['GET', 'POST']) def categories(): categories = session.query(Category).all() return render_template('main.html', categories=categories) # Routing function to add a new category to the categories database @app.route('/categories/new', methods=['GET', 'POST']) def newCategory(): if 'username' not in login_session: flash('Please login to continue.') return redirect('/login') if request.method == 'POST': newItem = Category(name=request.form['name'], user_id=login_session['user_id']) session.add(newItem) session.commit() flash('New category, %s, successfully created.' ' You can now add books for this category.' % newItem.name) return redirect(url_for('categories')) else: return render_template('addCategory.html') # Routing function to delete a category you have created @app.route('/categories/<int:category_id>/delete', methods=['GET', 'POST']) def deleteCategory(category_id): if 'username' not in login_session: flash('Please login to continue.') return redirect('/login') itemToDelete = session.query(Category).filter_by(id=category_id).one() if itemToDelete.user_id != login_session['user_id']: flash('You are not authorized to delete this category.') return redirect(url_for('categories')) if request.method == 'POST': session.delete(itemToDelete) flash('%s Successfully Deleted' % itemToDelete.name) session.commit() return redirect(url_for('categories')) else: return render_template('deleteCategory.html', category_id=category_id, item=itemToDelete) # Routing function to view all books in a category @app.route('/categories/<int:category_id>') def books(category_id): category = session.query(Category).filter_by(id=category_id).one() creator = getUserInfo(category.user_id) books = session.query(Book).filter_by(category_id=category_id).all() return render_template('books.html', category=category, books=books, category_id=category_id, creator=creator) # routing function to view a particular book @app.route('/categories/<int:category_id>/<int:book_id>') def viewBook(category_id, book_id): category = session.query(Category).filter_by(id=category_id).one() book = session.query(Book).filter_by(id=book_id).one() creator = getUserInfo(category.user_id) books = session.query(Book).filter_by(category_id=category_id).all() return render_template('viewBook.html', category=category, books=books, book=book, category_id=category_id, book_id=book_id, creator=creator) # Allow for the user to upload images UPLOAD_FOLDER = 'static/images' ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024 # Determine if file uploaded by the user is allowed def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS # routing funtion to add a new book to a category @app.route('/categories/<int:category_id>/new', methods=['GET', 'POST']) def newBook(category_id): if 'username' not in login_session: flash('Please login to continue.') return redirect('/login') if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) newItem = Book(name=request.form['name'], picture=filename, author=request.form['author'], description=request.form['description'], category_id=category_id, user_id=login_session['user_id']) session.add(newItem) session.commit() flash("New book successfully created for %s." % newItem.name) return redirect(url_for('books', category_id=category_id)) else: return render_template('create.html', category_id=category_id) # routing funtion to edit information about a book @app.route('/categories/<int:category_id>/<int:book_id>/edit', methods=['GET', 'POST']) # noqa E501 def editBook(category_id, book_id): if 'username' not in login_session: flash('Please login to continue.') return redirect('/login') editedItem = session.query(Book).filter_by(id=book_id).one() category = session.query(Category).filter_by(id=category_id).one() book = session.query(Book).filter_by(id=book_id).one() if login_session['user_id'] != book.user_id: flash('You are not authorized to edit this book.') return redirect(url_for('books', category_id=category_id)) if request.method == 'POST': if request.form['name']: editedItem.name = request.form['name'] session.add(editedItem) session.commit() flash('Book successfully edited.') else: flash('Please edit name or enter a new name in order to edit additional information.') # noqa E501 return redirect(url_for('books', category_id=category_id)) else: return render_template('edit.html', category_id=category_id, book_id=book_id, item=editedItem) # routing function to delete a particular book @app.route('/categories/<int:category_id>/<int:book_id>/delete', methods=['GET', 'POST']) # noqa E501 def deleteBook(category_id, book_id): if 'username' not in login_session: flash('Please login to continue.') return redirect('/login') itemToDelete = session.query(Book).filter_by(id=book_id).one() if itemToDelete.user_id != login_session['user_id']: flash('You are not authorized to delete this book.') return redirect(url_for('books', category_id=category_id)) if request.method == 'POST': session.delete(itemToDelete) flash('%s Successfully Deleted' % itemToDelete.name) session.commit() return redirect(url_for('books', category_id=category_id)) else: return render_template('delete.html', category_id=category_id, book_id=book_id, item=itemToDelete) # uploaded image @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) # Disconnect based on provider @app.route('/disconnect') def disconnect(): print(login_session) if 'provider' in login_session: if login_session['provider'] == 'google': gdisconnect() del login_session['gplus_id'] del login_session['access_token'] if login_session['provider'] == 'facebook': fbdisconnect() del login_session['facebook_id'] del login_session['username'] del login_session['email'] del login_session['picture'] del login_session['user_id'] del login_session['provider'] flash("You have successfully been logged out.") return redirect(url_for('categories')) else: flash('You were not logged in') return redirect(url_for('categories')) if __name__ == '__main__': app.secret_key = 'super_secret_key' app.debug = True app.run(host='0.0.0.0', port=8000) <file_sep>/catalog/populate_db.py from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import User, Category, Base, Book engine = create_engine('sqlite:///virtual_bookstore.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create user Catalog User1 = User(name="User", email="<EMAIL>", picture='https://goo.gl/images/343vyt') session.add(User1) session.commit() # Fiction and Literature category category1 = Category(user_id=1, name="Fiction & Literature") session.add(category1) session.commit() book1 = Book(user_id=1, name="a spark of light", picture="aSparkOfLight.jpg", author="<NAME>", description="#1 NEW YORK TIMES BESTSELLER • The author of Small Great Things returns with a powerful and provocative new novel about ordinary lives that intersect during a heart-stopping crisis.", # noqa E501 category=category1) session.add(book1) session.commit() book2 = Book(user_id=1, name="The Girl with the Dragon Tattoo", picture="theGirlWithTheDragonTattoo.jpg", author="<NAME>", description="Murder mystery, family saga, love story, and financial intrigue combine into one satisfyingly complex and entertainingly atmospheric novel, the first in Stieg Larsson's thrilling Millenium series featuring Lisbeth Salander.", # noqa E501 category=category1) session.add(book2) session.commit() book3 = Book(user_id=1, name="Hippie", picture="Hippie.jpg", author="<NAME>", description="Drawing on the rich experience of his own life, best-selling author <NAME> takes us back in time to relive the dreams of a generation that longed for peace and dared to challenge the established social order. In Hippie, he tells the story of Paulo, a young, skinny Brazilian man with a goatee and long, flowing hair, who wants to become a writer and sets off on a journey in search of a deeper meaning for his life.", # noqa E501 category=category1) session.add(book3) session.commit() # Sci Fi & Fantasy Category category2 = Category(user_id=1, name="Sci-Fi & Fantasy") session.add(category2) session.commit() book1 = Book(user_id=1, name="<NAME> and the Goblet of Fire", picture="harryPotterAndTheGobletOfFire.jpg", author="<NAME>", description="<NAME> is midway through his training as a wizard and his coming of age. Harry wants to get away from the pernicious Dursleys and go to the International Quidditch Cup. He wants to find out about the mysterious event that's supposed to take place at Hogwarts this year, an event involving two other rival schools of magic, and a competition that hasn't happened for a hundred years. He wants to be a normal, fourteen-year-old wizard. But unfortunately for <NAME>, he's not normal - even by wizarding standards. And in his case, different can be deadly.", # noqa E501 category=category2) session.add(book1) session.commit() book2 = Book(user_id=1, name="The Lord of the Rings", picture="theLordOfTheRings.jpg", author="<NAME>", description="In ancient times the Rings of Power were crafted by the Elven-smiths, and Sauron, the Dark Lord, forged the One Ring, filling it with his own power so that he could rule all others. But the One Ring was taken from him, and though he sought it throughout Middle-earth, it remained lost to him. After many ages it fell by chance into the hands of the hobbit Bilbo Baggins.", # noqa E501 category=category2) session.add(book2) session.commit() book3 = Book(user_id=1, name="Perelandra", picture="Perelandra.jpg", author="<NAME>", description="The second book in C. S. Lewis's acclaimed Space Trilogy, which also includes Out of the Silent Planet and That Hideous Strength, Perelandra continues the adventures of the extraordinary Dr. Ransom. Pitted against the most destructive of human weaknesses, temptation, the great man must battle evil on a new planet -- Perelandra -- when it is invaded by a dark force. Will Perelandra succumb to this malevolent being, who strives to create a new world order and who must destroy an old and beautiful civilization to do so? Or will it throw off the yoke of corruption and achieve a spiritual perfection as yet unknown to man? The outcome of Dr. Ransom's mighty struggle alone will determine the fate of this peace-loving planet.", # noqa E501 category=category2) session.add(book3) session.commit() # Mystery category category3 = Category(user_id=1, name="Mystery") session.add(category3) session.commit() book1 = Book(user_id=1, name="The Neon Rain", picture="theNeonRain.jpg", author="<NAME>", description="New Orleans Detective <NAME> has fought too many battles: in Vietnam, with police brass, with killers and hustlers, and the bottle. Lost without his wife's love, Robicheaux haunts the intense and heady French Quarter—the place he calls home, and the place that nearly destroys him when he beomes involved in the case of a young prostitute whose body is found in a bayou. Thrust into the seedy world of drug lords and arms smugglers, Robicheaux must face down the criminal underworld and come to terms with his own bruised heart and demons to survive.", # noqa E501 category=category3) session.add(book1) session.commit() book2 = Book(user_id=1, name="<NAME>", picture="magpieMurders.jpg", author="<NAME>", description="From the New York Times bestselling author of Moriarty and <NAME>, this fiendishly brilliant, riveting thriller weaves a classic whodunit worthy of <NAME> into a chilling, ingeniously original modern-day mystery.", # noqa E501 category=category3) session.add(book2) session.commit() book3 = Book(user_id=1, name="The Word is Murder: A Novel", picture="TheWordIsMurderANovel.jpg", description="New York Times bestselling author of <NAME> and Moriarty, <NAME> has yet again brilliantly reinvented the classic crime novel, this time writing a fictional version of himself as the Watson to a modern-day Holmes.", # noqa E501 author="<NAME>", category=category3) session.add(book3) session.commit() # History Category category4 = Category(user_id=1, name="History") session.add(category4) session.commit() book1 = Book(user_id=1, name="The History of the Ancient World", picture="TheHistoryoftheAncientWorld.jpg", description="A lively and engaging narrative history showing the common threads in the cultures that gave birth to our own.", # noqa E501 author="<NAME>", category=category4) session.add(book1) session.commit() book2 = Book(user_id=1, name="The History of the Medieval World", picture="theHistoryOfTheMedievalWorld.jpg", author="<NAME>", description="A masterful narrative of the Middle Ages, when religion became a weapon for kings all over the world.", # noqa E501 category=category4) session.add(book2) session.commit() book3 = Book(user_id=1, name="Rome's Last Citizen", picture="romesLastCitizen.jpg", author="<NAME>", description="Rome's Last Citizen is a timeless story of an uncompromising man in a time of crisis and his lifelong battle to save the Republic.", # noqa E501 category=category4) session.add(book3) session.commit() # Business Category category5 = Category(user_id=1, name="Business") session.add(category5) session.commit() book1 = Book(user_id=1, name="Start Your Own Business", picture="startYourOwnBusiness.jpg", author="Entrepreneur Media, Inc.", description="Tapping into more than 33 years of small business expertise, the staff at Entrepreneur Media takes today’s entrepreneurs beyond opening their doors and through the first three years of ownership. This revised edition features amended chapters on choosing a business, adding partners, getting funded, and managing the business structure and employees, and also includes help understanding the latest tax and healthcare reform information and legalities.", # noqa E501 category=category5) session.add(book1) session.commit() book2 = Book(user_id=1, name="The Business Book", picture="theBusinessBook.jpg", author="DK", description="The Business Book is the perfect primer to key theories of business and management, covering inspirational business ideas, business strategy and alternative business models. One hundred key quotations introduce you to the work of great commercial thinkers, leaders, and gurus from <NAME> to <NAME>, and to topics spanning from start-ups to ethics.", # noqa E501 category=category5) session.add(book2) session.commit() book3 = Book(user_id=1, name="Good To Great", picture="goodToGreat.jpg", author="<NAME>", description="The Challenge: Built to Last, the defining management study of the nineties, showed how great companies triumph over time and how long-term sustained performance can be engineered into the DNA of an enterprise from the very beginning. But what about the company that is not born with great DNA? How can good companies, mediocre companies, even bad companies achieve enduring greatness?", # noqa E501 category=category5) session.add(book3) session.commit() print("added books!")
53fe1d1349bb81b2c740c750021aecb70989a7e6
[ "Python" ]
2
Python
emilia-renner/virtual-bookstore
7bbb0d396297aee19c3c4ebf932204596716ee44
990481e13481b24b13daba0f75709160c21d66fd
refs/heads/master
<file_sep>package lesson3; import java.util.*; public class HomeworkPt1 { public static void main(String[] args) { String[] array = {"Яблоко", "Пони", "Орех", "Паста", "Кофе", "Яблоко", "Часы", "Чайник", "Паста", "Яблоко", "Вишня", "Вишня", "Молоко", "Яблоко", "Перец", "Часы", "Кружка", "Ложка", "Мышка", "Кофе"}; FindUnique(array); System.out.println("-----"); CountRepeat(array); } private static void FindUnique(String[] array) { Set<String> set = new TreeSet<>(); for (String s : array) { set.add(s); } System.out.println("Перечень уникальных слов:"); System.out.println(set); } private static void CountRepeat(String[] array) { Map<String, Integer> hm = new TreeMap<>(); for (String str : array) { int count = 1; if (hm.containsKey(str)) { count += hm.get(str); } hm.put(str, count); } System.out.println("Количество повторений слов:"); for (Map.Entry<String, Integer> entry : hm.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } <file_sep>package ru.gb.java2.chat.server.chat; import ru.gb.java2.chat.server.chat.auth.AuthService; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MyServer { private final List<ClientHandler> clients = new ArrayList<>(); private final HashMap<String, ClientHandler> usersMatchClientHandlerHm = new HashMap<>(); private final List<String> usersOnline = new ArrayList<>(); private AuthService authService; public void start(int port) { try(ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server has been started"); authService = new AuthService(); while (true) { waitAndProcessNewClientConnection(serverSocket); } } catch (IOException e) { System.err.println("Failed to bind port " + port); e.printStackTrace(); } } private void waitAndProcessNewClientConnection(ServerSocket serverSocket) throws IOException { System.out.println("Waiting for new Client connection..."); Socket clientSocket = serverSocket.accept(); System.out.println("Client has been connected..."); ClientHandler clientHandler = new ClientHandler(this, clientSocket); clientHandler.handle(); } public void broadcast(ClientHandler sender, String message) throws IOException { for (ClientHandler client : clients) { if (sender != client) { client.sendMessage(message); } } } public void sendPrivateMessage(ClientHandler sender, String receiver, String message) throws IOException { usersMatchClientHandlerHm.get(receiver).sendMessage(message); } protected boolean subscribe(ClientHandler clientHandler, String username) { if (usersMatchClientHandlerHm.containsKey(username)) { return false; } else { clients.add(clientHandler); usersMatchClientHandlerHm.put(username, clientHandler); return true; } } protected void unsubscribe(ClientHandler clientHandler, String username) { clients.remove(clientHandler); usersMatchClientHandlerHm.remove(username); } public AuthService getAuthService() { return authService; } } <file_sep>package lesson6; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { public static final int PORT = 8189; private DataInputStream input; private DataOutputStream output; public static void main(String[] args) { new Server().start(); } private void start() { try (ServerSocket serverSocket = new ServerSocket(PORT)) { System.out.println("Server has been started, waiting for connection..."); Socket clientSocket = serverSocket.accept(); System.out.println("Client is connected"); input = new DataInputStream(clientSocket.getInputStream()); output = new DataOutputStream(clientSocket.getOutputStream()); inputMessage(); outputMessage(); } catch (IOException e) { System.err.println("Failed to bind port " + PORT); e.printStackTrace(); } } private void inputMessage() { Thread thread = new Thread(() -> { while (true) { try { String message = input.readUTF(); System.out.println("Client: " + message); if (message.equals("/end")) { System.out.println("Connection has been closed from client."); System.exit(0); } } catch (IOException e) { System.out.println("Connection has been closed."); break; } } }); thread.start(); } private void outputMessage() { Scanner scanner = new Scanner(System.in); while (true) { try { String message = scanner.next(); output.writeUTF(message); if (message.equals("/end")) { System.out.println("Connection is closing."); break; } } catch (IOException e) { System.out.println("Connection has been closed."); break; } } } } <file_sep>package lesson1; public interface Contestant { int run(); int jump(); void doActivity(Obstruction obstruction); int getMaxJump(); int getMaxRun(); } <file_sep>package lesson1; public class Human implements Contestant { private final String name; private final int maxJump; private final int maxRun; public Human(String name, int maxJump, int maxRun) { this.name = name; this.maxJump = maxJump; this.maxRun = maxRun; } public int getMaxJump() { return maxJump; } public int getMaxRun() { return maxRun; } @Override public int run() { System.out.println("Человек " + name + " пытается пробежать дистанцию"); return maxRun; } @Override public int jump() { System.out.println("Человек " + name + " пытается перепрыгнуть препятствие"); return maxJump; } @Override public void doActivity(Obstruction obstruction) { obstruction.doTry(this); } @Override public String toString() { return name; } } <file_sep>package lesson1; public interface Obstruction { void doTry(Contestant contestant); }
d7e8ba4b2e085a48f502a7ec1b7003056b6cf693
[ "Java" ]
6
Java
MuzafarovAA/GBJavaLvl2
03c18b6f052fd87cfdb43f81de64bd0781961b00
e6c5174a704303fa7618cb96c5222a5aa73c1065
refs/heads/master
<repo_name>Minidodo1/Forge-1.10.2<file_sep>/Forge-1.10.2/src/java/me/Minidodo/Scoocyjuice/OurMod/crafting/grasstoseed.java package me.Minidodo.Scoocyjuice.OurMod.crafting; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; public class grasstoseed { public grasstoseed(){ GameRegistry.addShapelessRecipe(new ItemStack(Items.WHEAT_SEEDS, 4), Blocks.GRASS); GameRegistry.addShapelessRecipe(new ItemStack(Items.WHEAT_SEEDS, 1), Blocks.DIRT); } } <file_sep>/Forge-1.10.2/src/java/me/Minidodo/Scoocyjuice/OurMod/items/SpiegelEi.java package me.Minidodo.Scoocyjuice.OurMod.items; import net.minecraft.item.Item; public final class SpiegelEi extends Item{ public SpiegelEi(String unlocalizedName){ super(); all(unlocalizedName); } @SuppressWarnings("static-access") public void all(String unlocalizedName){ this.setUnlocalizedName(unlocalizedName); this.setCreativeTab(getCreativeTab().FOOD); } }
6b3877fe5dc03b6e01ddab388305363863b409df
[ "Java" ]
2
Java
Minidodo1/Forge-1.10.2
51466014202d6af0d980bf1747b6892f3643f472
6925c9d7b65fdfa4a1e61415001e5823f4f26457
refs/heads/master
<repo_name>juliahw/i-hate-everyone<file_sep>/js/engines.js ////////////////////////////////////////////////////////// // BACTERIA ENGINE ////////////////////////////////////////////////////////// function BacteriaEngine(maxParticles) { this.maxParticles = maxParticles || 1000; this.particles = []; this.population = 0; // number of live particles this.resistance = 0; // average % resistance this.infectivity = 0; // average % infectivity } BacteriaEngine.prototype.spawnFrom = function (parent) { if (this.population >= this.maxParticles) return null; var bacterium = new Bacterium(parent.getPositionX(), parent.getPositionY()); // simulate cell division parent.resistance = Math.min(1, Math.random() * 2 * parent.mutationRate + parent.resistance); bacterium.resistance = parent.resistance; parent.infectivity = Math.min(1, Math.random() * 2 * parent.mutationRate + parent.infectivity); bacterium.infectivity = parent.infectivity; bacterium.growthRate = parent.growthRate; this.particles.push(bacterium); return bacterium; }; BacteriaEngine.prototype.spawnAt = function (positionX, positionY) { if (this.population >= this.maxParticles) return null; var bacterium = new Bacterium(positionX, positionY); this.particles.push(bacterium); return bacterium; }; BacteriaEngine.prototype.divide = function () { var length = this.particles.length; for (var i = 0; i < length; i++) { var bacterium = this.particles[i]; if (!bacterium.alive) continue; if (Math.random() < bacterium.growthRate) { this.spawnFrom(bacterium); } } } BacteriaEngine.prototype.update = function () { this.population = 0; this.resistance = 0; this.infectivity = 0; for (var i = 0; i < this.particles.length; i++) { var bact = this.particles[i]; if (!bact.alive) continue; // update positions bact.update(); // kill if life is used up if (bact.life-- <= 0) bact.kill(); // update stats this.population++; this.resistance += bact.resistance; this.infectivity += bact.infectivity; } // these are average percentages this.resistance = (this.resistance / this.population) || 0; this.infectivity = (this.infectivity / this.population) || 0; } BacteriaEngine.prototype.clean = function () { var bact = []; for (var i = 0; i < this.particles.length; i++) { if (this.particles[i].alive) bact.push(this.particles[i]); } this.particles = bact; } ////////////////////////////////////////////////////////// // POWERUP ENGINE ////////////////////////////////////////////////////////// function PowerupEngine() { this.particles = []; this.type = null; } PowerupEngine.prototype.spawnAt = function (positionX, positionY) { for (var i = 0; i < this.type.instances; i++) { var powerup = new Powerup(positionX, positionY, this.type); this.particles.push(powerup); } }; PowerupEngine.prototype.spawnFrom = function (parent) { var powerup = new Powerup(parent.getPositionX(), parent.getPositionY(), parent.type); this.particles.push(powerup); }; PowerupEngine.prototype.update = function () { for (var i = 0; i < this.particles.length; i++) { var powerup = this.particles[i]; if (!powerup.alive) continue; powerup.update(); } } PowerupEngine.prototype.clean = function () { var power = []; for (var i = 0; i < this.particles.length; i++) { if (this.particles[i].alive) power.push(this.particles[i]); } this.particles = power; } PowerupEngine.prototype.TYPES = { agar: { url: 'img/sprites/agar.png', radius: 5, MIN_SPEED: 0.1, MAX_SPEED: 0.5, price: 1, instances: 25, turningvelocity: Math.random() - 0.5, tagline: '<h5>Agar</h5>Feed your bacteria with this delicious seaweed gel.' }, penicillin: { url: 'img/sprites/anti-p.png', radius: 2, MIN_SPEED: 1, MAX_SPEED: 2, price: 5, instances: 100, tagline: '<h5>Penicillin</h5>Any superbacterium must be resistant to this common antibiotic.' }, streptomycin: { url: 'img/sprites/anti-s.png', radius: 2, MIN_SPEED: 1, MAX_SPEED: 2, price: 8, instances: 100, tagline: '<h5>Streptomycin</h5>Effective against both Gram-positive & Gram-negative bacteria.' }, ceftobiprole: { url: 'img/sprites/anti-c.png', radius: 4, MIN_SPEED: 1, MAX_SPEED: 2, price: 15, instances: 100, tagline: '<h5>Ceftobiprole</h5>A 5th-generation cephalosporin. Careful: this stuff is <i>strong</i>!' }, plasmids: { url: 'img/sprites/plasmid.png', radius: 2, MIN_SPEED: 0.1, MAX_SPEED: 0.2, price: 50, instances: 5, tagline: '<h5>Plasmids</h5>Insert plasmids from the flesh-eating Streptococcus A strand.' }, mutagens: { url: 'img/sprites/mutagen.png', radius: 4, MIN_SPEED: 0.5, MAX_SPEED: 1.0, price: 100, instances: 10, tagline: '<h5>Mutagens</h5>Chances are this will give you cancer...but YOLO, right?' } };<file_sep>/js/cutscenes.js intro1 = { element: $sceneTextMain, text: ['This is you.', 'You are a miserable grad student working at a bacterial genetics lab.', 'Your PI just received tenure. Hooray!', 'This means she no longer needs to care about your life, career, or wellbeing.' ] }; var intro2 = { element: $sceneTextMain, text: ['...as if she ever did.', 'As of a minute ago, you received the following email from her:' ] }; var intro3 = { element: $sceneTextLetter, text: ['Hello Slave,', '', 'I need you to run a 10,000 generation experiment on the bacilli in Incubator B.', 'Details are attached.', '', 'I’m on a lecture tour in Europe but I’ll be back in 4 weeks.', 'Have fun!!', '', '- Your PI', '', 'P.S. Don\'t bother me for help.' ] }; var intro4 = { element: $sceneTextMain, text: ['After some rough calculations, you realize the experiment will take approximately 6 years of your life.', 'This is the last straw. The world has treated you like dirt for far too long!!', 'It\'s time to plot your ultimate revenge.....', ] }; var week0 = { element: $sceneTextLetter, text: ['Dear Diary,', '', 'So it begins.', 'I have chosen a virulent strand of bacteria to begin my experiments.', '', 'The apocalypse starts now!' ] }; var week1 = { element: $sceneTextLetter, text: ['Dear Diary,', '', 'Today I was assigned an undergrad who\'s working on his thesis.', 'Thank goodness he\'s a premed... He doesn\'t question my motives as long as I promise him an A.', ] }; var week2 = { element: $sceneTextLetter, text: ['Dear Diary,', '', 'Today a female colleague took me out to lunch.', 'It was surprisingly pleasant. This is a small ray of hope for humanity.', '', 'It\'s a pity she\'ll have to die with the rest of them...' ] }; var week3 = { element: $sceneTextLetter, text: ['Dear Diary,', '', 'My PI is posting pictures of herself all over Facebook.', 'There she is, taking selfies in front of the Eiffel Tower.', '', 'Is she even working?!' ] }; var win = { element: $sceneTextMain, text: ['Great job!', 'You bred some pretty cool bacteria.', 'Unfortunately, while you were making your culture resistant to all kinds of antibiotics, you forgot to make it resistant to Tylenol.', 'You did, however, succeed in causing a meningitis scare at the university.', 'Your PI is impressed with your work and promotes you to a window desk.' ] }; function playScene(name) { switch (name) { case 'intro1': Velocity($sceneScreen, 'transition.fadeIn', 1000); Velocity($playerIntro, 'transition.bouncyIn', { display: 'block', duration: 1000, delay: 1000, complete: function () { typewriter(intro1, 0, function () { Velocity($playerIntro, 'transition.fadeOut'); playScene('intro2'); }); } }); break; case 'intro2': typewriter(intro2, 0, function () { playScene('intro3'); }); break; case 'intro3': typewriter(intro3, 0, function () { playScene('intro4'); }, true); break; case 'intro4': typewriter(intro4, 0, showHomeScreen); break; case 'week0': skip = false; Velocity($skipBtn, 'transition.slideUpIn'); Velocity($sceneScreen, 'transition.fadeIn', 1000); typewriter(week0, 0, function () { Velocity($sceneScreen, 'transition.fadeOut', 500); animateIn(); Game.init('NORMAL'); }, true); break; case 'week1': skip = false; Velocity($skipBtn, 'transition.slideUpIn'); Velocity($sceneScreen, 'transition.fadeIn'); typewriter(week1, 0, function () { Velocity($sceneScreen, 'transition.fadeOut', 500); Game.resume(); }, true); break; case 'week2': skip = false; Velocity($skipBtn, 'transition.slideUpIn'); Velocity($sceneScreen, 'transition.fadeIn', 1000); typewriter(week2, 0, function () { Velocity($sceneScreen, 'transition.fadeOut', 500); Game.resume(); }, true); break; case 'week3': skip = false; Velocity($skipBtn, 'transition.slideUpIn'); Velocity($sceneScreen, 'transition.fadeIn', 1000); typewriter(week3, 0, function () { Velocity($sceneScreen, 'transition.fadeOut', 500); Game.resume(); }, true); break; case 'win': skip = false; Game.over = true; animateOut(function () { Game.stopped = true; Velocity($skipBtn, 'transition.slideUpIn'); Velocity($sceneScreen, 'transition.fadeIn', 1000); typewriter(win, 0, function () { Velocity($sceneScreen, 'transition.fadeOut', 500); Velocity($gameover, 'transition.fadeIn', 1000); $gameoverText.innerHTML = 'It was fun while it lasted.'; }); for (var i = stage.children.length - 1; i >= 0; i--) { stage.removeChild(stage.children[i]); } buttons.forEach(function (button) { dehighlight(button); }); }); break; } } var skip = false; // Display text with a typewriter effect function typewriter(screen, index, callback, noDeletion) { if (index >= screen.text.length) { if (callback) callback(); return; } var charTime, extraTime; if (skip) { charTime = 0; extraTime = 0; } else if (screen.text[index].length === 0) { extraTime = 0; } else { charTime = 50; extraTime = 500; } // separate by letter var text = screen.text[index].split(''); // type each letter one by one text.forEach(function (letter, i) { setTimeout(function () { screen.element.insertAdjacentHTML('BeforeEnd', letter); }, charTime * i); }); // move on to the next index setTimeout(function () { if (noDeletion && index < screen.text.length - 1) { screen.element.insertAdjacentHTML('BeforeEnd', '<br>'); } else { screen.element.innerHTML = ''; } typewriter(screen, index + 1, callback, noDeletion); }, charTime * text.length + extraTime); } // Speed through the sequence function skipSequence() { skip = true; Velocity($skipBtn, 'transition.slideDownOut'); }<file_sep>/js/ui.js ////////////////////////////////////////////////////////// // DOM OBJECTS CACHE ////////////////////////////////////////////////////////// // cutscenes var $sceneScreen = document.getElementById('scene-screen'), $sceneTextMain = document.getElementById('scene-text-main'), $sceneTextLetter = document.getElementById('scene-text-letter'), $playerIntro = document.getElementById('player-intro'), $skipBtn = document.getElementById('btn-skip'); // gameplay var $playerProfile = document.getElementById('player-profile'), $piProfile = document.getElementById('pi-profile'), $canvas = document.getElementById('canvas'), $agar = document.getElementById('agar'), $penicillin = document.getElementById('penicillin'), $streptomycin = document.getElementById('streptomycin'), $ceftobiprole = document.getElementById('ceftobiprole'), $plasmids = document.getElementById('plasmids'), $mutagens = document.getElementById('mutagens'), $info = document.getElementById('info-box'), $alert = document.getElementById('alert-box'), $week = document.getElementById('week'), $day = document.getElementById('day'), $population = document.getElementById('population'), $resistance = document.getElementById('resistance'), $infectivity = document.getElementById('infectivity'), $funds = document.getElementById('funds'), $footer = document.getElementById('footer'), $stats = document.getElementById('stats'); // screens var $gameover = document.getElementById('gameover-screen'), $gameoverText = document.getElementById('gameover-text'), $homeScreen = document.getElementById('home-screen'), $startBtns = document.getElementsByClassName('btn-start'), $ihe = document.querySelectorAll('#home-screen h1'), $helpScreen = document.getElementById('about-screen'), $utilBtns = document.getElementById('util-btns'); ////////////////////////////////////////////////////////// // VELOCITY ANIMATIONS ////////////////////////////////////////////////////////// Velocity.RegisterEffect('transition.bouncyIn', { defaultDuration: 1000, calls: [ [{ opacity: [1, 0], translateY: [0, -1000] }, 0.60, { easing: "easeOutCirc" }], [{ translateY: -25 }, 0.15], [{ translateY: 0 }, 0.25]] }); Velocity.RegisterEffect("transition.bouncyOut", { defaultDuration: 1000, calls: [ [{ translateY: [-30, 0] }, 0.20], [{ translateY: [0, -30] }, 0.20], [{ opacity: [0, "easeInCirc", 1], translateY: -1000 }, 0.60] ] }) ////////////////////////////////////////////////////////// // SCREEN CHANGE HANDLERS ////////////////////////////////////////////////////////// // Display the launcher page function showHomeScreen() { Velocity($skipBtn, 'transition.slideDownOut'); Velocity($sceneScreen, 'transition.fadeOut'); // animate in home screen elements Velocity($homeScreen, 'transition.fadeIn', 1000); Velocity($ihe, 'transition.bounceDownIn', { delay: 1000, display: 'inline-block', stagger: 500, duration: 500 }); Velocity($startBtns, 'transition.slideUpIn', { duration: 500, delay: 2500 }); } // Start a new game canvas function newGame(mode) { if (mode === 'NORMAL') { Velocity($homeScreen, 'transition.slideUpOut'); playScene('week0'); } else { Velocity([$homeScreen, $gameover], 'transition.slideUpOut'); animateIn(); Game.init(mode || Game.mode); } } function restartGame() { Game.pause(function () { for (var i = stage.children.length - 1; i >= 0; i--) { stage.removeChild(stage.children[i]); } setTimeout(newGame, 500); }); } function animateIn(callback) { // animate in all game UI elements Velocity($footer, 'transition.slideUpIn', 1000); Velocity($playerProfile, 'transition.slideUpIn', { delay: 250 }) Velocity($piProfile, 'transition.slideUpIn', { delay: 500 }) Velocity($stats, 'transition.bouncyIn', { delay: 1000 }); Velocity([$canvas, $utilBtns], 'transition.fadeIn', { duration: 2000, delay: 1000, complete: callback }); } function animateOut(callback) { Velocity($stats, 'transition.bouncyOut'); Velocity($footer, 'transition.slideDownOut', 1000); Velocity($playerProfile, 'transition.slideDownOut', { delay: 250 }); Velocity($piProfile, 'transition.slideDownOut', { delay: 500 }); Velocity([$canvas, $utilBtns], 'transition.fadeOut', { duration: 1000, delay: 1000, complete: callback }); } // Display how-to-play screen function showHelpScreen() { Game.pause(function () { Velocity($helpScreen, 'transition.fadeIn', 1000); }); } function hideHelpScreen() { Velocity($helpScreen, 'transition.fadeOut', 500); Game.resume(); } // Display game over screen with endgame description function gameOver(text) { if (Game.over) return; Game.over = true; Game.pause(function () { for (var i = stage.children.length - 1; i >= 0; i--) { stage.removeChild(stage.children[i]); } Velocity($gameover, 'transition.fadeIn', 1000); }); $gameoverText.innerHTML = text; buttons.forEach(function (button) { dehighlight(button); }) } // show an in-game alert function showAlert(text) { var alert = document.createElement('p'); alert.innerHTML = text; $alert.appendChild(alert); setTimeout(function () { Velocity(alert, 'fadeOut'); }, 1000); } ////////////////////////////////////////////////////////// // BUTTON/MOUSE HANDLERS ////////////////////////////////////////////////////////// var buttons = [$agar, $penicillin, $streptomycin, $ceftobiprole, $plasmids, $mutagens]; // set powerup type to none function dehighlight(btn) { btn.className = 'col-xs-2 button'; Game.powerEngine.type = null; $info.innerHTML = 'Power up your bacteria:'; } // set powerup type to corresponding type function highlight(btn) { buttons.forEach(function (button) { button.className = 'col-xs-2 button'; }); btn.className += ' highlighted'; Game.powerEngine.type = Game.powerEngine.TYPES[btn.id]; $info.innerHTML = Game.powerEngine.TYPES[btn.id].tagline; } // assign click handlers for each button function setupButtons() { var toggleButton = function () { if (this.className === 'col-xs-2 button') highlight(this); else dehighlight(this); }; buttons.forEach(function (button) { button.onclick = toggleButton; }); } // assign mouseover and click handlers for petri dish function setupMouseHandlers() { // change cursor style on hover over petri dish renderer.view.addEventListener('mousemove', function (e) { if (isCollision(e.x, e.y, 0, Game.dish.positionX, Game.dish.positionY, Game.dish.radius)) { document.body.style.cursor = 'crosshair'; } else { document.body.style.cursor = 'default'; } }); // spawn powerup on click on petri dish renderer.view.addEventListener('mousedown', function (e) { if (!isCollision(e.x, e.y, 0, Game.dish.positionX, Game.dish.positionY, Game.dish.radius)) return; if (!Game.powerEngine.type) return // make sure player has enough funds var remaining = Game.funds - Game.powerEngine.type.price; if (Game.mode === 'SANDBOX' || remaining >= 0) { Game.powerEngine.spawnAt(e.x, e.y); Game.funds = remaining; // 2% chance that player gets cancer from mutagens if (Game.powerEngine.type === Game.powerEngine.TYPES.mutagens) { if (Math.random() < 0.02) { Game.cancer = true; } } } else { showAlert('Out of funds!'); } }); } document.addEventListener('keydown', function(e) { if (e.keyCode === 13 && e.altKey && !Game.win) { Game.win = true; playScene('win'); } });<file_sep>/js/powerup.js function Powerup(positionX, positionY, type) { this.sprite = PIXI.Sprite.fromImage(type.url); this.sprite.x = positionX; this.sprite.y = positionY; this.sprite.anchor.set(0.5); this.sprite.rotation = randomUniform(0, 2 * Math.PI); Game.powerContainer.addChild(this.sprite); this.turningvelocity = type.turningvelocity || 0; this.speed = randomUniform(type.MIN_SPEED, type.MAX_SPEED); this.direction = this.sprite.rotation; this.radius = type.radius; this.type = type; this.alive = true; } Powerup.prototype.kill = function () { Game.powerContainer.removeChild(this.sprite); this.alive = false; } Powerup.prototype.getPositionX = function () { return this.sprite.position.x; } Powerup.prototype.getPositionY = function () { return this.sprite.position.y; } Powerup.prototype.setPosition = function (x, y) { this.sprite.position.x = x; this.sprite.position.y = y; } Powerup.prototype.update = function () { this.direction += this.turningvelocity * 0.01; this.setPosition(this.getPositionX() + Math.sin(this.direction) * this.speed, this.getPositionY() + Math.cos(this.direction) * this.speed); } Powerup.prototype.onCollisionWithBacterium = function (bact) { this.kill(); };<file_sep>/js/game.js ////////////////////////////////////////////////////////// // GAME ////////////////////////////////////////////////////////// var Game = {}; Game.init = function (mode) { this.mode = mode; this.tick = 0; this.day = 1; this.week = 1; this.funds = 2500; this.stipend = 50; this.bactEngine = new BacteriaEngine(750); this.powerEngine = new PowerupEngine(); this.bactContainer = new PIXI.ParticleContainer(); this.powerContainer = new PIXI.Container(); stage.addChild(this.bactContainer); stage.addChild(this.powerContainer); width = window.innerWidth; height = window.innerHeight; this.dish = new PetriDish(width / 2, (height - 100) / 2, (height - 100) / 3); // (x, y, radius) this.cancer = false; this.stopped = false; this.over = false; $day.innerHTML = this.day; $week.innerHTML = this.week; // initialize cell growth for (var i = 0; i < 10; i++) { this.bactEngine.spawnAt(this.dish.positionX, this.dish.positionY); } animate(); }; Game.pause = function (callback, param) { animateOut(function () { callback(param); Game.stopped = true; }); } Game.resume = function () { animateIn(); this.stopped = false; animate(); } Game.updateStats = function () { $population.innerHTML = this.bactEngine.population; var resist = Math.min(this.bactEngine.resistance * 100, 100); $resistance.innerHTML = resist.toFixed(1); var infect = Math.min(this.bactEngine.infectivity * 100, 100); $infectivity.innerHTML = infect.toFixed(1); $funds.innerHTML = this.funds.toFixed(2); }; Game.updateTime = function () { this.tick++; if (this.tick % 900 === 0) { this.day++; this.funds += this.stipend; // daily stipend showAlert('+$50!') // if necessary, increment week if (this.day > 7) { this.day = 1; this.week++; if (this.mode === 'NORMAL') { if (this.week === 2) { this.pause(playScene, 'week1'); } if (this.week === 3) { this.pause(playScene, 'week2'); } if (this.week === 4) { this.pause(playScene, 'week3'); } } Velocity($week, 'transition.flipBounceYIn', 1000); $week.innerHTML = this.week; } Velocity($day, 'transition.flipBounceYIn', 1000); $day.innerHTML = this.day; this.tick = 0; } }; Game.updateParticles = function () { // update positions this.powerEngine.update(); this.bactEngine.update(); // dish collisions this.dish.update(); // bacterium-bacterium collisions for (var i = 0; i < this.bactEngine.particles.length - 1; i++) { for (var j = i + 1; j < this.bactEngine.particles.length; j++) { var bact1 = this.bactEngine.particles[i]; var bact2 = this.bactEngine.particles[j]; if (!bact1.alive || !bact2.alive) continue; if (isCollision(bact1.getPositionX(), bact1.getPositionY(), bact1.radius, bact2.getPositionX(), bact2.getPositionY(), bact2.radius)) { bact1.onCollisionWithBacterium(bact2); bact2.onCollisionWithBacterium(bact1); } } } // bacterium-powerup collisions for (var i = 0; i < this.bactEngine.particles.length; i++) { for (var j = 0; j < this.powerEngine.particles.length; j++) { var bact = this.bactEngine.particles[i]; var powerup = this.powerEngine.particles[j]; if (!bact.alive || !powerup.alive) continue; if (isCollision(bact.getPositionX(), bact.getPositionY(), bact.radius, powerup.getPositionX(), powerup.getPositionY(), powerup.radius)) { bact.onCollisionWithPowerup(powerup); powerup.onCollisionWithBacterium(bact); } } } }; ////////////////////////////////////////////////////////// // GAME LOOP & RENDERING ////////////////////////////////////////////////////////// var width = window.innerWidth, height = window.innerHeight, renderer, stage, meter; window.onload = function () { playScene('intro1'); // create a stage for the renderer stage = new PIXI.Container(); // initialize canvas renderer = PIXI.autoDetectRenderer(width, height, { view: $canvas, backgroundColor: 0x1099bb, antialias: true, autoResize: true }); setupButtons(); setupMouseHandlers(); // meter = new FPSMeter(); }; function animate() { if (Game.stopped) { console.log('stopped'); return; } Game.updateParticles(); Game.bactEngine.divide(); Game.updateStats(); Game.updateTime(); // memory management: clear out dead particles Game.bactEngine.clean(); Game.powerEngine.clean(); // detect screen change conditions if (!Game.over) { if (Game.bactEngine.population <= 0) { setTimeout(function () { gameOver('Your bacteria died.'); }, 500); } else if (Game.cancer && Game.mode === 'NORMAL') { setTimeout(function () { gameOver('You got cancer and died. Don\'t say I didn\'t warn you.'); }, 500); } else if (Game.week >= 5 && Game.mode === 'NORMAL') { setTimeout(function () { gameOver('You\'re out of time. Your PI is back and she\'s not pleased...'); }, 500); } else if (Game.bactEngine.resistance > 0.95 && Game.bactEngine.infectivity > 0.95 && Game.mode === 'NORMAL') { playScene('win'); } } // meter.tick(); renderer.render(stage); requestAnimationFrame(animate); }<file_sep>/js/dish.js function PetriDish(positionX, positionY, radius) { this.positionX = positionX; this.positionY = positionY; this.radius = radius; var graphics = new PIXI.Graphics(); graphics.lineStyle(1, 0xFFFFFF); graphics.drawCircle(positionX, positionY, radius + 10); var petriInner = graphics.drawCircle(positionX, positionY, radius); stage.addChild(graphics); } PetriDish.prototype.onCollisionWithBacterium = function (particle) { particle.speed = -particle.speed; // add offset to avoid thrashing var offsetX = this.positionX - particle.getPositionX(); var offsetY = this.positionY - particle.getPositionY(); var length = Math.sqrt(offsetX * offsetX + offsetY * offsetY); particle.setPosition(particle.getPositionX() + offsetX / length, particle.getPositionY() + offsetY / length); }; PetriDish.prototype.onCollisionWithPowerup = function (particle) { particle.kill(); } PetriDish.prototype.update = function () { // dish-bacterium collisions for (var i = 0; i < Game.bactEngine.particles.length; i++) { var particle = Game.bactEngine.particles[i]; if (!particle.alive) continue; var dist = getDistance(this.positionX, this.positionY, particle.getPositionX(), particle.getPositionY()); if (dist >= this.radius - particle.radius - 2) { this.onCollisionWithBacterium(particle); } } // dish-powerup collisions for (var i = 0; i < Game.powerEngine.particles.length; i++) { var particle = Game.powerEngine.particles[i]; if (!particle.alive) continue; var dist = getDistance(this.positionX, this.positionY, particle.getPositionX(), particle.getPositionY()); if (dist >= this.radius - particle.radius - 2) { this.onCollisionWithPowerup(particle); } } }<file_sep>/js/util.js // return the Euclidean distance between two points function getDistance(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } // return a random number in [lo, hi) function randomUniform(lo, hi) { return (hi - lo) * Math.random() + lo; } // return an exponentially distributed random number function randomExponential(expected) { return Math.log(Math.random()) / -(1 / expected); } // return true if collision is detected between two circles function isCollision(x1, y1, radius1, x2, y2, radius2) { return getDistance(x1, y1, x2, y2) < radius1 + radius2; }<file_sep>/js/bacterium.js function Bacterium(positionX, positionY) { this.sprite = PIXI.Sprite.fromImage('img/sprites/bact2.png'); this.sprite.x = positionX; this.sprite.y = positionY; this.sprite.anchor.set(0.5); this.sprite.rotation = randomUniform(0, 2 * Math.PI); Game.bactContainer.addChild(this.sprite); this.speed = randomUniform(this.MIN_SPEED, this.MAX_SPEED); this.direction = this.sprite.rotation; this.turningvelocity = Math.random() - 0.8; this.alive = true; this.life = randomExponential(this.LIFESPAN); this.growthRate = randomUniform(0.0005, 0.001); this.mutationRate = randomUniform(0, 0.005); this.resistance = randomUniform(0.25, 0.35); this.infectivity = randomUniform(0.25, 0.35); } Bacterium.prototype.radius = 5; Bacterium.prototype.MIN_SPEED = 0.05; Bacterium.prototype.MAX_SPEED = 0.1; Bacterium.prototype.LIFESPAN = 1800; Bacterium.prototype.kill = function () { Game.bactContainer.removeChild(this.sprite); this.alive = false; } Bacterium.prototype.getPositionX = function () { return this.sprite.position.x; } Bacterium.prototype.getPositionY = function () { return this.sprite.position.y; } Bacterium.prototype.setPosition = function (x, y) { this.sprite.position.x = x; this.sprite.position.y = y; } Bacterium.prototype.update = function () { this.direction += this.turningvelocity * 0.01; this.setPosition(this.getPositionX() + Math.sin(this.direction) * this.speed, this.getPositionY() + Math.cos(this.direction) * this.speed); } Bacterium.prototype.onCollisionWithBacterium = function (bact) { this.speed = -this.speed; // add offset to avoid thrashing var offsetX = this.getPositionX() - bact.getPositionX(); var offsetY = this.getPositionY() - bact.getPositionY(); var length = Math.sqrt(offsetX * offsetX + offsetY * offsetY); this.setPosition(this.getPositionX() + offsetX / length, this.getPositionY() + offsetY / length); }; Bacterium.prototype.onCollisionWithPowerup = function (powerup) { switch (powerup.type) { case PowerupEngine.prototype.TYPES.agar: this.growthRate = Math.min(this.growthRate + 0.0005, 0.003); this.life = Math.min(this.LIFESPAN, this.life + this.LIFESPAN / 2); break; case PowerupEngine.prototype.TYPES.penicillin: var rand = Math.random(); if (rand < 0.75 - this.resistance) { this.kill(); } break; case PowerupEngine.prototype.TYPES.streptomycin: var rand = Math.random(); if (rand < 0.85 - this.resistance) { this.kill(); } break; case PowerupEngine.prototype.TYPES.ceftobiprole: var rand = Math.random(); if (rand < 0.99 - this.resistance) { this.kill(); } break; case PowerupEngine.prototype.TYPES.plasmids: var rand = Math.random(); if (rand < this.infectivity) { this.infectivity = Math.min(1, this.infectivity + randomUniform(-this.mutationRate / 3, this.mutationRate / 2)); } else { Game.powerEngine.spawnFrom(powerup); Game.powerEngine.spawnFrom(powerup); this.kill(); } break; case PowerupEngine.prototype.TYPES.mutagens: var rand = Math.random(); if (rand < 0.5) { this.kill(); } else if (rand < 0.9) { this.mutationRate += 0.01; } else if (rand < 0.95) { showAlert('Exponential Growth!'); for (var i = 0; i < 25; i++) { var bacterium = Game.bactEngine.spawnFrom(this); if (!bacterium) { continue; } bacterium.mutationRate += 0.001; bacterium = Game.bactEngine.spawnAt(this.getPositionX(), this.getPositionY()); if (!bacterium) { continue; } bacterium.mutationRate += 0.001; } } else { showAlert('MUTANT GROWTH!!!') for (var i = 0; i < 50; i++) { var bacterium = Game.bactEngine.spawnFrom(this); if (!bacterium) { continue; } bacterium.mutationRate += 0.005; bacterium.growthRate *= 1.1; bacterium = Game.bactEngine.spawnAt(this.getPositionX(), this.getPositionY()); if (!bacterium) { continue; } bacterium.mutationRate += 0.005; bacterium.growthRate *= 1.1; } } break; default: console.log('bruh what are you even trying to do') break; } };<file_sep>/README.md # I Hate Everyone! A cheeky 2D particle system game.
0b8eaa37ea3a7bed402477773f159b92198c86e6
[ "JavaScript", "Markdown" ]
9
JavaScript
juliahw/i-hate-everyone
41fbca19695dcb550714812556820faf5a50e549
1fab40f73d754ce5184c6a06e54c907804998deb
refs/heads/main
<repo_name>shahzadqadir/update_interface_desc<file_sep>/cdp_config.py import paramiko import time #pylint:disable=unused-variable class ConfigCisco: """ Configure device interfaces using information collected through CDP. Only works for Cisco devices with cdp enabled. """ def __init__(self, hostname, username, password, command="show cdp neighbor | begin Device"): self.hostname = hostname self.username = username self.password = <PASSWORD> self.command = command def show_cmd_ssh(self): """ Runs commands on remote device(s) and returns output. """ try: conn = paramiko.SSHClient() conn.set_missing_host_key_policy(paramiko.AutoAddPolicy()) conn.connect(hostname=self.hostname, username=self.username, password=<PASSWORD>, allow_agent=False, look_for_keys=False) stdin, stdout, stderr = conn.exec_command(self.command) stdout = stdout.readlines() return stdout except paramiko.ssh_exception.AuthenticationException: return False except paramiko.ssh_exception.NoValidConnectionsError: return False def create_device_dict(self, results): """ Takes unformatted output of show cdp neighbor and returns a dictionary in format {remote_device: [local_port, remote_port]}. This can be used to configure interface descriptions later.""" updated_results = [] devices = {} for result in results: # get rid of extra spacing and carriage returns updated_results.append(result.strip(' ').strip('\n').strip('\r')) # get rid of output table header updated_results.pop(0) # add devices to devices dictionary for num in range(len(updated_results)-2): if num % 2 == 0: devices[updated_results[num]] = [updated_results[num+1][:10], updated_results[num+1][-10:]] return devices def configure_interfaces(self, device_dict): """ Update remote device(s) and write configurations to memory. """ try: conn = paramiko.SSHClient() conn.set_missing_host_key_policy(paramiko.AutoAddPolicy()) conn.connect(hostname=self.hostname, username=self.username, password=<PASSWORD>, allow_agent=False, look_for_keys=False) except paramiko.ssh_exception.AuthenticationException: return False except paramiko.ssh_exception.NoValidConnectionsError: return False rtcon = conn.invoke_shell() time.sleep(1) list_of_commands = ["terminal length 0", "configure terminal"] for data in device_dict.keys(): list_of_commands.append(f"interface {device_dict[data][0]}") list_of_commands.append(f"description connected to {data} on {device_dict[data][1]}") list_of_commands.append("write mem") for command in list_of_commands: rtcon.send(command + '\n') time.sleep(1) # Main execution sw_hostname = input("Hostname/IP: ") sw_username = input("Username: ") sw_password = input("<PASSWORD>: ") config_class = ConfigCisco(sw_hostname, sw_username, sw_password) results = config_class.show_cmd_ssh() if results: device_dict = config_class.create_device_dict(results) config_class.configure_interfaces(device_dict) else: print("Check connection to device and re-try!")
0ff635f18a6ad009b18629027b45e87fe53a8f35
[ "Python" ]
1
Python
shahzadqadir/update_interface_desc
86aca31b9773139d9d0df4ac572eddcffc2e8083
e23f122c18424d5588399e00a6e03dfa91e19b18
refs/heads/master
<repo_name>eikibriem/RecipeApplication<file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/Activities/RecipeListActivity.java package com.example.helen_000.recipeapplication.Activities; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.helen_000.recipeapplication.Entities.Recipe; import com.example.helen_000.recipeapplication.R; import com.example.helen_000.recipeapplication.RecipesListFetch; import com.example.helen_000.recipeapplication.SearchRecipeListFetch; import com.example.helen_000.recipeapplication.YourRecipesListFetch; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RecipeListActivity extends AppCompatActivity { private static final String TAG = "RecipeListActivity"; private String message; private String searchMessage; private String loggedInUser; boolean ContainsRecipeGroupInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_list); Bundle bundle = getIntent().getExtras(); message = bundle.getString("message"); searchMessage = bundle.getString("searchMessage"); if(searchMessage != null){ AsyncTask task = new FetchSearchTask().execute(); return; } //Athugum hvort verið er að leita eftir notanda eða recipeGroup ContainsRecipeGroupInfo = messageContainsRecipeGroup(message); //Leitað eftir notanda if (ContainsRecipeGroupInfo == false){ AsyncTask task = new RecipeListActivity.FetchYourRecipeListTask().execute(); } //Leitað eftir recipeGroup else { AsyncTask task = new RecipeListActivity.FetchRecipeListTask().execute(); } } /* Checks if the message includes information about a recipe group */ public static boolean messageContainsRecipeGroup(String message) { List<String> recipeGroups = new ArrayList<String>(); recipeGroups.add(0, "appetizers"); recipeGroups.add(1, "dinners"); recipeGroups.add(2, "desserts"); recipeGroups.add(3, "raw"); recipeGroups.add(4, "breakfast"); recipeGroups.add(5, "baking"); boolean ContainsRecipeGroupInfo = recipeGroups.contains(message); Log.d(TAG, "niðurstaðan: " + ContainsRecipeGroupInfo); return ContainsRecipeGroupInfo; } private List<Recipe> mRecipes = new ArrayList<Recipe>(); /* This AsyncTask is used when searching by a recipe group */ private class FetchRecipeListTask extends AsyncTask<String, Void, List<Recipe>> { @Override protected List<Recipe> doInBackground(String... params ){ List<Recipe> recipes = new RecipesListFetch().fetchRecipeList(message); return recipes; } @Override protected void onPostExecute(List<Recipe> recipes) { mRecipes = recipes; LinearLayout myLayout = (LinearLayout) findViewById(R.id.linear); if (recipes.size() == 0){ TextView textView = new TextView(RecipeListActivity.this); textView.setText("No recipes"); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(20, 0, 20, 20); // (left, top, right, bottom) textView.setLayoutParams(lp); myLayout.addView(textView); } ImageView[] myRecipesImages = new ImageView[recipes.size()]; Button[] myButtons = new Button[recipes.size()]; for(int i = 0; i < recipes.size(); i++){ myRecipesImages[i] = new ImageView(RecipeListActivity.this); myButtons[i] = new Button(RecipeListActivity.this); Picasso.with(RecipeListActivity.this).load(mRecipes.get(i).getImage()).into(myRecipesImages[i]); myButtons[i].setText(mRecipes.get(i).getRecipeName()); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(20, 0, 20, 20); // (left, top, right, bottom) myRecipesImages[i].setLayoutParams(lp); myButtons[i].setLayoutParams(lp); final Long recipeId = mRecipes.get(i).getId(); myButtons[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(RecipeListActivity.this, RecipeActivity.class); Long message = recipeId; intent.putExtra("message", message); startActivity(intent); } }); myRecipesImages[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(RecipeListActivity.this, RecipeActivity.class); Long message = recipeId; intent.putExtra("message", message); startActivity(intent); } }); myLayout.addView(myRecipesImages[i]); myLayout.addView(myButtons[i]); } } } /* This AsyncTask is used when searching by a user */ private class FetchYourRecipeListTask extends AsyncTask<String, Void, List<Recipe>> { @Override protected List<Recipe> doInBackground(String... params ){ Log.d(TAG, "User: " + message); List<Recipe> recipes = new YourRecipesListFetch().fetchRecipeList(message); return recipes; } @Override protected void onPostExecute(List<Recipe> recipes) { mRecipes = recipes; LinearLayout myLayout = (LinearLayout) findViewById(R.id.linear); if (recipes.size() == 0){ TextView textView = new TextView(RecipeListActivity.this); textView.setText("No recipes"); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(20, 0, 20, 20); // (left, top, right, bottom) textView.setLayoutParams(lp); myLayout.addView(textView); } ImageView[] myRecipesImages = new ImageView[recipes.size()]; Button[] myButtons = new Button[recipes.size()]; for(int i = 0; i < recipes.size(); i++){ myRecipesImages[i] = new ImageView(RecipeListActivity.this); myButtons[i] = new Button(RecipeListActivity.this); Picasso.with(RecipeListActivity.this).load(mRecipes.get(i).getImage()).into(myRecipesImages[i]); myButtons[i].setText(mRecipes.get(i).getRecipeName()); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(20, 0, 20, 20); // (left, top, right, bottom) myRecipesImages[i].setLayoutParams(lp); myButtons[i].setLayoutParams(lp); final Long recipeId = mRecipes.get(i).getId(); myButtons[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(RecipeListActivity.this, RecipeActivity.class); Long message = recipeId; intent.putExtra("message", message); startActivity(intent); } }); myRecipesImages[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(RecipeListActivity.this, RecipeActivity.class); Long message = recipeId; intent.putExtra("message", message); startActivity(intent); } }); myLayout.addView(myRecipesImages[i]); myLayout.addView(myButtons[i]); } } } private class FetchSearchTask extends AsyncTask<String, Void, List<Recipe>>{ @Override protected List<Recipe> doInBackground(String... params ){ Log.d(TAG, "SearchString: " + searchMessage); List<Recipe> recipes = new SearchRecipeListFetch().fetchRecipeList(searchMessage); return recipes; } @Override protected void onPostExecute(List<Recipe> recipes) { mRecipes = recipes; LinearLayout myLayout = (LinearLayout) findViewById(R.id.linear); if (recipes.size() == 0){ TextView textView = new TextView(RecipeListActivity.this); textView.setText("No recipes"); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(20, 0, 20, 20); // (left, top, right, bottom) textView.setLayoutParams(lp); myLayout.addView(textView); } ImageView[] myRecipesImages = new ImageView[recipes.size()]; Button[] myButtons = new Button[recipes.size()]; for(int i = 0; i < recipes.size(); i++){ myRecipesImages[i] = new ImageView(RecipeListActivity.this); myButtons[i] = new Button(RecipeListActivity.this); Picasso.with(RecipeListActivity.this).load(mRecipes.get(i).getImage()).into(myRecipesImages[i]); myButtons[i].setText(mRecipes.get(i).getRecipeName()); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(20, 0, 20, 20); // (left, top, right, bottom) myRecipesImages[i].setLayoutParams(lp); myButtons[i].setLayoutParams(lp); final Long recipeId = mRecipes.get(i).getId(); myButtons[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(RecipeListActivity.this, RecipeActivity.class); Long message = recipeId; intent.putExtra("message", message); startActivity(intent); } }); myRecipesImages[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(RecipeListActivity.this, RecipeActivity.class); Long message = recipeId; intent.putExtra("message", message); startActivity(intent); } }); myLayout.addView(myRecipesImages[i]); myLayout.addView(myButtons[i]); } } } } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/Activities/SearchActivity.java package com.example.helen_000.recipeapplication.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.example.helen_000.recipeapplication.R; public class SearchActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); } public void mButtonSearchOnClick (View v){ EditText input = (EditText) findViewById(R.id.editTextSearch); String searchInput = input.getText().toString(); Intent intent = new Intent(SearchActivity.this, RecipeListActivity.class); intent.putExtra("searchMessage", searchInput); startActivity(intent); } } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/Entities/Recipe.java package com.example.helen_000.recipeapplication.Entities; /** * Created by helen_000 on 28.2.2017. */ public class Recipe { private Long id; private String recipeName; private String recipeGroup; private String ingredients; //private User user; private String username; private String instructions; private String image; private float rate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRecipeName() { return recipeName; } public void setRecipeName(String recipeName) { this.recipeName = recipeName; } public String getRecipeGroup() { return recipeGroup; } public void setRecipeGroup(String recipeGroup) { this.recipeGroup = recipeGroup; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public float getRate() { return rate; } public void setRate(float rate) { this.rate = rate; } } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/API/RecipeAPI.java package com.example.helen_000.recipeapplication.API; import com.example.helen_000.recipeapplication.Entities.Recipe; import java.util.List; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.Path; /** * Created by helen_000 on 3.3.2017. */ public interface RecipeAPI { // @GET("/mej3hi/tonlistv2/master/tonlist.json") // Call<List<Recipe>> getEvent(); @GET("/m/") Call<List<Recipe>> getIndex(); // @POST("/m/createRecipe") //Call<Void> postCreateEvent(@Body Recipe recipe, @Part MultipartBody.Part image, @Part("name") RequestBody name); //@GET("/m/editRecipe") //Call<Void> getEditRecipe(@Body Recipe recipe, @Part MultipartBody.Part image, @Part("name") RequestBody name); } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/Activities/UploadRecipeActivity.java package com.example.helen_000.recipeapplication.Activities; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.helen_000.recipeapplication.CreateRecipeSend; import com.example.helen_000.recipeapplication.Entities.Recipe; import com.example.helen_000.recipeapplication.R; import com.example.helen_000.recipeapplication.RecipeDelete; import com.example.helen_000.recipeapplication.RecipeFetch; import com.example.helen_000.recipeapplication.RecipeFetchId; import com.mobsandgeeks.saripaar.ValidationError; import com.mobsandgeeks.saripaar.Validator; import com.mobsandgeeks.saripaar.annotation.NotEmpty; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class UploadRecipeActivity extends AppCompatActivity implements Validator.ValidationListener{ private static final String TAG = "CreateRecipe"; @NotEmpty private EditText recipeNameEdit; private Spinner recipeGroupEdit; @NotEmpty private EditText ingredientsEdit; @NotEmpty private EditText instructionsEdit; @NotEmpty private EditText imageEdit; private Long message; private Long operationId; private Validator validator; private ArrayAdapter<String> adapter; private String operation = "createRecipe"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getIntent().getExtras(); //getting the id of the recipe from the recipeListActivity message = bundle.getLong("message"); //getting the id of the recipe from the recipeListActivity/UploadRecipeActivity operationId = bundle.getLong("operation"); //check if you are editing or saving a new recipe Log.d(TAG, "hér er id-ið á recipe-inu: " + message); setContentView(R.layout.activity_upload_recipe); Spinner dropdown = (Spinner)findViewById(R.id.spinnerRecipeGroup); String[] items = new String[]{"appetizers", "baking", "breakfast", "dinner", "dessert", "raw"}; adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items); dropdown.setAdapter(adapter); Log.d(TAG, "aloha2"); this.validator = new Validator(this); this.validator.setValidationListener(this); this.recipeNameEdit = (EditText) findViewById(R.id.editTextRecipeName); this.recipeGroupEdit = (Spinner)findViewById(R.id.spinnerRecipeGroup); this.ingredientsEdit = (EditText) findViewById(R.id.editTextIngredients); this.instructionsEdit = (EditText) findViewById(R.id.editTextInstructions); this.imageEdit = (EditText) findViewById(R.id.editTextImage); Log.d(TAG, "aloha3"); //Yes if you are editing a recipe if (operationId != 0L){ operation = "editRecipe"; Log.d(TAG, "aloha10"); AsyncTask task = new UploadRecipeActivity.SendRecipeEditDeviceDetails().execute(); Log.d(TAG, "aloha11"); //Get position of spinner element } } /* public String getRecipeName(View v){ EditText recipeName = (EditText) findViewById(R.id.editTextRecipeName); String recipeNameValue = recipeName.getText().toString(); Log.d("AddRecipe","Recipe Name: "+recipeName); return recipeNameValue; } public String getRecipeGroupView(View v){ Spinner recipeGroup = (Spinner)findViewById(R.id.spinnerRecipeGroup); String recipeGroupValue = recipeGroup.getSelectedItem().toString(); Log.d("AddRecipeGroup","RecipeGroup Name: "+recipeGroupValue); return recipeGroupValue; } public String getIngredients(View v){ EditText ingredients = (EditText) findViewById(R.id.editTextIngredients); String ingredientsValue = ingredients.getText().toString(); Log.d("AddIngredients","Ingredients: "+ingredients); return ingredientsValue; } public String getInstructions(View v){ EditText instructions = (EditText) findViewById(R.id.editTextInstructions); String instructionsValue = instructions.getText().toString(); Log.d("AddInstructions","instructions: "+instructions); return instructionsValue; } public String getImage(View v){ EditText image = (EditText) findViewById(R.id.editTextImage); String imageValue = image.getText().toString(); Log.d("AddImage","image: "+image); return imageValue; } */ public void mButtonSaveRecipeOnClick (View v){validator.validate();} /* Retrieves the recipe that you want to edit */ private class SendRecipeEditDeviceDetails extends AsyncTask<Void, Void, Recipe> { @Override protected Recipe doInBackground(Void... params) { Recipe recipeToEdit = new RecipeFetch().fetchRecipe(operationId); return recipeToEdit; } @Override protected void onPostExecute(Recipe recipeToEdit) { String recipeGroup = recipeToEdit.getRecipeGroup(); int selectionPosition= adapter.getPosition(recipeGroup); //Set the saved values of the recipe in the text views for the user to change recipeNameEdit.setText(recipeToEdit.getRecipeName()); recipeGroupEdit.setSelection(selectionPosition); ingredientsEdit.setText(recipeToEdit.getIngredients()); instructionsEdit.setText(recipeToEdit.getInstructions()); imageEdit.setText(recipeToEdit.getImage()); } } private class SendRecipeDeviceDetails extends AsyncTask<Recipe, Void, String> { @Override protected String doInBackground(Recipe... recipes) { if(recipes.length > 0){ String message1 = new CreateRecipeSend().sendRecipe(recipes[0]); RecipeFetchId rp = new RecipeFetchId(); Recipe RecipeidNew = rp.fetchRecipeId(recipes[0].getRecipeName()); Long idNew = RecipeidNew.getId(); message = idNew; return message1; } return "Doesnt work, there is no recipe"; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); Log.e("TAG", response); // this is expecting a response code to be sent from your server upon receiving the POST data Log.d(TAG,response.toString()); if("OK".equals(response)){ Intent intent = new Intent(UploadRecipeActivity.this, RecipeActivity.class); intent.putExtra("message", message); startActivity(intent); finish(); } else{ try { JSONObject jsonObject = new JSONObject(response); if(jsonObject.getJSONArray("recipeName").length() > 0){ for(int i=0; i < jsonObject.getJSONArray("recipeName").length(); i++){ String errorMessage = jsonObject.getJSONArray("recipeName").getString(i); recipeNameEdit.setError(errorMessage); } } if(jsonObject.getJSONArray("ingredients").length() > 0){ for(int i=0; i < jsonObject.getJSONArray("ingredients").length(); i++){ String errorMessage = jsonObject.getJSONArray("ingredients").getString(i); ingredientsEdit.setError(errorMessage); } } if(jsonObject.getJSONArray("instructions").length() > 0){ for(int i=0; i < jsonObject.getJSONArray("instructions").length(); i++){ String errorMessage = jsonObject.getJSONArray("instructions").getString(i); instructionsEdit.setError(errorMessage); } } if(jsonObject.getJSONArray("image").length() > 0){ for(int i=0; i < jsonObject.getJSONArray("image").length(); i++){ String errorMessage = jsonObject.getJSONArray("image").getString(i); imageEdit.setError(errorMessage); } } } catch (JSONException e) { Log.e(TAG, "Error when handling json"); Toast toast = Toast.makeText(UploadRecipeActivity.this, "Upload not successful, try again later", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); e.printStackTrace(); } } } } @Override public void onValidationSucceeded() { if(operation.equals("editRecipe")){ AsyncTask task = new UploadRecipeActivity.DeleteRecipeTask().execute(); } Recipe recipe = new Recipe(); recipe.setRecipeName(recipeNameEdit.getText().toString()); recipe.setRecipeGroup(recipeGroupEdit.getSelectedItem().toString()); recipe.setIngredients(ingredientsEdit.getText().toString()); recipe.setInstructions(instructionsEdit.getText().toString()); recipe.setImage(imageEdit.getText().toString()); String loggedInUser = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).getString("userName", "No logged in user"); recipe.setUsername(loggedInUser); new SendRecipeDeviceDetails().execute(recipe); } @Override public void onValidationFailed(List<ValidationError> errors) { for (ValidationError error : errors) { View view = error.getView(); String message = error.getCollatedErrorMessage(this); // Display error messages ;) if (view instanceof EditText) { ((EditText) view).setError(message); } else { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } } } private class DeleteRecipeTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params ){ String returnMessage = new RecipeDelete().deleteRecipe(operationId); return returnMessage; } @Override protected void onPostExecute(String returnMessage) { Intent intent = new Intent(UploadRecipeActivity.this, HomeScreenActivity.class); startActivity(intent); } } } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/RecipeSave.java package com.example.helen_000.recipeapplication; import android.net.Uri; import android.util.Log; import com.example.helen_000.recipeapplication.Entities.Recipe; import com.example.helen_000.recipeapplication.Entities.RecipeGroup; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by helen_000 on 7.3.2017. */ public class RecipeSave { private static final String TAG = "RecipeSave"; public Recipe saveRecipe(String recipeData) throws JSONException { Recipe recipe = new Recipe(); String recipeData1 = "[" + recipeData + "]"; JSONArray jsonBody = new JSONArray(recipeData1); JSONObject recipeObject = jsonBody.getJSONObject(0); String recipeName = recipeObject.getString("recipeName"); String recipeGroup = recipeObject.getString("recipeGroup"); String ingredients = recipeObject.getString("ingredients"); String instructions = recipeObject.getString("instructions"); String image = recipeObject.getString("image"); recipe.setRecipeName(recipeName); recipe.setRecipeGroup(recipeGroup); recipe.setIngredients(ingredients); recipe.setInstructions(instructions); recipe.setImage(image); Log.d(TAG, "HOLA!!" + recipeName + " - " + recipeGroup + " - " + ingredients + " - " + instructions + " - " + image); try { String url = Uri.parse("http://10.0.2.2:8080/m/createRecipe/" + recipeName + "/" + recipeGroup + "/" + ingredients + "/" + instructions + "/" + image) // String url = Uri.parse("http://10.0.2.2:8080/m/createRecipe/anything") .buildUpon() .build().toString(); String jsonString = setData(url); Log.i(TAG, "Received JSON: " + jsonString); }catch (IOException ioe) { Log.e(TAG, "Failed to save recipe", ioe); } return recipe; } public String setData(String urlSpec) throws IOException { BufferedReader reader = null; try { URL url = new URL(urlSpec); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); Log.d(TAG, "hæ4 :)"); /* if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(conn.getResponseMessage() + ": with " + urlSpec); } */ //InputStream in = conn.getInputStream(); StringBuilder sb = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null){ sb.append(line + "\n"); Log.d("Response: ", "> " + line); //Here you get the whole response } return sb.toString(); } catch (IOException e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); return null; } } } } private void parseRecipe(Recipe recipe, JSONObject jsonBody) throws JSONException { try { recipe.setId(jsonBody.getLong("id")); recipe.setRecipeName(jsonBody.getString("recipeName")); recipe.setRecipeGroup(jsonBody.getString("recipeGroup")); recipe.setIngredients(jsonBody.getString("ingredients")); recipe.setInstructions(jsonBody.getString("instructions")); recipe.setUsername(jsonBody.getString("username")); recipe.setImage(jsonBody.getString("image")); } catch (JSONException je) { Log.e(TAG, "Failed to parse JSON", je); } }} <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/HttpRequest/HttpRequestRecipes.java package com.example.helen_000.recipeapplication.HttpRequest; /** * Created by helen_000 on 3.3.2017. */ public class HttpRequestRecipes { } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/HttpResponse/HttpResponseRecipes.java package com.example.helen_000.recipeapplication.HttpResponse; import com.example.helen_000.recipeapplication.Entities.Recipe; import java.util.List; /** * Created by helen_000 on 3.3.2017. */ public class HttpResponseRecipes { private List<Recipe> recipeList; private int code; public HttpResponseRecipes(List<Recipe> recipeList, int code) { this.recipeList = recipeList; this.code = code; } public List<Recipe> getRecipeList() { return recipeList; } public void setRecipeList(List<Recipe> recipeList) { this.recipeList = recipeList; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/Activities/RecipeActivity.java package com.example.helen_000.recipeapplication.Activities; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.helen_000.recipeapplication.Entities.Recipe; import com.example.helen_000.recipeapplication.R; import com.example.helen_000.recipeapplication.RecipeDelete; import com.example.helen_000.recipeapplication.RecipeFetch; import com.squareup.picasso.Picasso; public class RecipeActivity extends AppCompatActivity { private String TAG = "recipeActivity"; private Long message; ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe); image = (ImageView)findViewById(R.id.imageView); AsyncTask task = new RecipeActivity.FetchRecipeTask().execute(); Bundle bundle = getIntent().getExtras(); //getting the id of the recipe from the recipeListActivity message = bundle.getLong("message"); //getting the id of the recipe from the recipeListActivity/UploadRecipeActivity } private Recipe mRecipe = new Recipe(); private class FetchRecipeTask extends AsyncTask<Void, Void, Recipe> { @Override protected Recipe doInBackground(Void... params ){ Recipe recipe = new RecipeFetch().fetchRecipe(message); return recipe; } @Override protected void onPostExecute(Recipe recipe) { mRecipe = recipe; TextView textViewRecipeName = (TextView) findViewById(R.id.textViewRecipeName); textViewRecipeName.setText(mRecipe.getRecipeName()); Picasso.with(RecipeActivity.this).load(mRecipe.getImage()).into(image); TextView textViewIngredients = (TextView) findViewById(R.id.textViewIngredients); textViewIngredients.setText(mRecipe.getIngredients()); TextView textViewInstructions = (TextView) findViewById(R.id.textViewInstructions); textViewInstructions.setText(mRecipe.getInstructions()); TextView textViewUsername = (TextView) findViewById(R.id.textViewUsername); textViewUsername.setText("Posted by " + mRecipe.getUsername()); Button buttonEditRecipe = (Button) findViewById(R.id.mEditRecipe); Button buttonDeleteRecipe = (Button) findViewById(R.id.mDeleteRecipe); String loggedInUser = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).getString("userName", "No logged in user"); String recipeUser = mRecipe.getUsername(); //If the loggedInUser is the same as the recipeUser we display the delete and edit recipe buttons if (loggedInUser.equals(recipeUser)) { buttonEditRecipe.setVisibility(View.VISIBLE); buttonDeleteRecipe.setVisibility(View.VISIBLE); } } } public void mDeleteRecipeButtonOnClick (View v){ AsyncTask task = new RecipeActivity.DeleteRecipeTask().execute(mRecipe); } private class DeleteRecipeTask extends AsyncTask<Recipe, Void, String> { @Override protected String doInBackground(Recipe... params ){ String returnMessage = new RecipeDelete().deleteRecipe(message); return returnMessage; } @Override protected void onPostExecute(String returnMessage) { Intent intent = new Intent(RecipeActivity.this, HomeScreenActivity.class); startActivity(intent); finish(); } } public void mEditRecipeButtonOnClick (View v){ AsyncTask task = new RecipeActivity.EditRecipeTask().execute(mRecipe); } private class EditRecipeTask extends AsyncTask<Recipe, Void, Recipe> { @Override protected Recipe doInBackground(Recipe... params ){ return params[0]; } @Override protected void onPostExecute(Recipe recipeToEdit) { Intent intent = new Intent(RecipeActivity.this, UploadRecipeActivity.class); Long recipeToEditId = recipeToEdit.getId(); intent.putExtra("operation", recipeToEditId); startActivity(intent); } } } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/Activities/UserPageActivity.java package com.example.helen_000.recipeapplication.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import com.example.helen_000.recipeapplication.R; public class UserPageActivity extends AppCompatActivity { private String TAG = "UserPageActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_page); } public void mButtonChangePasswordOnClick (View v){ Intent intent = new Intent(UserPageActivity.this, ChangePasswordActivity.class); startActivity(intent); } public void mButtonMyRecipesOnClick (View v){ Intent intent = new Intent(UserPageActivity.this, RecipeListActivity.class); String loggedInUser = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).getString("userName", "No logged in user"); intent.putExtra("message", loggedInUser); startActivity(intent); } } <file_sep>/app/src/main/java/com/example/helen_000/recipeapplication/Activities/RecipeGroupActivity.java package com.example.helen_000.recipeapplication.Activities; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.helen_000.recipeapplication.Entities.Recipe; import com.example.helen_000.recipeapplication.Entities.RecipeGroup; import com.example.helen_000.recipeapplication.R; import com.example.helen_000.recipeapplication.RecipeFetch; import com.example.helen_000.recipeapplication.RecipeGroupFetch; import java.util.ArrayList; import java.util.List; public class RecipeGroupActivity extends AppCompatActivity { private static final String TAG = "MyActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_group); AsyncTask task = new FetchRecipeGroupsTask().execute(); } private List<RecipeGroup> mRecipeGroups = new ArrayList<RecipeGroup>(); private class FetchRecipeGroupsTask extends AsyncTask<Void, Void, List<RecipeGroup>> { @Override protected List<RecipeGroup> doInBackground(Void... params ){ List<RecipeGroup> recipeGroups = new RecipeGroupFetch().fetchRecipeGroups(); return recipeGroups; } @Override protected void onPostExecute(List<RecipeGroup> recipeGroups) { mRecipeGroups = recipeGroups; Button buttonAppetizers = (Button) findViewById(R.id.mButtonAppetizers); buttonAppetizers.setText(mRecipeGroups.get(0).getGroupName()); Button buttonBaking = (Button) findViewById(R.id.mButtonBaking); buttonBaking.setText(mRecipeGroups.get(1).getGroupName()); Button buttonBreakfast = (Button) findViewById(R.id.mButtonBreakfast); buttonBreakfast.setText(mRecipeGroups.get(2).getGroupName()); Button buttonDessert = (Button) findViewById(R.id.mButtonDessert); buttonDessert.setText(mRecipeGroups.get(3).getGroupName()); Button buttonDinner = (Button) findViewById(R.id.mButtonDinner); buttonDinner.setText(mRecipeGroups.get(4).getGroupName()); Button buttonRaw = (Button) findViewById(R.id.mButtonRaw); buttonRaw.setText(mRecipeGroups.get(5).getGroupName()); } } public void mButtonAppetizersButtonOnClick (View v){ Intent intent = new Intent(RecipeGroupActivity.this, RecipeListActivity.class); String message = "appetizers"; intent.putExtra("message", message); startActivity(intent); } public void mButtonBakingButtonOnClick (View v){ Intent intent = new Intent(RecipeGroupActivity.this, RecipeListActivity.class); String message = "baking"; intent.putExtra("message", message); startActivity(intent); } public void mButtonBreakfastButtonOnClick (View v){ Intent intent = new Intent(RecipeGroupActivity.this, RecipeListActivity.class); String message = "breakfast"; intent.putExtra("message", message); startActivity(intent); } public void mButtonDinnerButtonOnClick (View v){ Intent intent = new Intent(RecipeGroupActivity.this, RecipeListActivity.class); String message = "dinner"; intent.putExtra("message", message); startActivity(intent); } public void mButtonDessertButtonOnClick (View v){ Intent intent = new Intent(RecipeGroupActivity.this, RecipeListActivity.class); String message = "dessert"; intent.putExtra("message", message); startActivity(intent); } public void mButtonRawButtonOnClick (View v){ Intent intent = new Intent(RecipeGroupActivity.this, RecipeListActivity.class); String message = "raw"; intent.putExtra("message", message); startActivity(intent); } }
b883a9a4ce7929ac09781c8c4af62663223bda66
[ "Java" ]
11
Java
eikibriem/RecipeApplication
309b45797a815ec01fe4873b7078ec1629283c2b
72e0da68051c4594e15d2ce25f5cd4daaa963744
refs/heads/master
<repo_name>harishb2k/gox-errors<file_sep>/error_impl_test.go package errors import ( "github.com/stretchr/testify/assert" "testing" ) func TestErrorObj(t *testing.T) { var err error err = &ErrorObj{ Name: "error_name", Description: "error_description", Err: New("error_err"), Object: "error_object", } // Test 1 - Make sure wrap works errWrapped := Wrap(err, "error_1") assert.True(t, Is(errWrapped, err)) // Test 2 - make sure wrapped error is able to get back the original error errorObj, ok := Cause(errWrapped).(*ErrorObj) assert.True(t, ok) assert.NotNil(t, errorObj) assert.Equal(t, "error_name", errorObj.Name) assert.Equal(t, "error_description", errorObj.Description) assert.Equal(t, "error_err", errorObj.Err.Error()) assert.Equal(t, "error_object", errorObj.Object) // Test 3 - make sure wrapped error is able to get back the original error errorObj, ok = Cause(err).(*ErrorObj) assert.True(t, ok) assert.NotNil(t, errorObj) assert.Equal(t, "error_name", errorObj.Name) assert.Equal(t, "error_description", errorObj.Description) assert.Equal(t, "error_err", errorObj.Err.Error()) assert.Equal(t, "error_object", errorObj.Object) } <file_sep>/error_impl.go package errors import ( "fmt" ) type ErrorObj struct { Name string Description string Err error Object interface{} } func (e *ErrorObj) Error() string { return fmt.Sprintf("Name=%s, Description=[%s] Err=[%v] Object=[%v]", e.Name, e.Description, e.Err, e.Object) } func (e *ErrorObj) FormattedDebugString() interface{} { return fmt.Sprintf("Name=%s \nDescription=%s \nErr=%v \nObject=%v", e.Name, e.Description, e.Err, e.Object) } <file_sep>/errors.go package errors import ( "errors" e "github.com/pkg/errors" ) type Error interface { error } func New(text string) error { return errors.New(text) } func Wrap(err error, message string) error { return e.Wrap(err, message) } func Cause(err error) error { return e.Cause(err) } func Is(err, target error) bool { return errors.Is(err, target) } func As(err error, target interface{}) bool { return errors.As(err, target) } func AsErrorObj(err error) (e *ErrorObj, ok bool) { ok = errors.As(err, &e) return } func Version() string { return "v0.0.3" } <file_sep>/error_usage_test.go package errors import ( "github.com/stretchr/testify/assert" "testing" ) type testingInterface interface { SomeMethod() (err error) SomeMethodWithErrorObj() (err error) SomeMethodWithErrorObjFull() (err error) } type testingInterfaceImpl struct { Data string } func (t *testingInterfaceImpl) SomeMethod() (err error) { return New("some_error") } func (t *testingInterfaceImpl) SomeMethodWithErrorWrap() (err error) { return Wrap(New("some_error"), "SomeMethodWithErrorObj") } func (t *testingInterfaceImpl) SomeMethodWithErrorObj() (err error) { return Wrap( &ErrorObj{ Name: "error_name", Description: "error_description", Err: New("error_err"), Object: "error_object", }, "SomeMethodWithErrorObj", ) } func TestUsage(t *testing.T) { var ti = &testingInterfaceImpl{Data: "Data"} err := ti.SomeMethod() assert.NotNil(t, err) errorObj, ok := Cause(err).(*ErrorObj) assert.False(t, ok) assert.Nil(t, errorObj) } func TestUsageWrap(t *testing.T) { var ti = &testingInterfaceImpl{Data: "Data"} err := ti.SomeMethodWithErrorWrap() assert.NotNil(t, err) errorObj, ok := Cause(err).(*ErrorObj) assert.False(t, ok) assert.Nil(t, errorObj) } func TestUsageErrorObj(t *testing.T) { var ti = &testingInterfaceImpl{Data: "Data"} err := ti.SomeMethodWithErrorObj() assert.NotNil(t, err) errorObj, ok := Cause(err).(*ErrorObj) assert.True(t, ok) assert.NotNil(t, errorObj) assert.Equal(t, "error_name", errorObj.Name) assert.Equal(t, "error_description", errorObj.Description) assert.Equal(t, "error_err", errorObj.Err.Error()) assert.Equal(t, "error_object", errorObj.Object) if e, ok := AsErrorObj(err); ok { assert.Equal(t, "error_name", e.Name) assert.Equal(t, "error_description", e.Description) assert.Equal(t, "error_err", e.Err.Error()) assert.Equal(t, "error_object", e.Object) } else { assert.Fail(t, "Expected to get Error Object from err") } }
70f126b72e19d1c18bb65106aba0aa11c1bad212
[ "Go" ]
4
Go
harishb2k/gox-errors
4d34d64e5e85be46adeb72aae627b5ed1815401e
7e7fc2119d3da6792a22761000a802bc2e77b0bc
refs/heads/main
<repo_name>SaifulOMG/Loop-Test<file_sep>/Loop/Loop/Program.cs using System; using System.Collections.Generic; namespace Loop { class Program { static void CustomerMeetingOptions() { Console.WriteLine("Enter 0 to join remote group meeting"); Console.WriteLine("Enter 1 to exit"); } static Customer AddCustomer(string name, string phoneNumber) { Customer customer = new Customer(); customer.Name = name; customer.PhoneNumber = phoneNumber; return customer; } static void Main(string[] args) { int optionNum; Boolean exitLoop = false; string customerName; string customerPhoneNumber; CustomerMenu menu = new CustomerMenu(); List<Customer> customers = new List<Customer>(); CustomerMeetingOptions(); for (int i = 0; exitLoop != true; i++) { try { optionNum = Int16.Parse(Console.ReadLine()); switch (optionNum) { case 0: // input customer name Console.WriteLine("Please enter name to join"); customerName = String.Format("{0}", Console.ReadLine()); // phone number input: +441339612345 output: 01339 612345 Console.WriteLine("Please enter phone number to join"); customerPhoneNumber = String.Format("{0}", Console.ReadLine()); customers.Add(AddCustomer(customerName, customerPhoneNumber)); break; case 1: Console.WriteLine("Are you sure you would like to exit enter Y to exit and N to continue"); char exitOption = Char.Parse(Console.ReadLine()); if (Char.ToUpper(exitOption) == 'Y') { exitLoop = true; } else if (Char.ToUpper(exitOption) != 'N') { throw new Exception("Only characters accepted are Y and N"); } break; default: Console.WriteLine("Please enter a valid option from the list"); CustomerMeetingOptions(); break; } menu.AddCustomer(customers); menu.DisplayCustomerMenu(); CustomerMeetingOptions(); } catch (Exception exception) { Console.WriteLine(exception.Message); } } } } } <file_sep>/Loop/Loop/Customer.cs using System; namespace Loop { public class Customer { protected string _phoneNumber; public string Name { get; set; } public string PhoneNumber { get; set; } public string DisplayCustomerDetail() { RegionalAreaCode areaCode = new RegionalAreaCode(); string readablePhoneNumber = areaCode.MatchUKAreaCode(PhoneNumber); return "Username: " + Name + " " + "Phone Number: " + readablePhoneNumber; } } } <file_sep>/Loop/Loop/CustomerMenu.cs using System; using System.Collections.Generic; namespace Loop { public class CustomerMenu { List<Customer> customers; public void AddCustomer(List<Customer> customers) { this.customers = customers; } public void DisplayCustomerMenu() { foreach(var customer in this.customers) { Console.WriteLine("Details of all users joined"); Console.WriteLine(customer.DisplayCustomerDetail()); } } } } <file_sep>/Loop/Loop/RegionalAreaCode.cs using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Loop { public class RegionalAreaCode { //matching UK formatting rules public string MatchUKAreaCode(string phoneNumber) { string phoneNumberResult = phoneNumber; try { List<Regex> regexBritishNumbers = new List<Regex> { new Regex(@"\+447\d{3}(\s)?\d{5}\b"), //01### ##### new Regex(@"\+441\d{3}(\s)?\d{6}\b"), //01### ###### new Regex(@"\+4411\d{1}(\s)?\d{3}(\s)?\d{4}\b"), //011# ### #### new Regex(@"\+441\d{1}1(\s)?\d{3}(\s)?\d{4}\b"), //01#1 ### #### new Regex(@"\+4413397(\s)?\d{5}\b"), //013397 ##### new Regex(@"\+4413398(\s)?\d{5}\b"), //013398 ##### new Regex(@"\+4413873(\s)?\d{5}\b"), //013873 ##### new Regex(@"\+4415242(\s)?\d{5}\b"), //015242 ##### new Regex(@"\+4415394(\s)?\d{5}\b"), //015394 ##### new Regex(@"\+4415395(\s)?\d{5}\b"), //015395 ##### new Regex(@"\+4415396(\s)?\d{5}\b"), //015396 ##### new Regex(@"\+4416973(\s)?\d{5}\b"), //016973 ##### new Regex(@"\+4416974(\s)?\d{5}\b"), //016974 ##### new Regex(@"\+4416977(\s)?\d{4}\b"), //016977 #### new Regex(@"\+4416977(\s)?\d{5}\b"), //016977 ##### new Regex(@"\+4417683(\s)?\d{5}\b"), //017683 ##### new Regex(@"\+4417684(\s)?\d{5}\b"), //017684 ##### new Regex(@"\+4417687(\s)?\d{5}\b"), //017687 ##### new Regex(@"\+4419467(\s)?\d{5}\b"), //019467 ##### new Regex(@"\+4419755(\s)?\d{5}\b"), //019755 ##### new Regex(@"\+4419756(\s)?\d{5}\b"), //019756 ##### new Regex(@"\+442\d{1}(\s)?\d{4}(\s)?\d{4}\b"), //02# #### #### new Regex(@"\+443\d{2}(\s)?\d{3}(\s)?\d{4}\b"), //03## ### #### new Regex(@"\+445\d{3}(\s)?\d{6}\b"), //05### ###### new Regex(@"\+447\d{3}(\s)?\d{6}\b"), //07### ###### new Regex(@"\+44800(\s)?\d{6}\b"), //0800 ###### new Regex(@"\+448\d{2}(\s)?\d{3}(\s)?\d{4}\b"), //08## ### #### new Regex(@"\+449\d{2}(\s)?\d{3}(\s)?\d{4}\b") //09## ### #### }; foreach (Regex numberMatch in regexBritishNumbers) { if (numberMatch.IsMatch(phoneNumber)) { phoneNumberResult = ConvertToReadable(numberMatch.ToString(), phoneNumber); } } } catch(Exception exception) { Console.WriteLine(exception.Message); } return phoneNumberResult; } //Convert to human readable private string ConvertToReadable(string regexValue, string phoneNumber) { string result = phoneNumber; try { if (phoneNumber.StartsWith("+44")) { result = AddWhiteSpace(regexValue, phoneNumber); result = Regex.Replace(result, @"\+44", @"0"); } } catch (Exception exception) { Console.WriteLine(exception.Message); } return result; } //Adds white space to phone number if needed private string AddWhiteSpace(string regexValue, string phoneNumber) { string result = phoneNumber; try { if (!phoneNumber.Contains(" ")) { if (regexValue == "\\+447\\d{3}(\\s)?\\d{5}\\b" || regexValue == "\\+441\\d{3}(\\s)?\\d{6}\\b" || regexValue == "\\+445\\d{3}(\\s)?\\d{6}\\b" || regexValue == "\\+447\\d{3}(\\s)?\\d{6}\\b") { result = phoneNumber.Insert(7, " "); } else if (regexValue == "\\+4411\\d{1}(\\s)?\\d{3}(\\s)?\\d{4}\\b" || regexValue == "\\+441\\d{1}1(\\s)?\\d{3}(\\s)?\\d{4}\\b" || regexValue == "\\+441\\d{1}1(\\s)?\\d{3}(\\s)?\\d{4}\\b" || regexValue == "\\+443\\d{2}(\\s)?\\d{3}(\\s)?\\d{4}\\b" || regexValue == "\\+448\\d{2}(\\s)?\\d{3}(\\s)?\\d{4}\\b" || regexValue == "\\+449\\d{2}(\\s)?\\d{3}(\\s)?\\d{4}\\b") { result = phoneNumber.Insert(6, " "); result = result.Insert(10, " "); } else if (regexValue == "\\+442\\d{1}(\\s)?\\d{4}(\\s)?\\d{4}\\b") { result = phoneNumber.Insert(5, " "); result = result.Insert(10, " "); } else if (regexValue == "\\+44800(\\s)?\\d{6}\\b") { result = phoneNumber.Insert(6, " "); } else { result = phoneNumber.Insert(8, " "); } } } catch (Exception exception) { Console.WriteLine(exception.Message); } return result; } } }
234d1a50d87cfc90cbc5fc58cd8848bce3b2a7f8
[ "C#" ]
4
C#
SaifulOMG/Loop-Test
73d4ec75431937407e9c28faf7cd2bfd3bdcd126
874e518d8f862b80ad06c8e672087394b2f1e161
refs/heads/master
<repo_name>pharzan/Mithcalc<file_sep>/sendrequest.php <?php /** * Created by PhpStorm. * User: Farzan * Date: 9/4/2015 * Time: 5:34 PM */ header("Access-Control-Allow-Origin: *"); include 'assets\lib\wa_wrapper\WolframAlphaEngine.php'; $response = 'Nothing here'; $appID = 'API-CODE-GOES-HERE'; $qArgs = array(); if (isset($_GET['str'])) { // echo json_encode($_GET['str']); $engine = new WolframAlphaEngine($appID); $response = $engine->getResults($_GET['str'], $qArgs); $ans = array(); //echo json_encode($response); //the if to see if the request suceeded: if ($response->attributes['success']) { if (count($response->getPods()) > 0) { foreach ($response->getPods() as $pod) { array_push($ans, $pod->attributes['title']); // each pod can contain multiple sub pods but must have at least one foreach ($pod->getSubpods() as $subpod) { // if format is an image, the subpod will contain a WAImage object //echo '"'.$subpod->image->attributes['src'].'",'; array_push($ans, $subpod->image->attributes['src']); } } } echo (json_encode($ans)); //echo '["Input","http:\/\/www4b.wolframalpha.com\/Calculate\/MSP\/MSP151iac346h8915gfg500001630h0249f5dci06?MSPStoreType=image\/gif&s=7","Result","http:\/\/www4b.wolframalpha.com\/Calculate\/MSP\/MSP161iac346h8915gfg5000040dah7b92616458h?MSPStoreType=image\/gif&s=7","Number name","http:\/\/www4b.wolframalpha.com\/Calculate\/MSP\/MSP171iac346h8915gfg500002dd1a8c158947igg?MSPStoreType=image\/gif&s=7","Visual representation","http:\/\/www4b.wolframalpha.com\/Calculate\/MSP\/MSP181iac346h8915gfg500004dc0e451abib9i2f?MSPStoreType=image\/gif&s=7","Number line","http:\/\/www4b.wolframalpha.com\/Calculate\/MSP\/MSP191iac346h8915gfg500000ff99bcb7h7bi59i?MSPStoreType=image\/gif&s=7","Illustration","http:\/\/www4b.wolframalpha.com\/Calculate\/MSP\/MSP201iac346h8915gfg500003fii278bae8d87cg?MSPStoreType=image\/gif&s=7"]'; } } else { echo json_encode($response); } <file_sep>/README.md # Mithcalc First try to create a calculator with Mithril js library
456b8256bb2cd84cd9ee1411063100457766bfeb
[ "Markdown", "PHP" ]
2
PHP
pharzan/Mithcalc
38e6f15b15174824cb558d583563484dc9675a86
17c944920f0f448309296d527f166cc63e0b2bd1
refs/heads/master
<repo_name>matiasmoron/cv-matiasmoron<file_sep>/src/containers/GeneralInformationContainer.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import WorkExperience from '../components/GeneralInformation/WorkExperience'; import Languages from '../components/GeneralInformation/Languages'; import Studies from '../components/GeneralInformation/Studies'; import Volunteer from '../components/GeneralInformation/Volunteer'; import Loading from '../components/Loading'; class GeneralInformationContainer extends Component { constructor() { super(); this.state = {}; } componentDidMount() { fetch('data/db.json') .then(response => response.json()) .then(({ generalInformation }) => { this.setState({ generalInformation }); }); } renderComponent() { const { experience, education, languages, volunteer } = this.state.generalInformation; return ( <div className='generalInformation-block'> <WorkExperience data={experience} language={this.props.language}></WorkExperience> <Studies data={education} language={this.props.language}></Studies> <Languages data={languages} language={this.props.language}></Languages> <Volunteer data={volunteer} language={this.props.language}></Volunteer> </div> ); } render() { return this.state.generalInformation ? this.renderComponent() : <Loading></Loading>; } } GeneralInformationContainer.propTypes = { language: PropTypes.string.isRequired }; const mapStateToProps = ({ language }) => ({ language }); export default connect(mapStateToProps, null)(GeneralInformationContainer); <file_sep>/src/components/PersonalInformation/PersonalHeader/index.js import React from 'react'; import PropTypes from 'prop-types'; import './styles.scss'; const PersonalHeader = ({ name, occupation, picture }) => { return ( <div className='personal-header-block'> <div className='profile-card__container'> <div className='profile-card__image'></div> </div> <div className='name-block'>{name}</div> <div className='occupation-block'>{occupation}</div> </div> ); }; PersonalHeader.propTypes = { name: PropTypes.string.isRequired, occupation: PropTypes.string.isRequired }; export default PersonalHeader; <file_sep>/src/actions/index.js // Constants export const SET_LANGUAGE = 'SET_LANGUAGE' // Action creator export const setLanguage = payload => ({ type: SET_LANGUAGE, payload });<file_sep>/src/constants/languagesTypes.js export const ES_AR = 'es_AR'; export const EN_EN = 'en_EN';<file_sep>/src/components/PersonalInformation/index.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import PersonalHeader from './PersonalHeader'; import PersonalBody from './PersonalBody'; import SocialPanel from './SocialPanel'; import transformPersonalData from '../../services/transformPersonalData'; import './styles.scss'; import Loading from '../Loading'; class PersonalInformation extends Component { constructor() { super(); this.state = {} } renderBody() { const { name, occupation, email, extract, picture, phone, socialConnections } = transformPersonalData(this.props.data, this.props.language); return ( <div className="personal-block"> <div className="card profile-card"> <PersonalHeader name={name} occupation={occupation} picture={picture}> </PersonalHeader> <div className="extract"> {extract} </div> <PersonalBody phone={phone} email={email}> </PersonalBody> <SocialPanel data={socialConnections} > </SocialPanel> </div> </div> ) } render() { return ( this.props.data ? this.renderBody() : <Loading></Loading> ); } } PersonalInformation.propTypes = { language: PropTypes.string.isRequired, data:PropTypes.object }; export default PersonalInformation;<file_sep>/README.md Virtual CV , created with React. This is a personal project in which i use React with Redux. I created a Virtual CV. The same was hosting using g-pages. This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). <file_sep>/src/components/GeneralInformation/GeneralItem.js import React from 'react'; import PropTypes from 'prop-types'; import './style.scss'; const GeneralItem = ({ companyName, position, description, time, icon, certificate, classes, moreInfo, children }) => { const itemClasses = `general-item__body ${classes ? classes : ''}`; return ( <div className={itemClasses}> <div className='header-block'> <div className='title__item'> {icon ? <img src={icon} className='general-item__img' alt={description} /> : null} <div> <span className='title__body'>{companyName}</span> <div className='title-time'> <span className='title-time__year-start'>{time.start}</span> <span className='title-time__year-end'>{time.end}</span> </div> </div> </div> </div> <div className='body__block'> <div className='body__data'> <div className='body__occupation'>{position}</div> <div className='body__description'>{description}</div> {certificate ? ( <div className='body__certificate no-print'> <a href={certificate} target='_blank'> {moreInfo.certificateBtn} </a> </div> ) : null} </div> </div> {children} </div> ); }; GeneralItem.propTypes = { companyName: PropTypes.string.isRequired, position: PropTypes.string.isRequired, description: PropTypes.string.isRequired, time: PropTypes.object.isRequired, certificate: PropTypes.string, moreInfo: PropTypes.object, icon: PropTypes.string, classes: PropTypes.string, }; export default GeneralItem; <file_sep>/src/components/PersonalInformation/PersonalBody/Item/index.js import React from 'react'; import PropTypes from 'prop-types'; import './style.scss'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; const Item = ({ title, icon, action = () => { }}) => { return ( <div className="item-block" onClick={ () => action()}> <div className="item-icon-block"> <FontAwesomeIcon icon={icon} /> </div> <div> { <span className="item-title"> {title} </span> } </div> <div> </div> </div> ); }; Item.propTypes = { title : PropTypes.string, icon: PropTypes.array.isRequired, } export default Item;<file_sep>/src/App.js import React, { Component } from 'react'; import { library } from '@fortawesome/fontawesome-svg-core'; import { far } from '@fortawesome/free-regular-svg-icons'; import { fab } from '@fortawesome/free-brands-svg-icons'; import { fas } from '@fortawesome/free-solid-svg-icons'; import './style.scss'; import PanelButtonsLanguagesContainer from './containers/PanelButtonsLanguagesContainer'; import PersonalInformationContainer from "./containers/PersonalInformationContainer"; import GeneralInformationContainer from "./containers/GeneralInformationContainer"; import HtmlToPDF from "./components/HtmlToPDF"; // import ButtonsNavigation from "./components/ButtonsNavigation"; library.add(fas,fab,far) class App extends Component { render() { return ( <div id="capture" className="cv-block"> <PersonalInformationContainer></PersonalInformationContainer> <GeneralInformationContainer></GeneralInformationContainer> {/* <ButtonsNavigation></ButtonsNavigation> */} <PanelButtonsLanguagesContainer></PanelButtonsLanguagesContainer> <HtmlToPDF></HtmlToPDF> </div> ); } } export default App; <file_sep>/src/components/HtmlToPDF/index.js import React, { Component } from 'react'; import html2canvas from 'html2canvas'; import imgPDF from '../../images/pdf.png'; import jsPDF from 'jspdf'; import './style.scss'; class HtmlToPdf extends Component { ocultarElementos = () => { const elements = document.getElementsByClassName('no-print'); for (var i = 0; i < elements.length; i++) { elements[i].style.visibility = 'hidden'; } } mostrarElementos = () => { const elements = document.getElementsByClassName('no-print'); for (var i = 0; i < elements.length; i++) { elements[i].style.visibility = 'visible'; } } convertHtmlToPdf(e) { this.ocultarElementos(); html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas); // if you want see your screenshot in body. const imgData = canvas.toDataURL('image/png'); const pdf = new jsPDF("p", "mm", "a4"); var imgWidth = pdf.internal.pageSize.getWidth(); var pageHeight = 295; var imgHeight = canvas.height * imgWidth / canvas.width; var heightLeft = imgHeight; var position = 0; pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); heightLeft -= pageHeight; while (heightLeft >= 0) { position = heightLeft - imgHeight; pdf.addPage(); pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); heightLeft -= pageHeight; } pdf.save("CV - <NAME> - Full stack developer.pdf"); document.body.removeChild(canvas); this.mostrarElementos(); }); } render() { return ( <div className="print no-print" onClick={this.convertHtmlToPdf.bind(this)}> <img src={imgPDF} className='' alt="pdf"/> </div> ); } } export default HtmlToPdf;<file_sep>/src/components/GeneralInformation/ItemHeader.js import React from 'react'; import PropTypes from 'prop-types'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { OBJECTIVES, WORK, EDUCATION, LANGUAGES, VOLUNTEER } from "../../../src/constants/generalItems"; import './style.scss'; const strToIcon = iconDesc => { switch (iconDesc) { case OBJECTIVES: return ['fas', 'lightbulb']; case WORK: return ['fas', 'briefcase']; case EDUCATION: return ['fas', 'graduation-cap']; case LANGUAGES: return ['fas', 'globe']; case VOLUNTEER: return ['fas', 'hands-helping']; default: break; } } const ItemHeader = ({ title, icon }) => { return ( <div className="general-item__title"> <FontAwesomeIcon icon={strToIcon(icon)} /> <span className="title-description">{title}</span> </div> ) } ItemHeader.propTypes = { title: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, } export default ItemHeader;<file_sep>/src/components/PersonalInformation/PersonalBody/ItemPro/index.js import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import PropTypes from 'prop-types'; import '../Item/style.scss'; const itemsToList = data => ( data.map(({ type, level }, index) => ( <div key={index}> <span className="item-title"> {type} </span> <span className="item-additional"> ({level}) </span> </div> )) ); const ItemPro = ({ title, data, icon }) => { return ( <div className="item-block"> <div className="item-icon-block"> <FontAwesomeIcon icon={icon} /> </div> <div> {itemsToList(data)} </div> </div> ); }; ItemPro.propTypes = { title : PropTypes.string.isRequired, additional : PropTypes.string, } export default ItemPro;<file_sep>/src/components/PanelButtonsLanguages/index.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { ES_AR, EN_EN } from '../../constants/languagesTypes'; import flagArg from '../../images/flagArg.png'; import flagEng from '../../images/flagEng.jpg'; import './style.scss'; class PanelButtonsLanguages extends Component { constructor(props) { super(); } render() { return ( <div className="panel-buttons-languages no-print"> <div className={`language-item ${this.props.language === ES_AR ? 'active': ''} `} onClick={() => this.props.handleClick(ES_AR)}> <img src={flagArg} className="language-flag" alt="arg-flag" /> </div> <div className={`language-item ${this.props.language === EN_EN ? 'active': ''} `} onClick={() => this.props.handleClick(EN_EN)}> <img src={flagEng} className="language-flag" alt="eng-flag"/> </div> </div> ); } } PanelButtonsLanguages.propTypes = { language: PropTypes.string.isRequired, }; const mapStateToProps = ({language}) => ({ language }); export default connect(mapStateToProps,null)(PanelButtonsLanguages);<file_sep>/src/components/ButtonsNavigation/index.js import React from 'react'; import './style.scss'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; const ButtonsNavigation = () => { return ( <div className="buttons-navigation-block"> <ul className="buttons-navigation__list"> <li className="buttons-navigation__item"> <span className="item__icon"> <FontAwesomeIcon icon={['fas', 'lightbulb']} /> </span> <span className="item__description">Objetivos</span> </li> <li className="buttons-navigation__item"> <span className="item__icon"><FontAwesomeIcon icon={['fas', 'briefcase']}/></span> <span className="item__description">Experiencia</span> </li> <li className="buttons-navigation__item"> <span className="item__icon"><FontAwesomeIcon icon={['fas', 'wrench']}/></span> <span className="item__description">Habilidades</span> </li> <li className="buttons-navigation__item"> <span className="item__icon"><FontAwesomeIcon icon={['fas', 'graduation-cap']}/></span> <span className="item__description">Formación</span> </li> <li className="buttons-navigation__item"> <span className="item__icon"><FontAwesomeIcon icon={['fas', 'globe']}/></span> <span className="item__description">Idioma</span> </li> <li className="buttons-navigation__item"> <span className="item__icon"><FontAwesomeIcon icon={['fas', 'hands-helping']}/></span> <span className="item__description">Voluntariados</span> </li> <li className="buttons-navigation__item"> <span className="item__icon"><FontAwesomeIcon icon={['fas', 'info']}/></span> <span className="item__description">Extra</span> </li> </ul> </div> ) } export default ButtonsNavigation;<file_sep>/src/containers/PersonalInformationContainer.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import PersonalInformation from '../components/PersonalInformation'; class PersonalInformationContainer extends Component { constructor() { super(); this.state = {} } componentDidMount() { fetch('data/db.json').then(response => ( response.json() )).then(({ personal }) => { this.setState({ personal }) }); } render() { return ( this.props.language && <PersonalInformation language={this.props.language} data={this.state.personal}> </PersonalInformation> ); } } PersonalInformationContainer.propTypes = { language: PropTypes.string.isRequired, }; const mapStateToProps = ({language}) => ({ language }); export default connect(mapStateToProps,null)(PersonalInformationContainer);<file_sep>/src/components/PersonalInformation/PersonalBody/index.js import React from 'react'; import PropTypes from 'prop-types'; import Item from "./Item"; import './Item/style.scss'; const PersonalBody = ({ phone, email }) => { return ( <div className="personal-body-block"> <Item title={email} icon={["fas","envelope"]} action={ () => openEmail(email)}></Item> <Item title={phone} icon={["fab","whatsapp"]} action={ () => openWhatsAppWeb(phone)} ></Item> </div> ); }; const openWhatsAppWeb = (phone) => { const whatsappUrl = isAMobile() ? 'https://api.whatsapp.com/send?phone=' : 'https://web.whatsapp.com/send?phone='; window.open(`${whatsappUrl}${phone}&text=Hola, me contacto por una propuesta laboral.`); } const openEmail = (email) => { const href = `mailto:${email}`; window.open(href); } const isAMobile = () => { const isMobile = { Android() { return navigator.userAgent.match(/Android/i); }, BlackBerry() { return navigator.userAgent.match(/BlackBerry/i); }, iOS() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera() { return navigator.userAgent.match(/Opera Mini/i); }, Windows() { return ( navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i) ); }, any() { return ( isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows() ); }, }; return Boolean(isMobile.any()); } PersonalBody.propTypes = { phone : PropTypes.string, email: PropTypes.string.isRequired, } export default PersonalBody;<file_sep>/src/containers/PanelButtonsLanguagesContainer.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { setLanguage } from '../actions'; import { connect } from 'react-redux'; import PanelButtonsLanguages from '../components/PanelButtonsLanguages'; class PanelButtonsLanguagesContainer extends Component { constructor() { super(); this.state = {}; } handleLanguagesClick = (language) => { this.props.setLanguage(language); } render() { return ( <PanelButtonsLanguages handleClick={this.handleLanguagesClick}></PanelButtonsLanguages> ); } } PanelButtonsLanguagesContainer.propTypes = { setLanguage: PropTypes.func.isRequired, }; const mapDispatchToProps = dispatch => ({ setLanguage: value => dispatch(setLanguage(value)) }); export default connect(null, mapDispatchToProps)(PanelButtonsLanguagesContainer);
2d7d58cbc3c36bf42ea85dd242c026d1a6df5c29
[ "JavaScript", "Markdown" ]
17
JavaScript
matiasmoron/cv-matiasmoron
845d2703671264d2b629897dcccb38926c94ebd0
14954ca52d0e03cbf65c527bb04d1722c7ce6c96
refs/heads/master
<file_sep> #coding=utf-8 print("hello chenlei") print("请输入第一个数值") num1 = float(input()) print("请输入第二个数值") num2 = float(input()) print("选择运算:") print("1、相加") print("2、相减") print("3、相乘") print("4、相除") ysf=int(input()) def addition(x,y): return x + y def subtraction(x,y): return x - y def multiplication(x,y): return x * y def division(x,y): return x / y if ysf==1: print(num1, "+", num2, "=", addition(num1, num2)) elif ysf==2: print(num1, "-", num2, "=", subtraction(num1, num2)) elif ysf==3: print(num1, "*", num2, "=", multiplication(num1, num2)) elif ysf==4: print(num1, "/", num2, "=", division(num1, num2)) else: print("非法输入")
0bb4657775f2d42b03e51238a7248d66a88a25ee
[ "Python" ]
1
Python
jialeipeng-learn/zuoye
8f45ebf0ba1793f05e5b93ec80d0721edfaac65f
dc80a67ebd93d8e42c9aa7f7058c430afd5a2bd5
refs/heads/master
<file_sep># resuablecomponents dfbjdf dkbdf dfgnkldg dgndmgnd dg,fndklsf sdfm sdkf sd fsdf sd f sd fsdhfkasf sdf sd do itawefawe nsdbcklas adding refs <file_sep>import {useState} from 'react'; import UserInput from "./userInput"; import List from './List'; import classes from './App.module.css'; function App() { const [userData, setUserData] = useState([]); const onSubmit =(newUser) => setUserData([newUser, ...userData]) return ( <div className={classes.contaiiner}> <UserInput onSubmit={onSubmit}/> <List userData={userData}></List> </div> ); } export default App; <file_sep>import React, {useState, useRef} from 'react'; import Button from './Button'; import Card from './Card'; import classes from './UserInput.module.css'; import ErrorModel from './ErrorModel'; function UserInput(props){ const [isError, setIsError] = useState() // const defaultUser ={ // name:'', // age:'' // }; const newUserNameRef = useRef(); const newUserAgeRef = useRef(); // const [newUser, setNewUser] = useState(defaultUser); const submitHandeler = () => { const enteredName= newUserNameRef.current.value; const enteredAge = newUserAgeRef.current.value; if(enteredName === '' || enteredAge === ''){ setIsError({ message:'Please enter valid input (non empty value)!', title:'Error!' });return; }; if(+enteredAge < 0 ){ setIsError({ title:'Error!', message:'Age should be greater then 0' }); } props.onSubmit({name:enteredName,age:enteredAge}); // setNewUser(defaultUser); newUserNameRef.current.value = ''; newUserAgeRef.current.value =''; }; const errorHandeler =() => setIsError(''); return( <React.Fragment> {isError && <ErrorModel onClick={errorHandeler} message={isError.message} title={isError.title} />} <Card className={classes.card}> <> <label className={classes.label} >User Name</label> <input className={classes.input_input} // onChange={(event) => setNewUser({...newUser, name:event.target.value})} // value={newUser.name} type='text' ref={newUserNameRef} /> </> <> <label className={classes.label}>Age(Years)</label> <input className={classes.input_input} // onChange={(event) => setNewUser({...newUser, age:event.target.value})} // value={newUser.age} type='number' min='1' max='100' ref={newUserAgeRef} /> </> <Button className={classes.button} onClick={submitHandeler} type='button'>Add User</Button> </Card> </React.Fragment> ); }; export default UserInput;<file_sep>import classes from './List.module.css'; import Card from "./Card"; function List(props){ return( <div > <Card className={classes.card} > {props.userData.map((user) => { return <div className={classes.list__item}> {user.name} ({user.age}) </div> })} </Card> </div> ); }; export default List;
d9ef5a372be3c57c62691088aa3f24b62fa7d5b2
[ "Markdown", "JavaScript" ]
4
Markdown
vi-verma/resuablecomponents
4e51d213e8c2e9e11a1ae3f9ac7df4db4fe472df
cf0505e7ad58811352f0ee51ec0dd49eb01c13d3
refs/heads/master
<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import AppRouter from './routes/AppRouter' import './styles/styles.css'; import { addAllExpenses } from './actions/expenses' import { addAllIncomes } from './actions/incomes' import configureStore from './store/configureStore'; import { Provider } from 'react-redux'; const store = configureStore(); const expensesDefault = [ { name: "Elektrik", currency: "TRY", value: 222, type: "expense" }, { name: "Su", currency: "TRY", value: 333, type: "expense" }, { name: "Doğalgaz", currency: "USD", value: 111, type: "expense" }, { name: "Kurs", currency: "TRY", value: 44, type: "expense" }, { name: "<NAME>", currency: "TRY", value: 541, type: "expense" }, { name: "Monitör", currency: "USD", value: 651, type: "expense" }, { name: "Telefon", currency: "USD", value: 123, type: "expense" }, { name: "<NAME>", currency: "TRY", value: 48, type: "expense" }, ] let savedExpenses = JSON.parse(localStorage.getItem("expenses")) if (savedExpenses === null) { store.dispatch(addAllExpenses(expensesDefault)) localStorage.setItem("expenses", JSON.stringify(expensesDefault)) } else { store.dispatch(addAllExpenses(savedExpenses)) } let savedIncomes = JSON.parse(localStorage.getItem("incomes")) const incomesDefault = [ { name: "<NAME>", currency: "TRY", value: 2000, type: "income" }, { name: "<NAME>", currency: "TRY", value: 1400, type: "income" }, { name: "Freelance", currency: "USD", value: 500, type: "income" } ] if (savedIncomes === null) { store.dispatch(addAllIncomes(incomesDefault)) localStorage.setItem("incomes", JSON.stringify(incomesDefault)) } else { store.dispatch(addAllIncomes(savedIncomes)) } const jsx = ( <Provider store={store}> <AppRouter /> </Provider> ); ReactDOM.render(jsx, document.getElementById("app"))<file_sep>import React from 'react'; import { NavLink } from 'react-router-dom'; import { connect } from 'react-redux'; import ResultBox from './ResultBox' import selectExpenses from '../selectors/selectExpenses'; import selectIncomes from '../selectors/selectIncomes'; import { setCurrencyFilter } from '../actions/filters' class Index extends React.Component { state = { total_expense: null, total_income: null, current_currency: "TRY" } componentDidMount() { let current_currency = document.getElementById("currencies-filter").value this.props.dispatch(setCurrencyFilter(current_currency)) /******************* */ let total_expense = 0 this.props.filtered_expenses.forEach((d) => { total_expense += d.value * this.getCurrencyValue(d.currency) // try cinsinde !!! }) this.setState(() => ({ total_expense })) /************ */ let total_income = 0 this.props.filtered_incomes.forEach((d) => { total_income += d.value * this.getCurrencyValue(d.currency) }) this.setState(() => ({ total_income })) /***************** */ } getCurrencyValue = (currency_name) => { currency_name = currency_name.toLowerCase() let currency_value = null if (currency_name === "try") { currency_value = 1 } else if (currency_name === "usd") { currency_value = 8.5 } else if (currency_name === "euro") { currency_value = 10.7 } return currency_value } componentDidUpdate() { let currency_value = this.getCurrencyValue(document.getElementById("currencies").value) let total_expense = 0 this.props.filtered_expenses.forEach((d) => { total_expense += d.value * this.getCurrencyValue(d.currency) }) /*****/ let total_income = 0 this.props.filtered_incomes.forEach((d) => { total_income += d.value * this.getCurrencyValue(d.currency) }) total_expense = Math.round(total_expense / currency_value*100)/100; total_income = Math.round(total_income / currency_value*100)/100; if (this.state.total_expense != total_expense || this.state.total_income != total_income ) { this.setState(() => ({ total_income, total_expense, })) } } onSelectChange = () => { let current_currency = document.getElementById("currencies").value // tl , usd if (this.state.current_currency != current_currency) { this.setState(() => ({ current_currency })) } } onFilterChange = () => { let current_currency = document.getElementById("currencies-filter").value let currency_value = this.getCurrencyValue(document.getElementById("currencies").value) this.props.dispatch(setCurrencyFilter(current_currency)) } render() { return ( <div className="container"> <div className="select-wrapper"> <div className="filter-currency"> <label>Filter by:</label> <select name="currencies-filter" id="currencies-filter" onChange={this.onFilterChange}> <option value="">All Currencies</option> <option value="try">TRY</option> <option value="usd">USD</option> <option value="euro">EURO</option> </select> </div> <div className="select-container"> <label>Choose a currency:</label> <select name="currencies" id="currencies" onChange={this.onSelectChange}> <option value="try">TRY</option> <option value="usd">USD</option> <option value="euro">EURO</option> </select> </div> </div> <div className="expenses-title category">Your Expenses:</div> <div className="expenses-container"> {this.props.filtered_expenses.map((expense) => <ResultBox key={expense.name} {...expense } /> )} <NavLink to="/add?type=expense" exact={true}> <div className="add-expense add">+ Add expense</div> </NavLink> <div className="total-info total-expenses">Total: {this.state.total_expense} {this.state.current_currency.toUpperCase()} </div> </div> <div className="incomes-title category">Your Incomes:</div> <div className="incomes-container"> {this.props.filtered_incomes.map((income) => <ResultBox key={income.name} {...income } /> )} <NavLink to="/add?type=income" exact={true}> <div className="add-income add">+ Add income</div> </NavLink> <div className="total-info total-incomes">Total: {this.state.total_income} {this.state.current_currency.toUpperCase()} </div> </div> </div> ) } } const mapStateToProps = (state) => { return { expenses: state.expenses, incomes: state.incomes, filtered_expenses: selectExpenses(state.expenses, state.filters), filtered_incomes: selectIncomes(state.incomes, state.filters), } } export default connect(mapStateToProps)(Index); <file_sep>import React from 'react'; import { addExpense } from '../actions/expenses' import { addIncome } from '../actions/incomes' import { connect } from 'react-redux'; import configureStore from '../store/configureStore'; import swal from 'sweetalert'; class Add extends React.Component { constructor(props) { super(props); } state = { type: undefined } componentDidMount() { let url_string = window.location.href let url = new URL(url_string); let type = url.searchParams.get("type"); if (type != "expense" && type != "income") window.location.href = window.location.origin this.setState(() => ({ type })) } add = () => { let name = document.getElementById("description_input").value let currency = document.getElementById("currency_input").value let value = parseInt(document.getElementById("value_input").value) let type = this.state.type if (this.state.type === "expense") { let expense = { name, currency, value, type } this.props.dispatch(addExpense(expense)) } else if (this.state.type === "income") { let income = { name, currency, value, type } this.props.dispatch(addIncome(income)) } document.querySelectorAll("input").forEach((d) => d.value = "") //alert(this.state.type + " added!") swal ( "Successful." , this.capitalizeFirstLetter(this.state.type) + " is added!" , "success" ) } capitalizeFirstLetter = (string) => { return string.charAt(0).toUpperCase() + string.slice(1); } render() { return ( <div className="form-container"> <div className="add-form"> <input id="description_input" name="description_input" type="text" placeholder="Add description..." /> <input id="value_input" name="value_input" type="text" placeholder="Enter amount..." type="number" /> <div className="select-container"> <select name="currencies" id="currency_input"> <option value="try">TRY</option> <option value="usd">USD</option> <option value="euro">EURO</option> </select> </div> <button onClick={this.add}>Add {this.state.type}!</button> </div> </div> ) } } const mapStateToProps = (state) => { return { expenses: state.expenses, incomes: state.incomes } } export default connect(mapStateToProps)(Add); <file_sep>import { BrowserRouter, Route, Switch, Link, NavLink } from 'react-router-dom'; import React from 'react'; import ReactDOM from 'react-dom'; import Add from '../components/Add'; import Edit from '../components/Edit'; import Index from '../components/Index'; import Header from '../components/Header'; const AppRouter = () => ( <BrowserRouter> <> <Header /> <Switch> <Route exact path='/' render={(props) => ( <Index {...props} /> )} /> <Route path="/add" component={Add} /> <Route path="/edit" component={Edit} /> </Switch> </> </BrowserRouter> ) export default AppRouter; <file_sep>export const setCurrencyFilter = (currency = "") => ({ type: "SET_CURRENCY_FILTER", currency }) <file_sep>import React from 'react'; import { NavLink } from 'react-router-dom'; class Header extends React.Component { render() { return ( <div className="header"> {/* <img src="/img/cg-logo.jpg" alt="cg-logo"/> */} <NavLink to="/" exact={true}> <div className="header-title">Expensify</div> </NavLink> </div> ) } } export default Header; <file_sep>const expensesReducerDefaultState = [] const expensesReducer = (state = expensesReducerDefaultState, action) => { switch (action.type) { case "ADD_EXPENSE": let newState = state newState.push(action.expense) localStorage.setItem("expenses", JSON.stringify(newState)) return newState case "EDIT_EXPENSE": let newState_ = state for (let i=0; i<newState_.length; i++) { if (newState_[i].name === action.expense.old_name) { console.log('bulduuuu'); newState_[i] = action.expense break } } localStorage.setItem("expenses", JSON.stringify(newState_)) return newState_ case "ADD_ALL_EXPENSES": return action.expenses case "REMOVE_EXPENSE": let filtered = state.filter((d) => d.name != action.expense.name) localStorage.setItem("expenses", JSON.stringify(filtered)) return filtered default: return state; } } export default expensesReducer;<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { removeExpense } from '../actions/expenses' import { removeIncome } from '../actions/incomes' class ResultBox extends React.Component { constructor(props) { super(props) } delete = () => { if (this.props.type === "expense") { this.props.dispatch(removeExpense({name: this.props.name})) } else if (this.props.type === "income") { this.props.dispatch(removeIncome({name: this.props.name})) } } edit = () => { //window.history.replaceState(null, "Edit Page", "/edit?type=" + this.props.type + "&name=" + this.props.name) // not consistent window.location.href = "/edit?type=" + this.props.type + "&name=" + this.props.name } render() { return ( <div className="result-box"> <div className="result-name"><span>Description: </span>{this.props.name}</div> <div className="result-value"><span>Amount: </span>{this.props.value} {this.props.currency.toUpperCase()}</div> <div className="edit-result" onClick={this.edit}>EDIT</div> <div className="delete-result" onClick={this.delete}>DELETE</div> </div> ) } } const mapStateToProps = (state) => { return { expenses: state.expenses, incomes: state.incomes } } export default connect(mapStateToProps)(ResultBox); <file_sep>export default (expenses, {currency=""}) => { if (currency === "") return expenses return expenses.filter((e) => e.currency.toLowerCase() === currency.toLowerCase()) } <file_sep>const incomesReducerDefaultState = [] const incomesReducer = (state = incomesReducerDefaultState, action) => { switch (action.type) { case "ADD_INCOME": let newState = state newState.push(action.income) localStorage.setItem("incomes", JSON.stringify(newState)) return newState case "ADD_ALL_INCOMES": return action.incomes case "REMOVE_INCOME": let filtered = state.filter((d) => d.name != action.income.name) localStorage.setItem("incomes", JSON.stringify(filtered)) return filtered case "EDIT_INCOME": let newState_ = state for (let i=0; i<newState_.length; i++) { if (newState_[i].name === action.income.old_name) { newState_[i] = action.income break } } localStorage.setItem("incomes", JSON.stringify(newState_)) return newState_ default: return state; } } export default incomesReducer;
f983d3ea6d3dfdd60bd7afefcc2f5139edfdfae6
[ "JavaScript" ]
10
JavaScript
blackwater17/react-cr
c117e50df987c4f8debbfa57f4bd48e242dedee1
bf4d6d859ea0bb5fb57cbaf4b86d503ed4d1779c
refs/heads/master
<file_sep>package br.daciosoftware.loterias; public class FileSelectionMode { public static final int MODE_CREATE = 0; public static final int MODE_OPEN = 1; } <file_sep>package br.daciosoftware.loterias; import java.util.ArrayList; import java.util.List; import br.daciosoftware.loterias.Megasena.MegasenaColunas; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.util.Log; public class MegasenaRepositorio { private static final String CATEGORIA = "loterias"; private static final String NOME_BANCO = "loterias"; private static final String NOME_TABELA = "megasena"; private static final String SCRIPT_CREATE_TABLE = "create table if not exists " + NOME_TABELA+"("+ "_id integer primary key autoincrement," + "numeroconcurso integer," + "dataconcurso text," + "d1 integer," + "d2 integer," + "d3 integer," + "d4 integer," + "d5 integer," + "d6 integer)"; //Contantes para ordenar e limitar a listagem private static final String ORDER_BY = MegasenaColunas.NUMEROCONCURSO+" desc"; private static final String LIMIT = "limit 0,100"; protected SQLiteDatabase db; public MegasenaRepositorio(Context ctx){ try{ //Abre o banco de dados ja existente db = ctx.openOrCreateDatabase(NOME_BANCO, Context.MODE_PRIVATE, null); db.execSQL(SCRIPT_CREATE_TABLE); }catch(Exception e){ Log.e(CATEGORIA, "Erro ao criar o banco de dados: "+e); } } protected MegasenaRepositorio(){ //Apenas para criar subclasse ... } public long Salvar(Megasena m){ long id = m.getId(); if(id != 0){ Atualizar(m); }else{ //Insere novo id = Inserir(m); } return id; } public long Inserir(Megasena m){ ContentValues values = new ContentValues(); values.put(MegasenaColunas.NUMEROCONCURSO,m.getNumeroConcurso()); values.put(MegasenaColunas.DATACONCURSO,m.getDataConcurso()); values.put(MegasenaColunas.D1,m.getD1()); values.put(MegasenaColunas.D2,m.getD2()); values.put(MegasenaColunas.D3,m.getD3()); values.put(MegasenaColunas.D4,m.getD4()); values.put(MegasenaColunas.D5,m.getD5()); values.put(MegasenaColunas.D6,m.getD6()); long id = Inserir(values); return id; } public long Inserir(ContentValues valores){ long id = db.insert(NOME_TABELA, "", valores); return id; } public int Atualizar(Megasena m){ ContentValues values = new ContentValues(); values.put(MegasenaColunas.NUMEROCONCURSO,m.getNumeroConcurso()); values.put(MegasenaColunas.DATACONCURSO,m.getDataConcurso()); values.put(MegasenaColunas.D1,m.getD1()); values.put(MegasenaColunas.D2,m.getD2()); values.put(MegasenaColunas.D3,m.getD3()); values.put(MegasenaColunas.D4,m.getD4()); values.put(MegasenaColunas.D5,m.getD5()); values.put(MegasenaColunas.D6,m.getD6()); String _id = String.valueOf(m.getId()); String where = MegasenaColunas._ID+"=?"; String[] whereArgs = new String[]{_id}; int count = Atualizar(values, where, whereArgs); return count; } //Atualiza vereador com os valores abaixo //A cláusula where é utilizada para identificar o carro a ser atualizado public int Atualizar(ContentValues valores, String where, String[] whereArgs){ int count = db.update(NOME_TABELA, valores, where, whereArgs); Log.i(CATEGORIA, "Atualizou["+count+"] registros"); return count; } //Delete o carro com o id fornecido public int Deletar(long id){ String where = MegasenaColunas._ID + "=?"; String _id = String.valueOf(id); String[] whereArgs = new String[]{_id}; int count = Deletar(where, whereArgs); return count; } public int Deletar(String where, String[] whereArgs){ int count = db.delete(NOME_TABELA, where, whereArgs); Log.i(CATEGORIA, "Deletou["+count+"] registros"); return count; } //Busca pelo id do concurso public Megasena buscarMegasenaId(long id){ // Select * from megasena where _id = ? Cursor c = db.query(true,NOME_TABELA, Megasena.colunas, MegasenaColunas._ID+"="+id,null, null, null, null, null); if(c.getCount()>0){ //Posiciona no primeiro elemento do cursor c.moveToFirst(); Megasena m = new Megasena(); m.setId(c.getLong(0)); m.setNumeroConcurso(c.getInt(1)); m.setDataConcurso(c.getString(2)); m.setD1(c.getInt(3)); m.setD2(c.getInt(4)); m.setD3(c.getInt(5)); m.setD4(c.getInt(6)); m.setD5(c.getInt(7)); m.setD6(c.getInt(8)); return m; } return null; } //Retorna um cursor com todos os resultados public Cursor getCursor(){ try{ //Select * from megasena return db.query(NOME_TABELA, Megasena.colunas, null, null, null, null, ORDER_BY+" "+LIMIT); }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar resultado da Megasena: "+e.toString()); return null; } } public int getCountReg(){ int countReg = 0; Cursor cursor; try{ //Select * from megasena cursor = db.query(NOME_TABELA, Megasena.colunas, null, null, null, null, null); countReg = cursor.getCount(); return countReg; }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar resultado da Megasena: "+e.toString()); return 0; } } //Retorna uma lista de todos os resultados public List<Megasena> listarMegasena(){ Cursor c = getCursor(); List<Megasena> listaMegasena = new ArrayList<Megasena>(); if(c.moveToFirst()){ int idxId = c.getColumnIndex(MegasenaColunas._ID); int idxNumeroConcurso = c.getColumnIndex(MegasenaColunas.NUMEROCONCURSO); int idxDataConcurso = c.getColumnIndex(MegasenaColunas.DATACONCURSO); int idxD1 = c.getColumnIndex(MegasenaColunas.D1); int idxD2 = c.getColumnIndex(MegasenaColunas.D2); int idxD3 = c.getColumnIndex(MegasenaColunas.D3); int idxD4 = c.getColumnIndex(MegasenaColunas.D4); int idxD5 = c.getColumnIndex(MegasenaColunas.D5); int idxD6 = c.getColumnIndex(MegasenaColunas.D6); //Loop até o fim do{ Megasena m = new Megasena(); listaMegasena.add(m); //recupera os atributos do vereador m.setId(c.getLong(idxId)); m.setNumeroConcurso(c.getInt(idxNumeroConcurso)); m.setDataConcurso(c.getString(idxDataConcurso)); m.setD1(c.getInt(idxD1)); m.setD2(c.getInt(idxD2)); m.setD3(c.getInt(idxD3)); m.setD4(c.getInt(idxD4)); m.setD5(c.getInt(idxD5)); m.setD6(c.getInt(idxD6)); }while(c.moveToNext()); } return listaMegasena; } //Consultar Resultado public List<Megasena> consultarResultados(String param){ Cursor c = db.query(true,NOME_TABELA, Megasena.colunas, param,null, null, null, null, null); List<Megasena> listaMegasena = new ArrayList<Megasena>(); if(c.moveToFirst()){ int idxId = c.getColumnIndex(MegasenaColunas._ID); int idxNumeroConcurso = c.getColumnIndex(MegasenaColunas.NUMEROCONCURSO); int idxDataConcurso = c.getColumnIndex(MegasenaColunas.DATACONCURSO); int idxD1 = c.getColumnIndex(MegasenaColunas.D1); int idxD2 = c.getColumnIndex(MegasenaColunas.D2); int idxD3 = c.getColumnIndex(MegasenaColunas.D3); int idxD4 = c.getColumnIndex(MegasenaColunas.D4); int idxD5 = c.getColumnIndex(MegasenaColunas.D5); int idxD6 = c.getColumnIndex(MegasenaColunas.D6); //Loop até o fim do{ Megasena m = new Megasena(); listaMegasena.add(m); //recupera os atributos do vereador m.setId(c.getLong(idxId)); m.setNumeroConcurso(c.getInt(idxNumeroConcurso)); m.setDataConcurso(c.getString(idxDataConcurso)); m.setD1(c.getInt(idxD1)); m.setD2(c.getInt(idxD2)); m.setD3(c.getInt(idxD3)); m.setD4(c.getInt(idxD4)); m.setD5(c.getInt(idxD5)); m.setD6(c.getInt(idxD6)); }while(c.moveToNext()); } return listaMegasena; } //Buscar um resultado da megasena utilizando as configurações definidas no //SQLiteQueryBuilder //utilizando pelo Content Provider de partido public Cursor query(SQLiteQueryBuilder queryBuilder, String[] projection, String selection, String[] selectionArgs,String groupBy, String having, String orderBy){ Cursor c = queryBuilder.query(this.db, projection, selection, selectionArgs, groupBy, having, orderBy); return c; } //Fecha o banco public void Fechar(){ if(db != null){ db.close(); } } } <file_sep>package br.daciosoftware.loterias; import java.util.List; import br.daciosoftware.loterias.Quina.QuinaColunas; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; public class QuinaListagemResultados extends Activity implements OnItemClickListener{ protected static final String CATEGORIA = "loteria"; protected static final int INSERIR_EDITAR = 1; public static QuinaRepositorio repositorio; private List<Quina> listaQuina; private ListView listViewDados; @Override public void onCreate(Bundle icicle){ super.onCreate(icicle); setContentView(R.layout.activity_listagem_resultados); LinearLayout tela = (LinearLayout) findViewById(R.id.LinearLayoutBackground); tela.setBackgroundResource(R.drawable.background_quina); ImageView imgHeader = (ImageView) findViewById(R.id.ImageViewHeader); imgHeader.setBackgroundResource(R.drawable.header_quina); repositorio = new QuinaRepositorio(this); if(repositorio.listarQuina().size()>0){ Log.i(CATEGORIA,"Inicializou a Tela de Listagem dos Resultados da Lotofacil"); atualizaLista(); } else{ Utils.showAlert(this, getString(R.string.textAtencao), getString(R.string.textInstrucoesQN), true); } Button btQuinaInserirResultado = (Button) findViewById(R.id.btInserirResultado); btQuinaInserirResultado.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent it = new Intent(QuinaListagemResultados.this, QuinaEditarResultado.class); startActivityForResult(it,INSERIR_EDITAR); //startActivity(it,INSERIR_EDITAR); } }); Button btConsultar = (Button) findViewById(R.id.btConsultar); btConsultar.setOnClickListener(new OnClickListener() { public void onClick(View view) { EditText edtConsultaNumeroConcurso = (EditText) findViewById(R.id.consultarNumeroConcurso); EditText edtConsultaDataConcurso = (EditText) findViewById(R.id.consultarDataConcurso); EditText edtConsultaDezenasConcurso = (EditText) findViewById(R.id.consultarDezenasConcurso); String param = QuinaColunas._ID +">0"; String textoNumeroConcurso = edtConsultaNumeroConcurso.getText().toString(); String textoDezenasConcurso = edtConsultaDezenasConcurso.getText().toString(); String textoDataConcurso = edtConsultaDataConcurso.getText().toString(); if(!textoNumeroConcurso.equals("")){ param += QuinaColunas.NUMEROCONCURSO+"="+textoNumeroConcurso; } if(!textoDataConcurso.equals("")){ param += " and "+QuinaColunas.DATACONCURSO+"='"+textoDataConcurso+"'"; } if(!textoDezenasConcurso.equals("")){ param += " and "+QuinaColunas.D1+" in("+textoDezenasConcurso+")"+ " and "+QuinaColunas.D2+" in("+textoDezenasConcurso+")"+ " and "+QuinaColunas.D3+" in("+textoDezenasConcurso+")"+ " and "+QuinaColunas.D4+" in("+textoDezenasConcurso+")"+ " and "+QuinaColunas.D5+" in("+textoDezenasConcurso+")"; } if(!param.equals("")){ atualizaLista(param); }else{ atualizaLista(); } } }); } @Override protected void onPause(){ super.onPause(); Log.i(CATEGORIA,"Pausou a Tela de Listagem de Resultados da Quina"); } protected void atualizaLista(){ //Pega a lista de partidos e exibe na tela listaQuina = repositorio.listarQuina(); //Adaptador da lista customizada para cada linha de um partido QuinaListAdapter adapter = new QuinaListAdapter(this,listaQuina); listViewDados = (ListView) findViewById(R.id.lista_resultados); listViewDados.setAdapter(adapter); listViewDados.setOnItemClickListener(this); Log.i(CATEGORIA,"Atualizou a Listagem de Resultados Quina"); } protected void atualizaLista(String param){ //Pega a lista de resultados e exibe na tela listaQuina = repositorio.consultarResultados(param); if(listaQuina.size()>0){ //Adaptador da lista customizada para cada linha de um resultado QuinaListAdapter adapter = new QuinaListAdapter(this,listaQuina); listViewDados = (ListView) findViewById(R.id.lista_resultados); listViewDados.setAdapter(adapter); listViewDados.setOnItemClickListener(this); Log.i(CATEGORIA,"Atualizou a Listagem de Resultados Quina"); }else{ Toast.makeText(this, "Nenhum resultado encontrado!", Toast.LENGTH_SHORT).show(); } } //Recupera o id dos resultados abre a tela de edição protected void editarResultadoQuina(int posicao){ Quina m = listaQuina.get(posicao); Log.i(CATEGORIA,"Iniciando Intent Editar"); Intent it = new Intent(this, QuinaEditarResultado.class); it.putExtra(QuinaColunas._ID, m.getId()); Log.i(CATEGORIA,"Abrindo a Tela de Edição "); startActivityForResult(it, INSERIR_EDITAR); Log.i(CATEGORIA,"Tela de Edição de aberta"); } @Override protected void onActivityResult(int codigo, int codigoRetorno, Intent it){ super.onActivityResult(codigo, codigoRetorno, it); //Quando a activty EditarVereador retornar, seja se foi para editar, atualizar ou excluir //Vamos atualizar a lista if(codigoRetorno == RESULT_OK){ //Atualiza a lista atualizaLista(); } } @Override protected void onDestroy(){ super.onDestroy(); //Fecha o banco repositorio.Fechar(); Log.i(CATEGORIA,"Destruiu a Tela de Listagem de Resultado da Quina"); } /* * (non-Javadoc) * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) * Método sobreposto; */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub editarResultadoQuina(position); } public void onItemClick(int position) { // TODO Auto-generated method stub editarResultadoQuina(position); } } <file_sep>package br.daciosoftware.loterias; import java.util.List; import br.daciosoftware.loterias.MegasenaMaisSorteadas.MegasenaMaisSorteadasColunas; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; public class MegasenaDezenasMaisSorteadas extends Activity{ protected static final String CATEGORIA = "loterias"; public static MegasenaMaisSorteadasRepositorio repositorio; public static MegasenaRepositorio mr; private List<MegasenaMaisSorteadas> listaMegasenaMaisSorteadas; private ListView listViewDados; private ProgressDialog dialog; private Spinner spinnerConcursos; private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dezenas_mais_sorteadas); LinearLayout tela = (LinearLayout) findViewById(R.id.LinearLayoutBackground); tela.setBackgroundResource(R.drawable.background_megasena); ImageView imgHeader = (ImageView) findViewById(R.id.ImageViewHeader); imgHeader.setBackgroundResource(R.drawable.header_megasena); mr = new MegasenaRepositorio(this); repositorio = new MegasenaMaisSorteadasRepositorio(this); if(mr.getCursor().getCount() > 0){ Log.i(CATEGORIA,"Inicializou a Tela de Listagem dos Resultados da Mega-Sena"); dialog = ProgressDialog.show(this, "", "Aguarde...",false,true); carregaDados(0); atualizaLista(); } else{ Utils.showAlert(this, getString(R.string.textAtencao), getString(R.string.textInstrucoesMS), true); } spinnerConcursos = (Spinner) findViewById(R.id.spinnerConcursos); Button btListar = (Button) findViewById(R.id.btListar); btListar.setOnClickListener(new OnClickListener() { public void onClick(View view) { int n; n = spinnerConcursos.getSelectedItemPosition(); switch(n){ case 1: n = 10; break; case 2: n = 30; break; case 3: n = 30; break; case 4: n = 40; break; case 5: n = 50; break; case 6: n = 100; break; } if(mr.getCursor().getCount() > 0){ dialog = ProgressDialog.show(MegasenaDezenasMaisSorteadas.this, "", "Aguarde...",false,true); carregaDados(n); } } }); Button btGerarJogos = (Button) findViewById(R.id.btGerarJogos); btGerarJogos.setOnClickListener(new OnClickListener() { public void onClick(View view) { if(repositorio.getDezenasSelecionadas().getCount()<6){ Toast.makeText(MegasenaDezenasMaisSorteadas.this, "Selecione pelo menos 6 dezenas", Toast.LENGTH_SHORT).show(); }else{ gerarJogos(); } } }); } @Override protected void onPause(){ super.onPause(); Log.i(CATEGORIA,"Pausou a Tela de Listagem de Resultados da Megasena"); } protected void atualizaLista(){ //Pega a lista de partidos e exibe na tela listaMegasenaMaisSorteadas = repositorio.listarMegasenaMaisSorteadas(); //Adaptador da lista customizada para cada linha de um partido MegasenaMaisSorteadasListAdapter adapter = new MegasenaMaisSorteadasListAdapter(this,listaMegasenaMaisSorteadas); listViewDados = (ListView) findViewById(R.id.lista_dezenas_mais_sorteadas); listViewDados.setAdapter(adapter); Log.i(CATEGORIA,"Atualizou a Listagem de Dezenas Mais Sorteadas"); } protected void gerarJogos(){ //Aqui fazer as conbinações com as dezenas marcadas Intent it = new Intent(this, MegasenaGerarJogos.class); startActivity(it); } private void carregaDados(final int concursos){ new Thread(){ @Override public void run(){ repositorio.Deletar(MegasenaMaisSorteadasColunas._ID + ">?", new String[]{"0"}); repositorio.InserirDezenas(concursos); finalizaCarga(); } }.start(); } private void finalizaCarga(){ handler.post(new Runnable(){ public void run(){ //Fecha a janela de progresso dialog.dismiss(); atualizaLista(); } }); } @Override protected void onDestroy(){ super.onDestroy(); //Fecha o banco repositorio.Fechar(); Log.i(CATEGORIA,"Destruiu a Tela de Listagem de Resultado da Megasena"); } } <file_sep>package br.daciosoftware.loterias; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class MegasenaJogosGeradosListAdapter extends BaseAdapter{ private Context context; private ArrayList<String> lista; public MegasenaJogosGeradosListAdapter(Context context, ArrayList<String> lista){ this.context = context; this.lista = lista; } public int getCount(){ return lista.size(); } public Object getItem(int position){ return lista.get(position); } public long getItemId(int position){ return position; } public View getView(int position, View convertView, ViewGroup parent){ //Recupera o partido da posição atual LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view1 = inflater.inflate(R.layout.activity_jogos_gerados_linha_adapter, null); //Atualiza o valor do TextView TextView jogoGerado = (TextView) view1.findViewById(R.id.textDezenasJogos); jogoGerado.setText(lista.get(position).toString()); return view1; } } <file_sep>package br.daciosoftware.loterias; import java.util.ArrayList; import java.util.List; import br.daciosoftware.loterias.Lotofacil.LotofacilColunas; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.util.Log; public class LotofacilRepositorio { private static final String CATEGORIA = "loterias"; private static final String NOME_BANCO = "loterias"; private static final String NOME_TABELA = "lotofacil"; private static final String SCRIPT_CREATE_TABLE = "create table if not exists " + NOME_TABELA+"("+ "_id integer primary key autoincrement," + "numeroconcurso integer," + "dataconcurso text," + "d1 integer," + "d2 integer," + "d3 integer," + "d4 integer," + "d5 integer," + "d6 integer," + "d7 integer," + "d8 integer," + "d9 integer," + "d10 integer," + "d11 integer," + "d12 integer," + "d13 integer," + "d14 integer," + "d15 integer)"; //Contantes para ordenar e limitar a listagem private static final String ORDER_BY = LotofacilColunas.NUMEROCONCURSO+" desc"; private static final String LIMIT = "limit 0,100"; protected SQLiteDatabase db; public LotofacilRepositorio(Context ctx){ try{ //Abre o banco de dados ja existente db = ctx.openOrCreateDatabase(NOME_BANCO, Context.MODE_PRIVATE, null); db.execSQL(SCRIPT_CREATE_TABLE); }catch(Exception e){ Log.e(CATEGORIA, "Erro ao criar o banco de dados: "+e); } } protected LotofacilRepositorio(){ //Apenas para criar subclasse ... } public long Salvar(Lotofacil l){ long id = l.getId(); if(id != 0){ Atualizar(l); }else{ //Insere novo id = Inserir(l); } return id; } public long Inserir(Lotofacil l){ ContentValues values = new ContentValues(); values.put(LotofacilColunas.NUMEROCONCURSO,l.getNumeroConcurso()); values.put(LotofacilColunas.DATACONCURSO,l.getDataConcurso()); values.put(LotofacilColunas.D1,l.getD1()); values.put(LotofacilColunas.D2,l.getD2()); values.put(LotofacilColunas.D3,l.getD3()); values.put(LotofacilColunas.D4,l.getD4()); values.put(LotofacilColunas.D5,l.getD5()); values.put(LotofacilColunas.D6,l.getD6()); values.put(LotofacilColunas.D7,l.getD7()); values.put(LotofacilColunas.D8,l.getD8()); values.put(LotofacilColunas.D9,l.getD9()); values.put(LotofacilColunas.D10,l.getD10()); values.put(LotofacilColunas.D11,l.getD11()); values.put(LotofacilColunas.D12,l.getD12()); values.put(LotofacilColunas.D13,l.getD13()); values.put(LotofacilColunas.D14,l.getD14()); values.put(LotofacilColunas.D15,l.getD15()); long id = Inserir(values); return id; } public long Inserir(ContentValues valores){ long id = db.insert(NOME_TABELA, "", valores); return id; } public int Atualizar(Lotofacil l){ ContentValues values = new ContentValues(); values.put(LotofacilColunas.NUMEROCONCURSO,l.getNumeroConcurso()); values.put(LotofacilColunas.DATACONCURSO,l.getDataConcurso()); values.put(LotofacilColunas.D1,l.getD1()); values.put(LotofacilColunas.D2,l.getD2()); values.put(LotofacilColunas.D3,l.getD3()); values.put(LotofacilColunas.D4,l.getD4()); values.put(LotofacilColunas.D5,l.getD5()); values.put(LotofacilColunas.D6,l.getD6()); values.put(LotofacilColunas.D7,l.getD7()); values.put(LotofacilColunas.D8,l.getD8()); values.put(LotofacilColunas.D9,l.getD9()); values.put(LotofacilColunas.D10,l.getD10()); values.put(LotofacilColunas.D11,l.getD11()); values.put(LotofacilColunas.D12,l.getD12()); values.put(LotofacilColunas.D13,l.getD13()); values.put(LotofacilColunas.D14,l.getD14()); values.put(LotofacilColunas.D15,l.getD15()); String _id = String.valueOf(l.getId()); String where = LotofacilColunas._ID+"=?"; String[] whereArgs = new String[]{_id}; int count = Atualizar(values, where, whereArgs); return count; } //Atualiza vereador com os valores abaixo //A cláusula where é utilizada para identificar o carro a ser atualizado public int Atualizar(ContentValues valores, String where, String[] whereArgs){ int count = db.update(NOME_TABELA, valores, where, whereArgs); Log.i(CATEGORIA, "Atualizou["+count+"] registros"); return count; } //Delete o carro com o id fornecido public int Deletar(long id){ String where = LotofacilColunas._ID + "=?"; String _id = String.valueOf(id); String[] whereArgs = new String[]{_id}; int count = Deletar(where, whereArgs); return count; } public int Deletar(String where, String[] whereArgs){ int count = db.delete(NOME_TABELA, where, whereArgs); Log.i(CATEGORIA, "Deletou["+count+"] registros"); return count; } //Busca pelo id do concurso public Lotofacil buscarLotofacilId(long id){ // Select * from lotofacil where _id = ? Cursor c = db.query(true,NOME_TABELA, Lotofacil.colunas, LotofacilColunas._ID+"="+id,null, null, null, null, null); if(c.getCount()>0){ //Posiciona no primeiro elemento do cursor c.moveToFirst(); Lotofacil l = new Lotofacil(); l.setId(c.getLong(0)); l.setNumeroConcurso(c.getInt(1)); l.setDataConcurso(c.getString(2)); l.setD1(c.getInt(3)); l.setD2(c.getInt(4)); l.setD3(c.getInt(5)); l.setD4(c.getInt(6)); l.setD5(c.getInt(7)); l.setD6(c.getInt(8)); l.setD7(c.getInt(9)); l.setD8(c.getInt(10)); l.setD9(c.getInt(11)); l.setD10(c.getInt(12)); l.setD11(c.getInt(13)); l.setD12(c.getInt(14)); l.setD13(c.getInt(15)); l.setD14(c.getInt(16)); l.setD15(c.getInt(17)); return l; } return null; } //Retorna um cursor com todos os resultados public Cursor getCursor(){ try{ //Select * from lotofacil return db.query(NOME_TABELA, Lotofacil.colunas, null, null, null, null, ORDER_BY+" "+LIMIT); }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar resultado da Lotofacil: "+e.toString()); return null; } } public int getCountReg(){ int countReg = 0; Cursor cursor; try{ //Select * from lotofacil cursor = db.query(NOME_TABELA, Lotofacil.colunas, null, null, null, null, null); countReg = cursor.getCount(); return countReg; }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar resultado da Lotofacil: "+e.toString()); return 0; } } //Retorna uma lista de todos os resultados public List<Lotofacil> listarLotofacil(){ Cursor c = getCursor(); List<Lotofacil> listaLotofacil = new ArrayList<Lotofacil>(); if(c.moveToFirst()){ int idxId = c.getColumnIndex(LotofacilColunas._ID); int idxNumeroConcurso = c.getColumnIndex(LotofacilColunas.NUMEROCONCURSO); int idxDataConcurso = c.getColumnIndex(LotofacilColunas.DATACONCURSO); int idxD1 = c.getColumnIndex(LotofacilColunas.D1); int idxD2 = c.getColumnIndex(LotofacilColunas.D2); int idxD3 = c.getColumnIndex(LotofacilColunas.D3); int idxD4 = c.getColumnIndex(LotofacilColunas.D4); int idxD5 = c.getColumnIndex(LotofacilColunas.D5); int idxD6 = c.getColumnIndex(LotofacilColunas.D6); int idxD7 = c.getColumnIndex(LotofacilColunas.D7); int idxD8 = c.getColumnIndex(LotofacilColunas.D8); int idxD9 = c.getColumnIndex(LotofacilColunas.D9); int idxD10 = c.getColumnIndex(LotofacilColunas.D10); int idxD11 = c.getColumnIndex(LotofacilColunas.D11); int idxD12 = c.getColumnIndex(LotofacilColunas.D12); int idxD13 = c.getColumnIndex(LotofacilColunas.D13); int idxD14 = c.getColumnIndex(LotofacilColunas.D14); int idxD15 = c.getColumnIndex(LotofacilColunas.D15); //Loop até o fim do{ Lotofacil l = new Lotofacil(); listaLotofacil.add(l); //recupera os atributos do vereador l.setId(c.getLong(idxId)); l.setNumeroConcurso(c.getInt(idxNumeroConcurso)); l.setDataConcurso(c.getString(idxDataConcurso)); l.setD1(c.getInt(idxD1)); l.setD2(c.getInt(idxD2)); l.setD3(c.getInt(idxD3)); l.setD4(c.getInt(idxD4)); l.setD5(c.getInt(idxD5)); l.setD6(c.getInt(idxD6)); l.setD7(c.getInt(idxD7)); l.setD8(c.getInt(idxD8)); l.setD9(c.getInt(idxD9)); l.setD10(c.getInt(idxD10)); l.setD11(c.getInt(idxD11)); l.setD12(c.getInt(idxD12)); l.setD13(c.getInt(idxD13)); l.setD14(c.getInt(idxD14)); l.setD15(c.getInt(idxD15)); }while(c.moveToNext()); } return listaLotofacil; } //Consultar Resultado public List<Lotofacil> consultarResultados(String param){ Cursor c = db.query(true,NOME_TABELA, Lotofacil.colunas, param,null, null, null, null, null); List<Lotofacil> listaLotofacil = new ArrayList<Lotofacil>(); if(c.moveToFirst()){ int idxId = c.getColumnIndex(LotofacilColunas._ID); int idxNumeroConcurso = c.getColumnIndex(LotofacilColunas.NUMEROCONCURSO); int idxDataConcurso = c.getColumnIndex(LotofacilColunas.DATACONCURSO); int idxD1 = c.getColumnIndex(LotofacilColunas.D1); int idxD2 = c.getColumnIndex(LotofacilColunas.D2); int idxD3 = c.getColumnIndex(LotofacilColunas.D3); int idxD4 = c.getColumnIndex(LotofacilColunas.D4); int idxD5 = c.getColumnIndex(LotofacilColunas.D5); int idxD6 = c.getColumnIndex(LotofacilColunas.D6); int idxD7 = c.getColumnIndex(LotofacilColunas.D7); int idxD8 = c.getColumnIndex(LotofacilColunas.D8); int idxD9 = c.getColumnIndex(LotofacilColunas.D9); int idxD10 = c.getColumnIndex(LotofacilColunas.D10); int idxD11 = c.getColumnIndex(LotofacilColunas.D11); int idxD12 = c.getColumnIndex(LotofacilColunas.D12); int idxD13 = c.getColumnIndex(LotofacilColunas.D13); int idxD14 = c.getColumnIndex(LotofacilColunas.D14); int idxD15= c.getColumnIndex(LotofacilColunas.D15); //Loop até o fim do{ Lotofacil l = new Lotofacil(); listaLotofacil.add(l); //recupera os atributos do vereador l.setId(c.getLong(idxId)); l.setNumeroConcurso(c.getInt(idxNumeroConcurso)); l.setDataConcurso(c.getString(idxDataConcurso)); l.setD1(c.getInt(idxD1)); l.setD2(c.getInt(idxD2)); l.setD3(c.getInt(idxD3)); l.setD4(c.getInt(idxD4)); l.setD5(c.getInt(idxD5)); l.setD6(c.getInt(idxD6)); l.setD7(c.getInt(idxD7)); l.setD8(c.getInt(idxD8)); l.setD9(c.getInt(idxD9)); l.setD10(c.getInt(idxD10)); l.setD11(c.getInt(idxD11)); l.setD12(c.getInt(idxD12)); l.setD13(c.getInt(idxD13)); l.setD14(c.getInt(idxD14)); l.setD15(c.getInt(idxD15)); }while(c.moveToNext()); } return listaLotofacil; } //Buscar um resultado da lotofacil utilizando as configurações definidas no //SQLiteQueryBuilder //utilizando pelo Content Provider de partido public Cursor query(SQLiteQueryBuilder queryBuilder, String[] projection, String selection, String[] selectionArgs,String groupBy, String having, String orderBy){ Cursor c = queryBuilder.query(this.db, projection, selection, selectionArgs, groupBy, having, orderBy); return c; } //Fecha o banco public void Fechar(){ if(db != null){ db.close(); } } } <file_sep>package br.com.daciosoftware.meumapa.db; import android.provider.BaseColumns; public class MeuMapaContratoDatabase { public static final String NOME_BANCO = "meumapa.db"; public static final int VERSAO = 1; // Informações da tabela 'aula' public static abstract class Localizacao implements BaseColumns{ // Colunas da tabela 'localizacao' public static final String NOME_TABELA = "localizacao"; public static final String COLUNA_LATITUDE = "latitude"; public static final String COLUNA_LONGITUDE = "longitude"; public static final String COLUNA_NOME_LOCAL = "nome_local"; // Query de criação da tabela public static final String SQL_CRIAR_TABELA_LOCALIZACAO = "CREATE TABLE " + NOME_TABELA + "(" + Localizacao._ID + " INTEGER PRIMARY KEY, " + Localizacao.COLUNA_LATITUDE + " FLOAT, " + Localizacao.COLUNA_LONGITUDE + " FLOAT, " + Localizacao.COLUNA_NOME_LOCAL + " TEXT" + ")"; } } <file_sep>package br.com.daciosoftware.meumapa.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class MeuMapaHelperDatabase extends SQLiteOpenHelper{ public MeuMapaHelperDatabase(Context context){ super(context, MeuMapaContratoDatabase.NOME_BANCO, null, MeuMapaContratoDatabase.VERSAO); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(MeuMapaContratoDatabase.Localizacao.SQL_CRIAR_TABELA_LOCALIZACAO); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } } <file_sep>package br.daciosoftware.loterias; import br.daciosoftware.loterias.Quina.QuinaColunas; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; /** * Activity que utiliza o TableLayout para editar o Resultado da Quina * * @author fdacio * */ public class QuinaEditarResultado extends Activity { protected static final String CATEGORIA = "loteria"; static final int RESULT_SALVAR = 3; static final int RESULT_EXCLUIR = 4; // Campos texto private EditText edtNumeroConcurso; private EditText edtDataConcurso; private EditText edtD1; private EditText edtD2; private EditText edtD3; private EditText edtD4; private EditText edtD5; private Long id; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.activity_editar_resultado_quina); LinearLayout tela = (LinearLayout) findViewById(R.id.LinearLayoutBackground); tela.setBackgroundResource(R.drawable.background_quina); ImageView imgHeader = (ImageView) findViewById(R.id.ImageViewHeader); imgHeader.setBackgroundResource(R.drawable.header_quina); edtNumeroConcurso = (EditText) findViewById(R.id.edtQuinaNumeroConscurso); edtDataConcurso = (EditText) findViewById(R.id.edtQuinaDataConcurso); edtD1 = (EditText) findViewById(R.id.edtQuinaD1); edtD2 = (EditText) findViewById(R.id.edtQuinaD2); edtD3 = (EditText) findViewById(R.id.edtQuinaD3); edtD4 = (EditText) findViewById(R.id.edtQuinaD4); edtD5 = (EditText) findViewById(R.id.edtQuinaD5); id = null; Bundle extras = getIntent().getExtras(); // Se for para Editar, recuperar os valores ... if (extras != null) { id = extras.getLong(QuinaColunas._ID); if (id != null) { // é uma edição, busca o resutado... Quina m = buscarQuinaId(id); edtNumeroConcurso.setText(String.valueOf(m.getNumeroConcurso())); edtDataConcurso.setText(String.valueOf(m.getDataConcurso())); edtD1.setText(String.valueOf(m.getD1())); edtD2.setText(String.valueOf(m.getD2())); edtD3.setText(String.valueOf(m.getD3())); edtD4.setText(String.valueOf(m.getD4())); edtD5.setText(String.valueOf(m.getD5())); } } Button btCancelar = (Button) findViewById(R.id.btCancelar); btCancelar.setOnClickListener(new OnClickListener() { public void onClick(View view) { setResult(RESULT_CANCELED); //Fecha a tela finish(); } }); // Listener para salvar o Vereador Button btSalvar = (Button) findViewById(R.id.btSalvar); btSalvar.setOnClickListener(new OnClickListener() { public void onClick(View view) { salvar(); } }); Button btExcluir = (Button) findViewById(R.id.btExcluir); if (id == null) { // Se id está nulo, não pode excluir //btExcluir.setVisibility(View.INVISIBLE); btExcluir.setEnabled(false); } else { // Listener para excluir o resultado btExcluir.setOnClickListener(new OnClickListener() { public void onClick(View view) { excluir(); } }); } Log.i(CATEGORIA,"Iniciou a Tela de Editar de Partidos"); } @Override protected void onPause() { super.onPause(); // Cancela para nao ficar nada na tela pendente setResult(RESULT_CANCELED); // Fecha a tela finish(); } @Override protected void onDestroy(){ super.onDestroy(); Log.i(CATEGORIA,"Destruiu a Tela de Editar de Resultado Quina"); } @SuppressLint("ParserError") public boolean salvar() { if(!Validador.validateNotNull(edtNumeroConcurso, "Informe o numero do concurso",QuinaEditarResultado.this)){ return false; } if(!Validador.validateNotNull(edtDataConcurso, "Informe a data do concurso",QuinaEditarResultado.this)){ return false; } if(!Validador.validateDateFormat(edtDataConcurso,"dd/mm/yyyy","Data do concurso inválida",QuinaEditarResultado.this)){ return false; } if(!Validador.validateNotNull(edtD1, "Informe a 1ª dezena do concurso",QuinaEditarResultado.this)){ return false; } if(!Validador.validateNotNull(edtD2, "Informe a 2ª dezena do concurso",QuinaEditarResultado.this)){ return false; } if(!Validador.validateNotNull(edtD3, "Informe a 3ª dezena do concurso",QuinaEditarResultado.this)){ return false; } if(!Validador.validateNotNull(edtD4, "Informe a 4ª dezena do concurso",QuinaEditarResultado.this)){ return false; } if(!Validador.validateNotNull(edtD5, "Informe a 5ª dezena do concurso",QuinaEditarResultado.this)){ return false; } int numeroconcurso = Integer.parseInt(edtNumeroConcurso.getText().toString()); String dataconcurso = edtDataConcurso.getText().toString(); int d1 = Integer.parseInt(edtD1.getText().toString()); int d2 = Integer.parseInt(edtD2.getText().toString()); int d3 = Integer.parseInt(edtD3.getText().toString()); int d4 = Integer.parseInt(edtD4.getText().toString()); int d5 = Integer.parseInt(edtD5.getText().toString()); Quina q = new Quina(); if (id != null) { // é uma atualização q.setId(id); } q.setNumeroConcurso(numeroconcurso); q.setDataConcurso(dataconcurso); q.setD1(d1); q.setD2(d2); q.setD3(d3); q.setD4(d4); q.setD5(d5); // Salvar salvarQuina(q); // OK setResult(RESULT_OK, new Intent()); // Fecha a tela finish(); return true; } public void excluir() { if (id != null) { excluirQuina(id); } // OK setResult(RESULT_OK, new Intent()); // Fecha a tela finish(); } // Buscar o resultado quina pelo id protected Quina buscarQuinaId(long id) { return QuinaListagemResultados.repositorio.buscarQuinaId(id); } // Salvar o resultado quina protected void salvarQuina(Quina m) { QuinaListagemResultados.repositorio.Salvar(m); } // Excluir o resultado quina protected void excluirQuina(long id) { QuinaListagemResultados.repositorio.Deletar(id); } } <file_sep>package br.daciosoftware.loterias; import java.util.ArrayList; import java.util.List; import br.daciosoftware.loterias.Megasena.MegasenaColunas; import br.daciosoftware.loterias.MegasenaMaisSorteadas.MegasenaMaisSorteadasColunas; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.util.Log; public class MegasenaMaisSorteadasRepositorio { private static final String CATEGORIA = "loterias"; private static final String NOME_BANCO = "loterias"; private static final String NOME_TABELA = "megasena_mais_sorteadas"; private static final String NOME_TABELA_2 = "megasena"; private static final String SCRIPT_CREATE_TABLE = "create table if not exists " + NOME_TABELA+"("+ "_id integer primary key autoincrement," + "dezena integer," + "frequencia integer," + "selecionada integer)"; //Contantes para ordenar e limitar a listagem private static final String ORDER_BY = MegasenaMaisSorteadasColunas.FREQUENCIA+" desc"; private static final int QTDE_DEZENAS = 60; protected SQLiteDatabase db; public MegasenaMaisSorteadasRepositorio(Context ctx){ try{ //Abre o banco de dados ja existente db = ctx.openOrCreateDatabase(NOME_BANCO, Context.MODE_PRIVATE, null); db.execSQL(SCRIPT_CREATE_TABLE); }catch(Exception e){ Log.e(CATEGORIA, "Erro ao criar o banco de dados: "+e); } } protected MegasenaMaisSorteadasRepositorio(){ //Apenas para criar subclasse ... } public long Inserir(MegasenaMaisSorteadas m){ ContentValues values = new ContentValues(); values.put(MegasenaMaisSorteadasColunas.DEZENA,m.getDezena()); values.put(MegasenaMaisSorteadasColunas.FREQUENCIA,m.getFrequencia()); values.put(MegasenaMaisSorteadasColunas.SELECIONADA,m.getSelecionada()); long id = Inserir(values); return id; } public long Inserir(ContentValues valores){ //Insert objeto long id = db.insert(NOME_TABELA, "", valores); return id; } public int getFrequencia(int dezena, String condicao2){ /* "concursos" é uma variavel que informa os concuros a serem pesquisado a dezena(10 ultimos, 20 ultimos)*/ Cursor cursor; int countReg = 0; String condicao1 = "(("+MegasenaColunas.D1+"="+dezena+")or" + "("+MegasenaColunas.D2+"="+dezena+")or" + "("+MegasenaColunas.D3+"="+dezena+")or" + "("+MegasenaColunas.D4+"="+dezena+")or" + "("+MegasenaColunas.D5+"="+dezena+")or" + "("+MegasenaColunas.D6+"="+dezena+"))"; try{ //Select * from megasena MegasenaMaisSorteadas.colunas, MegasenaMaisSorteadasColunas._ID+"="+id cursor = db.query(NOME_TABELA_2, Megasena.colunas, condicao1+" "+condicao2, null, null, null,null,null); countReg = cursor.getCount(); return countReg; }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar frequencia: "+e.toString()); return 0; } } public void InserirDezenas(int concursos){ int i; int maxConcurso = 0; int countConcurso = 0; int limite = 0; Cursor cursor; String condicao = ""; try{ cursor = db.rawQuery("select numeroconcurso from megasena order by numeroconcurso desc;", null); //query(NOME_TABELA_2, (new String[]{MegasenaColunas.NUMEROCONCURSO}), MegasenaColunas.NUMEROCONCURSO+"=(select max("+MegasenaColunas.NUMEROCONCURSO+"))", null, null, null,null); countConcurso = cursor.getCount(); if(cursor.getCount() >0){ cursor.moveToFirst(); maxConcurso = cursor.getInt(0); } else{ countConcurso = 0; } }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar max concurso: "+e.toString()); } Log.i(CATEGORIA,"Concursos: "+concursos+" countConcurso: "+countConcurso); if((countConcurso > concursos)&&(concursos > 1)){ limite = (maxConcurso - concursos)+1; condicao = "and ("+MegasenaColunas.NUMEROCONCURSO+" between "+limite+" and "+maxConcurso+")"; Log.i(CATEGORIA,"Condicao: "+condicao); } MegasenaMaisSorteadas m = new MegasenaMaisSorteadas(); for(i = 1; i<= QTDE_DEZENAS;i++){ m.setDezena(i); m.setFrequencia(getFrequencia(i, condicao)); m.setSelecionada(0); Inserir(m); } } public int AtualizarSelecionada(MegasenaMaisSorteadas m){ ContentValues values = new ContentValues(); values.put(MegasenaMaisSorteadasColunas.SELECIONADA,m.getSelecionada()); String _id = String.valueOf(m.getId()); String where = MegasenaMaisSorteadasColunas._ID+"=?"; String[] whereArgs = new String[]{_id}; int count = Atualizar(values, where, whereArgs); return count; } //Metodo para obter as dezenas selecionada public Cursor getDezenasSelecionadas(){ Cursor cursor = null; try{ //Select * from megasena MegasenaMaisSorteadas.colunas, MegasenaMaisSorteadasColunas._ID+"="+id cursor = db.query(NOME_TABELA, (new String[]{MegasenaMaisSorteadasColunas.DEZENA}), MegasenaMaisSorteadasColunas.SELECIONADA+"=1", null, null, null,null,null); return cursor; }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar obter a qtde selecionada: "+e.toString()); return null; } } //Atualiza vereador com os valores abaixo //A cláusula where é utilizada para identificar o carro a ser atualizado public int Atualizar(ContentValues valores, String where, String[] whereArgs){ int count = db.update(NOME_TABELA, valores, where, whereArgs); Log.i(CATEGORIA, "Atualizou["+count+"] registros"); return count; } //Delete o carro com o id fornecido public int Deletar(long id){ String where = MegasenaMaisSorteadasColunas._ID + "=?"; String _id = String.valueOf(id); String[] whereArgs = new String[]{_id}; int count = Deletar(where, whereArgs); return count; } public int Deletar(String where, String[] whereArgs){ int count = db.delete(NOME_TABELA, where, whereArgs); Log.i(CATEGORIA, "Deletou["+count+"] registros"); return count; } //Busca pela dezena public MegasenaMaisSorteadas buscarMegasenaMaisSorteadasDezena(int dezena){ // Select * from megasena where numeroconcurso = ? Cursor c = db.query(true,NOME_TABELA, MegasenaMaisSorteadas.colunas, MegasenaMaisSorteadasColunas.DEZENA+"="+dezena,null, null, null, null, null); if(c.getCount()>0){ //Posiciona no primeiro elemento do cursor c.moveToFirst(); MegasenaMaisSorteadas m = new MegasenaMaisSorteadas(); m.setId(c.getLong(0)); m.setDezena(c.getInt(1)); m.setFrequencia(c.getInt(2)); m.setSelecionada(c.getInt(3)); return m; } return null; } //Retorna um cursor com todos os resultados public Cursor getCursor(){ try{ //Select * from megasena return db.query(NOME_TABELA, MegasenaMaisSorteadas.colunas, null, null, null, null, ORDER_BY); }catch(SQLException e){ Log.e(CATEGORIA,"Erro ao buscar megasena mais sorteadas: "+e.toString()); return null; } } //Retorna uma lista de todos public List<MegasenaMaisSorteadas> listarMegasenaMaisSorteadas(){ Cursor c = getCursor(); List<MegasenaMaisSorteadas> megasenamaissorteadas = new ArrayList<MegasenaMaisSorteadas>(); if(c.moveToFirst()){ int idxId = c.getColumnIndex(MegasenaMaisSorteadasColunas._ID); int idxDezena = c.getColumnIndex(MegasenaMaisSorteadasColunas.DEZENA); int idxFrequencia = c.getColumnIndex(MegasenaMaisSorteadasColunas.FREQUENCIA); int idxSelecionada = c.getColumnIndex(MegasenaMaisSorteadasColunas.SELECIONADA); //Loop até o fim do{ MegasenaMaisSorteadas m = new MegasenaMaisSorteadas(); megasenamaissorteadas.add(m); //recupera os atributos do vereador m.setId(c.getLong(idxId)); m.setDezena(c.getInt(idxDezena)); m.setFrequencia(c.getInt(idxFrequencia)); m.setSelecionada(c.getInt(idxSelecionada)); }while(c.moveToNext()); } return megasenamaissorteadas; } //Buscar um resultado da megasena utilizando as configurações definidas no //SQLiteQueryBuilder //utilizando pelo Content Provider de partido public Cursor query(SQLiteQueryBuilder queryBuilder, String[] projection, String selection, String[] selectionArgs,String groupBy, String having, String orderBy){ Cursor c = queryBuilder.query(this.db, projection, selection, selectionArgs, groupBy, having, orderBy); return c; } //Fecha o banco public void Fechar(){ if(db != null){ db.close(); } } } <file_sep>package br.com.daciosoftware.androidgui; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MapaSimples2 extends Activity { static final LatLng HAMBURG = new LatLng(53.558, 9.927); static final LatLng KIEL = new LatLng(53.551, 9.993); private GoogleMap map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mapa_simples2); map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); map.addMarker(new MarkerOptions().position(HAMBURG).title("Hamburg")); map.addMarker(new MarkerOptions() .position(KIEL) .title("Kiel") .snippet("Kiel is cool") .icon(BitmapDescriptorFactory .fromResource(R.drawable.ic_launcher))); // Move the camera instantly to hamburg with a zoom of 15. map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15)); // Zoom in, animating the camera. map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); } } <file_sep>package br.com.daciosoftware.androidgui; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; @SuppressWarnings("deprecation") public class TelaActionBar extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_action_bar); ActionBar actionBar = getSupportActionBar(); actionBar.getDisplayOptions(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_action_bar, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_search: Toast.makeText(getApplicationContext(), "Abrir Consulta", Toast.LENGTH_SHORT).show(); return true; case R.id.action_add: Toast.makeText(getApplicationContext(), "Chamar Tela de Adição", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } } <file_sep>package br.daciosoftware.loterias; import android.provider.BaseColumns; public class Megasena { private long id; private int numeroconcurso; private String dataconcurso ; private int d1; private int d2; private int d3; private int d4; private int d5; private int d6; public void setId(long id){ this.id = id; } public long getId(){ return this.id; } public void setNumeroConcurso(int numeroconcurso){ this.numeroconcurso = numeroconcurso; } public int getNumeroConcurso(){ return this.numeroconcurso; } public void setDataConcurso(String dataconcurso){ this.dataconcurso = dataconcurso; } public String getDataConcurso(){ return this.dataconcurso; } public void setD1(int d1){ this.d1 = d1; } public int getD1(){ return this.d1; } public void setD2(int d2){ this.d2 = d2; } public int getD2(){ return this.d2; } public void setD3(int d3){ this.d3 = d3; } public int getD3(){ return this.d3; } public void setD4(int d4){ this.d4 = d4; } public int getD4(){ return this.d4; } public void setD5(int d5){ this.d5 = d5; } public int getD5(){ return this.d5; } public void setD6(int d6){ this.d6 = d6; } public int getD6(){ return this.d6; } public static String[] colunas = new String[]{MegasenaColunas._ID, MegasenaColunas.NUMEROCONCURSO, MegasenaColunas.DATACONCURSO, MegasenaColunas.D1, MegasenaColunas.D2, MegasenaColunas.D3, MegasenaColunas.D4, MegasenaColunas.D5, MegasenaColunas.D6}; public Megasena(){ } /** * Classe interna para representa colunas que serao inseridas por um Content * Provider * @author fdacio * Filha de BaseColumns que ja define (_id e _count), para seguir o padrao android * */ public static final class MegasenaColunas implements BaseColumns{ //Não pode estanciar essa classe private MegasenaColunas(){ } //Ordenação default para inserir no order by public static final String DEFAULT_SORT_ORDER = "_id ASC"; public static final String NUMEROCONCURSO = "numeroconcurso"; public static final String DATACONCURSO = "dataconcurso"; public static final String D1 = "d1"; public static final String D2 = "d2"; public static final String D3 = "d3"; public static final String D4 = "d4"; public static final String D5 = "d5"; public static final String D6 = "d6"; } } <file_sep>package br.com.daciosoftware.androidgui; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import br.com.daciosoftware.androidgui.fragments.FragmentsDinamicoMain; import br.com.daciosoftware.androidgui.fragments.FragmentsPropagandaMain; public class MenuMain extends ListActivity { private static final String[] itensMenu = new String[] { "Cantos Arredondados", "Estrela RatinBar", "Visão Balançar", "Detecção de Gestos", "Animação Rasterizada", "Mapa", "Mapa2", "Processamento AsyncTask", "Fragments 1", "Fragments Dinâmico", "ActionBar","Advice - Socket","Sair" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itensMenu)); } protected void onListItemClick(ListView l, View v, int position, long id) { switch (position) { case 0: startActivity(new Intent(this, CantosArredondados.class)); break; case 1: startActivity(new Intent(this, EstrelasRatingBar.class)); break; case 2: startActivity(new Intent(this, VisaoBalancar.class)); break; case 3: startActivity(new Intent(this, DeteccaoGestos.class)); break; case 4: startActivity(new Intent(this, AnimacaoRasterizadaSimples.class)); break; case 5: startActivity(new Intent(this, MapaSimples.class)); break; case 6: startActivity(new Intent(this, MapaSimples2.class)); break; case 7: startActivity(new Intent(this, ProcessamentoAsyncTask.class)); break; case 8: startActivity(new Intent(this, FragmentsPropagandaMain.class)); break; case 9: startActivity(new Intent(this, FragmentsDinamicoMain.class)); break; case 10: startActivity(new Intent(this, TelaActionBar.class)); break; case 11: startActivity(new Intent(this, DailyAdviceSocket.class)); break; default: finish(); } } } <file_sep>package br.com.daciosoftware.meumapa; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import br.com.daciosoftware.meumapa.db.Localizacao; import br.com.daciosoftware.meumapa.db.MeuMapaDatabase; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; @SuppressLint("NewApi") public class MainActivity extends ActionBarActivity implements LocationListener { private Toolbar mToobar; //private Toolbar mToobarBottom; private MapFragment mapFragment; private LocationManager locationManager; public GoogleMap mapa; private LatLng localizacaoAtual; public static final int EDITAR = 1; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mToobar = (Toolbar) findViewById(R.id.tb_main); mToobar.setTitle(R.string.app_name); mToobar.setLogo(R.drawable.ic_launcher); setSupportActionBar(mToobar); /* * Inicializar o banco de dados SQLite */ MeuMapaDatabase.inicializar(getApplicationContext()); mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); try{ Bundle extras = getIntent().getExtras(); if(extras != null){ Localizacao localizacao = (Localizacao) extras.getSerializable("LOCALIZACAO"); goToMap(new LatLng(localizacao.getLatitude(), localizacao.getLongitude()), localizacao.getNomeLocal()); } }catch(Exception e){ e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_gravar_local: gravarLocal(); return true; case R.id.action_registrar_local: registrarLocal(); return true; case R.id.action_listar_locais: listarLocais(); return true; case R.id.action_sair: finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onLocationChanged(Location location) { localizacaoAtual = new LatLng(location.getLatitude(),location.getLongitude()); goToMap(localizacaoAtual, "Localização Atual"); } @Override public void onProviderDisabled(String provide) { EnableGPSIfPossible(); } @Override public void onProviderEnabled(String provide) { } @Override public void onStatusChanged(String provide, int status, Bundle extra) { } /** * Método para apontar uma localização(latitude e longitude) * em Google Map * * @param localizacao * @param nomeLocal */ public void goToMap(LatLng localizacao, String nomeLocal){ mapa = mapFragment.getMap(); mapa.setMyLocationEnabled(true); MarkerOptions markerOption = new MarkerOptions(); markerOption.title(nomeLocal); markerOption.position(localizacao); mapa.addMarker(markerOption); mapa.moveCamera(CameraUpdateFactory.newLatLngZoom(localizacao, 15)); mapa.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null); locationManager.removeUpdates(this); } @Override public void onDestroy() { super.onDestroy(); locationManager.removeUpdates(this); } @Override public void onPause() { super.onPause(); locationManager.removeUpdates(this); } @Override public void onResume() { super.onResume(); } /** * Método para habilitar o gps caso esteja desabilitado; */ private void EnableGPSIfPossible() { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { buildAlertMessageNoGps(); } } /* * Método para construir o diálogo para habilitar o GPS */ private void buildAlertMessageNoGps() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("O GPS está desabilitado! Deseja habilitá-lo?") .setCancelable(false) .setPositiveButton("Sim", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { startActivity(new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }) .setNegativeButton("Não", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); final AlertDialog alert = builder.create(); alert.show(); } private void gravarLocal() { if(localizacaoAtual != null){ Intent it = new Intent(this,ActivityEditarLocal.class); it.putExtra("LATITUDE", localizacaoAtual.latitude); it.putExtra("LONGITUDE", localizacaoAtual.longitude); startActivity(it); }else{ Toast.makeText(this, "Aguarde o GPS detectar sua localização atual", Toast.LENGTH_SHORT).show(); } } private void registrarLocal() { Intent it = new Intent(this,ActivityEditarLocal.class); startActivity(it); } private void listarLocais() { Intent it = new Intent(this,ListaLocais.class); startActivity(it); } } <file_sep>package br.daciosoftware.loterias; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.os.Bundle; public class QuinaMenu extends Activity implements OnItemClickListener{ private ListView listViewMenu; @Override public void onCreate(Bundle icicle){ super.onCreate(icicle); setContentView(R.layout.activity_menu_loterias); LinearLayout tela = (LinearLayout) findViewById(R.id.LinearLayoutBackground); tela.setBackgroundResource(R.drawable.background_quina); ImageView imgHeader = (ImageView) findViewById(R.id.ImageViewHeader); imgHeader.setBackgroundResource(R.drawable.header_quina); ArrayList<String> itensMenu = new ArrayList<String>(); itensMenu.add("Arquivo com resultados"); itensMenu.add("Dezenas mais sorteadas"); itensMenu.add("Concursos"); itensMenu.add("Sair"); MenuAdapter adapter = new MenuAdapter(this,itensMenu,R.drawable.icon_quina); listViewMenu = (ListView) findViewById(R.id.lista_menu_loteria); listViewMenu.setAdapter(adapter); listViewMenu.setOnItemClickListener(this); } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub switch(position){ case 0: startActivity(new Intent(this, QuinaCarregarArquivo.class)); break; case 1: startActivity(new Intent(this, QuinaDezenasMaisSorteadas.class)); break; case 2: startActivity(new Intent(this, QuinaListagemResultados.class)); break; default: // Encerra a activity (encerra o ciclo de vida) finish(); } } } <file_sep>package br.daciosoftware.loterias; public class LerHtml { public String getValorHtml(String linha){ String s; int i=0; int count = linha.length()-1; char C; s = ""; for(i = 0; i < count;i++){ C = linha.charAt(i); if( C == '>'){ i++; while(linha.charAt(i) != '<'){ s = s + linha.charAt(i); i++; } } } return s; } public String getTagValor(String linha){ if(linha.length() > 3){ return linha.substring(0,4); }else{ return linha; } } public String getTagInicio(String linha){ if(linha.length() > 2){ return linha.substring(0,3); }else{ return linha; } } public String getTagFim(String linha){ //return linha; if(linha.length() > 4){ return linha.substring(0,5); }else{ return linha; } } } <file_sep>package br.daciosoftware.loterias; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.Context; public class Utils { static ProgressDialog dialog; public static void showAlert(Context context, String title, String text, boolean showOk) { Builder alertBuilder = new Builder(context); alertBuilder.setTitle(title); alertBuilder.setMessage(text); if (showOk) alertBuilder.setNeutralButton("OK", null); alertBuilder.create().show(); } public static void showAlert(Context context, String title, String text) { showAlert(context, title, text, true); } public static void showProgressDialog(Context context, String title, String msg, boolean cancelable){ dialog = new ProgressDialog(context); dialog.setTitle(title); dialog.setMessage(msg); dialog.setIndeterminate(true); dialog.setCancelable(cancelable); dialog.show(); } public static void hiddenProgressDialog(){ dialog.dismiss(); } } <file_sep>package br.com.daciosoftware.androidgui; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RatingBar; import android.widget.RatingBar.OnRatingBarChangeListener; import android.widget.Toast; public class EstrelasRatingBar extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_estrelas_rating_bar); OnRatingBarChangeListener barChangeListener = new OnRatingBarChangeListener(){ @Override public void onRatingChanged(RatingBar arg0, float arg1, boolean arg2) { int rating = (int) arg1; String message = null; switch(rating){ case 1:message = "Sorry you're really upset wint us";break; case 2:message = "Sorry you're not happy";break; case 3:message = "Good enough is not good enough";break; case 4:message = "Thanks, we're glad you liked it.";break; case 5:message = "Awesome - thanks!";break; } Toast.makeText(EstrelasRatingBar.this, message, Toast.LENGTH_LONG).show(); } }; final RatingBar ratingBarService = (RatingBar)findViewById(R.id.ratingBarService); ratingBarService.setOnRatingBarChangeListener(barChangeListener); final RatingBar ratingBarPrice = (RatingBar)findViewById(R.id.ratingBarPrice); ratingBarPrice.setOnRatingBarChangeListener(barChangeListener); Button buttonDone = (Button)findViewById(R.id.buttonDone); OnClickListener buttonDoneClick = new OnClickListener() { @Override public void onClick(View arg0) { String message = String.format("Final Answer: Service %.0f/%d, Price %.0f/%d%nThank you!",ratingBarService.getRating(), ratingBarService.getNumStars(),ratingBarPrice.getRating(), ratingBarPrice.getNumStars() ); Toast.makeText(EstrelasRatingBar.this, message, Toast.LENGTH_SHORT).show(); finish(); } }; buttonDone.setOnClickListener(buttonDoneClick); } } <file_sep>package br.daciosoftware.loterias; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import br.daciosoftware.loterias.Megasena.MegasenaColunas; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MegasenaCarregarArquivo extends Activity { private static final String CATEGORIA = "loterias"; private static final String TITLE = "Arquivo de Resultados"; private static final String MSG_PROCESSAMENTO = "Processando Arquivo, aguarde..."; private static final String MSG_VALIDACAO = "Erro. Informe o arquivo de resultados!"; private static final String MSG_PROCESSO_CONCLUIDO = "Processamento Concluído . Concursos Cadastrados"; private static final String TAG_VALOR = "<td>"; private static final int DIRECTORY_BROWSER = 1; private EditText edArquivo; private TextView textResultado; private Context context = MegasenaCarregarArquivo.this; private ProgressDialog pDialog; private Handler handler = new Handler(); public static MegasenaRepositorio repositorio; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_carregar_arquivo); LinearLayout tela = (LinearLayout) findViewById(R.id.LinearLayoutBackground); tela.setBackgroundResource(R.drawable.background_megasena); ImageView imgHeader = (ImageView) findViewById(R.id.ImageViewHeader); imgHeader.setBackgroundResource(R.drawable.header_megasena); edArquivo = (EditText) findViewById(R.id.edtArquivoResultados); Button btArquivo = (Button) findViewById(R.id.btArquivo); Button btProcessar = (Button) findViewById(R.id.btProcessar); textResultado = (TextView) findViewById(R.id.textMsgCarregarArquivo); TextView textInstrucoes = (TextView) findViewById(R.id.textInstrucoes); textInstrucoes.setText(getText(R.string.textInstrucoesMSAr)); repositorio = new MegasenaRepositorio(this); btArquivo.setOnClickListener(new OnClickListener() { public void onClick(View view) { /* * Rotinas para chamar um dialogo para selecao de diretorio. */ Intent it = new Intent(MegasenaCarregarArquivo.this, FileDialog.class); String starPath = android.os.Environment.getExternalStorageDirectory().toString(); it.putExtra(FileDialog.START_PATH,starPath); it.putExtra(FileDialog.CAN_SELECT_DIR, false); it.putExtra(FileDialog.FORMAT_FILTER,(new String[]{"htm","html"})); it.putExtra(FileDialog.SELECTION_MODE,FileSelectionMode.MODE_OPEN); startActivityForResult(it, DIRECTORY_BROWSER); /* * FIM DA ROTINA */ } }); btProcessar.setOnClickListener(new OnClickListener() { public void onClick(View view) { if (!edArquivo.getText().toString().equals("")){ processarArquivo(edArquivo.getText().toString()); pDialog = ProgressDialog.show(context,TITLE,MSG_PROCESSAMENTO,true,false); } else{ Toast.makeText(context, MSG_VALIDACAO,Toast.LENGTH_SHORT).show(); } } }); } //Atualiza o arquivo pro EditText do arquivo quando selecionado protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == DIRECTORY_BROWSER){ if (resultCode == RESULT_OK) { edArquivo.setText(data.getStringExtra(FileDialog.RESULT_PATH)); } else if (resultCode == RESULT_CANCELED) { edArquivo.setText(""); } } } protected void processarArquivo(final String arquivo){ new Thread(){ @Override public void run(){ Log.i(CATEGORIA,"Arquivo LIDO: "+arquivo); String linha = ""; String tagValor = ""; String DataConcurso=""; ArrayList<String> megasenaResultados = new ArrayList<String>(); LerHtml html = new LerHtml(); try { File f = new File(arquivo); if(f.exists()) { repositorio.Deletar(MegasenaColunas._ID + ">?", new String[]{"0"}); BufferedReader br = new BufferedReader(new FileReader(arquivo)); //Loop para encontrar o ponto de partida dos resultado <td>1</td> concurso 1; while((linha = br.readLine()) != null) { linha = linha.trim(); tagValor = html.getTagValor(linha); linha = linha.replace("/", ""); if(tagValor.equals(TAG_VALOR)){ megasenaResultados.add(html.getValorHtml(linha)); Log.i(CATEGORIA,"Valor pro array LISTA ARRAY: "+html.getValorHtml(linha)); } if(megasenaResultados.size() == 19){ Log.i(CATEGORIA,"Array para gravacao: "+megasenaResultados.toString()); /* * Gravação dos Dados */ Megasena m = new Megasena(); m.setNumeroConcurso(Integer.parseInt(megasenaResultados.get(0))); DataConcurso = megasenaResultados.get(1); DataConcurso = DataConcurso.substring(0, 2) + "/"+DataConcurso.substring(2, 4)+"/"+DataConcurso.substring(4, 8); m.setDataConcurso(DataConcurso); m.setD1(Integer.parseInt(megasenaResultados.get(2))); m.setD2(Integer.parseInt(megasenaResultados.get(3))); m.setD3(Integer.parseInt(megasenaResultados.get(4))); m.setD4(Integer.parseInt(megasenaResultados.get(5))); m.setD5(Integer.parseInt(megasenaResultados.get(6))); m.setD6(Integer.parseInt(megasenaResultados.get(7))); repositorio.Salvar(m); m = null; megasenaResultados.clear(); /* * Fim da gravação */ } } br.close(); /* * FINAL DO PROCESSAMENTO DO ARQUIVO E FECHA O DIALOGO DE PROGRESSO */ finalizaProcessamento(); } }catch(FileNotFoundException e){ }catch(IOException e){ } } }.start(); } private void finalizaProcessamento(){ handler.post(new Runnable(){ public void run(){ pDialog.dismiss(); Toast.makeText(context, MSG_PROCESSO_CONCLUIDO,Toast.LENGTH_SHORT).show(); textResultado.setText("Adicionou "+String.valueOf(repositorio.getCountReg())+" resultados"); }}); } }<file_sep>package br.com.daciosoftware.suaidade; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class ResultadoActivity extends Activity { Context context = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_resultado); TextView textViewIdade = (TextView) findViewById(R.id.textViewIdade); int soma = MainActivity.somaNumerosIniciais(); if(soma > 0){ textViewIdade.setText(soma+" ano(s)"); }else{ textViewIdade.setText("Você tem acima de 60 ano(s)"); } MainActivity.zeraNumerosIniciais(); Button btnReniciar = (Button) findViewById(R.id.btnReniciar); btnReniciar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); Intent it = new Intent(context,Tabela1Activity.class); startActivity(it); } }); } @Override public void onBackPressed(){ finish(); } } <file_sep>package br.daciosoftware.loterias; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import br.daciosoftware.loterias.MegasenaMaisSorteadas.MegasenaMaisSorteadasColunas; public class MegasenaGerarJogos extends Activity { protected static final String CATEGORIA = "loterias"; private static final int DIRECTORY_BROWSER = 1; private static final String NOME_ARQUIVO = "jogos_megasena.txt"; public static MegasenaMaisSorteadasRepositorio repositorio; private ArrayList<Integer> listaDezenasSelecionadas; private ListView listViewDados; private ArrayList<String> listaJogosGerados; private Spinner spinnerConcursos; private TextView jogosPossiveis; private long qtdeJogos; private int qtdeDezenas; private GeradorDeJogos geradorDeJogos; private ProgressDialog dialog; private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gerar_jogos_megasena); LinearLayout tela = (LinearLayout) findViewById(R.id.LinearLayoutBackground); tela.setBackgroundResource(R.drawable.background_megasena); ImageView imgHeader = (ImageView) findViewById(R.id.ImageViewHeader); imgHeader.setBackgroundResource(R.drawable.header_megasena); EditText edtNumerosSelecionados = (EditText) findViewById(R.id.edtNumerosSelecionados); listaDezenasSelecionadas = new ArrayList<Integer>(); repositorio = new MegasenaMaisSorteadasRepositorio(this); Cursor c = repositorio.getDezenasSelecionadas(); if(c.moveToFirst()){ int idxDezena = c.getColumnIndex(MegasenaMaisSorteadasColunas.DEZENA); String dezenasSelecionadas = ""; do{ if(dezenasSelecionadas.equals("")){ dezenasSelecionadas = String.valueOf(c.getInt(idxDezena)); } else{ dezenasSelecionadas = dezenasSelecionadas+", "+String.valueOf(c.getInt(idxDezena)); } listaDezenasSelecionadas.add(c.getInt(idxDezena)); }while(c.moveToNext()); edtNumerosSelecionados.setText(dezenasSelecionadas); } TextView textNumeroSelecionados = (TextView) findViewById(R.id.textNumeroSelecionados); textNumeroSelecionados.setText(textNumeroSelecionados.getText()+": "+String.valueOf(listaDezenasSelecionadas.size())+" dezenas"); spinnerConcursos = (Spinner) findViewById(R.id.spinnerConcursos); jogosPossiveis = (TextView) findViewById(R.id.textJogosPossiveis); Button btGerarJogos = (Button) findViewById(R.id.btGerarJogos); btGerarJogos.setOnClickListener(new OnClickListener() { public void onClick(View view) { int n; n = spinnerConcursos.getSelectedItemPosition(); switch(n){ case 0: qtdeDezenas = 6; break; case 1: qtdeDezenas = 7; break; case 2: qtdeDezenas = 8; break; case 3: qtdeDezenas = 9; break; case 4: qtdeDezenas = 10; break; case 5: qtdeDezenas = 11; break; case 6: qtdeDezenas = 12; break; case 7: qtdeDezenas = 13; break; case 8: qtdeDezenas = 14; break; case 9: qtdeDezenas = 15; break; } if(qtdeDezenas > listaDezenasSelecionadas.size()){ Toast.makeText(MegasenaGerarJogos.this, "Erro! Quantidade "+spinnerConcursos.getSelectedItem().toString()+" maior que dezenas selecionadas", Toast.LENGTH_SHORT).show(); } else{ dialog = ProgressDialog.show(MegasenaGerarJogos.this, "", "Aguarde...",false,true); carregaJogos(); } } }); Button btSalvarJogosTxt = (Button) findViewById(R.id.btSalvarJogosTxt); btSalvarJogosTxt.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent it = new Intent(MegasenaGerarJogos.this, FileDialog.class); String starPath = android.os.Environment.getExternalStorageDirectory().toString(); it.putExtra(FileDialog.START_PATH,starPath); it.putExtra(FileDialog.CAN_SELECT_DIR, true); it.putExtra(FileDialog.ONLY_SELECT_DIR, true); it.putExtra(FileDialog.SELECTION_MODE,FileSelectionMode.MODE_OPEN); startActivityForResult(it, DIRECTORY_BROWSER); } }); } protected void atualizaListaJogos(){ jogosPossiveis.setText("Jogos Possíveis: "+String.valueOf(qtdeJogos)); //Pega a lista de jogos gerados e exibe na tela listaJogosGerados = geradorDeJogos.getListaJogos(); //Adaptador da lista customizada para cada linha de um partido MegasenaJogosGeradosListAdapter adapter = new MegasenaJogosGeradosListAdapter(this,listaJogosGerados); listViewDados = (ListView) findViewById(R.id.lista_jogos_gerados); listViewDados.setAdapter(adapter); Log.i(CATEGORIA,"Atualizou a Listagem de Jogos Gerados"); } private void carregaJogos(){ new Thread(){ @Override public void run(){ geradorDeJogos = new GeradorDeJogos(); qtdeJogos = geradorDeJogos.qtdeJogosPossiveis(qtdeDezenas, listaDezenasSelecionadas.size()); Log.i(CATEGORIA,"Qtde Dezenas Selecionadas: "+listaDezenasSelecionadas.size()); Log.i(CATEGORIA,"Qtde Dezenas pro Jogo: "+qtdeDezenas); geradorDeJogos.gerarJogos(listaDezenasSelecionadas, qtdeDezenas); finalizaCarga(); } }.start(); } private void finalizaCarga(){ handler.post(new Runnable(){ public void run(){ //Fecha a janela de progresso dialog.dismiss(); atualizaListaJogos(); } }); } @Override protected void onDestroy(){ super.onDestroy(); //Fecha o banco repositorio.Fechar(); Log.i(CATEGORIA,"Destruiu a Tela de Listagem de Jogos Gerados"); } protected void montaArquivo(String directoryFile, String nomeArquivo){ String newLine = System.getProperty("line.separator"); File arquivo = null; try { //arquivo = new File(android.os.Environment.getExternalStorageDirectory(),ARQUIVO); arquivo = new File(directoryFile,nomeArquivo); FileOutputStream out = new FileOutputStream(arquivo); String texto1 = "<NAME>"+newLine; String texto2 = "===================================="+newLine; out.write(texto1.getBytes()); out.write(texto2.getBytes()); for(int i = 0; i < listaJogosGerados.size(); i++){ String jogoTexto = listaJogosGerados.get(i).toString(); jogoTexto = jogoTexto+newLine; out.write(jogoTexto.getBytes()); } out.flush();//para garantir que os dados sejam realmente gravados no arquivo. out.close(); Toast.makeText(MegasenaGerarJogos.this, "Arquivo: "+directoryFile+"/"+nomeArquivo +" salvo com sucesso", Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { // TODO: handle exception Log.e(CATEGORIA,e.getMessage(), e); } catch (IOException e){ // TODO: handle exception Log.e(CATEGORIA,e.getMessage(), e); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == DIRECTORY_BROWSER){ if (resultCode == RESULT_OK) { montaArquivo(data.getStringExtra(FileDialog.RESULT_PATH),NOME_ARQUIVO); } } } }<file_sep>package br.daciosoftware.loterias; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class MegasenaListAdapter extends BaseAdapter{ private Context context; private List<Megasena> lista; public MegasenaListAdapter(Context context, List<Megasena> lista){ this.context = context; this.lista = lista; } public int getCount(){ return lista.size(); } public Object getItem(int position){ return lista.get(position); } public long getItemId(int position){ return position; } public View getView(int position, View convertView, ViewGroup parent){ //Recupera o partido da posição atual Megasena m = lista.get(position); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view1 = inflater.inflate(R.layout.activity_listagem_resultados_linha_adapter, null); //Atualiza o valor do TextView TextView numeroconcurso = (TextView) view1.findViewById(R.id.loterial_numeroconcurso); numeroconcurso.setText(String.valueOf(m.getNumeroConcurso())); TextView dataconcurso = (TextView) view1.findViewById(R.id.loterial_dataconcurso); dataconcurso.setText(String.valueOf(m.getDataConcurso())); TextView d1 = (TextView) view1.findViewById(R.id.loterial_d1); d1.setText(String.valueOf(m.getD1())); TextView d2 = (TextView) view1.findViewById(R.id.loterial_d2); d2.setText(String.valueOf(m.getD2())); TextView d3 = (TextView) view1.findViewById(R.id.loterial_d3); d3.setText(String.valueOf(m.getD3())); TextView d4 = (TextView) view1.findViewById(R.id.loterial_d4); d4.setText(String.valueOf(m.getD4())); TextView d5 = (TextView) view1.findViewById(R.id.loterial_d5); d5.setText(String.valueOf(m.getD5())); TextView d6 = (TextView) view1.findViewById(R.id.loterial_d6); d6.setText(String.valueOf(m.getD6())); return view1; } } <file_sep>package br.daciosoftware.loterias; import android.provider.BaseColumns; public class QuinaMaisSorteadas { private long id; private int dezena; private int frequencia; private int selecionada; public void setId(long id){ this.id = id; } public long getId(){ return this.id; } public void setDezena(int dezena){ this.dezena = dezena; } public int getDezena(){ return this.dezena; } public void setFrequencia(int frequencia){ this.frequencia = frequencia; } public int getFrequencia(){ return this.frequencia; } public void setSelecionada(int selecionada){ this.selecionada = selecionada; } public int getSelecionada(){ return this.selecionada; } public static String[] colunas = new String[]{QuinaMaisSorteadasColunas._ID, QuinaMaisSorteadasColunas.DEZENA, QuinaMaisSorteadasColunas.FREQUENCIA, QuinaMaisSorteadasColunas.SELECIONADA}; public QuinaMaisSorteadas(){ } /** * Classe interna para representa colunas que serao inseridas por um Content * Provider * @author fdacio * Filha de BaseColumns que ja define (_id e _count), para seguir o padrao android * */ public static final class QuinaMaisSorteadasColunas implements BaseColumns{ //Não pode estanciar essa classe private QuinaMaisSorteadasColunas(){ } //Ordenação default para inserir no order by public static final String DEFAULT_SORT_ORDER = "_id ASC"; public static final String DEZENA = "dezena"; public static final String FREQUENCIA = "frequencia"; public static final String SELECIONADA = "selecionada"; } }
0113fc0061e6138037f3046cffbb526a98803c94
[ "Java" ]
24
Java
fdacio/androidgui
c85998f82ac43bec82cafa687585c9502d343dd1
8d7871f99f7d54a4e6cc30422f661721b1287b30
refs/heads/main
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Users.cpp * Author: Drake * * Created on April 18, 2021, 7:38 PM */ #include "Users.h" Users::Users() { string email; unsigned int encPswrd; dataFile.open("userData.dat"); adminDataFile.open("adminData.dat"); while(!dataFile.eof()) { dataFile >> email; dataFile >> encPswrd; uMap.insert(pair<string,unsigned int>(email, (encPswrd))); } while(!adminDataFile.eof()) { adminDataFile >> email; adminDataFile >> encPswrd; aMap.insert(pair<string,unsigned int>(email, (encPswrd))); } dataFile.close(); adminDataFile.close(); } Users::Users(const Users& orig) { } Users::~Users() { } bool Users::adminLogin() { string email; string pswrd; unsigned int encPswrd; bool success = false; int choice = 2; do { choice = 2; cout << "Input Email: "; cin >> email; cout << "Input password: "; cin >> pswrd; while (pswrd.length()>40) { cout << "Password is too long, re-input: "; cin >> pswrd; } encPswrd = PswrdCnvrt(pswrd); pswrd = "\0"; aMapItr = aMap.find(email); if (aMapItr==aMap.end()) { cout << "Email and password do not match.\n"; cout << "(1): Re-enter info\n(2): Exit to login menu\nEnter Choice:"; cin >> choice; } else if (aMapItr->second != encPswrd) { cout << "Email and password do not match.\n"; cout << "(1): Re-enter info\n(2): Exit to login menu\nEnter Choice:"; cin >> choice; } else success = true; }while (choice == 1); if (success) return true; else return false; } string Users::login() { string email; string pswrd; unsigned int encPswrd; bool success = false; int choice = 2; do { choice = 2; cout << "Input Email: "; cin >> email; cout << "Input password: "; cin >> pswrd; while (pswrd.length()>40) { cout << "Password is too long, re-input: "; cin >> pswrd; } encPswrd = PswrdCnvrt(pswrd); pswrd = "\0"; uMapItr = uMap.find(email); if (uMapItr==uMap.end()) { cout << "Email and password do not match.\n"; cout << "(1): Re-enter info\n(2): Exit to user menu\nEnter Choice:"; cin >> choice; } else if (uMapItr->second != encPswrd) { cout << "Email and password do not match.\n"; cout << "(1): Re-enter info\n(2): Exit to user menu\nEnter Choice:"; cin >> choice; } else success = true; }while (choice == 1); if (success) return uMapItr->first; else return "\0"; } void Users::createU() { string email; string pswrd; string cnfPswrd; int choice = 1; unsigned int encPswrd; cout << "Input Email: "; cin >> email; do { cout << "Create password (max of 40 characters): "; cin >> pswrd; while (pswrd.length()>40) { cout << "Password is too long, re-input: "; cin >> pswrd; } cout << "Confirm password: "; cin >> cnfPswrd; if (cnfPswrd!=pswrd) cout << "Password does not match with confirmation.\n"; } while (cnfPswrd!=pswrd); encPswrd = PswrdCnvrt(pswrd); pswrd = "\0"; cnfPswrd = "\0"; uMapItr = uMap.find(email); if (uMapItr == uMap.end()) { // Make sure that the email isnt already used uMap.insert(pair<string,unsigned int>(email, (encPswrd))); cout << "\nAccount created successfully."; } else { while (uMapItr != uMap.end() && choice == 1) { cout << "That email is already associated with an account.\n"; cout << "(1): Re-enter email\n(2): Exit to user menu\nEnter Choice:"; cin >> choice; if (choice==1) { cout << "Input Email: "; cin >> email; uMapItr = uMap.find(email); } } if (choice==1) { uMap.insert(pair<string,unsigned int>(email, (encPswrd))); cout << "\nAccount created successfully."; } } } string Users::editE(string gUser) { string inEmail; int choice = 1; unsigned int encPswrd; cout << "Input new email: "; cin >> inEmail; uMapItr = uMap.find(inEmail); if (uMapItr == uMap.end()) { // Make sure that the email isnt already used uMapItr = uMap.find(gUser); encPswrd = uMapItr->second; uMap.erase(gUser); uMap.insert(pair<string,unsigned int>(inEmail, (encPswrd))); cout << "\nAccount email changed successfully."; return inEmail; } else { while (uMapItr != uMap.end() && choice == 1) { cout << "That email is already associated with an account.\n"; cout << "(1): Re-enter email\n(2): Exit to user menu\nEnter Choice:"; cin >> choice; if (choice==1) { cout << "Input Email: "; cin >> inEmail; uMapItr = uMap.find(inEmail); } } if (choice==1) { //uMap.insert(pair<string,unsigned int>(email, (encPswrd))); uMapItr = uMap.find(gUser); encPswrd = uMapItr->second; uMap.erase(gUser); uMap.insert(pair<string,unsigned int>(inEmail, (encPswrd))); cout << "\nAccount email changed successfully."; return inEmail; } else return "\0"; } } void Users::editP(string gUser) { string pswrd; string cnfPswrd; unsigned int encPswrd; uMapItr = uMap.find(gUser); do { cout << "Create new password (max of 40 characters): "; cin >> pswrd; while (pswrd.length()>40) { cout << "Password is too long, re-input: "; cin >> pswrd; } cout << "Confirm password: "; cin >> cnfPswrd; if (cnfPswrd!=pswrd) cout << "Password does not match with confirmation.\n"; } while (cnfPswrd!=pswrd); encPswrd = PswrdCnvrt(pswrd); pswrd = "\0"; cnfPswrd = "\0"; uMap[gUser] = encPswrd; //uMap.insert(pair<string,unsigned int>(gUser, (encPswrd))); } unsigned int Users::PswrdCnvrt(const string& str) { // Initialize variables unsigned int hash = static_cast<unsigned int>(str.length()); for (int i=0; i<str.length(); i++) { // Loop through string // Compute hash hash = ((hash << 5) ^ (hash >> 27)) ^ str[i]; } return hash; // Return value } void Users::outputU() { cout << "User List:\n"; for(uMapItr = uMap.begin(); uMapItr != uMap.end(); ++uMapItr) { cout << uMapItr->first << endl; } } void Users::deleteU(string user) { uMapItr = uMap.find(user); if (uMapItr != uMap.end()) { cout << "User " << uMapItr->first << " deleted."; uMap.erase(uMapItr); } else cout << "User not found."; } void Users::pushUToFile() { std::ofstream userOF; userOF.open ("userData.dat", ofstream::trunc); for(uMapItr = uMap.begin(); uMapItr != uMap.end(); ++uMapItr) { userOF << uMapItr->first << ' ' << uMapItr->second << endl; } userOF.close(); }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Menu.h * Author: Drake * * Created on April 4, 2021, 7:15 PM */ #ifndef MENU_H #define MENU_H #include "Users.h" #include "Survey.h" class Menu: public Survey, public Users { private: bool cont; string curUser; bool isAdmin; public: Menu(); //Menu(const Menu& orig); ~Menu(); //bool ReturnCheck(); int userLogin(); int userMenu(); int adminMenu(); int adminLoginMenu(); int userAccount(); void promptSave(); }; #endif /* MENU_H */ <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: SurveyCreator.h * Author: Drake * * Created on March 14, 2021, 9:26 PM */ #ifndef SURVEYCREATOR_H #define SURVEYCREATOR_H #include "Survey.h" class SurveyCreator { private: Survey *sGroup; int sze; public: SurveyCreator(); //SurveyCreator(const SurveyCreator& orig); virtual ~SurveyCreator(); void addSurvey(); void outputSurveyList(int); void outputSurveyInfo(); }; #endif /* SURVEYCREATOR_H */<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: SurveyCreator.cpp * Author: Drake * * Created on March 14, 2021, 9:26 PM */ #include "SurveyCreator.h" SurveyCreator::SurveyCreator() { sze = 0; // Initialize size } //SurveyCreator::SurveyCreator(const SurveyCreator& orig) { //} SurveyCreator::~SurveyCreator() { delete sGroup; } void SurveyCreator::addSurvey() { Survey *group = new Survey[sze+1]; string sName; string sDesc; string sOD; string sCD; int sNumIt; cout << "Input survey name: "; cin >> sName; cout << "Input survey description: "; cin.ignore(); getline(cin, sDesc); cout << "Input survey opening date: "; cin >> sOD; cout << "Input survey close date: "; cin >> sCD; cout << "Input number of items in the survey: "; cin >> sNumIt; string *itm = new string[sNumIt]; for (int i=0; i<sNumIt; i++) { cout << "Input name of item " << i+1 << ": "; cin >> itm[i]; } Survey nSurv(sName, sDesc, sOD, sCD, itm); cout << "Test"; for(int i=0; i<sze; i++) { group[i] = sGroup[i]; } Survey *groupF = &group[sze]; group[sze] = nSurv; sGroup = group; sze++; } void SurveyCreator::outputSurveyList(int indx) { if (indx<sze) { cout << "Survey: " << sGroup[indx].getName() << endl; cout << " Item |" << " Vote Count "; for (int i=0; i<sGroup[indx].getSize(); i++) { cout << sGroup[indx].getItem(i) << " | " << sGroup[indx].getVote(i); } } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Survey.h * Author: Drake * * Created on March 14, 2021, 8:58 PM */ #ifndef SURVEY_H #define SURVEY_H #include <string> #include <iostream> using namespace std; class Survey { private: string *iList; // List of items in the survey int *iVotes; // List of votes for the items int sze; // Size of list string name; // Name of the survey string desc; // Description of the survey string dteOp; // Date the survey opens string dteClo;// Date the survey closes public: Survey(string, string, string, string, string*); Survey(); //Survey(const Survey& orig); ~Survey(); void addVote(int); string getName() {return name;} string getDesc() {return desc;} string getDO() {return dteOp;} string getDC() {return dteClo;} string getItem(int); int getSize() {return sze;} int getVote(int); }; #endif /* SURVEY_H */ <file_sep># # Generated - do not edit! # # NOCDDL # CND_BASEDIR=`pwd` CND_BUILDDIR=build CND_DISTDIR=dist # Debug configuration CND_PLATFORM_Debug=Cygwin-Windows CND_ARTIFACT_DIR_Debug=dist/Debug/Cygwin-Windows CND_ARTIFACT_NAME_Debug=surveyengine CND_ARTIFACT_PATH_Debug=dist/Debug/Cygwin-Windows/surveyengine CND_PACKAGE_DIR_Debug=dist/Debug/Cygwin-Windows/package CND_PACKAGE_NAME_Debug=surveyengine.tar CND_PACKAGE_PATH_Debug=dist/Debug/Cygwin-Windows/package/surveyengine.tar # Release configuration CND_PLATFORM_Release=Cygwin-Windows CND_ARTIFACT_DIR_Release=dist/Release/Cygwin-Windows CND_ARTIFACT_NAME_Release=surveyengine CND_ARTIFACT_PATH_Release=dist/Release/Cygwin-Windows/surveyengine CND_PACKAGE_DIR_Release=dist/Release/Cygwin-Windows/package CND_PACKAGE_NAME_Release=surveyengine.tar CND_PACKAGE_PATH_Release=dist/Release/Cygwin-Windows/package/surveyengine.tar # # include compiler specific variables # # dmake command ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \ (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk) # # gmake command .PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)) # include nbproject/private/Makefile-variables.mk <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Survey.cpp * Author: Drake * * Created on March 14, 2021, 8:58 PM */ #include "Survey.h" Survey::Survey() { string gName; // Name of the survey string gDesc; // Description of the survey string gDteOp; // Date the survey opens string gDteClo;// Date the survey closes string gUser; vector<uStruct> gUserRes; // Results from the users vector<qStruct> gQList; // List of questions int gQCount; int gPartCnt; string gQName; // Given question name int gCCount; // Given choice count int surIndx = 0; sDataF.open("surveyData.dat"); while(!sDataF.eof()) { if (surIndx>0) sDataF.ignore(2); getline (sDataF,gName); if (!gName.empty() && gName[gName.size() - 1] == '\r') { gName.erase(gName.size() - 1); } getline (sDataF,gDesc); if (!gDesc.empty() && gDesc[gDesc.size() - 1] == '\r') { gDesc.erase(gDesc.size() - 1); } getline (sDataF,gDteOp); if (!gDteOp.empty() && gDteOp[gDteOp.size() - 1] == '\r') { gDteOp.erase(gDteOp.size() - 1); } getline (sDataF,gDteClo); if (!gDteClo.empty() && gDteClo[gDteClo.size() - 1] == '\r') { gDteClo.erase(gDteClo.size() - 1); } sDataF >> gQCount; // Read in the questions, starting with how many for(int i=0; i<gQCount; i++) { qStruct gQStru; // A question sDataF.ignore(2); getline (sDataF,gQName); if (!gQName.empty() && gQName[gQName.size() - 1] == '\r') { gQName.erase(gQName.size() - 1); } sDataF >> gCCount; for(int i=0; i<gCCount; i++) { string tempVar; sDataF >> tempVar; gQStru.choices.push_back(tempVar); } gQStru.quest = gQName; gQStru.choCnt = gCCount; gQList.push_back(gQStru); gQStru.choices.clear(); } sDataF >> gPartCnt; for(int i=0; i<gPartCnt; i++) { uStruct gUsrStru; sDataF >> gUser; // store the email for(int i=0; i<gQCount; i++) { int tempVar; sDataF >> tempVar; gUsrStru.answers.push_back(tempVar); } gUsrStru.email = gUser; gUserRes.push_back(gUsrStru); gUsrStru.answers.clear(); } surStruc gSurStru; gSurStru.name = gName; gSurStru.desc = gDesc; gSurStru.dteOp = gDteOp; gSurStru.dteClo = gDteClo; gSurStru.qCount = gQCount; gSurStru.userRes = gUserRes; gSurStru.qList = gQList; gSurStru.partCnt = gPartCnt; survList.push_back(gSurStru); // Push back the list gUserRes.clear(); // Clear vector content gQList.clear(); surIndx++; } sTotal = surIndx; sDataF.close(); } //Survey::Survey(const Survey& orig) { //} Survey::~Survey() { } /* string Survey::getSName(int indx) { return survList[indx].name; } string Survey::getDesc(int indx) { return survList[indx].desc; } string Survey::getDO(int indx) { return survList[indx].dteOp; } string Survey::getDC(int indx) { return survList[indx].dteClo; } int Survey::getSize(int indx) { return survList[indx].qCount; } string Survey::getQName(int indx, int qIndx) { return this->survList[indx].qList[qIndx].quest; } */ /* int Survey::getVote(int indx) { // if (indx<sze) return iVotes[indx]; return 1; } */ void Survey::createSurvey() { int test; string tmpNm; string tmpDsc; string tmpOD; string tmpCD; string queNm; string tmpCho; int gQCount = 0; int tmpCC; vector<qStruct> tQList; // List of questions surStruc gSurStru; int cont = 1; cout << "***Create Survey Menu***\n"; cin >> test; cout << "What is the survey name: \n"; cin.ignore(); getline(cin,tmpNm); cout << "What is the description for this survey: \n"; getline(cin,tmpDsc); cout << "What is the opening date: \n"; getline(cin,tmpOD); cout << "What is the closing date: \n"; getline(cin,tmpCD); do { qStruct gQStru; // A question gQCount++; cout << "What is the question: \n"; getline(cin,queNm); cout << "How many choices are with this question: "; cin >> tmpCC; for (int i=0; i<tmpCC; i++) { cout << "What is choice #" << i+1 << ": "; cin >> tmpCho; gQStru.choices.push_back(tmpCho); } cout << "\n(1) Add question\n(2) Finish\nEnter Choice: "; cin >> cont; cin.ignore(); gQStru.quest = queNm; gQStru.choCnt = tmpCC; tQList.push_back(gQStru); gQStru.choices.clear(); } while (cont==1); gSurStru.name = tmpNm; gSurStru.desc = tmpDsc; gSurStru.dteOp = tmpOD; gSurStru.dteClo = tmpCD; gSurStru.qCount = gQCount; gSurStru.qList = tQList; gSurStru.partCnt = 0; survList.push_back(gSurStru); // Push back the list sTotal++; } void Survey::modSurvey(int indx) { int incre = 0; int choice = 0; int cInc = 0; int modMode = 1; int qModMode = 1; int qIndx; string queNm; int tmpCC; string tmpCho; char charInp; indx = indx-1; vector<surStruc>::iterator sIt; if(indx<sTotal && indx >= 0) { cout << "Modification modes:\n(1) Modify Survey\n(2) Delete Survey\n"; cout << "(3) Return to menu\nInput a modification mode: "; cin >> modMode; while (modMode < 1 || modMode > 3) { cout << "Invalid modification mode, reinput: "; cin >> modMode; } if (modMode == 1) { do { cout << "Editing Survey: " << survList[indx].name << endl; cout << "(1) Change Name\n"; cout << "(2) Change Description\n"; cout << "(3) Change Opening Date\n"; cout << "(4) Change Closing Date\n"; cout << "(5) Add/Modify/Remove a Question (Note: this will"; cout << " reset all participants of the survey)\n"; cout << "(6) Exit Modify Survey Menu\n"; cout << "Enter choice: "; cin >> choice; while (choice > 6 || choice < 1) { cout << "Invalid choice, re-enter: "; cin >> choice; } string gName; string gDesc; string gDteOp; string gDteClo; switch (choice) { case 1: cout << "Enter a new name for the survey: \n"; cin.ignore(); getline(cin, gName); survList[indx].name = gName; break; case 2: cout << "Enter a new description for the survey: \n"; cin.ignore(); getline(cin, gDesc); survList[indx].desc = gDesc; break; case 3: cout << "Enter a new opening date for the survey: \n"; cin.ignore(); getline(cin, gDteOp); survList[indx].dteOp = gDteOp; break; case 4: cout << "Enter a new closing date for the survey: \n"; cin.ignore(); getline(cin, gDteClo); survList[indx].dteClo = gDteClo; break; case 5: incre = 0; for (auto i = survList[indx].qList.begin(); i!= survList[indx].qList.end(); i++) { cout << "#" << ++incre << ": " << i->quest << endl; cInc = 0; for (auto j = i->choices.begin(); j!= i->choices.end(); j++) { cout << "\t(" << ++cInc << ") " << *j << endl; } } cout << "Modification modes:\n(1) Modify Question\n(2) Delete Question\n"; cout << "(3) Add Question\nInput a modification mode: "; cin >> modMode; while (modMode < 1 || modMode > 3) { cout << "Invalid modification mode, reinput: "; cin >> modMode; } if (modMode == 1) { cout << "Enter a question number to modify: "; cin >> choice; qIndx = choice-1; while (choice < 0 || choice > survList[indx].qCount) { cout << "Invalid question choice, enter a "; cout << "question # or 0 to return: "; cin >> choice; } if (choice > 0) { cout << "Change question prompt? (y/n)"; cin >> charInp; if (charInp == 'y') { cout << "Input a new question prompt: \n"; cin.ignore(); getline(cin, queNm); survList[indx].qList[qIndx].quest = queNm; } cout << "Change choices? (y/n)"; cin >> charInp; while (charInp == 'y') { cout << "(1) Add choice\n"; cout << "(2) Delete choice"; cout << "Enter choice: "; cin >> choice; if (choice==1) { cout << "\nEnter choice: "; cin >> tmpCho; survList[indx].qList[qIndx].choices.push_back(tmpCho); survList[indx].qList[qIndx].choCnt = survList[indx].qList[qIndx].choCnt+1; } else if (choice==2) { cout << "Enter choice to delete: "; cin >> choice; if (choice <1 || choice > survList[indx].qList[qIndx].choCnt) { cout << "Invalid choice to modify."; } else { auto cItr = survList[indx].qList[qIndx].choices.begin(); for (int i=0; i< choice-1; i++) { cItr++; } survList[indx].qList[qIndx].choices.erase(cItr); } } cout << "Change choices? (y/n)"; cin >> charInp; } survList[indx].userRes.clear(); } } else if (modMode == 2) { cout << "Enter a question number to delete: "; cin >> choice; while (choice < 0 || choice > survList[indx].qCount) { cout << "Invalid question choice, enter a "; cout << "question # or 0 to return: "; cin >> choice; } if (choice > 0) { qIndx = choice-1; auto qInc = survList[indx].qList.begin(); for (int i=0; i<qIndx; i++) { qInc++; } survList[indx].qList.erase(qInc); survList[indx].qCount = survList[indx].qCount-1; survList[indx].userRes.clear(); } } else if (modMode == 3) { survList[indx].qCount = survList[indx].qCount+1; qStruct gQStru; // A question cout << "What is the question: \n"; cin.ignore(); getline(cin,queNm); cout << "How many choices are with this question: "; cin >> tmpCC; for (int i=0; i<tmpCC; i++) { cout << "What is choice #" << i+1 << ": "; cin >> tmpCho; gQStru.choices.push_back(tmpCho); } gQStru.quest = queNm; gQStru.choCnt = tmpCC; survList[indx].qList.push_back(gQStru); gQStru.choices.clear(); survList[indx].userRes.clear(); } break; } } while (choice!=6); } else if (modMode == 2) { cout << "Deleting Survey: " << survList[indx].name << endl; for (int i=0; i<indx; i++) { sIt++; } survList.erase(sIt); sTotal--; } } } void Survey::editPart(string user, string newUser) { // Iterate through the survey list for (auto i = survList.begin(); i != survList.end(); i++) { for (auto j = i->userRes.begin(); j!= i->userRes.end(); j++) { if (j->email == user) { if (newUser!="\0") j->email = newUser; // modify else i->userRes.erase(j); // delete44 } } } cout << endl; } void Survey::viewSurveys(string user, bool isAdmin){ bool comp; string tName; string tDesc; int inc = 0; if(!isAdmin) { cout << " # Survey Name | Description |"; cout << " # Qs | Start Date | Close Date | Status |\n" << fixed; for (auto i = survList.begin(); i != survList.end(); i++) { inc++; comp = false; tName = i->name; tDesc = i->desc; if (tName.length() > 16) { tName = tName.substr(0, 13) + "..."; } if (tDesc.length() > 29) { tDesc = tDesc.substr(0, 26) + "..."; } cout << setw(4) << inc << setw(16) << tName << " |" << setw(29); cout << tDesc << " |" << setw(5) << i->qCount << " |" << setw(11); cout << i->dteOp << " |" << setw(11) << i->dteClo << " |"; cout << setw(13); for (auto j = i->userRes.begin(); j!= i->userRes.end(); j++) { if (j->email == user) { comp = true; } } if (comp) cout << "Taken" << " |\n"; else cout << "Not Started" << " |\n"; } } else { cout << " # Survey Name | Description |"; cout << " # Qs | Start Date | Close Date | # Taken |\n"; for (auto i = survList.begin(); i != survList.end(); i++) { inc++; comp = false; tName = i->name; tDesc = i->desc; if (tName.length() > 16) { tName = tName.substr(0, 13) + "..."; } if (tDesc.length() > 29) { tDesc = tDesc.substr(0, 26) + "..."; } //setw(16) cout << setw(4) << inc << setw(16) << tName << " |" << setw(29); cout << tDesc << " |" << setw(5) << i->qCount << " |" << setw(11); cout << i->dteOp << " |" << setw(11) << i->dteClo << " |"; cout << setw(8) << i->partCnt << " |" << endl; } } } void Survey::viewOneSurvey(int indx, string user, bool isAdmin) { indx = indx-1; if(indx<sTotal && indx >= 0) { cout << "Survey Name: " << survList[indx].name << endl; cout << "Description: " << survList[indx].desc << endl; cout << "# of Questions: " << survList[indx].qCount << endl; cout << "Start Date: " << survList[indx].dteOp << endl; cout << "Close Date: " << survList[indx].dteClo << endl; if (!isAdmin) { bool comp = false; for (auto j = survList[indx].userRes.begin(); j!= survList[indx].userRes.end(); j++) { if (j->email == user) { comp = true; } } if (comp) cout << "Status: Taken\n"; else cout << "Status: Not Started\n"; } else { cout << "Amount completed: " << survList[indx].partCnt; } } else cout << "Invalid survey selected.\n"; } void Survey::takeSurvey(int indx, string user) { indx = indx-1; int inc = 0; int choice; bool comp = false; uStruct tmpStruct; for (auto j = survList[indx].userRes.begin(); j!= survList[indx].userRes.end(); j++) { if (j->email == user) { comp = true; } } if(indx<sTotal && indx >= 0 && !comp) { tmpStruct.email = user; for (auto i = survList[indx].qList.begin(); i!= survList[indx].qList.end(); i++) { inc++; int cInc = 0; cout << "#" << inc << ": " << i->quest << endl; for (auto j = i->choices.begin(); j!= i->choices.end(); j++) { cInc++; cout << "\t(" << cInc << ") " << *j << endl; } cout << "Input choice: "; cin >> choice; while (choice < 1 || choice > cInc) { cout << "Invalid choice, input choice: "; cin >> choice; } tmpStruct.answers.push_back(choice); } survList[indx].userRes.push_back(tmpStruct); survList[indx].partCnt = survList[indx].partCnt+1; } else if (comp) { cout << "This survey was already taken.\n"; } /* for (auto i = survList[indx].userRes.begin(); i!= survList[indx].userRes.end(); i++) { cout << i->email << " "; for (auto j= i->answers.begin(); j!=i->answers.end(); j++) { cout << *j << " "; } } */ } void Survey::viewSurveyResults(int indx) { indx = indx-1; int inc = 0; vector<int> qRes; if(indx<sTotal && indx >= 0) { for (auto i = survList[indx].qList.begin(); i!= survList[indx].qList.end(); i++) { for (int j=0; j<i->choCnt; j++) { qRes.push_back(0); } for (auto j = survList[indx].userRes.begin(); j!= survList[indx].userRes.end(); j++) { int temp = j->answers[inc] - 1; qRes[temp] = qRes[temp] + 1; } cout << "Question #" << inc+1 << ": " << i->quest << endl; for (int j=0; j<i->choCnt; j++) { cout << "(" << j+1 << "): " << i->choices[j]; cout << " **Votes: " << qRes[j] << endl; } qRes.clear(); inc++; } } } void Survey::pushSToFile() { int sItr = 0; int pItr = 0; int itr = 0; vector<surStruc>::iterator survItr; vector<qStruct>::iterator qItr; vector<uStruct>::iterator userItr; vector<string>::iterator choItr; vector<int>::iterator ansItr; std::ofstream surveyOF; surveyOF.open ("surveyData.dat", ofstream::trunc); for(survItr = survList.begin(); survItr != survList.end(); ++survItr) { sItr++; surveyOF << survItr->name << endl << survItr->desc << endl; surveyOF << survItr->dteOp << endl << survItr->dteClo << endl; surveyOF << survItr->qCount << endl; for(qItr = survItr->qList.begin(); qItr != survItr->qList.end(); ++qItr) { surveyOF << qItr->quest << endl << qItr->choCnt; for(choItr = qItr->choices.begin(); choItr != qItr->choices.end(); ++choItr) { surveyOF << " " << *choItr; } surveyOF << endl; } surveyOF << survItr->partCnt; if (survItr->partCnt > 0) surveyOF << endl; pItr = 0; for(userItr = survItr->userRes.begin(); userItr != survItr->userRes.end(); ++userItr) { pItr++; surveyOF << userItr->email << endl; itr = 0; for(ansItr = userItr->answers.begin(); ansItr != userItr->answers.end(); ++ansItr) { itr++; surveyOF << *ansItr; if (itr < survItr->qCount) surveyOF << " "; } if (pItr < survItr->partCnt) surveyOF << endl; } if(sItr < sTotal) surveyOF << endl; } surveyOF.close(); }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: Drake * * Created on March 14, 2021, 3:18 AM */ #include <cstdlib> #include "SurveyCreator.h" using namespace std; /* * */ int main(int argc, char** argv) { SurveyCreator ballot; ballot.addSurvey(); ballot.outputSurveyList(0); return 0; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Survey.cpp * Author: Drake * * Created on March 14, 2021, 8:58 PM */ #include "Survey.h" Survey::Survey() { } Survey::Survey(string sName, string sDesc, string sOD, string sCD, string* list) { name = sName; desc = sDesc; dteOp = sOD; dteClo = sCD; iList = list; // Store list of items sze = list->size(); // Store size of list iVotes = new int[sze]; // Allocate new dynamic array for votes list for (int i=0; i<sze; i++) iVotes[i] = 0; } //Survey::Survey(const Survey& orig) { //} Survey::~Survey() { delete iList; // Delete dynamically allocated memory delete iVotes; } void Survey::addVote(int indx) { if (indx<sze) iVotes[indx]++; // Add a vote } string Survey::getItem(int indx) { if (indx<sze) return iList[indx]; } int Survey::getVote(int indx) { if (indx<sze) return iVotes[indx]; }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Users.h * Author: Drake * * Created on April 18, 2021, 7:38 PM */ #ifndef USERS_H #define USERS_H #include <map> #include <iterator> #include <string> #include <iostream> #include <fstream> using namespace std; class Users { private: map<string, unsigned int> uMap; // A map holding the user emails and password map<string, unsigned int>::iterator uMapItr; // Iterator for user map map<string, unsigned int> aMap; // A map holding the admin emails and password map<string, unsigned int>::iterator aMapItr; // Iterator for admin map fstream dataFile; fstream adminDataFile; public: Users(); Users(const Users& orig); virtual ~Users(); string login(); bool adminLogin(); void createU(); string editE(string); void editP(string); unsigned int PswrdCnvrt(const string&); void outputU(); void deleteU(string); void pushUToFile(); }; #endif /* USERS_H */ <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Menu.cpp * Author: Drake * * Created on April 4, 2021, 7:15 PM */ #include "Menu.h" Menu::Menu() { cont = true; isAdmin = false; curUser = "\0"; int choice; string newUser; string inUser; //this->editPart("<EMAIL>", "\0"); cout << "Run in:\n(1): Administrator\n(2): User\nEnter choice: "; //cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cin >> choice; while (choice<1 || choice>2) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; } if (choice==1) { while (cont) { if (!isAdmin) { choice = this->adminLoginMenu(); if (choice == 1) { isAdmin = this->adminLogin(); } if (choice == 2) { cont = false; } } else { choice = this->adminMenu(); if (choice == 1) { this->outputU(); cout << "Input a user to modify/delete: "; cin >> inUser; cout << "(1) Edit Username\n(2) Edit Password\n(3) "; cout << "Delete User\n(4) Return to menu\n"; cout << "Enter choice: "; cin >> choice; while (choice < 1 || choice > 4) { cout << "Invalid choice, re-enter: "; cin >> choice; } if (choice==1) { this->editE(inUser); } else if (choice==2) { this->editP(inUser); } else if (choice==3) { this->deleteU(inUser); } } else if (choice == 2) { this->viewSurveys(curUser, isAdmin); cout << "Input a survey to view/modify the info of.\n"; cout << "Input 0 to return to admin menu.\n"; cout << "Enter choice: "; cin >> choice; if (choice!=0) { this->viewOneSurvey(choice,curUser,isAdmin); this->modSurvey(choice); } } else if (choice == 3) { this->viewSurveys(curUser, isAdmin); cout << "Input a survey to view the results of.\n"; cout << "Input 0 to return to admin menu.\n"; cout << "Enter choice: "; cin >> choice; if (choice!=0) { this->viewSurveyResults(choice); } } else if (choice == 4) { isAdmin = false; } else if (choice == 5) { cont = false; } } } } else if (choice==2) { isAdmin = false; while (cont) { if (curUser=="\0") { // If the user is not logged in choice = this->userLogin(); if (choice==1) { curUser = this->login(); } else if (choice==2) { this->createU(); } else { cont = false; } } else { // If the user is logged in choice = this->userMenu(); if (choice==1) { this->viewSurveys(curUser, isAdmin); cout << "Input a survey to view the info of.\n"; cout << "Input 0 to return to user menu.\n"; cout << "Enter choice: "; cin >> choice; if (choice!=0) { char charInp; this->viewOneSurvey(choice,curUser,isAdmin); cout << "\nTake survey #" << choice << "? (y/n)"; cin >> charInp; if (charInp == 'y') { this->takeSurvey(choice,curUser); } } } else if (choice==2) { // View account details choice = this->userAccount(); if (choice==1) { newUser = this->editE(curUser); if(newUser!="\0") { this->editPart(curUser, newUser); curUser = newUser; } } else if (choice==2) { this->editP(curUser); } else if (choice>=4) cont = false; } else if (choice==3) { cout << "Reset"; curUser = "\0"; } else { cont = false; // Exit } } /* cout << "***User Menu***" << endl; cout << "(1): Create Survey"; cout << "(2): Take Survey"; cout << "Enter choice: "; cin >> choice; while (choice >2 || choice <1) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; } if (choice==1) { // Call create survey functions this->addSurvey(); cont = this->ReturnCheck(); } if (choice==2) { // Call take/display survey functions this->ballotSelect(); cont = this->ReturnCheck(); } cout << "LOOP";*/ } } this->promptSave(); } //Menu::Menu(const Menu& orig) { //} Menu::~Menu() { } /* bool Menu::ReturnCheck() { int choice; cout << "\nReturn to menu (1) or end program (2): "; cin >> choice; while (choice >2 || choice <1) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; } if (choice==1) { cout << "true"; return true; } else { cout << "false"; return false; } } */ int Menu::userLogin() { int choice; cout << "\n***Login Menu***\n" << endl; cout << "(1): Login\n"; cout << "(2): Create Account\n"; cout << "(3): Exit program\n"; cout << "Enter choice: "; cin >> choice; while (choice <1 || choice > 3) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; } return choice; } int Menu::userMenu() { int choice; cout << "\n***User Menu***\n" << endl; cout << "(1): View Survey List\n"; cout << "(2): View/Edit Account Details\n"; cout << "(3): Logout\n"; cout << "(4): Exit program\n"; cout << "Enter choice: "; cin >> choice; while (choice <1 || choice > 4) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; return choice; } } int Menu::userAccount() { int choice; cout << "\n***Account Menu***\n"; cout << "User Email: " << curUser; cout << "\n(1): Edit Email\n"; cout << "(2): Edit Password\n"; cout << "(3): Return to User Menu\n"; cout << "(4): Exit program\n"; cout << "Enter choice: "; cin >> choice; while (choice < 1 || choice > 4) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; } return choice; } int Menu::adminMenu() { int choice; cout << "\n***Administrator Menu***\n"; cout << "\n(1): View Users\n"; cout << "(2): View Surveys\n"; cout << "(3): View Survey Results\n"; cout << "(4): Logout\n"; cout << "(5): Exit program\n"; cout << "Enter choice: "; cin >> choice; while (choice < 1 || choice > 5) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; } return choice; } int Menu::adminLoginMenu() { int choice; cout << "\n***Admin Login Menu***\n" << endl; cout << "(1): Login\n"; cout << "(2): Exit program\n"; cout << "Enter choice: "; cin >> choice; while (choice <1 || choice > 2) { cout << "This is an invalid choice, re-enter choice: "; cin >> choice; } return choice; } void Menu::promptSave() { char choice; cout << "\nSave session to file? (y/n): "; cin >> choice; if (choice=='y') { this->pushUToFile(); this->pushSToFile(); cout << "Saving and exiting"; } else cout << "Exiting without saving."; }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Survey.h * Author: Drake * * Created on March 14, 2021, 8:58 PM */ #ifndef SURVEY_H #define SURVEY_H #include <iostream> #include <iomanip> #include <list> #include <iterator> #include <string> #include <vector> #include <fstream> using namespace std; // Questions are now stored in survey file under their survey, can remove question class struct qStruct { string quest; vector<string> choices; // List of choices int choCnt; // number of choices }; struct uStruct { string email; vector<int> answers; // List of questions }; struct surStruc { string name; // Name of the survey string desc; // Description of the survey string dteOp; // Date the survey opens string dteClo;// Date the survey closes int qCount; // Number of questions, used in reading the file int partCnt; // Number of participants who have taken the survey vector<qStruct> qList; // List of questions vector<uStruct> userRes; // Results from the users }; class Survey { private: vector<surStruc> survList; ifstream sDataF; ofstream oSDataF; int sTotal; // Total number of surveys public: Survey(); //Survey(const Survey& orig); ~Survey(); /* int getTot() { return sTotal; } // Get the total number of surveys string getSName(int); // Get a specific survey's name string getDesc(int); string getDO(int); string getDC(int); int getSize(int); string getQName(int, int); int getVote(int); */ // Modification void modSurvey(int); void createSurvey(); void editPart(string, string); // Edit participant of a survey void viewSurveys(string, bool); void viewOneSurvey(int, string, bool); void takeSurvey(int, string); void viewSurveyResults(int); void pushSToFile(); }; #endif /* SURVEY_H */
5d83a9637f468b1271423eb47f3ad5f0e18454a0
[ "Makefile", "C++" ]
12
C++
DarkDonut0207/Survey-Engine
692d1d19d7762c5224d6e64d684c5e8ec9d2c67e
417a8731a5635f4fb30e811f163ed908edec4819
refs/heads/master
<repo_name>Lynexis7/RamirezVillalpandoChristian<file_sep>/Practicas/PullToRefresh11/PullToRefresh11/Models/CitiesManager.cs using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; namespace PullToRefresh11.Models { public class CitiesManager { #region Singleton static readonly Lazy<CitiesManager> lazy = new Lazy<CitiesManager>(() => new CitiesManager()); public static CitiesManager SharedInstance { get => lazy.Value; } #endregion #region Class Variables HttpClient httpClient; Dictionary<string, List<string>> cities; #endregion #region Events public event EventHandler<CitiesEventArgs> CitiesFetched; public event EventHandler<EventArgs> FetchCitiesFailed; #endregion CitiesManager() { httpClient = new HttpClient(); } #region Public Functionality public Dictionary<string, List<string>> GetDefaultCities() { var citiesJson = File.ReadAllText("citites-incomplete.json"); return JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(citiesJson); } public void FetchCities() { Task.Factory.StartNew(FetchCitiesAsync); async Task FetchCitiesAsync() { try { var citiesJson = await httpClient.GetStringAsync("https://dropbox.com/s/0adq8yw6vd5r6bj/cities.json?dl=0"); cities = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(citiesJson); //Avisar al controller que ya estna disponibles los datos //1. A traves de eventos (Events/Delegate) //2. A traves de notificaciones (NSNotificationCenter) //3. (Solo aplica cuando estas dentro de un ViewController) A traves de Unwind Segues if(CitiesFetched == null) { return; } var e = new CitiesEventArgs(cities); CitiesFetched(this, e); } catch (Exception ex) { //Avisar al controller que algo fallo //1. A traves de eventos (Events/Delegate) //2. A traves de notificaciones (NSNotificationCenter) //3. (Solo aplica cuando estas dentro de un ViewController) A traves de Unwind Segues if (FetchCitiesFailed == null) return; FetchCitiesFailed(this, new EventArgs()); } } } #endregion } public class CitiesEventArgs : EventArgs { public Dictionary<string, List<string>> Cities { get; private set; } public CitiesEventArgs(Dictionary<string, List<string>> cities){ Cities = cities; } } } <file_sep>/Examen/ExamenSegundoParcial/ExamenSegundoParcial/Model/TwitterTableSource.cs using System; using System.Collections.Generic; using Foundation; using UIKit; namespace ExamenSegundoParcial.Model { public class TwitterTableSource : UITableViewSource { const string CellIdentifier = "TweetCell"; readonly List<Tweet> tweets; public TwitterTableSource(List<Tweet> tweets) { this.tweets = tweets; } public override int RowsInSection(UITableView tableview, int section) { return tweets.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); // if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier); cell.TextLabel.Text = tweets[indexPath.Row].ScreenName; cell.DetailTextLabel.Text = tweets[indexPath.Row].Text; return cell; } } } <file_sep>/Examen/ExamenSegundoParcial/ExamenSegundoParcial/Controller/ViewController.cs using System; using System.Collections.Generic; using ExamenSegundoParcial.Model; using ExamenSegundoParcial.Views; using Foundation; using LinqToTwitter; using UIKit; namespace ExamenSegundoParcial { public partial class ViewController : UIViewController, IUITableViewDataSource, IUITableViewDelegate, IUISearchResultsUpdating { #region Class variables UISearchController searchController; List<Status> tweets; #endregion protected ViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. InitializeComponents(); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } #region Internal Functionality void InitializeComponents() { tweets = new List<Status>(); LinqToTwitterManager.SharedInstance.TweetsFetchedEvent += SharedInstance_TweetsFetchedEvent1; LinqToTwitterManager.SharedInstance.FetchedTweetsFailedEvent += SharedInstance_FetchedTweetsFailedEvent1; searchController = new UISearchController(searchResultsController: null) { SearchResultsUpdater = this, DimsBackgroundDuringPresentation = false }; TweetTableView.DataSource = this; TweetTableView.Delegate = this; TweetTableView.TableHeaderView = searchController.SearchBar; TweetTableView.RowHeight = UITableView.AutomaticDimension; TweetTableView.EstimatedRowHeight = 50; } #endregion #region UITableView data Source [Export("numberOfSectionsInTableView:")] public nint NumberOfSections(UITableView tableView) { return 1; } public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { try { if (tweets.Count > 0) { var tweet = tweets[indexPath.Row]; var cell = tableView.DequeueReusableCell(TweetTableViewCell.Key, indexPath) as TweetTableViewCell; cell.Tweet = tweet.FullText; cell.Favorited = tweet.FavoriteCount.ToString() ?? "0"; cell.Retweeted = tweet.RetweetCount.ToString(); return cell; } else { var tweet = tweets[indexPath.Row]; var cell = tableView.DequeueReusableCell(TweetTableViewCell.Key, indexPath) as TweetTableViewCell; cell.Tweet = ""; cell.Favorited = ""; cell.Retweeted = ""; return cell; } } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } } public nint RowsInSection(UITableView tableView, nint section) { try { return tweets.Count; } catch (Exception ex) { Console.WriteLine(ex.Message); return 0; } } #endregion #region Search Results Updating public void UpdateSearchResultsForSearchController(UISearchController searchController) { if(searchController.SearchBar.Text != "") LinqToTwitterManager.SharedInstance.SearchTweets(searchController.SearchBar.Text); } #endregion #region Linq Events void SharedInstance_TweetsFetchedEvent1(object sender, Model.LinqToTwitterManager.TweetsFetchedEventArgs e) { tweets = e.Tweets; InvokeOnMainThread(() => TweetTableView.ReloadData()); } void SharedInstance_FetchedTweetsFailedEvent1(object sender, Model.LinqToTwitterManager.FetchedTweetsFailedEventArgs e) { Console.WriteLine(e.Message); } #endregion } } <file_sep>/Examen/ExamenSegundoParcial/ExamenSegundoParcial/Views/TweetTableViewCell.cs using System; using Foundation; using UIKit; namespace ExamenSegundoParcial.Views { public partial class TweetTableViewCell : UITableViewCell { public static readonly NSString Key = new NSString("TweetTableViewCell"); public string Tweet { get => lblTweet.Text; set => lblTweet.Text = value; } public string Favorited { get => lblFavorited.Text; set => lblFavorited.Text = value; } public string Retweeted { get => lblRetweeted.Text; set => lblRetweeted.Text = value; } protected TweetTableViewCell(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } } } <file_sep>/Examen/ExamenFinal/ProyectoFinal/ProyectoFinal/Gasto.cs using System; namespace ProyectoFinal { public class Gasto { public float Monto; public string Descripcion; public DateTime Fecha; } } <file_sep>/Practicas/BasicTable10/BasicTable10/ViewController.cs using System; using System.Collections.Generic; using Foundation; using UIKit; namespace BasicTable10 { public partial class ViewController : UIViewController, IUITableViewDataSource, IUITableViewDelegate { #region Class Variables UITextField alertText = new UITextField(); nint rowLimit = 0; UITableViewCell cell; List<int> lst; #endregion protected ViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. tableView.DataSource = this; tableView.Delegate = this; } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } #region UITableView DataSource [Export("numberOfSectionsInTableView:")] public nint NumberOfSections(UITableView tableView) { return 1; } public nint RowsInSection(UITableView tableView, nint section) { return rowLimit; } public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { cell = tableView.DequeueReusableCell("BasicTableViewCell", indexPath); //cell.TextLabel.Text = return cell; } #endregion #region Internal Functionality void NumberOneAlert(int num) { UIAlertController alert = UIAlertController.Create("Choose the limit", "Please write the multiplication limit your number will have. Invalid numbers will be taken as a 0", UIAlertControllerStyle.Alert); alert.AddTextField((alertText) => {}); var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); var okayAction = UIAlertAction.Create("Okay", UIAlertActionStyle.Default, action => NumberOne(num)); alert.AddAction(okayAction); alert.AddAction(cancelAction); PresentViewController(alert, true, null); } void NumberOne(int number) { //lst.Add(); Console.WriteLine(); rowLimit = nint.Parse(alertText.Text); cell.TextLabel.Text = "1"; } #endregion #region User Interactions partial void btnAdd_Clicked(NSObject sender) { ShowAlert(); } public void ShowAlert() { UIAlertController alert = UIAlertController.Create(null, "Choose a number.", UIAlertControllerStyle.ActionSheet); alert.AddAction(UIAlertAction.Create("1", UIAlertActionStyle.Default, action => NumberOneAlert(1))); alert.AddAction(UIAlertAction.Create("2", UIAlertActionStyle.Default, action => NumberOneAlert(2))); alert.AddAction(UIAlertAction.Create("3", UIAlertActionStyle.Default, action => NumberOneAlert(3))); alert.AddAction(UIAlertAction.Create("4", UIAlertActionStyle.Default, action => NumberOneAlert(4))); alert.AddAction(UIAlertAction.Create("5", UIAlertActionStyle.Default, action => NumberOneAlert(5))); alert.AddAction(UIAlertAction.Create("6", UIAlertActionStyle.Default, action => NumberOneAlert(6))); alert.AddAction(UIAlertAction.Create("7", UIAlertActionStyle.Default, action => NumberOneAlert(7))); alert.AddAction(UIAlertAction.Create("8", UIAlertActionStyle.Default, action => NumberOneAlert(8))); alert.AddAction(UIAlertAction.Create("9", UIAlertActionStyle.Default, action => NumberOneAlert(9))); alert.AddAction(UIAlertAction.Create("10", UIAlertActionStyle.Default, action => NumberOneAlert(10))); alert.AddAction(UIAlertAction.Create("11", UIAlertActionStyle.Default, action => NumberOneAlert(11))); alert.AddAction(UIAlertAction.Create("12", UIAlertActionStyle.Default, action => NumberOneAlert(12))); alert.AddAction(UIAlertAction.Create("Cancelar", UIAlertActionStyle.Cancel, null)); PresentViewController(alert, animated: true, completionHandler: null); } #endregion } } <file_sep>/Examen/ExamenSegundoParcial/ExamenSegundoParcial/Model/Tweet.cs using System; namespace ExamenSegundoParcial.Model { public class Tweet { public ulong StatusID { get; set; } public string ScreenName { get; set; } public string Text { get; set; } public int Favorited { get; set; } } } <file_sep>/Practicas/PhotoPicker09/PhotoPicker09/ViewController.cs using System; using Photos; using UIKit; using Foundation; using System.Threading.Tasks; using AVFoundation; namespace PhotoPicker09 { public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate { #region Class Variables UITapGestureRecognizer profileTap; UITapGestureRecognizer coverTap; #endregion protected ViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. InitializeComponents(); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } #region User Interactions void ShowOptions (UITapGestureRecognizer gesture) { alert = UIAlertController.Create("Profile", "Choose an option.", UIAlertControllerStyle.ActionSheet); alert.AddAction(UIAlertAction.Create("Choose from gallery", UIAlertActionStyle.Default, action => ChooseFromGallery())); alert.AddAction(UIAlertAction.Create("Take a photo", UIAlertActionStyle.Default, action => TakePhoto())); alert.AddAction(UIAlertAction.Create("Cancelar", UIAlertActionStyle.Cancel, null)); PresentViewController(alert, animated: true, completionHandler: null); } void ChooseFromGallery() { if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) { return; } CheckLibraryAuthorizationStatus(PHPhotoLibrary.AuthorizationStatus); } void TakePhoto() { if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { ShowMessage("Precaucion!", "Recurso no valido.", NavigationController); return; } CheckCameraAuthorizationStatus(AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video)); } void CheckLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: //TODO: Vamos a pedir el permiso para acceder PHPhotoLibrary.RequestAuthorization(CheckLibraryAuthorizationStatus); break; case PHAuthorizationStatus.Restricted: //TODO: Mostrar un mensaje diciendo que esta restringido InvokeOnMainThread(() => ShowMessage("Error", "El permiso esta restringido.", NavigationController)); break; case PHAuthorizationStatus.Denied: //TODO: El usuario denego el permiso. InvokeOnMainThread(() => ShowMessage("Error", "El permiso fue denegado.", NavigationController)); break; case PHAuthorizationStatus.Authorized: //TODO: Abrir la galeria InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } } void CheckCameraAuthorizationStatus(AVAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case AVAuthorizationStatus.NotDetermined: //TODO: Vamos a pedir el permiso para acceder AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Video, (accessGranted) => { if(!accessGranted) { CheckCameraAuthorizationStatus(authorizationStatus); } }); break; case AVAuthorizationStatus.Restricted: //TODO: Mostrar un mensaje diciendo que esta restringido InvokeOnMainThread(() => ShowMessage("Error", "El permiso esta restringido.", NavigationController)); break; case AVAuthorizationStatus.Denied: //TODO: El usuario denego el permiso. InvokeOnMainThread(() => ShowMessage("Error", "El permiso fue denegado.", NavigationController)); break; case AVAuthorizationStatus.Authorized: //TODO: Abrir la galeria InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.Camera, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } } #endregion #region UIImage Picker Controller Delegate [Export("imagePickerController:didFinishPickingMediaWithInfo:")] public void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info) { var image = info[UIImagePickerController.OriginalImage] as UIImage; ImgProfile.Image = image; picker.DismissViewController(true, null); } [Export("imagePickerControllerDidCancel:")] public void Canceled(UIImagePickerController picker) { picker.DismissViewController(true, null); } #endregion #region Internal Functionality void InitializeComponents() { lblEdit.Hidden = lblCover.Hidden = true; profileTap = new UITapGestureRecognizer(ShowOptions) { Enabled = true }; ProfileView.AddGestureRecognizer(profileTap); coverTap = new UITapGestureRecognizer(ShowOptions) { Enabled = true }; CoverView.AddGestureRecognizer(coverTap); } void ShowMessage(string title, string mensaje, UIViewController fromViewController) { var alert = UIAlertController.Create(title, mensaje, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Cancel, null)); fromViewController.PresentViewController(alert, true, null); } #endregion } } <file_sep>/Examen/ExamenSegundoParcial/ExamenSegundoParcial/Model/LinqToTwitterManager.cs using System; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using LinqToTwitter; namespace ExamenSegundoParcial.Model { public class LinqToTwitterManager { #region Singleton static Lazy<LinqToTwitterManager> lazy = new Lazy<LinqToTwitterManager>(() => new LinqToTwitterManager()); public static LinqToTwitterManager SharedInstance { get => lazy.Value; } #endregion #region Events public event EventHandler<TweetsFetchedEventArgs> TweetsFetchedEvent; public event EventHandler<FetchedTweetsFailedEventArgs> FetchedTweetsFailedEvent; #endregion #region Class Variables SingleUserAuthorizer auth; TwitterContext twitterContext; CancellationTokenSource cancellationTokenSource; #endregion #region Constructor LinqToTwitterManager() { auth = new SingleUserAuthorizer() { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = "<KEY>", ConsumerSecret = "<KEY>" }, }; twitterContext = new TwitterContext(auth); cancellationTokenSource = new CancellationTokenSource(); } #endregion #region Internal Functionality async Task<List<Status>> SearchTweetsAsync(string query, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace((query))) return null; cancellationToken.ThrowIfCancellationRequested(); Search searchResponse = await (from search in twitterContext.Search where search.Type == SearchType.Search && search.Query == query && search.IncludeEntities == true && search.TweetMode == TweetMode.Extended select search) .SingleOrDefaultAsync(); cancellationToken.ThrowIfCancellationRequested(); return searchResponse?.Statuses; } #endregion #region Public Functionality public void SearchTweets(string query) { if (cancellationTokenSource.IsCancellationRequested) cancellationTokenSource.Cancel(); cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; Task.Factory.StartNew(async () => { try { var tweets = await SearchTweetsAsync(query, cancellationToken); var e = new TweetsFetchedEventArgs(tweets); TweetsFetchedEvent?.Invoke(this, e); } catch (Exception ex) { var e = new FetchedTweetsFailedEventArgs(ex.Message); FetchedTweetsFailedEvent?.Invoke(this, e); } }); } #endregion public class TweetsFetchedEventArgs : EventArgs { public List<Status> Tweets { get; set; } public TweetsFetchedEventArgs(List<Status> tweets) { Tweets = tweets; } } public class FetchedTweetsFailedEventArgs : EventArgs { public string Message { get; set; } public FetchedTweetsFailedEventArgs(string errorMessage) { Message = errorMessage; } } } }
6e1af637c97e0e9f4b44560d05e1a10582249b03
[ "C#" ]
9
C#
Lynexis7/RamirezVillalpandoChristian
33c41b91b0f3e636f10d48c1ec624e64c6634021
5b887092b3f353a453ff58a0993e46f107b29783
refs/heads/master
<repo_name>GalmOne/ScoutomeUniversalApp10<file_sep>/Scoutome/Model/Presences.cs namespace Scoutome.Model { public class Presences { public double codeAnime { get; set; } public double codeReunion { get; set; } public int useless { get; set; } } } <file_sep>/Scoutome/ViewModel/MainViewModel.cs using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Views; using System.ComponentModel; using System.Windows.Input; namespace Scoutome.ViewModel { public class MainViewModel : ViewModelBase, INotifyPropertyChanged { private INavigationService _navigationService; private ICommand _editReunionCommand; public ICommand EditReunionCommand { get { if (this._editReunionCommand == null) { this._editReunionCommand = new RelayCommand(() => EditReunion()); } return this._editReunionCommand; } } private ICommand _newReunionCommand; public ICommand NewReunionCommand { get { if (this._newReunionCommand == null) { this._newReunionCommand = new RelayCommand(() => NewReunion()); } return this._newReunionCommand; } } private ICommand _childrenListCommand; public ICommand ChildrenListCommand { get { if (this._childrenListCommand == null) { this._childrenListCommand = new RelayCommand(() => GoToChildrenlist()); } return this._childrenListCommand; } } public MainViewModel(INavigationService navigationService = null) { _navigationService = navigationService; } private void EditReunion() { _navigationService.NavigateTo("ReunionPage"); } private void GoToChildrenlist() { _navigationService.NavigateTo("ChildrenList"); } private void NewReunion() { _navigationService.NavigateTo("AddReunion"); } } } <file_sep>/Scoutome/Model/Anime.cs using System.Collections.Generic; namespace Scoutome.Model { public class Anime { public List<object> reunions { get; set; } public double codeAnime { get; set; } public string nom { get; set; } public string prenom { get; set; } } } <file_sep>/Scoutome/ViewModel/ReunionViewModel.cs using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using Scoutome.Model; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Windows.UI.Xaml.Navigation; using Scoutome.DAO; using Windows.UI.Popups; namespace Scoutome.ViewModel { public class ReunionViewModel : ViewModelBase, INotifyPropertyChanged { private INavigationService _navigationService; private DataAccessObject data = new DataAccessObject(); private ObservableCollection<Reunion> _reunions; public ObservableCollection<Reunion> Reunions { get { return _reunions; } set { _reunions = value; RaisePropertyChanged("Reunions"); } } private Reunion _selectedReunion; public Reunion SelectedReunion { get { return _selectedReunion; } set { _selectedReunion = value; RaisePropertyChanged("SelectedReunion"); } } private ICommand _infoReunionCommand; public ICommand InfoReunionCommand { get { if (this._infoReunionCommand == null) { this._infoReunionCommand = new RelayCommand(() => GoToInformationsReunion()); } return this._infoReunionCommand; } } private ICommand _backCommand; public ICommand BackCommand { get { if (this._backCommand == null) { this._backCommand = new RelayCommand(() => BackToMain()); } return this._backCommand; } } [PreferredConstructor] public ReunionViewModel(INavigationService navigationService = null) { _navigationService = navigationService; } public async void OnNavigatedTo(NavigationEventArgs e) { Reunions = await data.CallWebApiReunionList("reunions"); if (Reunions == null) { CreatePopUp("ErrorInternet"); BackToMain(); } } private void GoToInformationsReunion() { if (SelectedReunion != null) _navigationService.NavigateTo("InformationsReunionPage", SelectedReunion); else { CreatePopUp("NoSelectReunion"); } } private void BackToMain() { _navigationService.NavigateTo("MainPage"); } public void CreatePopUp(String value) { var loader = new Windows.ApplicationModel.Resources.ResourceLoader(); var str = loader.GetString(value); var messageDialog = new MessageDialog(str); messageDialog.ShowAsync(); } } } <file_sep>/Scoutome/ViewModel/InotifyPropertyChanged.cs  namespace Scoutome.ViewModel { internal interface InotifyPropertyChanged { } } <file_sep>/Scoutome/DAO/DataAccessObject.cs using Newtonsoft.Json; using Scoutome.Model; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Scoutome.DAO { public class DataAccessObject { private HttpClient client; private const string urlApi = "http://scoutome.azurewebsites.net/api/"; public DataAccessObject() { client = new HttpClient(); } public async Task<ObservableCollection<Anime>> GetChildrenList(string type) { try { HttpResponseMessage response = await client.GetAsync(urlApi + type); string json = await response.Content.ReadAsStringAsync(); var animes = Newtonsoft.Json.JsonConvert.DeserializeObject<Anime[]>(json); if (response.IsSuccessStatusCode) { return CastListToObservableAnime(animes); } else { return null; } } catch(HttpRequestException e) { return null; } } private static ObservableCollection<Anime> CastListToObservableAnime(Anime[] animes) { List<Anime> li = new List<Anime>(); li = animes.ToList<Anime>(); ObservableCollection<Anime> myAnimeListView = new ObservableCollection<Anime>(); for (int i = 0; i < li.Count(); i++) { myAnimeListView.Add(li[i]); } return myAnimeListView; } public async Task<bool> AddReunion(Reunion reunion, ObservableCollection<Anime> selectedAnime) { try { string json = JsonConvert.SerializeObject(reunion); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(urlApi + "reunions", content); if (response.IsSuccessStatusCode) { return await AddPresences(reunion, selectedAnime); } else { return false; } } catch (HttpRequestException) { return false; } } private async Task<bool> AddPresences(Reunion reunion, ObservableCollection<Anime> selectedAnime) { // Pour ajouter les présences for (int i = 0; i < selectedAnime.Count(); i++) { Presences pre = new Presences(); pre.codeReunion = reunion.codeReunion; pre.useless = 1; pre.codeAnime = selectedAnime[i].codeAnime; string jsonPresence = JsonConvert.SerializeObject(pre); HttpContent contentPresence = new StringContent(jsonPresence, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(urlApi+"presences", contentPresence); if (response.IsSuccessStatusCode) { } } return true; } public async Task<ObservableCollection<Reunion>> CallWebApiReunionList(string type) { try { HttpResponseMessage response = await client.GetAsync(urlApi + type); string json = await response.Content.ReadAsStringAsync(); var reunions = Newtonsoft.Json.JsonConvert.DeserializeObject<Reunion[]>(json); if (response.IsSuccessStatusCode) { return CastListToObservableReunion(reunions); } else return null; } catch(HttpRequestException) { return null; } } private static ObservableCollection<Reunion> CastListToObservableReunion(Reunion[] reunions) { List<Reunion> li = new List<Reunion>(); li = reunions.ToList<Reunion>(); ObservableCollection<Reunion> myReunionList = new ObservableCollection<Reunion>(); for (int i = 0; i < li.Count(); i++) { myReunionList.Add(li[i]); } return myReunionList; } } } <file_sep>/Scoutome/ViewModel/InformationsReunionViewModel.cs using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using Scoutome.Model; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Windows.UI.Xaml.Navigation; namespace Scoutome.ViewModel { public class InformationsReunionViewModel : ViewModelBase, INotifyPropertyChanged { private INavigationService _navigationService; private Reunion _selectedReunion; public Reunion SelectedReunion { get { return _selectedReunion; } set { _selectedReunion = value; RaisePropertyChanged("SelectedReunion"); } } private ObservableCollection<Anime> childrenPresents; public ObservableCollection<Anime> ChildrenPresents { get { return childrenPresents; } set { childrenPresents = value; } } private ICommand _backCommand; public ICommand BackCommand { get { if (this._backCommand == null) { this._backCommand = new RelayCommand(() => BackToReunion()); } return this._backCommand; } } public string Libelle { get { return SelectedReunion.libelle; } set { SelectedReunion.libelle = value; } } public string Date { get { return SelectedReunion.dateReunion; } set { SelectedReunion.dateReunion = value; } } public string Lieu { get { return SelectedReunion.lieu; } set { SelectedReunion.lieu = value; } } public double Prix { get { return SelectedReunion.prix; } set { SelectedReunion.prix = value; } } [PreferredConstructor] public InformationsReunionViewModel(INavigationService navigationService = null) { _navigationService = navigationService; SelectedReunion = new Reunion(); childrenPresents = new ObservableCollection<Anime>(); PopulateListView(); } public void OnNavigatedTo(NavigationEventArgs e) { SelectedReunion = (Reunion)e.Parameter; } private void BackToReunion() { _navigationService.NavigateTo("ReunionPage"); } public void PopulateListView () { Anime anime = new Anime(); anime.nom = "Petit"; anime.prenom = "Arnaud"; childrenPresents.Add(anime); Anime anime1 = new Anime(); anime1.nom = "Mathieu"; anime1.prenom = "Bastien"; childrenPresents.Add(anime1); Anime anime2 = new Anime(); anime2.nom = "Herman"; anime2.prenom = "Axel"; childrenPresents.Add(anime2); } } } <file_sep>/Scoutome/ViewModel/AddReunionViewModel.cs using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using Scoutome.Model; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using Scoutome.DAO; using Windows.UI.Popups; using Windows.UI.Xaml.Navigation; namespace Scoutome.ViewModel { public class AddReunionViewModel : ViewModelBase, INotifyPropertyChanged { private INavigationService _navigationService; private DataAccessObject data = new DataAccessObject(); private Reunion reunion; private String mylieu; public String Mylieu { get { return mylieu; } set { mylieu = value; } } private String mylibelle = "Réunion du " + DateTime.Now.ToString("dd/MM/yyyy"); public String Mylibelle { get { return mylibelle; } set { mylibelle = value; } } private double myprix = 1; public double Myprix { get { return myprix; } set { myprix = value; } } private String myDate = DateTime.Now.ToString("dd/MM/yyyy"); public String MyDate { get { return myDate; } set { myDate = value; } } private ObservableCollection<Anime> myAnimeListView; public ObservableCollection<Anime> MyAnimeListView { get { return myAnimeListView; } set { myAnimeListView = value; RaisePropertyChanged("MyAnimeListView"); } } private ObservableCollection<Anime> selectedAnime; public ObservableCollection<Anime> SelectedAnime { get { return selectedAnime; } set { selectedAnime = value; RaisePropertyChanged("SelectedAnime"); } } private ICommand _addReunionCommand; public ICommand AddReunionCommand { get { if (_addReunionCommand == null) { _addReunionCommand = new RelayCommand(() => AddReunionCmd()); } return _addReunionCommand; } } private ICommand _backCommand; public ICommand BackCommand { get { if (_backCommand == null) { _backCommand = new RelayCommand(() => BackMainPage()); } return _backCommand; } } [PreferredConstructor] public AddReunionViewModel(INavigationService navigationService = null) { _navigationService = navigationService; reunion = new Reunion(); myAnimeListView = new ObservableCollection<Anime>(); SelectedAnime = new ObservableCollection<Anime>(); } public async void OnNavigatedTo(NavigationEventArgs e) { MyAnimeListView = await data.GetChildrenList("animes"); if (MyAnimeListView == null) { CreatePopUp("ErrorInternet"); BackMainPage(); } } public async void AddReunionCmd() { if (myAnimeListView == null || myAnimeListView.Count() < 1) { CreatePopUp("ErrorInternet"); } else { CreateReunionObject(); TrtSelectedItems(); await AddReunion(); } } private async Task AddReunion() { bool response = await data.AddReunion(reunion, selectedAnime); if (response) { CreatePopUp("SuccesAjoutReunion"); _navigationService.NavigateTo("MainPage"); } else { CreatePopUp("ErreurAjoutReunion"); } } public void BackMainPage() { _navigationService.NavigateTo("MainPage"); } public void CreateReunionObject() { DateTime date = DateTime.Now; reunion.codeReunion = date.Year * 10000 + date.Month * 100 + date.Day + date.Hour * 60 + date.Minute; reunion.dateReunion = date.ToString("dd/MM/yyyy"); reunion.libelle = mylibelle; reunion.lieu = mylieu; reunion.prix = myprix; } public void TrtSelectedItems() { for (int i = 0; i < 3; i++) { selectedAnime.Add(myAnimeListView[i]); } } public void CreatePopUp(String value) { var loader = new Windows.ApplicationModel.Resources.ResourceLoader(); var str = loader.GetString(value); var messageDialog = new MessageDialog(str); messageDialog.ShowAsync(); } } } <file_sep>/Scoutome/ViewModel/ChildrenListViewModel.cs using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using Scoutome.DAO; using Scoutome.Model; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Windows.UI.Popups; using Windows.UI.Xaml.Navigation; namespace Scoutome.ViewModel { public class ChildrenListViewModel : ViewModelBase, INotifyPropertyChanged { private INavigationService _navigationService; private DataAccessObject data = new DataAccessObject(); private ObservableCollection<Anime> myAnimeListView; public ObservableCollection<Anime> MyAnimeListView { get { return myAnimeListView; } set { myAnimeListView = value; RaisePropertyChanged("MyAnimeListView"); } } private ICommand _backCommand; public ICommand BackCommand { get { if (this._backCommand == null) { this._backCommand = new RelayCommand(() => BackToMain()); } return this._backCommand; } } [PreferredConstructor] public ChildrenListViewModel(INavigationService navigationService = null) { _navigationService = navigationService; myAnimeListView = new ObservableCollection<Anime>(); } public async void OnNavigatedTo(NavigationEventArgs e) { MyAnimeListView = await data.GetChildrenList("animes"); if (MyAnimeListView == null) { CreatePopUp("ErrorInternet"); BackToMain(); } } private void BackToMain() { _navigationService.NavigateTo("MainPage"); } public void CreatePopUp(string value) { var loader = new Windows.ApplicationModel.Resources.ResourceLoader(); var str = loader.GetString(value); var messageDialog = new MessageDialog(str); messageDialog.ShowAsync(); } } }<file_sep>/Scoutome/ViewModel/ViewModelLocator.cs using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; namespace Scoutome.ViewModel { public class ViewModelLocator { public ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<ReunionViewModel>(); SimpleIoc.Default.Register<InformationsReunionViewModel>(); SimpleIoc.Default.Register<AddReunionViewModel>(); SimpleIoc.Default.Register<ChildrenListViewModel>(); NavigationService navigationService = new NavigationService(); SimpleIoc.Default.Register<INavigationService>(() => navigationService); navigationService.Configure("MainPage", typeof(MainPage)); navigationService.Configure("ReunionPage", typeof(ReunionPage)); navigationService.Configure("InformationsReunionPage", typeof(InformationsReunionPage)); navigationService.Configure("AddReunion", typeof(AddReunion)); navigationService.Configure("ChildrenList", typeof(ChildrenList)); } public MainViewModel MainPage { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } public ReunionViewModel ReunionPage { get { return ServiceLocator.Current.GetInstance<ReunionViewModel>(); } } public InformationsReunionViewModel InformationsReunionPage { get { return ServiceLocator.Current.GetInstance<InformationsReunionViewModel>(); } } public AddReunionViewModel AddReunion { get { return ServiceLocator.Current.GetInstance<AddReunionViewModel>(); } } public ChildrenListViewModel ChildrenList { get { return ServiceLocator.Current.GetInstance<ChildrenListViewModel>(); } } } } <file_sep>/Scoutome/Model/Reunion.cs using System.Collections.Generic; using System.Runtime.Serialization; namespace Scoutome.Model { [DataContract] public class Reunion { [DataMember] public List<Anime> animes { get; set; } [DataMember] public double codeReunion { get; set; } [DataMember] public string libelle { get; set; } [DataMember] public string dateReunion { get; set; } [DataMember] public string lieu { get; set; } [DataMember] public double prix { get; set; } } }
1d1a8307a700a28b4a9e9170855d66539e685021
[ "C#" ]
11
C#
GalmOne/ScoutomeUniversalApp10
3b3d880f5aa046623cde5f10351c226fe17466d6
355ea3d1b80d5a061a08ae4899837e7487f39716
refs/heads/master
<file_sep>var sinon = require('sinon'); var expect = require('chai').expect; var parser = require('../../lib/markdown-parser'); var test = function(input, output) { var result = parser(input); expect(result).to.equal(output + '\n'); }; describe('Markdown Parser', function() { describe('Header', function() { describe('Common cases', function() { it('should convert # to H1 tag', function() { test( '# Hello there', '<h1>Hello there</h1>'); }); it('should convert ## to H2 tag', function() { test( '## Hello there', '<h2>Hello there</h2>'); }); it('should convert ### to H3 tag', function() { test( '### Hello there', '<h3>Hello there</h3>'); }); it('should convert ### to H4 tag', function() { test( '#### Hello there', '<h4>Hello there</h4>'); }); it('should convert ### to H5 tag', function() { test( '##### Hello there', '<h5>Hello there</h5>'); }); it('should convert ### to H6 tag', function() { test( '###### Hello there', '<h6>Hello there</h6>'); }); it('should ignore trailing #', function() { test( '## Hello there ##', '<h2>Hello there</h2>'); }); }); describe('Mixed cases', function() { it('should render header and paragraph', function() { test( '## Hello there\nAnd there', '<h2>Hello there</h2>\n<p>And there</p>'); }); it('should render header and emphasize word', function() { test( '## Hello *there*', '<h2>Hello <em>there</em></h2>'); }); it('should render header and strong word', function() { test( '## Hello **there**', '<h2>Hello <strong>there</strong></h2>'); }); it('should render header and emphasize and strong word', function() { test( '## *Hello* **there**', '<h2><em>Hello</em> <strong>there</strong></h2>'); }); it('should render header and emphasize and strong words that overlaps', function() { test( '## *Hello everyone out **there***', '<h2><em>Hello everyone out <strong>there</strong></em></h2>'); }); it('should render header and link', function() { test( '## Hello [here](http://example.com)', '<h2>Hello <a href="http://example.com">here</a></h2>'); }); }); }); describe('Paragraph', function() { describe('Common cases', function() { it('should convert simple line into paragraph tag', function() { test( 'Hello there', '<p>Hello there</p>'); }); it('should convert multiline into one paragraph tag', function() { test( 'Hello there\nAnd there', '<p>Hello there\nAnd there</p>'); }); }); describe('Mixed cases', function() { it('should render paragraph and empasize word', function() { test( 'Hello *there*', '<p>Hello <em>there</em></p>'); }); it('should render paragraph and strong word', function() { test( 'Hello **there**', '<p>Hello <strong>there</strong></p>'); }); it('should render paragraph and link', function() { test( 'Hello [there](http://example.com)', '<p>Hello <a href="http://example.com">there</a></p>'); }); }); }); describe('Emphasize', function() { describe('Common cases', function() { it('should emphasize line', function() { test( '*Hello there*', '<p><em>Hello there</em></p>'); }); it('should emphasize multiline', function() { test( '*Hello there\nAnd there*', '<p><em>Hello there\nAnd there</em></p>'); }); it('should empasize several words in line', function() { test( '*Hello there* but not *here*', '<p><em>Hello there</em> but not <em>here</em></p>'); }); it('should empasize several words in multiline', function() { test( '*Hello there* but\nnot *here*', '<p><em>Hello there</em> but\nnot <em>here</em></p>'); }); it('should properly handle nesting emphases', function() { test( '*Hello there *but* not here*', '<p><em>Hello there </em>but<em> not here</em></p>'); }); }); describe('Mixed cases', function() { it('should empasize words within strong', function() { test( '**Hello *here* **', '<p><strong>Hello <em>here</em> </strong></p>'); }); it('should empasize and strong the whole line', function() { test( '** *Hello everyone* **', '<p><strong> <em>Hello everyone</em> </strong></p>'); }); it('should empasize word within paragraph', function() { test( 'Hello *here* everyone', '<p>Hello <em>here</em> everyone</p>'); }); }); }); describe('Strong', function() { describe('Common cases', function() { it('should make line strong', function() { test( '**Hello there**', '<p><strong>Hello there</strong></p>'); }); it('should make multiline strong', function() { test( '**Hello there\nAnd there**', '<p><strong>Hello there\nAnd there</strong></p>'); }); it('should strong several words in line', function() { test( '**Hello there** but not **here**', '<p><strong>Hello there</strong> but not <strong>here</strong></p>'); }); it('should strong several words in multiline', function() { test( '**Hello there** but\nnot **here**', '<p><strong>Hello there</strong> but\nnot <strong>here</strong></p>'); }); it('should properly handle nesting strongs', function() { test( '**Hello there **but** not here**', '<p><strong>Hello there </strong>but<strong> not here</strong></p>'); }); }); describe('Mixed cases', function() { it('should render strong within empasized words', function() { test( '*Hello **here***', '<p><em>Hello <strong>here</strong></em></p>'); }); it('should strong words within paragraph', function() { test( 'Hello **here** everyone', '<p>Hello <strong>here</strong> everyone</p>'); }); }); }); describe('Link', function() { describe('Common cases', function() { it('should convert line into link', function() { test( '[Link to a site](http://example.com)', '<p><a href="http://example.com">Link to a site</a></p>'); }); }); describe('Mixed cases', function() { it('should render link in header', function() { test( '## [Link to a site](http://example.com)', '<h2><a href="http://example.com">Link to a site</a></h2>'); }); it('should convert line into link and emphasize word', function() { test( '[Link to a *site*](http://example.com)', '<p><a href="http://example.com">Link to a <em>site</em></a></p>'); }); it('should convert line into link and strong word', function() { test( '[Link to a **site**](http://example.com)', '<p><a href="http://example.com">Link to a <strong>site</strong></a></p>'); }); it('should convert line into link and emphasize and strong word', function() { test( '[Link *to* a **site**](http://example.com)', '<p><a href="http://example.com">Link <em>to</em> a <strong>site</strong></a></p>'); }); it('should render link within strong', function() { test( '**[Link to a site](http://example.com)**', '<p><strong><a href="http://example.com">Link to a site</a></strong></p>'); }); it('should render link within emphasis', function() { test( '*[Link to a site](http://example.com)*', '<p><em><a href="http://example.com">Link to a site</a></em></p>'); }); }); }); }); <file_sep>var Hapi = require('hapi'); var Good = require('good'); var goodConsole = require('good-console'); // DataBase var hapiMongo = require('hapi-mongodb'); var dbName = process.env.MONGO_DB_NAME || 'markdown-test-task'; var mongoUrl = 'mongodb://localhost:27017/' + dbName; var markdownCollectionName = process.env.MONGO_MARKDOWN_COLLECTION || 'notes'; // Main module var markdown = require('./index'); // Create a server with a host and port var server = module.exports = new Hapi.Server(); server.connection({ host: process.env.HOST || 'localhost', port: parseInt(process.env.PORT, 10) || 8000 }); // Reports filtering function // mutes reporters under test environment var getReporters = function(reporters) { return process.env.NODE_ENV === 'test' ? [] : reporters; }; var handleError = function(error) { if (error) { console.error(error); process.exit(); } }; server.register([ // Registering logger { register: Good, options: { reporters: getReporters([{ reporter: goodConsole, events: { response: '*', log: '*' } }]) } }, // Registering mongodb client { register: hapiMongo, options: { url: mongoUrl } } ], function (err) { handleError(err); // Registering markdown plugin // Because of need to specify routes: {prefix: ''} currently it's impossible // to register markdown module along with others with this adjustment // also it assures that we have an established db connection at this point server.register( { register: markdown, options: { // transfering connection to markdown module plugin: 'hapi-mongodb', collection: markdownCollectionName, } }, { // setting prefix for markdown module routes: { prefix: '/markdown' } }, function (err) { handleError(err); // Start the server server.start(function () { server.log('info', 'Server running at: ' + server.info.uri); }); } ); }); <file_sep>var parser = require('./markdown-parser'); var Joi = require('joi'); // hapi validation module var Boom = require('boom'); // hapi http error objects var db, collection, ObjectID; exports.register = function (server, options, next) { // set up variables ObjectID = server.plugins[options.plugin].ObjectID; db = server.plugins[options.plugin].db; collection = db.collection(options.collection); /** * Returns record stored in database * @param {ObjectID} String that is convertable to Mongo's ObjectID */ server.route({ method: 'GET', path: '/get', handler: function(request, reply) { var query = {_id: ObjectID(request.query.id)}; collection.findOne(query, function(err, result) { if (err) { return reply(Boom.internal('Internal MongoDB error', err)); } if (!result) { return reply(Boom.notFound('Record not found')); } reply(result); }); }, config: { validate: { query: { // Simplified mongo's objectId validation id: Joi.string().required().length(24) } } } }); /** * Converts markdown text into HTML and stores it in database * @param {String} Markdown sting provided in payload * @response {JSON} Object that has record _id and resulted HTML string */ server.route({ method: 'POST', path: '/save', handler: function(request, reply) { var payload = request.payload; // validation if (!(payload && typeof payload === 'string')) { return reply(Boom.badRequest('No data')); } var query = { markdown: payload, html: parser(payload) }; collection.insert(query, function(err, result) { if (err) { return reply(Boom.internal('Internal MongoDB error', err)); } var item = result.ops[0]; reply({ _id: item._id, html: item.html }); }); } }); // Passing controll to the next module next(); }; exports.register.attributes = { pkg: require('../package.json') }; <file_sep># Simple Markdown to HTML Hapi module ### Overview The module is a **Hapi** module that accepts text in markdown format and stores it in **MongoDB** storage ### Supported syntax construction <pre> ### - Header declaration **...** - Strong declaration *...* - Emphasis declaration [Link](http://example.com) - Link declaration </pre> ### Known issues Triple star syntax \*\*\*...\*\*\* - Is not supported Examples: <pre> **Hello *everyone*** ***Hello everyone*** </pre> Solution is to explicitly define tags <pre> **Hello *everyone* ** ** *Hello everyone* ** * **Hello everyone** * </pre> ### Warning **It has been written to accomplish test task** *It does not cover the whole markdown specification, so use it on your own risk* For fully functional markdown parser visit [**marked**](https://github.com/chjj/marked) project at github<file_sep> var expect = require('chai').expect; var hippie = require('hippie'); var baseUrl, db, collection, collectionName, ObjectID; // setting up env variables process.env.NODE_ENV = 'test'; process.env.MONGO_DB_NAME = 'markdown-test-task-testing-db'; process.env.MONGO_MARKDOWN_COLLECTION = collectionName = 'notes'; var server = require('../../lib/server.js'); // wait for server to run before(function(done) { server.on('start', function(){ baseUrl = server.info.uri; done(); }); }); function request() { return hippie().base(baseUrl); } beforeEach(function(done) { ObjectID = server.plugins['hapi-mongodb'].ObjectID; db = server.plugins['hapi-mongodb'].db; collection = db.collection(collectionName); // cleanup database collection.remove(done); }); describe('/markdown/get', function(){ describe('when valid id is provided and record exists', function(done) { beforeEach(function(done) { collection.insert({ _id: ObjectID("5591c1275ef8a0a917032fde"), text: '# Hello there', html: '<h1>Hello there</h1>' }, done); }); it('should respond with #200 and contain record', function(done){ request() .get('/markdown/get?id=5591c1275ef8a0a917032fde') .expectStatus(200) .expectBody('{"_id":"5591c1275ef8a0a917032fde","text":"# Hello there","html":"<h1>Hello there</h1>"}') .end(done); }); }); describe('when id is not defined', function(done) { it('should respond #400 with bad request', function(done){ request() .get('/markdown/get') .expectStatus(400) .end(done); }); }); describe('when id is invalid', function(done) { it('should respond with #400 bad request', function(done){ request() .get('/markdown/get?id="invalidId"') .expectStatus(400) .end(done); }); it('should respond with #400 bad request', function(done){ request() .get('/markdown/get?id=null') .expectStatus(400) .end(done); }); it('should respond with #400 bad request', function(done){ request() .get('/markdown/get?id=5591c12') .expectStatus(400) .end(done); }); }); describe('when record does not exist', function(done) { it('should respond with #404 not found', function(done){ request() .get('/markdown/get?id=5591c1275ef8a0a917032fde') .expectStatus(404) .end(done); }); }); }); describe('/markdown/save', function(){ describe('when post with non-empty body text', function() { it('should respond #200 with json that has _id and html', function(done){ request() .post('/markdown/save') .header('Content-Type', 'text/plain;charset=UTF-8') .send('# will it work?') .expectStatus(200) .expect(function(res, body, next) { try { var _record = JSON.parse(body); expect(_record._id).to.be.defined; expect(_record._id.length).to.equal(24); expect(_record.html).to.equal('<h1>will it work?</h1>\n'); next(); } catch (e) { next(e); } }) .end(done); }); }); describe('when post with empty body text', function() { it('should respond #400 bad request', function(done) { request() .post('/markdown/save') .header('Content-Type', 'text/plain;charset=UTF-8') .send('') .expectStatus(400) .end(done); }); }); });
09fae618eb8e0744b272dd06656b9b242b096882
[ "JavaScript", "Markdown" ]
5
JavaScript
knicefire/test-task-markdown
270b8638527539ace70ed85d97068f4f504e03ec
a5af11539cc49ea4864c6f6ac3241f0db28e51c3
refs/heads/main
<file_sep>import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import axios from "axios"; // 引入全局的样式文件 import "./assets/css/global.less"; //引入字体文件 import "./assets/font/iconfont.css"; import SocketService from "@/utils/socket_service"; // 对服务端进行websocket的连接 SocketService.Instance.connect(); Vue.prototype.$socket = SocketService.Instance; //请求基准配置 axios.defaults.baseURL = "http://127.0.0.1:8888/api/"; //将axios挂载到vue原型对象上 Vue.prototype.$http = axios; Vue.config.productionTip = false; // 将全局echarts对象挂载到vue的原型对象上 Vue.prototype.$echarts = window.echarts; new Vue({ router, store, render: (h) => h(App), }).$mount("#app"); <file_sep>// 服务器入口文件 // 创建koa实例对象 const Koa = require("koa"); const app = new Koa(); // 绑定中间件 // 1.绑定第一层中间件 const respDurationMiddleware = require("./middleware/koa_response_duration"); app.use(respDurationMiddleware); // 2.绑定第二层中间件 const respHeaderMiddleware = require("./middleware/koa_response_header"); app.use(respHeaderMiddleware); // 3.绑定第二层中间件 const respDataMiddleware = require("./middleware/koa_response_data"); app.use(respDataMiddleware); // 绑定端口号 app.listen(8888); const webSocketService = require("./service/web_socket_service"); //开启服务端的监听,监听客户端的连接 webSocketService.listen();
6ce1197094adcb3f33416c9cf5e6343a7160f2f4
[ "JavaScript" ]
2
JavaScript
dyf-001/seller
08729315645a05374be982b3be6299a23911106a
140b31dc0fd695beecf0a2e34ff7f278551870ad
refs/heads/master
<repo_name>zenyat123/bases-de-datos<file_sep>/Entidad/Entidad.sql -- Created by Vertabelo (http://vertabelo.com) -- Last modification date: 2018-09-02 03:19:53.12 CREATE DATABASE Entidad; USE Entidad; -- Tables -- Table: empleado CREATE TABLE empleado ( id_empleado int(10) NOT NULL, nombres text NOT NULL, apellidos text NOT NULL, dependencia text NOT NULL, email text NOT NULL, password text NOT NULL, fecha_ingreso date NOT NULL, CONSTRAINT empleado_pk PRIMARY KEY (id_empleado) ); -- Table: persona CREATE TABLE persona ( id_persona int(10) NOT NULL, tipo_identificacion text NOT NULL, nombres text NOT NULL, apellidos text NOT NULL, direccion text NOT NULL, telefono text NOT NULL, email text NOT NULL, password text NOT NULL, CONSTRAINT persona_pk PRIMARY KEY (id_persona) ); -- Table: tema CREATE TABLE tema ( id_tema int(10) NOT NULL, tema text NOT NULL, CONSTRAINT tema_pk PRIMARY KEY (id_tema) ); -- Table: tramite CREATE TABLE tramite ( radicado int(10) NOT NULL, titulo text NOT NULL, estado text NOT NULL, fecha date NOT NULL, id_persona int(10) NOT NULL, id_empleado int(10) NOT NULL, id_tema int NOT NULL, CONSTRAINT tramite_pk PRIMARY KEY (radicado) ); -- Foreign keys -- Reference: tramite_empleado (table: tramite) ALTER TABLE tramite ADD CONSTRAINT tramite_empleado FOREIGN KEY tramite_empleado (id_empleado) REFERENCES empleado (id_empleado); -- Reference: tramite_persona (table: tramite) ALTER TABLE tramite ADD CONSTRAINT tramite_persona FOREIGN KEY tramite_persona (id_persona) REFERENCES persona (id_persona); -- Reference: tramite_tema (table: tramite) ALTER TABLE tramite ADD CONSTRAINT tramite_tema FOREIGN KEY tramite_tema (id_tema) REFERENCES tema (id_tema); -- -- Volcado de datos para la tabla `empleado` -- INSERT INTO `empleado` (`id_empleado`, `nombres`, `apellidos`, `dependencia`, `email`, `password`, `fecha_ingreso`) VALUES (1024515308, '<NAME>', '<NAME>', 'Tecnología', '<EMAIL>', '$1$rasmusle$Ci5J5DCNJRVQPQkSPsIpp/', '2019-02-14'), (1035412620, '<NAME>', '<NAME>', 'Tecnología', '<EMAIL>', '$1$rasmusle$Ci5J5DCNJRVQPQkSPsIpp/', '2019-02-14'); -- -- Volcado de datos para la tabla `persona` -- INSERT INTO `persona` (`id_persona`, `tipo_identificacion`, `nombres`, `apellidos`, `direccion`, `telefono`, `email`, `password`) VALUES (1364874526, 'Cédula de Ciudadanía', '<NAME>', '<NAME>', 'Diag. 23 # 42 - 13 Sur', '<PASSWORD>', '<EMAIL>', '$1$rasmusle$4rmJ4ydTlY/OSqcNgnJwY1'), (1514751489, 'Cédula de Ciudadanía', '<NAME>', '<NAME>', 'Cra 70 D # 45 - 12 Sur', '2145874', '<EMAIL>', '$1$rasmusle$4rmJ4ydTlY/OSqcNgnJwY1'); -- -- Volcado de datos para la tabla `tema` -- INSERT INTO `tema` (`id_tema`, `tema`) VALUES (1, 'Consulta'), (2, 'Facturación'), (3, 'Pago'), (4, 'Exportación'); -- -- Volcado de datos para la tabla `tramite` -- INSERT INTO `tramite` (`radicado`, `titulo`, `estado`, `fecha`, `id_persona`, `id_empleado`, `id_tema`) VALUES (200701, 'Licencia', 'Tramitado', '2007-01-01', 1514751489, 1024515308, 3); -- End of file.<file_sep>/api.sql -- -- Base de datos: `Api` -- CREATE DATABASE Api; USE Api; -- -------------------------------------------------------- -- -- Estructura de tabla `Dolar` -- CREATE TABLE `dolar` ( `id` int(10) NOT NULL AUTO_INCREMENT, `valor` int(10) NOT NULL, `fecha` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -------------------------------------------------------- -- -- Estructura de tabla `Euro` -- CREATE TABLE `euro` ( `id` int(10) NOT NULL AUTO_INCREMENT, `valor` int(10) NOT NULL, `fecha` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Índices para las tablas -- -- -- Indices de la tabla `Dolar` -- ALTER TABLE `dolar` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `Euro` -- ALTER TABLE `euro` ADD PRIMARY KEY (`id`); <file_sep>/usuarios.sql -- -- Base de datos: `Usuarios` -- CREATE DATABASE Usuarios; USE Usuarios; -- -------------------------------------------------------- -- -- Estructura de tabla `Usuario` -- CREATE TABLE `usuario` ( `documento` int(10) NOT NULL, `nombres` text COLLATE utf8_spanish_ci NOT NULL, `apellidos` text COLLATE utf8_spanish_ci NOT NULL, `telefono` text COLLATE utf8_spanish_ci NOT NULL, `celular` text COLLATE utf8_spanish_ci NOT NULL, `email` text COLLATE utf8_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Indices de la tabla `Usuario` -- ALTER TABLE `usuario` ADD PRIMARY KEY (`documento`); <file_sep>/Ventas/Ventas.sql CREATE TABLE `products` ( `id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, `product` text COLLATE utf8_spanish_ci NOT NULL, `price` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; CREATE TABLE `bills` ( `id` int(10) NOT NULL PRIMARY KEY, `bill_date` date NOT NULL, `id_user` int(10) NOT NULL, `names` text COLLATE utf8_spanish_ci NOT NULL, `address` text COLLATE utf8_spanish_ci NOT NULL, `subtotal` int(10) NOT NULL, `tax` int(10) NOT NULL, `discount` int(10) NOT NULL, `total` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; CREATE TABLE `sales` ( `id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, `id_bill` int(10) NOT NULL, `id_product` int(10) NOT NULL, `price` int(10) NOT NULL, `quantity` int(10) NOT NULL, `discount` int(10) NOT NULL, `subtotal` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; ALTER TABLE `sales` ADD KEY `bill` (`id_bill`), ADD KEY `product` (`id_product`); <file_sep>/README.md # Bases de Datos Bases de Datos <file_sep>/Educar/Educar.sql -- Created by Vertabelo (http://vertabelo.com) -- Last modification date: 2019-02-15 19:51:07.959 CREATE DATABASE Educar; USE Educar; -- Tables -- Table: clase CREATE TABLE clase ( id_clase int(10) NOT NULL AUTO_INCREMENT, id_materia int(10) NOT NULL, id_estudiante int(10) NOT NULL, CONSTRAINT clase_pk PRIMARY KEY (id_clase) ); -- Table: estudiante CREATE TABLE estudiante ( documento int(10) NOT NULL, nombres text NOT NULL, apellidos text NOT NULL, telefono text NOT NULL, email text NOT NULL, CONSTRAINT estudiante_pk PRIMARY KEY (documento) ); -- Table: materia CREATE TABLE materia ( id_materia int(10) NOT NULL AUTO_INCREMENT, materia text NOT NULL, profesion text NOT NULL, CONSTRAINT materia_pk PRIMARY KEY (id_materia) ); -- Foreign keys -- Reference: clase_estudiante (table: clase) ALTER TABLE clase ADD CONSTRAINT clase_estudiante FOREIGN KEY clase_estudiante (id_estudiante) REFERENCES estudiante (documento); -- Reference: clase_materia (table: clase) ALTER TABLE clase ADD CONSTRAINT clase_materia FOREIGN KEY clase_materia (id_materia) REFERENCES materia (id_materia); -- End of file.<file_sep>/Empleados/Empleados.sql CREATE TABLE `areas` ( `id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, `nombre` varchar(255) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; INSERT INTO `areas` (`id`, `nombre`) VALUES (1, 'Sistemas'), (2, 'Contabilidad'); CREATE TABLE `roles` ( `id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, `nombre` varchar(255) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; INSERT INTO `roles` (`id`, `nombre`) VALUES (1, 'Programador Web'), (2, 'Contaduría'); CREATE TABLE `empleados` ( `id` int(10) NOT NULL PRIMARY KEY, `nombre` varchar(255) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL, `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL, `sexo` char(1) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL, `area_id` int(10) NOT NULL, `boletin` tinyint(1) NOT NULL, `descripcion` text CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; INSERT INTO `empleados` (`id`, `nombre`, `email`, `sexo`, `area_id`, `boletin`, `descripcion`) VALUES (1, 'test', '<EMAIL>', 'F', 1, 1, 'test'), (2, 'test', '<EMAIL>', 'M', 1, 0, 'test'), (3, 'test', '<EMAIL>', 'F', 2, 1, 'test'); CREATE TABLE `empleado_rol` ( `empleado_id` int(10) NOT NULL, `rol_id` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
eae05287e8ba3accb55a8d87c6998644b0fce60a
[ "Markdown", "SQL" ]
7
SQL
zenyat123/bases-de-datos
df98c57cd5ebf21ff2343ab7a00e748c5b996236
3a17b7e32b1aa50ff1519283be237ce859bca2bc
refs/heads/main
<file_sep>--- title: "Modelo de predicción de popularidad de películas" author: "<NAME>" date: "20/11/2020" output: html_document: default pdf_document: default word_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(warning = FALSE) ``` # Objetivos * Limpieza de un set de datos y análisis de popularidad de películas a partir del siguiente dataset https://www.kaggle.com/tmdb/tmdb-movie-metadata * Obtención de un modelo de predicción que no utilice como predictoras variables relacionadas con la popularidad de manera tal de emular un sistema de predicción de popularidad de una película __antes de su lanzamiento__. Para ello solo se utilizaran las siguientes variables: + Presupuesto (Budget) + Idioma original + Actores principales, director, guionista principal, productor ejecutivo, principales compañías de producción. + Duración de la película + Géneros + Mes de lanzamiento * El script en su totalidad debe correr rápido (< 1hs) en una computadora promedio. ```{r, warning=FALSE} if (!require("pacman")) install.packages("pacman") library(pacman) pacman::p_load(ggplot2, plyr, data.table, readr, jsonlite, lubridate, DT, caret, odelr, ISLR, pROC, cowplot, OneR, rlang, caret, RColorBrewer, ggbiplot, GGally, purrr, tidyr, tidymodels, dplyr, DiceKriging, mlrMBO) require("lightgbm") #probablemente la instalación de lgbm deba hacerse de forma manual json_to_df <- function(df, column){ column_1 <- df[apply(df[,column],1,nchar)>2,] list_1 <- lapply(column_1[[column]], fromJSON) values <- data.frame(unlist(lapply(list_1, function(x) paste(x$name,collapse = ",")))) final_df <- cbind(column_1$id, column_1$title, values) names(final_df) <- c("id", "title", column) return(final_df) } setwd("~/MAESTRIA/movies") #directorio de trabajo - CAMBIAR EN CASO DE EJECUTAR EN OTRA COMPUTADORA #cargo datasets movies = read_csv("tmdb_5000_movies.csv") credits = read_csv("tmdb_5000_credits.csv") ``` --- ```{r, include=FALSE} #Eliminar este bloque si se ejecuta en otra computadora load("~/MAESTRIA/movies/todoenviroment.RData") ``` *** # Preprocesamiento ```{r } #observar datasets head(credits,10) head(movies,10) numericas = c("budget", "popularity", "vote_average", "vote_count", "revenue", "runtime" ) ggpairs(select(movies, numericas)) ``` ```{r,echo=FALSE } par(mfrow=c(2,3)) for( i in numericas){ boxplot(movies[,i], main = i) } ``` El pair plot de las variable snuméricas muestra una __alta correlación entre la recaudación, popularidad y cantidad de votos en TMDB__. Además como se observa en los boxplots el dataset posee ruido y un proceso de limpieza de outliers y corección de ceros y NAs puede mejorar la performance de un modelo de predicción. ### Limpieza de Outliers y tratamiento de nulos ```{r} #corrijo ceros en los datos donde no tiene sentido. movies$budget[movies$budget == 0] <- NA movies$revenue[movies$revenue == 0] <- NA movies$runtime[movies$runtime == 0] <- NA #guardo en dataset auxiliar para no sacarlo en el filtrado df_aux = filter(movies, is.na(budget) | is.na(revenue) | is.na(runtime) ) #Remuevo outliers (el criterio es arbritrario,utilizando +-3 rango intercuartilico) movies = na.omit(movies) %>% filter(revenue < quantile(revenue)[4]+3*IQR(revenue)) %>% filter(popularity < quantile(popularity)[4]+3*IQR(popularity)) %>% filter(vote_count < quantile(vote_count)[4]+3*IQR(vote_count) ) %>% filter(budget < quantile(budget)[4]+3*IQR(budget) ) %>% filter(runtime > quantile(runtime)[2]-3*IQR(runtime) & runtime < quantile(runtime)[4]+3*IQR(runtime) ) #vuelvo a unir con NA movies = rbind(movies, df_aux) ``` ### Extracción mes del campo de fecha Lógicamente, el mes es más importante en el estreno de una película que el día. El año no aporta información comparable entre películas. ```{r} movies$mes_lanzamiento = month(as.POSIXlt(movies$release_date, format="%Y-%m-%d")) #creo columna con el mes de lanzamiento numericas = c("budget", "popularity", "vote_average", "vote_count", "mes_lanzamiento", "revenue", "runtime" ) ``` ```{r } par(mfrow=c(3,3)) for( i in numericas){ boxplot(movies[,i], main = i) } ggpairs(select(movies, numericas)) ``` ### Tratamiento de las columnas en formato JSON Los datos provistos poseen varias __columnas en formato json__ que R interpreta como strings, deben ser extraidos con la libreria jsonlite y posteriormente una selección criterioza para no incrementar drásticamente el tamaño del dataset con variables innecesarias. ```{r} # Extracción de dos productoras productoras = separate(json_to_df(movies, "production_companies"), production_companies, c("productora_1", "productora_2"), sep = ",") productoras$movie_id = productoras$id productoras$id = NULL #Extraigo campo de directores de la columna crew directores_df= plyr::ldply(mapply(cbind, lapply(credits$crew, fromJSON), "movie_id"=credits$movie_id, SIMPLIFY=F), data.frame) directores_df = directores_df %>% filter( job %in% c("Director", "Executive Producer", "Screenplay")) %>% select(job, name, movie_id) %>% pivot_wider(id_cols = movie_id, names_from = job, values_from = name) #Me quedo solo con el 1er director, guionista y productor for(i in 1:nrow(directores_df)){ if(length(directores_df$Director[i][[1]]) > 1){ directores_df$Director[i][[1]] = directores_df$Director[i][[1]][1] } if(length(directores_df$`Executive Producer`[i][[1]]) > 1){ directores_df$`Executive Producer`[i][[1]] = directores_df$`Executive Producer`[i][[1]][1] } if(length(directores_df$Screenplay[i][[1]]) > 1){ directores_df$Screenplay[i][[1]] = directores_df$Screenplay[i][[1]][1] } } directores_df$movie_id = as.numeric(directores_df$movie_id) #Extraigo campo de actor de la columna cast actores_df = ldply(mapply(cbind, lapply(credits$cast, fromJSON), "movie_id"=credits$movie_id, SIMPLIFY=F), data.frame) actores_df$movie_id = as.numeric(actores_df$movie_id) #limpio actores_df = actores_df %>% filter(order %in% c(0,1,2)) %>% select(name, order, movie_id) %>% pivot_wider(id_cols = movie_id, names_from = order, values_from = name) #solo retengo 3 actores para facilitar costo computacional colnames(actores_df)[2:4] <- c("actor_1", "actor_2", "actor_3") #Generos generos = ldply(mapply(cbind, lapply(movies$genres, fromJSON), "movie_id"=movies$id, SIMPLIFY=F), data.frame) %>% mutate(value = 1) %>% spread(name, value, fill = 0 ) #one Hot Enconding generos$movie_id = as.numeric(generos$movie_id) generos$id = NULL colnames(generos[22]) = 'Otros' generos = generos %>% group_by(movie_id) %>% summarise_all(sum) #agrupamiento ``` ### Combinacion de todos los data.frames y limpieza final ```{r} #subset de Movies movies_df = select(movies, budget, original_language, status, mes_lanzamiento, revenue, title, id, popularity, runtime, vote_average, vote_count) movies_df$movie_id = movies_df$id movies_df$id = NULL dataset = list(movies_df, actores_df, directores_df, generos, productoras) %>% reduce(full_join, by = "movie_id") #join de todos #mas limpieza dataset = dplyr::rename(dataset, Otros = `<NA>`, titulo = title.x) dataset = dplyr::filter(dataset, status == "Released") dataset = dplyr::select(dataset, -c("status", "title.y")) #mas corrección dataset$actor_1 = as.factor(as.character(dataset$actor_1)) dataset$actor_2 = as.factor(as.character(dataset$actor_2)) dataset$actor_3 = as.factor(as.character(dataset$actor_3)) dataset$Director = as.factor(as.character(dataset$Director)) dataset$Screenplay = as.factor(as.character(dataset$Screenplay)) dataset$Producer = as.factor(as.character(dataset$`Executive Producer`)) dataset$`Executive Producer` = NULL dataset$original_language = as.factor(dataset$original_language) ``` *** # Modelo de predicción ### Modelo Lineal Multiple Un modelo muy simple pero rápido para evaluar importancia de variables. No permite el manejo de variables categóricas con alta cardinalidad como los campos de actores o directores, además la gran cantidad de variables reduce su significatividad estadística. El máximo R^2^ obtenido es de 0.34. ```{r} modelo_lineal = lm(popularity ~ budget + original_language + mes_lanzamiento + runtime + Action + Adventure + Animation + Comedy + Crime + Documentary + Drama + Family + Fantasy + Foreign + History + Horror + Music + Mystery + Romance + `Science Fiction` + Thriller + `TV Movie` + War + Western + Otros , data = dataset ) #reporto modelo summary(modelo_lineal) ``` ### Modelo de predicción LGBM __Light Gradient Boosting Machines (LGBM)__ es un algoritmo de creciente popularidad con una velocidad mucho mayor que otros algoritmos de gradient boosting como CatBoost o XGBOOST. A diferencia de otros métodos de partición como Random forest, permite trabajar con valores nulos y variables categóricas no encodeadas, por otra parte, al no ser un método lineal permite trabajar con variables correlacionadas como hay en este set de datos. ### Partición de los datos en entrenamiento, validación y test ```{r} #### Separacion en entrenamiento, validación y test # Partición Train y test, indicando proporción train_test <- initial_split(dataset, prop = 0.9) entrenamiento <- training(train_test) test <- testing(train_test) # Partición Train y validacion, indicando proporción train_test <- initial_split(entrenamiento, prop = 0.8) entrenamiento <- training(train_test) validacion <- testing(train_test) campos_buenos = setdiff( colnames(dataset) , c("vote_average","vote_count", "popularity", "titulo", "movie_id", "revenue") ) #dejo los datos en el formato que necesita LightGBM dBO_train <- lgb.Dataset( data = data.matrix(select(entrenamiento, all_of(campos_buenos))), label = entrenamiento$popularity, free_raw_data=F) dBO_test <- lgb.Dataset( data = data.matrix(select(validacion, all_of(campos_buenos))), label = validacion$popularity, free_raw_data=F) ``` ### Búsqueda de hyperparámetros con Optimización Bayesiana La optimización bayesiana funciona realizando la aproximación del modelo a un función matemática determinada, arroja mejores resultados que un método de random search manteniendo un balance de recursos en comparación con un grid search ```{r, eval=FALSE} #en este archivos queda el resultado kbayesiana <- paste0("./bayesiana_MOVIES", ".RDATA" ) kBO_iter <- 100 #cantidad de iteraciones categoricas = c("Director", "Screenplay", "original_language", "Producer", "productora_1", "productora_2", "actor_1", "actor_2", "actor_3") estimar_lightgbm <- function( x ){ set.seed( 36761116 ) # para que siempre me de el mismo resultado modelo <- lgb.train(data= dBO_train, objective= "regression", #eval= fganancia_logistic_lightgbm, #esta es la fuciona optimizar eval= c("rmse"), valids= list( valid= dBO_test), #metric= "rmse", boosting = "gbdt", num_iterations= 999999, early_stopping_rounds= as.integer(50 + 5/x$plearning_rate), learning_rate= x$plearning_rate, #min_data_in_leaf= as.integer(x$pmin_data_in_leaf), feature_fraction= x$pfeature_fraction, min_gain_to_split= x$pmin_gain_to_split, num_leaves= x$pnum_leaves, lambda_l1= x$plambda_l1, lambda_l2= x$plambda_l2, categorical_feature = categoricas, #feature_pre_filter=FALSE, #max_bin= 31, verbosity= -1, verbose= -1 ) nrounds_optimo <- modelo$best_iter pRMSE <- unlist(modelo$record_evals$valid$rmse$eval)[ nrounds_optimo ] attr(pRMSE ,"extras" ) <- list("pnum_iterations"= modelo$best_iter) #esta es la forma de devolver un parametro extra cat( pRMSE, " " ) return(pRMSE) } #------------------------------------------------------------------------------ configureMlr(show.learner.output = FALSE) funcion_optimizar <- estimar_lightgbm #configuro la busqueda bayesiana obj.fun <- makeSingleObjectiveFunction( name = "OptimBayesiana", fn = funcion_optimizar, minimize= TRUE, #quiero miminizar el error par.set = makeParamSet( makeIntegerParam("pnum_leaves", lower= 2L , upper= 2000L), makeNumericParam("pfeature_fraction", lower= 0.10 , upper= 1.0), makeNumericParam("pmin_gain_to_split",lower= 0.0 , upper= 50), makeNumericParam("plearning_rate", lower= 0.01 , upper= 0.1), makeNumericParam("plambda_l1", lower= 0.0 , upper= 10), #makeNumericParam("pmin_data_in_leaf", lower= 1, upper= 200 ), makeNumericParam("plambda_l2", lower= 0.0 , upper= 100) ), has.simple.signature = FALSE, noisy= TRUE ) ctrl <- makeMBOControl( save.on.disk.at.time = 600, save.file.path = kbayesiana ) ctrl <- setMBOControlTermination(ctrl, iters = kBO_iter ) ctrl <- setMBOControlInfill(ctrl, crit = makeMBOInfillCritEI()) surr.km <- makeLearner("regr.km", predict.type= "se", covtype= "matern3_2", control = list(trace = FALSE)) ###################### #Paso valores de la búsqueda bayesiana a hiperparámetros run <- mbo(obj.fun, learner = surr.km, control = ctrl) ``` ### Entrenamiento del modelo con los mejores hyperparametros hallados ```{r modelo train, eval=FALSE } info_bo <- as.data.frame(run$opt.path) setorder( info_bo , y) categoricas = c("Director", "Screenplay", "original_language", "Producer", "productora_1", "productora_2", "actor_1", "actor_2", "actor_3") modelo <- lgb.train( data= dBO_train, obj= "regression", metric = "rmse", boosting = "gbdt", #max_bin= 200, num_iterations= info_bo$pnum_iterations[1], learning_rate= info_bo$plearning_rate[1], feature_fraction= info_bo$pfeature_fraction[1], min_gain_to_split= info_bo$pmin_gain_to_split[1], num_leaves= info_bo$pnum_leaves[1], lambda_l1= info_bo$plambda_l1[1], lambda_l2= info_bo$plambda_l2[1], #min_data_in_leaf = info_bo$pmindata_in_leaf[1], categorical_feature = categoricas ) #PREDICCION EN VALIDACION ---------------------------------- prediccion <- predict(modelo, data.matrix(select(validacion, all_of(campos_buenos)))) #Paso resultado a dataframe -------------------------------------------------- resultado <- as.data.frame(cbind( "pelicula"= validacion$titulo, "recaudacion" = validacion$revenue, "real" = validacion$popularity, "prediccion" =prediccion) ) #corección de formato de datos (posible bug de R) resultado$recaudacion = as.numeric(resultado$recaudacion) resultado$real = as.numeric(resultado$real) resultado$prediccion = as.numeric(resultado$prediccion) melted = tidyr::pivot_longer(resultado, cols = 3:4, names_to ="tipo") %>% arrange(desc(value)) #pivot de la tabla melted$value = as.numeric(melted$value ) #corección de formato de datos (posible bug de R) ``` ### Graficos de performance en set de validacion El modelo muestra un buen ajuste de los datos predichos en el set de validación, con un valor mínimo de RMSE cercano a 14. Si los valores de popularidad predichos fuesen muy distintos, no debería haber ninguna correlación entre uno y otro y las curvas de distribución no deberían solaparse. ```{r} ggplot(info_bo, aes(x= exec.time, y = y)) + geom_line() + geom_smooth(method = lm) + labs(title ="Evolucion del RMSE con las sucesivas iteraciones", y = "RMSE: error medio cuadrático", x= " ") ### GRAFICOS ----------------------------------------------------------------------------------------------------- ggplot(melted, aes(x=pelicula, y= value, color = tipo))+ geom_point(alpha=0.5) + labs(title = "Popularidad de las peliculas", y="popularidad", x = "Película") + theme(axis.text.x = element_blank(), axis.text.y = element_blank()) ggplot(melted, aes(value, fill =tipo)) + geom_density(kernel = "gaussian", alpha = 0.5, color = NA) + labs(title = "Popularidad de las peliculas", y="frecuencia", x = "popularidad") + scale_x_continuous(trans = "sqrt") ggplot(resultado, aes(real, prediccion, size=recaudacion)) + labs(title = paste0("Predicción vs. valor real. r = ", cor(resultado$prediccion, resultado$real)), y="Predicción del modelo", x = "Popularidad real", legend ="Recaudación") + geom_point(alpha = 0.6, color= "limegreen") ``` ### Evaluación de dataset de test Dado que la optimización bayesiana determino los hyperparametros óptimos realizando predicciones sobre el dataset de validación, observar solamente la performance del modelo sobre el mismo dataset de validación podría llevar a una sobreestimación del modelo ya que se ignora la posibilidad de __overfitting__ . La predicción sobre el dataset reservado de test cuyos datos no han sido observados durante el entrenamiento permite un juicio con menor sesgo sobre el modelo realizado, no obstante no se observa una diferencia significativa en la calidad del modelo. ```{r, eval = FALSE} #PREDICCION EN TEST ---------------------------------- prediccion_test <- predict(modelo, data.matrix(select(test, all_of(campos_buenos)))) #Paso resultado a dataframe -------------------------------------------------- resultado_test <- as.data.frame(cbind( "pelicula"= test$titulo, "recaudacion" = test$revenue, "real" = test$popularity, "prediccion" =prediccion_test) ) #corección de formato de datos (posible bug de R) resultado_test$recaudacion = as.numeric(resultado_test$recaudacion) resultado_test$real = as.numeric(resultado_test$real) resultado_test$prediccion = as.numeric(resultado_test$prediccion) melted = tidyr::pivot_longer(resultado_test, cols = 3:4, names_to ="tipo") %>% arrange(desc(value)) #pivot de la tabla melted$value = as.numeric(melted$value ) #corección de formato de datos (posible bug de R) ``` ```{r} ### GRAFICOS ----------------------------------------------------------------------------------------------------- ggplot(melted, aes(x=pelicula, y= value, color = tipo))+ geom_point(alpha=0.5) + labs(title = "Popularidad de las peliculas", y="popularidad", x = "Película") + theme(axis.text.x = element_blank(), axis.text.y = element_blank()) ggplot(melted, aes(value, fill =tipo)) + geom_density(kernel = "gaussian", alpha = 0.5, color = NA) + labs(title = "Popularidad de las peliculas", y="frecuencia", x = "popularidad") + scale_x_continuous(trans = "sqrt") ggplot(resultado_test, aes(real, prediccion, size=recaudacion)) + labs(title = paste0("Predicción vs. valor real. r = ", cor(resultado_test$prediccion, resultado_test$real)), y="Predicción del modelo", x = "Popularidad real", legend ="Recaudación") + geom_point(alpha = 0.6, color= "limegreen") ``` *** # Conclusiones * Las variables que más se correlación con la popularidad de una película son la cantidad de votos y la recaudanción, no obstante, estas son variables no independientes de la popularidad y por lo tanto no pueden ser usadas para predecirla a priori de su lanzamiento. Las variable de presupuesto tiene una correlación moderada (cercana a 0.5). * Se puede realizar un modelo lineal múltiple parcialmente signifivativo pero sin un resultado óptimo (R^2^ = 0.34). No permite la introducción de variables categóricas con alta cardinalidad como actores, directores o compañías. * El modelo lgbm realizado arroja una predicción correlacionada con la popularidad real de la película solamente con datos previos a su lanzamiento. Sin embargo, se trata de un modelo perfectible que podría mejorar su performance en detrimento del tiempo de ejecución mediante: + Optimización Bayesiana prolongada o grid search de hyperparametros + Incremento del volumen de datos mediante la __API de TMDB__. + Utilización de k-fold cross validation en lugar de una partición simple. + Utilizar más variables cateogóricas, por ejemplo todo el elenco de la película. + Combinación con datos externos provenientes de redes sociales (Búsqueda en Google de una película o ranking de actores en IMDB, premios de los directores, etc. ) + La aplicación de técnicas de minería de texto como __association rules__ permitiría el análisis de datos no explotados como el resumen de la película. + __feature engeneering__ : corrección de presupuesto en función del año. Cruce de datos de fecha de lanzamiento con "fechas de estrenos" como cercanía a Navidad o vacaciones. + Otro algoritmo de gradient boosting como __XGBOOST__ <file_sep>--- layout: default --- ## Welcome to Pablo's portfolio _Soy un geologo devenido en aprendiz de ciencias de datos / I'm a geologist trying to be data scientist! _ <img src="https://raw.githubusercontent.com/pablofp92/pablofp92/main/polci.png" width="150" height="150" /> :argentina: Buenos Aires, Argentina. :blue_book: [linkedIn](https://www.linkedin.com/in/pablofprz/) :mailbox: __<EMAIL>__ ## Some R notebooks: ### TMDB 5000 Movie Dataset. Lgbm regression model to predict popularity relying on pre-release features (R) * [Movies lgbm regression model](movies_lgbm/Movies.html) ### Prostate cancer clasified models: SVM and Logistic regression (R) * [Prostate cancer clasification models](/prostate/prostate_cancer_models.md) ### Spotify unclasified models: k-means and hierarchical clustering (R) * [Spotify clustering](/clustering_spotify/clustering_spotify.html) ## Some python code: ### Dash (Python 3) * [Dashboard de incendios de la República Argentina](/incendios) * Puede visitarse en (https://dash-incendios.herokuapp.com/ ) no obstante Dash supera la cuota de memoria de heroku, por lo que puede no cargar correctamente. Para correr localmente descomentar las lineas 12 y 13 y comentar la 56 de app.py. <file_sep># -*- coding: utf-8 -*- """ Created on Sat Mar 13 16:53:26 2021 @author: pablo """ import pandas as pd import json import plotly.express as px #import plotly.io as pio #pio.renderers.default='browser' import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output ############# DASH dfprovinciascausas = pd.read_csv('incendios-cantidad-causas-provincia.csv', sep = ';', encoding='latin-1') dfsuperficieprovincias = pd.read_csv('superficie-incendiada-provincias-tipo-de-vegetacion.csv', sep = ';', encoding='latin-1') dfsuperficieprovincias = dfsuperficieprovincias.rename(columns = {'superficie_afectada_por_incendios_anio' : 'incendio_anio', 'superficie_afectada_por_incendios_provincia': 'incendio_provincia'} ) df = pd.merge(dfprovinciascausas, dfsuperficieprovincias, how='outer', on=['incendio_anio', 'incendio_provincia']) df = df.rename(columns = {'incendio_provincia' : 'Provincia'} ) with open('provincia.json', encoding='utf-8') as provincias: provincias_shape = json.load(provincias) YEARS = df.incendio_anio.unique() CAUSAS = {'Número total': 'incendio_total_numero', 'Negligencia': 'incendio_negligencia_numero', 'Intencional': 'incendio_intencional_numero', 'Natural': 'incendio_natural_numero', 'Desconocida': 'incendio_desconocida_numero', 'Superficie afectada en hectareas': 'superficie_afectada_por_incendios_total_hectareas', 'Superficie afectada (ha) en bosque nativo': 'superficie_afectada_por_incendios_bosque_nativo_hectareas', 'Superficie afectada (ha) en bosque cultivado': 'superficie_afectada_por_incendios_bosque_cultivado_hectareas', 'Superficie afectada (ha) en arbustales': 'superficie_afectada_por_incendios_arbustal_hectareas', 'Superficie afectada (ha) en pastizales': 'superficie_afectada_por_incendios_pastizal_hectareas', 'Superficie afectada (ha) en vegetación sin determinar': 'superficie_afectada_por_incendios_sin_determinar_hectareas' } external_stylesheets = [ { "href": "https://fonts.googleapis.com/css2?" "family=Lato:wght@400;700&display=swap", "rel": "stylesheet", }, ] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) server = app.server app.layout = html.Div( children =[ html.Div( children=[ html.H1(children= "Mapa de incendios de la República Argentina", className = "header-title"), html.P( children = " Se denomina Incendio forestal a cualquier fuego que se extiende sin control en terreno forestal afectando vegetación \ que no estaba destinada a arder. Datos del Ministerio de Ambiente y Desarrollo Sostenible. Dirección Nacional de Bosques. \ Seleccione año y tipo de incendio:", className ="header-description" ), ], className="header", ), html.Div( children=[ html.Div( children=[ html.Div(children="Años", className="menu-title"), dcc.Dropdown( id='select_anios', options=[{'label': k, 'value': k} for k in YEARS], value=YEARS[0], className ="dropdown", ), ] ), html.Div( children=[ html.Div(children="Representación", className="menu-title"), dcc.Dropdown( id='select_causa', options=[{'label': k, 'value': CAUSAS[k]} for k in CAUSAS], value='incendio_total_numero', className ="dropdown", ), ], ), ], className="menu", ), html.Div( children=[ html.Div( children= dcc.Graph( id="choropleth" ), className="card", ), ], className = "wrapper", ), html.Div( children=[ html.Footer( children ="Hecho por <NAME> https://pablofp92.github.io/data/ - https://linkedin.com/in/pablofprz", className = "footer" ), ], className = "footer", ), ] ) @app.callback( Output("choropleth", "figure"), [Input("select_anios", "value"), Input("select_causa", "value")]) def display_choropleth(anio, causa): data_select = df[df.incendio_anio == int(anio)] fig = px.choropleth( data_select, geojson=provincias_shape, color=str(causa), locations="Provincia", featureidkey="properties.nam", projection="mercator", scope = 'south america') fig.update_geos(fitbounds="locations", visible=False) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.update_layout(title=f"<b>{anio}</b>", title_x=0.5) return fig if __name__ == "__main__": app.run_server(debug=False) <file_sep>--- title: "Modelo de predicción de cáncer de prostata con regresión logística y Support Vector Machines" output: "prostatemodels" --- ```{r} #Chequea e instala paquetes if (!require("pacman")) install.packages("pacman") library(pacman) pacman::p_load(readxl, ggplot2, RColorBrewer, ggbiplot, GGally,dendextend, corrplot, gridExtra, plot3D, dplyr, tidyr, devtools, arules, caret, mvnormtest, heplots, mvnormtest, e1071, cluster, pracma, factoextra, NbClust) # carga manual de paquetes library(readxl) #lee xls como dataframe library(ggplot2) #paquete de graficos library(RColorBrewer) #complemento ggplot library(ggbiplot) #para graficar biplot library(GGally) #complemento ggplot library(dendextend) #complemento para graficar dendrograma library(corrplot) #para graficar matrices de correlacion library(gridExtra) #complemento ggplot library(plot3D) #graficos scatter 3D library(dplyr) #herramienta de manejo de datos library(tidyr) #herramienta de manejo de datos library(devtools) # herramientas estadísticas library(arules) # herramientas estadísticas library(caret) #herramientas de regresion y clasificacion library(mvnormtest) #test normalidad multivariada library(heplots) # herramientas estadísticas library(e1071) # herramientas estadísticas library(cluster) #paquete de clusters library(pracma) # herramientas estadísticas library(factoextra) # herramientas estadísticas library(NbClust) # tests de cantidad de clusters optimos ``` ```{r} ###### PRIMERA PARTE: clasificación supervisada ###### ###### Carga de datos ########### Alumno: <NAME> prostata_completo = read_xlsx('prostata.xlsx') dni=36761117 n=round(0.8* nrow(prostata_completo)) set.seed(dni); cuales= sample(1:nrow(prostata_completo), size=n, replace=FALSE) prostata = prostata_completo[cuales,] ``` ```{r} ######### preprocesamiento ######### #elimino NAs prostata = filter(prostata, !is.na(GLEASON)) #tratamiento de outliers prostata = filter(prostata, AGE>48, GLEASON>0) #pasa a factor las variables categóricas prostata$CAPSULE = as.factor(prostata$CAPSULE) prostata$RACE = as.factor(prostata$RACE) prostata$DPROS = as.factor(prostata$DPROS) prostata$DCAPS = as.factor(prostata$DCAPS) ``` ```{r} #### GRAFICOS EXPLORATORIOS ########## #Histogramas variables continuas h1 <- ggplot(prostata, aes(AGE, fill= CAPSULE)) + geom_histogram(binwidth = 4) + theme_minimal() + theme(legend.position = "top") h2 <- ggplot(prostata, aes(PSA, fill= CAPSULE)) + geom_histogram(binwidth = 4) + theme_minimal() + theme(legend.position = "none") h3 <- ggplot(prostata, aes(GLEASON, fill= CAPSULE)) + geom_histogram(binwidth = 1) + theme_minimal() + theme(legend.position = "none") grid.arrange(h1, h2, h3, nrow = 3) #Boxplots variables continuas b1<- ggplot(prostata, aes(x=CAPSULE, y=AGE, fill=CAPSULE)) + geom_boxplot() + coord_flip() + theme_minimal() + theme(axis.title.y = element_blank()) + theme(legend.position = "top") ylim2 = boxplot.stats(prostata$PSA)$stats[c(1, 5)] #mejoro visualizacion tapando outliers b2<- ggplot(prostata, aes(x=CAPSULE, y=PSA, fill=CAPSULE)) + geom_boxplot() + scale_y_continuous(limits = ylim2 * 1.5 ) + coord_flip() + theme_minimal() + theme(axis.title.y = element_blank()) + theme(legend.position = "none") b3<- ggplot(prostata, aes(x=CAPSULE, y=GLEASON, fill=CAPSULE)) + geom_boxplot() + coord_flip() + theme_minimal() + theme(axis.title.y = element_blank()) + theme(legend.position = "none") grid.arrange(b1, b2, b3, nrow = 3) #Gráficos de barra para variables categóricas d1 <- ggplot(prostata, aes(RACE, fill=CAPSULE)) + geom_bar(position="fill")+ theme_minimal() + scale_x_discrete(breaks = seq(2), labels= c("Blanca", "Negra")) + theme(axis.title.y = element_blank()) + theme(legend.position = "none") d2 <- ggplot(prostata, aes(factor(DCAPS), fill=CAPSULE)) + geom_bar(position="fill")+ theme_minimal() + scale_x_discrete(breaks = seq(2), labels= c("Sí", "No")) + labs(x= 'DCAPS') + theme(axis.title.y = element_blank()) + theme(legend.position = "none") d3 <- ggplot(prostata, aes(DPROS, fill=CAPSULE)) + geom_bar(position="fill")+ theme_minimal() + scale_x_discrete(breaks = seq(4), labels = c('No nódulo', 'Nod. izq.', 'Nod. derecha', 'Nod. ambos lados')) + theme(axis.title.y = element_blank()) + theme(legend.position = "bottom") grid.arrange(d1,d2, d3, layout_matrix = rbind(c(1,2),3)) ``` ```{r} ####### REGRESION LINEAL SOBRE LA VARIABLE VOL ########### prostata_vol = filter(prostata, VOL>0) prostata_no_vol = filter(prostata, VOL==0) prostata_no_vol$VOL = NA vol_lg <- lm(VOL ~ AGE + PSA + RACE + GLEASON + DCAPS + DPROS, data = prostata_vol) prostata_no_vol$VOL <- predict(vol_lg, prostata_no_vol ) prostata_no_vol$ORIGEN = 'predicho' prostata_vol$ORIGEN = 'real' prostata_vol = rbind(prostata_vol, prostata_no_vol ) prostata_vol= arrange(prostata_vol, VOL) ggplot(prostata_vol, aes(y= VOL, x=seq(1,length((prostata_vol$VOL))), colour=ORIGEN)) + geom_jitter() prostata = prostata_vol ``` ```{r} ######## TEST DE NORMALIDAD ###### #Separa las variables numéricas prostata_num = prostata[c(3,7,8,9)] mshapiro.test(t(prostata_num)) #rechaza test shapiro wilks multivariado #qqplots qq1<- ggplot(prostata) + geom_qq(aes(sample = AGE)) + geom_qq_line(aes(sample = AGE)) qq2<-ggplot(prostata) + geom_qq(aes(sample = PSA)) + geom_qq_line(aes(sample = PSA)) qq3<- ggplot(prostata) + geom_qq(aes(sample = GLEASON)) + geom_qq_line(aes(sample = GLEASON)) grid.arrange(qq1,qq2,qq3, layout_matrix = rbind(c(1,2),3)) ``` ```{r} ##### EVALUACION HOMOCEDASTICIDAD ######### M = cor(prostata_num) corrplot(M,method="number") #matriz de correlación para ambas clases capsule0 = filter(prostata, CAPSULE == 0) capsule1 = filter(prostata, CAPSULE == 1) corrplot(cor(capsule0[c(3,7,8,9)]),method="circle") corrplot(cor(capsule1[c(3,7,8,9)] ),method="circle") # test Levene leveneTests(prostata_num, prostata$CAPSULE, center = median) #rechaza en PSA ``` ```{r} boxM(prostata_num, prostata$CAPSULE) #rechaza test M Box ``` ```{r} # Componentes principales datos.pc = prcomp(prostata[c(3,7,8,9)] ,scale = T) prostata$PC = datos.pc$x[,1] prostata$PC2 = datos.pc$x[,2] #biplot ggbiplot(datos.pc, obs.scale=0.5 ,var.scale=1, alpha=0.5,groups=factor(prostata$CAPSULE)) + scale_color_manual(name="Rotura capsular (CAPSULE)", values=c("indianred2","deepskyblue3"),labels=c("0", "1")) + theme_minimal()+ theme(legend.direction ="horizontal", legend.position = "top") #Jitter plot entre la primera componente principal y DCAPS ggplot(prostata, aes(x = PC , y= DCAPS , colour =CAPSULE)) + geom_jitter()+ labs(x= 'PC1') + theme_minimal() ``` ```{r} ############ REGRESION LOGISTICA ########### #Separación en 5 k-folds set.seed(dni); #shuffle aleatorio rows <- sample(nrow(prostata)) prostata <- prostata[rows, ] test_folds = list() train_folds = list() for(i in 1:5){ test_folds[[i]] = slice(prostata, (1+(i*round(nrow(prostata)/5))-round(nrow(prostata)/5)):(i*round(nrow(prostata)/5))) train_folds[[i]] = anti_join(prostata, test_folds[[i]]) } ``` ```{r} # Evaluacion de modelos de regresion logística con distintas combinaciones de variables variables = c('AGE', 'DCAPS', 'DPROS', 'PSA', 'GLEASON', 'VOL', 'PC', 'PC2') lista_formulas = vector() for(k in 1:(length(variables)-1)){ combinaciones = combn(variables,k) for(i in 1:ncol(combinaciones)){ formula = paste0('CAPSULE ~ ', paste(combinaciones[,i], collapse = ' + ')) lista_formulas = c(lista_formulas, formula) }} #entrena varios modelos y reporto varias métricas modelos = data.frame() modelos_lg_kfolds = data.frame() for(v in 1:length(lista_formulas)){ for(i in 1:5){ modelo_lg <- glm(as.formula(lista_formulas[v]), data = train_folds[[i]], family=binomial) pred_lg_test <- predict(modelo_lg,test_folds[[i]],type = "response") clase_lg_test = ifelse(pred_lg_test>0.4,1,0) matrizconfusion = table(test_folds[[i]]$CAPSULE, clase_lg_test, dnn = c("Clase real","Clase predicha")) TN = round(matrizconfusion[1]) FN = round(matrizconfusion[2]) FP = round(matrizconfusion[3]) TP = round(matrizconfusion[4]) precision = TP/(TP + FP) recall = TP/(TP + FN) modelos[i,'TP'] = TP modelos[i,'FN'] = FN modelos[i,'TN'] = TN modelos[i,'FP'] = FP modelos[i,'tasa de error'] = (FN + FP)/nrow(test_folds[[i]])*100 modelos[i,'Precision'] = precision modelos[i,'Recall'] = recall modelos[i,'F1 score'] = 2*((precision*recall)/(precision+recall)) } modelos = summarise_all(modelos, .funs=mean) modelos_lg_kfolds = bind_rows(modelos_lg_kfolds, modelos) modelos_lg_kfolds[v,'formula'] = lista_formulas[v] } ``` ```{r} #Elección del modelo con menor error modelos = data.frame() for(i in 1:5){ modelo_lg <- glm(CAPSULE ~ DCAPS + DPROS + PSA + GLEASON, data = train_folds[[i]], family=binomial) pred_lg_test <- predict(modelo_lg,test_folds[[i]],type = "response") clase_lg_test = ifelse(pred_lg_test>(0.33),1,0) matrizconfusion = table(test_folds[[i]]$CAPSULE, clase_lg_test, dnn = c("Clase real","Clase predicha")) TN = round(matrizconfusion[1]) FN = round(matrizconfusion[2]) FP = round(matrizconfusion[3]) TP = round(matrizconfusion[4]) precision = TP/(TP + FP) recall = TP/(TP + FN) modelos[i,'TP'] = TP modelos[i,'FN'] = FN modelos[i,'TN'] = TN modelos[i,'FP'] = FP modelos[i,'tasa de error'] = (FN + FP)/nrow(test_folds[[i]])*100 modelos[i,'Precision'] = precision modelos[i,'Recall'] = recall modelos[i,'F1 score'] = 2*((precision*recall)/(precision+recall)) } modelos = summarise_all(modelos, .funs=mean) modelos[1:4] = round(modelos[1:4]) #Matriz de confusion Real <- factor(c(0, 0, 1, 1)) Prediccion <- factor(c(0, 1, 0, 1)) Freq <- c(modelos[,'TN'], modelos[,'FP'], modelos[,'FN'], modelos[,'TP']) matrizconfusion <- data.frame(Real, Prediccion, Freq) ggplot(data = matrizconfusion, mapping = aes(x = Real, y = Prediccion)) + geom_tile(aes(fill = Freq), colour = "white") + geom_text(aes(label = sprintf("%1.0f", Freq)), vjust = 1, size=6, colour = "white") + scale_fill_gradient(low = "dodgerblue1", high = "firebrick2") + theme_minimal() + theme(legend.position = "none") ``` ```{r} ############ SUPPORT VECTOR MACHINES ########### #configura random search fitControl <- trainControl(method = "cv", number = 10, search = "random") # Prueba diferentes funciones de Kernel para el SVM kernels = c('svmLinear2','svmLinearWeights','svmPoly','svmRadial') lista_modelos_svm = data.frame() lista_modelos_svm_kfolds = data.frame() for(k in 1:length(kernels)){ for(i in 1:5){ modelo_svm <- train(CAPSULE ~., data = train_folds[[i]], method = kernels[k], tuneLength = 10, trControl = fitControl, metric = "Accuracy") pred_svm=predict(modelo_svm, test_folds[[i]]) matrizconfusion = table(test_folds[[i]]$CAPSULE, pred_svm, dnn = c("Clase real", "Clase predicha")) error_svm<- mean(test_folds[[i]]$CAPSULE!= pred_svm) * 100 precision = matrizconfusion[4] / (matrizconfusion[4]+ matrizconfusion[3]) recall = matrizconfusion[4] / (matrizconfusion[4]+ matrizconfusion[2]) lista_modelos_svm[i,'kernel'] = kernels[k] lista_modelos_svm[i,'accuracy'] = modelo_svm$results[2] lista_modelos_svm[i,'tasa de error'] = error_svm lista_modelos_svm[i,'Precision'] = precision lista_modelos_svm[i,'Recall'] = recall lista_modelos_svm[i,'F1 score'] = 2*((precision*recall)/(precision+recall)) } lista_modelos_svm_kfolds = bind_rows(lista_modelos_svm_kfolds, lista_modelos_svm) lista_modelos_svms_kfolds = lista_modelos_svm %>% group_by(kernel[k]) %>% summarise_all(.funs = mean) } lista_modelos_svm_kfolds = lista_modelos_svm_kfolds %>% group_by(kernel) %>% summarise_all(.funs = mean) # elijo kernel Lineal # Con este kernel evalúo mejor combinacion de variables lista_modelos_svm = data.frame() lista_modelos_svm_kfolds = data.frame() for(v in 1:length(lista_formulas)){ for(i in 1:5){ modelo_svm <- train(as.formula(lista_formulas[v]), data = train_folds[[i]], method = 'svmLinear2', tuneLength = 10, trControl = fitControl, metric = "Accuracy") pred_svm=predict(modelo_svm, test_folds[[i]]) matrizconfusion = table(test_folds[[i]]$CAPSULE, pred_svm, dnn = c("Clase real", "Clase predicha")) error_svm<- mean(test_folds[[i]]$CAPSULE!= pred_svm) * 100 precision = matrizconfusion[4] / (matrizconfusion[4]+ matrizconfusion[3]) recall = matrizconfusion[4] / (matrizconfusion[4]+ matrizconfusion[2]) lista_modelos_svm[i,'formula'] = lista_formulas[v] lista_modelos_svm[i,'tasa de error'] = error_svm lista_modelos_svm[i,'Precision'] = precision lista_modelos_svm[i,'Recall'] = recall lista_modelos_svm[i,'F1 score'] = 2*((precision*recall)/(precision+recall)) } lista_modelos_svm_kfolds = bind_rows(lista_modelos_svm_kfolds, lista_modelos_svm) lista_modelos_svm_kfolds = lista_modelos_svm_kfolds %>% group_by(formula) %>% summarise_all(.funs = mean) } ``` ```{r} #Vuelvo a entrenar el modelo buscando más hiperparámetros lista_modelos_svm = data.frame() lista_modelos_svm_kfolds = data.frame() for(i in 1:5){ modelo_svm <- train(CAPSULE ~ DPROS + DCAPS + GLEASON +PSA , data = train_folds[[i]], method = 'svmLinear2', tuneLength = 100, trControl = fitControl, metric = "Accuracy") pred_svm=predict(modelo_svm, test_folds[[i]]) matrizconfusion = table(test_folds[[i]]$CAPSULE, pred_svm, dnn = c("Clase real", "Clase predicha")) TN = round(matrizconfusion[1]) FN = round(matrizconfusion[2]) FP = round(matrizconfusion[3]) TP = round(matrizconfusion[4]) precision = TP/(TP + FP) recall = TP/(TP + FN) lista_modelos_svm[i,'TP'] = TP lista_modelos_svm[i,'FN'] = FN lista_modelos_svm[i,'TN'] = TN lista_modelos_svm[i,'FP'] = FP lista_modelos_svm[i,'tasa de error'] = (FN + FP)/nrow(test_folds[[i]])*100 lista_modelos_svm[i,'Precision'] = precision lista_modelos_svm[i,'Recall'] = recall lista_modelos_svm[i,'F1 score'] = 2*((precision*recall)/(precision+recall)) } lista_modelos_svm_kfolds = lista_modelos_svm %>% summarise_all(.funs = mean) #Matriz de confusion SVM Real <- factor(c(0, 0, 1, 1)) Prediccion <- factor(c(0, 1, 0, 1)) Freq <- c(lista_modelos_svm_kfolds[1,'TN'], lista_modelos_svm_kfolds[1,'FP'], lista_modelos_svm_kfolds[1,'FN'], lista_modelos_svm_kfolds[1,'TP']) matrizconfusion_svm <- data.frame(Real,Prediccion, Freq) ggplot(data = matrizconfusion_svm, mapping = aes(x = Real, y = Prediccion)) + geom_tile(aes(fill = Freq), colour = "white") + geom_text(aes(label = sprintf("%1.0f", Freq)), vjust = 1, size=6, colour = "white") + scale_fill_gradient(low = "dodgerblue1", high = "firebrick2") + theme_minimal() + theme(legend.position = "none") ``` ```{r} #Jitter plot para comparar modelos prostata$capsule_lg = as.factor(ifelse(predict(modelo_lg, prostata, type='response')>0.33,1,0)) prostata$capsule_svm = as.factor(predict(modelo_svm, prostata)) prostata_grafico = dplyr::select(prostata, CAPSULE, PC, PC2) prostata_grafico$tipo = 'Real' prostata_lg = dplyr::select(prostata, capsule_lg, PC, PC2) prostata_lg$CAPSULE = prostata_lg$capsule_lg prostata_lg$tipo = 'Regresion logistica' prostata_svm = dplyr::select(prostata, capsule_svm, PC, PC2) prostata_svm$CAPSULE = prostata_svm$capsule_svm prostata_svm$tipo = 'SVM' prostata_grafico = bind_rows(prostata_grafico, prostata_lg, prostata_svm) ggplot(prostata_grafico, aes(x = PC, y= tipo , colour = CAPSULE)) + geom_jitter(height =0.3 , width = 0, alpha = 0.6)+ labs(x= 'PC 1', y='Modelo') + coord_flip() + theme_minimal() + theme(legend.position = "top") + theme(axis.text.y = element_text(angle = 90, vjust=1, hjust=0.5)) + theme(axis.text.x=element_text(size=12, face='bold')) ``` <file_sep>--- title: "Metodos de clusterización para features de alto nivel de Spotify" output: html_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(warning = FALSE) ``` ```{r} #Chequea e instala paquetes if (!require("pacman")) install.packages("pacman") library(pacman) pacman::p_load(readxl, ggplot2, RColorBrewer, ggbiplot, GGally,dendextend, corrplot, gridExtra, plot3D, dplyr, tidyr, devtools, arules, caret, mvnormtest, heplots, mvnormtest, e1071, cluster, pracma, factoextra, NbClust) # carga manual de paquetes library(readxl) #lee xls como dataframe library(ggplot2) #paquete de graficos library(RColorBrewer) #complemento ggplot library(ggbiplot) #para graficar biplot library(GGally) #complemento ggplot library(dendextend) #complemento para graficar dendrograma library(corrplot) #para graficar matrices de correlacion library(gridExtra) #complemento ggplot library(plot3D) #graficos scatter 3D library(dplyr) #herramienta de manejo de datos library(tidyr) #herramienta de manejo de datos library(devtools) # herramientas estadísticas library(arules) # herramientas estadísticas library(caret) #herramientas de regresion y clasificacion library(mvnormtest) #test normalidad multivariada library(heplots) # herramientas estadísticas library(e1071) # herramientas estadísticas library(cluster) #paquete de clusters library(pracma) # herramientas estadísticas library(factoextra) # herramientas estadísticas library(NbClust) # tests de cantidad de clusters optimos library(ape) ``` ```{r} ####################################### clasificación no supervisada ################################################ ######## Carga de datos ########### spotify_completo = read_xlsx('spotify.xlsx') n=round(0.7* nrow(spotify_completo)) set.seed(36761117); cuales= sample(1:nrow(spotify_completo), size=n, replace=FALSE) spotify = spotify_completo[cuales,] ``` ```{r ##### pre-procesamiento ####} #conversion genero a factors spotify$genre = as.factor(spotify$genre) #eliminacion de algunos outliers spotify = filter(spotify, duration_ms < 900000, speechiness < 0.60) # Escalado de los datos numericos spotify_num = data.frame(scale(spotify[-c(1)])) #Alternativa, escalado robusto #spotify_num = data.frame(scale(spotify[-c(1)], center=apply(spotify[-c(1)],2, "median"), scale=apply(spotify[-c(1)],2, "IQR"))) ``` ```{r # Scatter plots exploratorio } funcionscatter <- function(data,mapping, ...){ x <- GGally::eval_data_col(data, mapping$x) y <- GGally::eval_data_col(data, mapping$y) df <- data.frame(x = x, y = y) pp <- ggplot(df, aes(x=x, y=y, color = spotify$genre)) + ggplot2::geom_point(shape=16, show.legend = T, size= 1.5, alpha = 0.6) + guides(color = guide_legend(override.aes = list(size = 4))) + ggplot2::scale_alpha(range = c(0.05, 0.6)) + ggplot2::labs(colour = "Genre") + theme_minimal() + theme(legend.position = "bottom", legend.key.size = unit(5,"point")) return(pp) } leyenda = grab_legend(funcionscatter(spotify, aes(popularity, tempo, color = genre)) ) #completo ggpairs(spotify, columns = c(2:9), lower = list(continuous = funcionscatter), axisLabels = "none", legend = leyenda, upper = "blank") + theme_minimal() + theme(legend.position = "bottom") #resumido ggpairs(spotify, columns = c(2,3,4), lower = list(continuous = funcionscatter), axisLabels = "none", legend = leyenda, upper = "blank") + theme_minimal() + theme(legend.position = "bottom") ``` ```{r ###### Componentes principales ####### } datos.pc = prcomp(spotify_num,scale = T) spotify_componentes = data.frame(datos.pc$x) #biplot coloreado con generos musicales ggbiplot(datos.pc, obs.scale=1 , alpha=0.5, labels.size= 4, varname.adjust=1.5, groups = as.factor(spotify$genre), ellipse = F, var.axes= T, circle = F, varname.abbrev= F ) + theme_minimal() #biplot coloreado con genero y popularidad ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify$genre), alpha = 0.4, size = spotify$popularity/15 ) + labs(color = 'Generos') + guides(color = guide_legend(override.aes = list(size = 4))) + scale_color_manual(values = colorRampPalette(brewer.pal(8, "Set1"))(13)) + theme_minimal() + theme(legend.position = 'bottom') #biplot coloreado con variable numérica valence ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify_num$valence, size = spotify$popularity/15 ),alpha = 0.4) + scale_color_gradient(low="limegreen", high="red") + theme_minimal() + theme(legend.position = 'bottom') #biplot coloreado con variable numérica liveness ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify_num$liveness, size = spotify$popularity/15 ),alpha = 0.4) + scale_color_gradient(low="yellow2", high="red") + theme_minimal() + theme(legend.position = 'bottom') #biplot coloreado con variable numérica acousticness ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify_num$acousticness, size = spotify$popularity/15 ),alpha = 0.4) + scale_color_gradient(low="cyan", high="red") + theme_minimal() + theme(legend.position = 'bottom') #biplot coloreado con variable numérica energy ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify_num$energy, size = spotify$popularity/15 ),alpha = 0.4) + scale_color_gradient(low="slateblue2", high="red") + theme_minimal() + theme(legend.position = 'bottom') #biplot coloreado con variable numérica speechiness ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify_num$speechiness, size = spotify$popularity/15 ),alpha = 0.4) + scale_color_gradient(low="grey62", high="red") + theme_minimal() + theme(legend.position = 'bottom') #biplot coloreado con variable numérica speechiness ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify_num$danceability, size = spotify$popularity/15 ),alpha = 0.4) + scale_color_gradient(low="grey62", high="dodgerblue4") + theme_minimal() + theme(legend.position = 'bottom') ``` ```{r} ####### EVALUACION NUMERO OPTIMO DE CLUSTERS ##### optimo <- NbClust(spotify_num, distance='euclidean', max.nc=9, method="kmeans") table(optimo$Best.nc[1,]) barplot(table(optimo$Best.nc[1,]), xlab="Clusters", ylab="Criterios", main="Numero de clusters por criterio") # SSW fviz_nbclust(spotify_num, kmeans, method = "wss") + geom_vline(xintercept = 4, linetype = 2)+ labs(subtitle = "Elbow method") # Silhouette fviz_nbclust(spotify_num, kmeans, method = "silhouette")+ labs(subtitle = "Silhouette method") # Gap set.seed(36761117) fviz_nbclust(spotify_num, kmeans, nstart = 25, method = "gap_stat", nboot = 50)+ labs(subtitle = "Gap statistic method") ``` ```{r ########## KMEANS #######} set.seed(3676117) CL = kmeans(spotify_num,4,nstart=25,iter.max = 100) spotify_kmeans = spotify spotify_kmeans$kmeans = as.factor(CL$cluster) ``` ```{r PLOTS KMEANS} # Visualizacion en biplot ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify_kmeans$kmeans), alpha = 0.4, size = spotify_kmeans$popularity/15 ) + labs(color = 'Clusters') + guides(color = guide_legend(override.aes = list(size = 4))) + scale_color_manual(values =c("dodgerblue2", "deeppink2", "orangered2", "springgreen4")) + theme_minimal() + theme(legend.position = 'bottom') #Visualización como clusplot clusplot(spotify_num, spotify_kmeans$kmeans, color=TRUE, shade=TRUE, labels=8) #Visualización 3 componentes principales scatter3D(x=datos.pc$x[,1], y=datos.pc$x[,2], z=datos.pc$x[,3], colvar=as.integer(spotify_kmeans$kmeans), bty = "g", pch = 20, cex = 1,theta = 140, phi = 30, xlab = "pc1", ylab ="pc2", zlab = "pc3", labels = c("1", "2", "3", "4")) # Que variables representa cada cluster (K-MEANS) spotify_kmeans %>% group_by(kmeans) %>% summarise(Acustico = mean(acousticness), Volumen = mean(loudness), Danza = mean(danceability), Energia = mean(energy), Publico = mean(liveness), Palabras = mean(speechiness), Popularidad = mean(popularity), Tempo = mean(tempo), Positividad = mean(valence)) %>% dplyr::select(kmeans, Acustico, Volumen, Danza, Energia, Publico, Palabras, Popularidad, Positividad, Tempo) %>% gather("Name","Value",-kmeans) %>% ggplot(aes(y=Value,x = kmeans,col=Name,group = Name)) + geom_point()+ geom_line()+ facet_wrap(~Name,scales = "free_y")+ scale_color_brewer(palette = "Paired")+ theme_minimal()+ theme(legend.position = "none") + labs(x="Cluster",col = "Variable",title = "Variables para cada cluster") # cluster y generos ggplot(spotify_kmeans, aes(kmeans, genre, color=kmeans)) + geom_jitter(width = 0.2, height = 0.1, alpha = 0.3, size = 2) + scale_color_manual(values =c("dodgerblue2", "deeppink2", "orangered2", "springgreen4")) + theme_minimal() + theme(legend.position = 'none') ``` ```{r ######## CLUSTER JERARQUICO #########} #Comparación de coeficientes cofenéticos distancias = c("euclidean", "manhattan", "minkowski") metodos = c("ward.D2", "single", "complete", "average", "median", "centroid") for( i in 1:length(distancias)){ matdist <- dist(x = spotify_num, method = distancias[i]) for(j in 1:length(metodos)){ hc = hclust(d = matdist, method= metodos[j]) cofenetico = cor(x = matdist, cophenetic(hc)) print(c(distancias[i],metodos[j],cofenetico)) } } ``` ```{r} mat_dist <- dist(x = spotify_num, method = "euclidean") # Dendrogramas (según el tipo de segmentación jerárquica aplicada) #hc_complete <- hclust(d = mat_dist, method = "complete") #hc_average <- hclust(d = mat_dist, method = "average") #hc_single <- hclust(d = mat_dist, method = "single") hc_ward <- hclust(d = mat_dist, method = "ward.D2") # Finalmente decido método de Ward ``` ```{r} #Elección de 4 clusters grupos = cutree(hc_ward,k=4) spotify$clusters = as.factor(grupos) # construccion de un dendograma, se prueba con diferentes k y algoritmos plot(hc_ward) rect.hclust(hc_ward, k=4, border="red") #Dendograma circular spotify$genre_n = as.numeric(as.factor(spotify$genre)) plot(ape::as.phylo(hc_ward), type = "fan", tip.color = as.integer(spotify$clusters), label.offset = 1, cex = 0.7) ``` ```{r PLOTS CLUSTERIZACION JERARQUICA} ggplot(spotify, aes(clusters, genre, color=genre)) + geom_jitter(width = 0.2, height = 0.1, alpha = 0.5, size = 2) + theme_minimal() # Visualizacion en biplot ggplot(spotify_componentes, aes(x= PC1, y=PC2)) + geom_point(aes(color=spotify$clusters), alpha = 0.4, size = spotify$popularity/15 ) + labs(color = 'Clusters') + guides(color = guide_legend(override.aes = list(size = 4))) + scale_color_manual(values =c("orangered2", "deeppink2", "dodgerblue2", "springgreen4"), labels = c("A", "B", "C", "D")) + theme_minimal() + theme(legend.position = 'bottom') # Que variables representa cada cluster (WARD) spotify %>% group_by(clusters) %>% summarise(Acustico = mean(acousticness), Volumen = mean(loudness), Danza = mean(danceability), Energia = mean(energy), Publico = mean(liveness), Palabras = mean(speechiness), Popularidad = mean(popularity), Tempo = mean(tempo), Positividad = mean(valence)) %>% dplyr::select(clusters, Acustico, Volumen, Danza, Energia, Publico, Palabras, Popularidad, Positividad, Tempo) %>% gather("Name","Value",-clusters) %>% ggplot(aes(y=Value,x = clusters,col=Name,group = Name)) + scale_x_discrete(labels = c("A", "B", "C", "D")) + geom_point()+ geom_line()+ facet_wrap(~Name,scales = "free_y")+ scale_color_brewer(palette = "Paired")+ theme_minimal()+ theme(legend.position = "none") + labs(x="Cluster",col = "Variable") # genero en cada cluster ggplot(spotify, aes(clusters, genre, color=clusters)) + geom_jitter(width = 0.2, height = 0.1, alpha = 0.3, size = 2) + scale_x_discrete(labels = c("A", "B", "C", "D")) + scale_color_manual(values =c("orangered2", "deeppink2", "dodgerblue2", "springgreen4")) + theme_minimal() + theme(legend.position = 'none') ``` ```{r} #### CLUSTERIZACION JERARQUICA SOBRE GENERO spotify_var = spotify[-c(2,5,7)] %>% group_by(genre) %>% summarise_if(is.numeric, .funs = c('media' = mean, 'var' = var)) spotify_var[-1] = scale(spotify_var[-1]) mat_dist_generos <- dist(x = spotify_var[-1], method = "euclidean") hc_generos <- hclust(d = mat_dist_generos, method = "ward.D") hc_generos$labels = spotify_var$genre dend = as.dendrogram(hc_generos) dend %>% set("labels_cex", 1.2) %>% set("labels_col", value = c("orangered2", "deeppink2", "dodgerblue2", "orange2", "springgreen4"), k=5) %>% plot abline(h = 5, lty = 2) ``` <file_sep>dash==1.19.0 pandas==1.1.3 gunicorn==20.0.4 plotly==4.14.3
31c5af5de8feeb11357dab08e85b47be7356e35a
[ "Markdown", "Python", "Text", "RMarkdown" ]
6
RMarkdown
pablofp92/pablofp92.github.io
aa16677f8abc94cd448d4c73c5aeb1f3de4ac53e
7aeb9b49e8c03f53c67fff0b36a9076caa93da6a
refs/heads/master
<file_sep>def dot(x, y): s = 0 for i in xrange(len(x)): s += x[i] * y[i] return s n = 10000000 x = [0] * n y = [0] * n <file_sep># JuliaTokyo3LT JuliaTokyo #3 の発表資料とサンプルコードです。 JupyterのNoteboo.ipynbで実行もできます。 スライド: http://www.slideshare.net/KentaSato/whats-wrong-47403774 <file_sep>class: center, middle # What's wrong with this <img src="julia.png" style="height: 250px;"> <NAME> (佐藤建太) Twitter/GitHub: @bicycle1885 <img src="./X2e2PWfr.jpeg" style="height: 70px;"> --- layout: true ### A Sad Story <ul style="list-style-type: none; padding-left: 5px;"> <li> 😆 Is Julia as fast as C/C++? Where is the download link!? </li> <li> 😊 Oh, the syntax looks really neat! </li> <li> 😃 Ok, it works. Now let's compare it with my Python script. </li> <li> 😥 Huh? not so fast as he said, maybe comparable with Python? </li> <li> 😒 Julia? Yes, I tried it last month but blahblah... </li> </ul> --- --- Prob(their code does something wrong | newbies complain about performance) > 0.95 We are going to learn very basic skills to write (nearly) optimal Julia code from three cases. --- layout: true ### Case 1 --- .columns[ <div> .code-wrap[ .watermark.top[Julia 😣] ```julia s = 0 n = 50000000 for i in 1:n s += i end println(s) ``` ] .code-wrap.plain[ ``` $ time julia case1.jl real 0m9.859s ... ``` ] </div> <div> .code-wrap[ .watermark.top[Python 😆] ```python s = 0 n = 50000000 for i in xrange(1, n + 1): s += i print(s) ``` ] .code-wrap.plain[ ``` $ time python case1.py real 0m5.998s ... ``` ] </div> ] <p style="margin: -20px;"> <img src="images/case1.png" style="height: 220px;"> Is Julia slower than Python? Really?? </p> --- layout: true ### Case 1 .keypoint[**Do Not Write a Heavy Loop at the Top Level!**] * The top-level code is interpreted, not compiled. * Top level is not intended to run numeric computation. * Should be written in a `function`/`let` block. --- .columns[ <div> .code-wrap[ .watermark.top[Julia 😣] ```julia s = 0 n = 50000000 for i in 1:n s += i end println(s) ``` .code-wrap.plain[ ``` $ time julia case1.jl real 0m9.859s ... ``` ] ] </div> <div> .code-wrap[ .watermark.top[Julia 😃] ```julia *let s = 0 n = 50000000 for i in 1:n s += i end println(s) *end ``` ] .code-wrap.plain[ ``` $ time julia case1.fix.jl real 0m0.494s ... ``` ] </div> ] --- <img src="images/case1.fix.png"> 9.859s / 0.494s = 20x faster --- layout: true ### Case 2 --- .columns[ <div> .code-wrap[ .watermark.top[Julia 😣] ```julia function dot(x, y) s = 0 for i in 1:length(x) s += x[i] * y[i] end s end n = 10000000 x = zeros(n) y = zeros(n) dot(x[1:3], y[1:3]) # compile ``` ] .code-wrap.plain[ ``` $ julia -L case2.jl -e '@time dot(x, y)' elapsed time: 0.814667538 seconds (320013880 bytes allocated, 17.52% gc time) ``` ] </div> <div> .code-wrap[ .watermark.top[Python 😏] ```python def dot(x, y): s = 0 for i in xrange(len(x)): s += x[i] * y[i] return s n = 10000000 x = [0] * n y = [0] * n ``` ] .code-wrap.plain[ ``` % timeit dot(x, y) 1 loops, best of 3: 1.1 s per loop ``` ] </div> ] <p style="margin: -20px;"> <img src="images/case2.png" style="height: 180px;"> </p> --- .keypoint[**Make Variable Types Stable!**] * Literal `0` is typed as `Int`. * Hence Julia assumes the type of the variable `s` is `Int`. * The element type of `x` and `y` is `Float64`. * In Julia, `Int + Float64 * Float64` is `Float64`. * `s += x[i] * y[i]` disturbs the type stability of `s`. .column-left[ .code-wrap[ .watermark.top[Julia 😣] ```julia function dot(x, y) * s = 0 for i in 1:length(x) s += x[i] * y[i] end s end ... ``` ]] .column-right[ .code-wrap[ .watermark.top[Julia 😊] ```julia function dot(x, y) * s = zero(eltype(x)) for i in 1:length(x) s += x[i] * y[i] end s end ... ``` ]] --- * Type stability of variables dramatically improves the performance. <img src="images/case2.fix.png" style="height: 250px;"> * Much less memory allocation and GC time .code-wrap.plain[ ``` $ julia -L case2.jl -e '@time dot(x, y)' elapsed time: 0.814667538 seconds (320013880 bytes allocated, 17.52% gc time) ``` ``` $ julia -L case2.fix.jl -e '@time dot(x, y)' elapsed time: 0.017035491 seconds (13896 bytes allocated) ``` ] 0.814667538s / 0.017035491s = 48x faster --- * The emitted LLVM code is cleaner when types are stable. .columns[ <div> <figure> <img src="images/case2.llvm.png" style="height: 350px;"> <caption>Type-unstable code</caption> </figure> </div> <div> <figure> <img src="images/case2.llvm.fix.png", style="height: 350px;"> <caption>Type-stable code</caption> </figure> </div> ] --- layout: true ### Case 3 --- .columns[ <div> .code-wrap[ .watermark.top[Julia 😭] ```julia ... function optimize(x0, n_iter) η = 0.1 x = copy(x0) g = zeros(length(x0)) for i in 1:n_iter grad!(g, x) x -= η * g end x end ``` ] </div> <div> .code-wrap[ .watermark.top[Python 😜] ```python ... def optimize(x0, n_iter): eta = 0.1 x = np.copy(x0) g = np.zeros(len(x0)) for i in xrange(n_iter): set_grad(g, x) x -= eta * g return x ``` </div> ] ] <p style="margin: -20px;"> <img src="images/case3.png" style="height: 250px;"> </p> --- .keypoint[**`-=` for array types is not an in-place operator!**] * `x -= η * g` works like: * `y = η * g`: product * `z = x - y`: subtract * `x = z`: bind * For each iteration: * Create two arrays (`y` and `z`) and * Discard two arrays (`x` and `y`) * Lots of memories are wasted! * 53% of time is consumed in GC! ``` $ julia -L case3.jl -e '@time optimize(x0, 50000)' elapsed time: 0.527045846 seconds (812429992 bytes allocated, 53.60% gc time) ``` --- .columns[ <div> .code-wrap[ .watermark.top[Julia 😭] ```julia ... function optimize(x0, n_iter) ... for i in 1:n_iter grad!(g, x) * x -= η * g end x end ``` ] </div> <div> .code-wrap[ .watermark.top[Julia 😝] ```julia ... function optimize(x0, n_iter) ... for i in 1:n_iter grad!(g, x) * for j in 1:n * x[j] -= η * g[j] * end end x end ``` ] </div> ] <p style="margin: -20px;"> <img src="images/case3.fix.png" style="height: 240px;"> </p> --- .columns[ <div> .code-wrap[ .watermark.top[Julia 😝] ```julia ... function optimize(x0, n_iter) ... for i in 1:n_iter grad!(g, x) * for j in 1:n * x[j] -= η * g[j] * end end x end ``` ] </div> <div> .code-wrap[ .watermark.top[Julia 😍] ```julia ... function optimize(x0, n_iter) ... for i in 1:n_iter grad!(g, x) * BLAS.scal!(n, η, g, 1) end x end ``` ] </div> ] <p style="margin: -20px;"> <img src="images/case3.blas.png" style="height: 240px;"> </p> --- layout: false ## Take-home Points * Julia is definitely fast unless you do it wrong. * You should know what code is *smooth* in Julia. * [Manual/Performance Tips](http://julia.readthedocs.org/en/release-0.3/manual/performance-tips/) is a definitive guide to know the smoothness of Julia. * Utilize standard tools to analyze bottlenecks: * `@time` macro * `@profile` macro * `--track-allocation` option * `@code_typed`/`@code_lowered`/`@code_llvm`/`@code_native` macros (from higher level to lower) * `@code_warntype` (v0.4) <file_sep>import numpy as np def set_grad(g, x): pass def optimize(x0, n_iter): eta = 0.1 x = np.copy(x0) g = np.zeros(len(x0)) for i in xrange(n_iter): set_grad(g, x) x -= eta * g return x <file_sep>s = 0 n = 50000000 for i in xrange(1, n + 1): s += i print(s)
3c6279856cccc7e41281db5d093c9e0b9ecaf34f
[ "Markdown", "Python" ]
5
Python
bicycle1885/JuliaTokyo3LT
8a35d3490b9b65fc99e2b1c63577737c63023db8
dcb37772296bc0380f352a0be3e8424c88f933cf
refs/heads/master
<repo_name>michaelwheatman/PasswordGeneration<file_sep>/pcfgc.c #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <string.h> #include <assert.h> #include "hash.h" /*#define NDEBUG*/ #define MAX_LENGTH 32 #define N_LETTERS 26 #define N_DIGITS 10 #define N_SYMBOLS 33 #define PRINT_DEBUG #define IS_UPPER 'U' #define IS_LOWER 'L' #define IS_DIGIT 'D' #define IS_SYMBOL 'S' typedef struct { char szNonTerminals[2*MAX_LENGTH+1]; double dPercentage; } PwdStructure; extern void BuildPassword(char *szPwd, int xPwd, char *szSyntax, int nGrams, int NChars, int nModReduce, int *pxLetterSingle, double *pdLetterSingle, int *pxStartLetterCombo, double *pdStartLetterCombo, int (*paxStateLetterCombo)[N_LETTERS], double (*padStateLetterCombo)[N_LETTERS], int *pxStartDigit, double *pdStartDigit, int (*paxStateDigit)[N_DIGITS], double (*padStateDigit)[N_DIGITS], int *pxStartSymbol, double *pdStartSymbol, int (*paxStateSymbol)[N_SYMBOLS], double (*padStateSymbol)[N_SYMBOLS], char *szSymbols, double dProbSoFar, double dThresholdP, HashTable *phtPasswords, int *pnBillions, int *pnGuesses); void AddLetters(int nLetters, int xState, char *szCase, char *szPwd, int xPwd, char *szSyntax, int nGrams, int NChars, int nModReduce, int *pxLetterSingle, double *pdLetterSingle, int *pxStartLetterCombo, double *pdStartLetterCombo, int (*paxStateLetterCombo)[N_LETTERS], double (*padStateLetterCombo)[N_LETTERS], int *pxStartDigit, double *pdStartDigit, int (*paxStateDigit)[N_DIGITS], double (*padStateDigit)[N_DIGITS], int *pxStartSymbol, double *pdStartSymbol, int (*paxStateSymbol)[N_SYMBOLS], double (*padStateSymbol)[N_SYMBOLS], char *szSymbols, double dProbSoFar, double dThresholdP, HashTable *phtPasswords, int *pnBillions, int *pnGuesses) { int i, iLetter, xPreState; #ifdef PRINT_DEBUG printf("Pwd = %.*s\n", xPwd, szPwd); #endif if ( nLetters <= 0 ) { BuildPassword(szPwd, xPwd, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar, dThresholdP, phtPasswords, pnBillions, pnGuesses); } else { xPreState = (xState % nModReduce) * N_LETTERS; for ( i = 0; i < N_LETTERS; ++i ) { iLetter = paxStateLetterCombo[xState][i]; if ( dProbSoFar * padStateLetterCombo[xState][iLetter] < dThresholdP ) break; szPwd[xPwd] = iLetter + ((*szCase == IS_UPPER) ? 'A' : 'a'); AddLetters(nLetters-1, xPreState + iLetter, szCase+1, szPwd, xPwd+1, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar * padStateLetterCombo[xState][iLetter], dThresholdP, phtPasswords, pnBillions, pnGuesses); } } } void AddSingleLetter(int nLetters, char *szCase, char *szPwd, int xPwd, char *szSyntax, int nGrams, int NChars, int nModReduce, int *pxLetterSingle, double *pdLetterSingle, int *pxStartLetterCombo, double *pdStartLetterCombo, int (*paxStateLetterCombo)[N_LETTERS], double (*padStateLetterCombo)[N_LETTERS], int *pxStartDigit, double *pdStartDigit, int (*paxStateDigit)[N_DIGITS], double (*padStateDigit)[N_DIGITS], int *pxStartSymbol, double *pdStartSymbol, int (*paxStateSymbol)[N_SYMBOLS], double (*padStateSymbol)[N_SYMBOLS], char *szSymbols, double dProbSoFar, double dThresholdP, HashTable *phtPasswords, int *pnBillions, int *pnGuesses) { int i, iLetter; #ifdef PRINT_DEBUG printf("Pwd = %.*s\n", xPwd, szPwd); #endif if ( nLetters <= 0 ) { BuildPassword(szPwd, xPwd, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar, dThresholdP, phtPasswords, pnBillions, pnGuesses); } else { for ( i = 0; i < N_LETTERS; ++i ) { iLetter = pxLetterSingle[i]; if ( dProbSoFar * pdLetterSingle[iLetter] < dThresholdP ) break; szPwd[xPwd] = iLetter + ((*szCase == IS_UPPER) ? 'A' : 'a'); AddSingleLetter(nLetters-1, szCase+1, szPwd, xPwd+1, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar * pdLetterSingle[iLetter], dThresholdP, phtPasswords, pnBillions, pnGuesses); } } } void AddSymbols(int nSymbols, int xState, char *szPwd, int xPwd, char *szSyntax, int nGrams, int NChars, int nModReduce, int *pxLetterSingle, double *pdLetterSingle, int *pxStartLetterCombo, double *pdStartLetterCombo, int (*paxStateLetterCombo)[N_LETTERS], double (*padStateLetterCombo)[N_LETTERS], int *pxStartDigit, double *pdStartDigit, int (*paxStateDigit)[N_DIGITS], double (*padStateDigit)[N_DIGITS], int *pxStartSymbol, double *pdStartSymbol, int (*paxStateSymbol)[N_SYMBOLS], double (*padStateSymbol)[N_SYMBOLS], char *szSymbols, double dProbSoFar, double dThresholdP, HashTable *phtPasswords, int *pnBillions, int *pnGuesses) { int i, iSymbol; #ifdef PRINT_DEBUG printf("Pwd = %.*s\n", xPwd, szPwd); #endif if ( nSymbols <= 0 ) { BuildPassword(szPwd, xPwd, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar, dThresholdP, phtPasswords, pnBillions, pnGuesses); } else { for ( i = 0; i < N_SYMBOLS; ++i ) { iSymbol = paxStateSymbol[xState][i]; if ( dProbSoFar * padStateSymbol[xState][iSymbol] < dThresholdP ) break; szPwd[xPwd] = szSymbols[iSymbol]; AddSymbols(nSymbols-1, iSymbol, szPwd, xPwd+1, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar * padStateSymbol[xState][iSymbol], dThresholdP, phtPasswords, pnBillions, pnGuesses); } } } void AddDigits(int nDigits, int xState, char *szPwd, int xPwd, char *szSyntax, int nGrams, int NChars, int nModReduce, int *pxLetterSingle, double *pdLetterSingle, int *pxStartLetterCombo, double *pdStartLetterCombo, int (*paxStateLetterCombo)[N_LETTERS], double (*padStateLetterCombo)[N_LETTERS], int *pxStartDigit, double *pdStartDigit, int (*paxStateDigit)[N_DIGITS], double (*padStateDigit)[N_DIGITS], int *pxStartSymbol, double *pdStartSymbol, int (*paxStateSymbol)[N_SYMBOLS], double (*padStateSymbol)[N_SYMBOLS], char *szSymbols, double dProbSoFar, double dThresholdP, HashTable *phtPasswords, int *pnBillions, int *pnGuesses) { int i, iDigit; #ifdef PRINT_DEBUG printf("Pwd = %.*s\n", xPwd, szPwd); #endif if ( nDigits <= 0 ) { BuildPassword(szPwd, xPwd, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar, dThresholdP, phtPasswords, pnBillions, pnGuesses); } else { for ( i = 0; i < N_DIGITS; ++i ) { iDigit = paxStateDigit[xState][i]; if ( dProbSoFar * padStateDigit[xState][iDigit] < dThresholdP ) break; szPwd[xPwd] = iDigit + '0'; AddDigits(nDigits-1, iDigit, szPwd, xPwd+1, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar * padStateDigit[xState][iDigit], dThresholdP, phtPasswords, pnBillions, pnGuesses); } } } int globintProcessor = 'a'; void BuildPassword(char *szPwd, int xPwd, char *szSyntax, int nGrams, int NChars, int nModReduce, int *pxLetterSingle, double *pdLetterSingle, int *pxStartLetterCombo, double *pdStartLetterCombo, int (*paxStateLetterCombo)[N_LETTERS], double (*padStateLetterCombo)[N_LETTERS], int *pxStartDigit, double *pdStartDigit, int (*paxStateDigit)[N_DIGITS], double (*padStateDigit)[N_DIGITS], int *pxStartSymbol, double *pdStartSymbol, int (*paxStateSymbol)[N_SYMBOLS], double (*padStateSymbol)[N_SYMBOLS], char *szSymbols, double dProbSoFar, double dThresholdP, HashTable *phtPasswords, int *pnBillions, int *pnGuesses) { int xClass, nChars, i, iChar; char szClass[MAX_LENGTH+1]; if ( !*szSyntax ) { if ( ++*pnGuesses == 1000000000 ) { ++*pnBillions; *pnGuesses = 0; } szPwd[xPwd] = '\0'; #ifdef PRINT_DEBUG printf("Guessing %s\n", szPwd); #endif if ( DeleteHashElement(phtPasswords, szPwd) ) { printf( "%c\t%d.%09d\t%s\t%.3lf\n", globintProcessor, *pnBillions, *pnGuesses, szPwd, 1e-9/dProbSoFar ); fflush(stdout); #ifdef PRINT_DEBUG getchar(); #endif } } else { #ifdef PRINT_DEBUG printf("Pwd = %s\tSyntax = %s\n", szPwd, szSyntax); #endif xClass = 0; do { szClass[xClass++] = *szSyntax++; for ( nChars = 0; isdigit((int)*szSyntax); ++szSyntax ) { nChars = nChars * 10 + (*szSyntax - '0'); } for ( i = 1; i < nChars; ++i, ++xClass ) { szClass[xClass] = szClass[xClass-1]; } } while ( (szClass[xClass-1] == IS_UPPER && *szSyntax == IS_LOWER) || (szClass[xClass-1] == IS_LOWER && *szSyntax == IS_UPPER) ); szClass[xClass] = '\0'; switch ( szClass[0] ) { case IS_DIGIT: for ( i = 0; i < N_DIGITS; ++i ) { iChar = pxStartDigit[i]; if ( dProbSoFar * pdStartDigit[iChar] < dThresholdP ) break; szPwd[xPwd] = iChar + '0'; AddDigits(xClass-1, iChar, szPwd, xPwd+1, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar * pdStartDigit[iChar], dThresholdP, phtPasswords, pnBillions, pnGuesses); } break; case IS_SYMBOL: for ( i = 0; i < N_SYMBOLS; ++i ) { iChar = pxStartSymbol[i]; if ( dProbSoFar * pdStartSymbol[iChar] < dThresholdP ) break; szPwd[xPwd] = szSymbols[iChar]; AddSymbols(xClass-1, iChar, szPwd, xPwd+1, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar * pdStartSymbol[iChar], dThresholdP, phtPasswords, pnBillions, pnGuesses); } break; case IS_UPPER: case IS_LOWER: if ( xClass < nGrams ) { AddSingleLetter(xClass, szClass, szPwd, xPwd, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar, dThresholdP, phtPasswords, pnBillions, pnGuesses); } else { for ( i = 0; i < NChars; ++i ) { iChar = pxStartLetterCombo[i]; if ( dProbSoFar * pdStartLetterCombo[iChar] < dThresholdP ) break; switch ( nGrams ) { case 1: szPwd[xPwd] = iChar + ((szClass[0] == IS_UPPER) ? 'A' : 'a'); break; case 2: szPwd[xPwd] = (iChar / N_LETTERS) + ((szClass[0] == IS_UPPER) ? 'A' : 'a'); szPwd[xPwd+1] = (iChar % N_LETTERS) + ((szClass[1] == IS_UPPER) ? 'A' : 'a'); break; case 3: szPwd[xPwd] = (iChar / (N_LETTERS * N_LETTERS)) + ((szClass[0] == IS_UPPER) ? 'A' : 'a'); szPwd[xPwd+1] = ((iChar / N_LETTERS) % N_LETTERS) + ((szClass[1] == IS_UPPER) ? 'A' : 'a'); szPwd[xPwd+2] = (iChar % N_LETTERS) + ((szClass[2] == IS_UPPER) ? 'A' : 'a'); break; default: return; } AddLetters(xClass-nGrams, iChar, szClass+nGrams, szPwd, xPwd+nGrams, szSyntax, nGrams, NChars, nModReduce, pxLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, pxStartDigit, pdStartDigit, paxStateDigit, padStateDigit, pxStartSymbol, pdStartSymbol, paxStateSymbol, padStateSymbol, szSymbols, dProbSoFar * pdStartLetterCombo[iChar], dThresholdP, phtPasswords, pnBillions, pnGuesses); } } break; default: printf( "Unexpected token %c in grammatical structure!!!\n", szClass[0]); break; } } } double *globpdSortMeUsingIndex; int SortDoubleDescendingUsingIndex(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return (globpdSortMeUsingIndex[x] > globpdSortMeUsingIndex[y]) ? -1 : (globpdSortMeUsingIndex[x] != globpdSortMeUsingIndex[y]); } PwdStructure **globppStructures; int SortStructureDescendingIndirectUsingIndex(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return (globppStructures[x]->dPercentage > globppStructures[y]->dPercentage) ? -1 : (globppStructures[x]->dPercentage != globppStructures[y]->dPercentage); } void ThresholdGuessing(FILE *fp, int nGrams, int NChars, int nModReduce, HashTable *phtGrammar, double *pdLetterSingle, double *pdStartLetterCombo, double (*padStateLetterCombo)[N_LETTERS], double *pdStartDigit, double (*padStateDigit)[N_DIGITS], double *pdStartSymbol, double (*padStateSymbol)[N_SYMBOLS], char *szSymbols, double dThresholdP) { char szBuf[2048]; unsigned b; int nBillions = 0, nGuesses = 0, xGrammar, i, j, iPwdLen, jStart, jEnd, nStructures; int *pxSyntax; int *pxStartLetterCombo, (*paxStateLetterCombo)[N_LETTERS], axLetterSingle[N_LETTERS]; int axStartDigit[N_DIGITS], aaxStateDigit[N_DIGITS][N_DIGITS]; int axStartSymbol[N_SYMBOLS], aaxStateSymbol[N_SYMBOLS][N_SYMBOLS]; HashTable *phtPasswords = CreateHashTable(5000011, 1+MAX_LENGTH); HashTable_Element *pEl; double dCumProb; // Store passwords to crack in hash table while ( fgets(szBuf, sizeof(szBuf), fp) ) { iPwdLen = strlen(szBuf) - 1; if ( iPwdLen <= MAX_LENGTH ) { szBuf[iPwdLen] = '\0'; InsertHashTable(phtPasswords, szBuf); } } // Grab memory for indexing pxStartLetterCombo = (int *)malloc(NChars * sizeof(pxStartLetterCombo[0])); paxStateLetterCombo = (int (*)[26])malloc(NChars * sizeof(paxStateLetterCombo[0])); // Build indexing arrays and sort ... // ... letters first for ( i = 0; i < NChars; ++i ) { pxStartLetterCombo[i] = i; for ( j = 0; j < N_LETTERS; ++j ) { paxStateLetterCombo[i][j] = j; } globpdSortMeUsingIndex = padStateLetterCombo[i]; qsort(paxStateLetterCombo[i], N_LETTERS, sizeof(paxStateLetterCombo[i][0]), SortDoubleDescendingUsingIndex); } globpdSortMeUsingIndex = pdStartLetterCombo; qsort(pxStartLetterCombo, NChars, sizeof(pxStartLetterCombo[0]), SortDoubleDescendingUsingIndex); #ifdef PRINT_DEBUG printf("Most common starting nGram is %c (%.6lf)\n", pxStartLetterCombo[0] + 'a', pdStartLetterCombo[pxStartLetterCombo[0]]); #endif // ... digits next for ( i = 0; i < N_DIGITS; ++i ) { axStartDigit[i] = i; for ( j = 0; j < N_DIGITS; ++j ) { aaxStateDigit[i][j] = j; } globpdSortMeUsingIndex = padStateDigit[i]; qsort(aaxStateDigit[i], N_DIGITS, sizeof(aaxStateDigit[i][0]), SortDoubleDescendingUsingIndex); } globpdSortMeUsingIndex = pdStartDigit; qsort(axStartDigit, N_DIGITS, sizeof(axStartDigit[0]), SortDoubleDescendingUsingIndex); #ifdef PRINT_DEBUG printf("Most common starting digit is %c (%.6lf)\n", axStartDigit[0] + '0', pdStartDigit[axStartDigit[0]]); #endif // ... then symbols for ( i = 0; i < N_SYMBOLS; ++i ) { axStartSymbol[i] = i; for ( j = 0; j < N_SYMBOLS; ++j ) { aaxStateSymbol[i][j] = j; } globpdSortMeUsingIndex = padStateSymbol[i]; qsort(aaxStateSymbol[i], N_SYMBOLS, sizeof(aaxStateSymbol[i][0]), SortDoubleDescendingUsingIndex); } globpdSortMeUsingIndex = pdStartSymbol; qsort(axStartSymbol, N_SYMBOLS, sizeof(axStartSymbol[0]), SortDoubleDescendingUsingIndex); #ifdef PRINT_DEBUG printf("Most common starting symbol is %c (%.6lf)\n", szSymbols[axStartSymbol[0]], pdStartSymbol[axStartSymbol[0]]); #endif // ... single letters last for ( i = 0; i < N_LETTERS; ++i ) { axLetterSingle[i] = i; } globpdSortMeUsingIndex = pdLetterSingle; qsort(axLetterSingle, N_LETTERS, sizeof(axLetterSingle[0]), SortDoubleDescendingUsingIndex); #ifdef PRINT_DEBUG printf("Most common single letter is %c (%.6lf)\n", axLetterSingle[0] + ' ', pdLetterSingle[axLetterSingle[0]]); #endif // Get the grammatical structures into an array for sorting pxSyntax = (int *)malloc(phtGrammar->uCount * sizeof(pxSyntax[0])); globppStructures = (PwdStructure **)malloc(phtGrammar->uCount * sizeof(globppStructures[0])); for ( nStructures = b = 0; b < phtGrammar->nBuckets; ++b ) { for ( pEl = phtGrammar->ppChain[b]; pEl != NULL; pEl = pEl->pNext ) { globppStructures[nStructures] = (PwdStructure *)pEl->pData; pxSyntax[nStructures] = nStructures; ++nStructures; } } #ifdef PRINT_DEBUG printf("nStructures = %d ; uCount = %d\n", nStructures, phtGrammar->uCount); #endif qsort(pxSyntax, nStructures, sizeof(pxSyntax[0]), SortStructureDescendingIndirectUsingIndex); #ifdef PRINT_DEBUG printf("Most common structure is %s (%.6lf)\n", globppStructures[pxSyntax[0]]->szNonTerminals, globppStructures[pxSyntax[0]]->dPercentage); #endif // Split the load across 10 different processors #ifdef PRINT_DEBUG jStart = jEnd = 0; dCumProb = 1.0; #else for ( dCumProb = 0.0, j = jStart = jEnd = 0; j < nStructures; ++j ) { dCumProb += globppStructures[pxSyntax[j]]->dPercentage; if ( dCumProb > 0.10 ) { jEnd = j+1; if ( !fork() ) break; jStart = jEnd; dCumProb = 0.0; ++globintProcessor; } } #endif if ( jStart == jEnd ) { jEnd = nStructures; } //printf( "%c - %d to %d - %.4lf\n", globintProcessor, jStart, jEnd-1, dCumProb ); return; for ( j = jStart; j < jEnd; ++j ) { xGrammar = pxSyntax[j]; if ( globppStructures[xGrammar]->dPercentage < dThresholdP ) break; BuildPassword(szBuf, 0, globppStructures[xGrammar]->szNonTerminals, nGrams, NChars, nModReduce, axLetterSingle, pdLetterSingle, pxStartLetterCombo, pdStartLetterCombo, paxStateLetterCombo, padStateLetterCombo, axStartDigit, pdStartDigit, aaxStateDigit, padStateDigit, axStartSymbol, pdStartSymbol, aaxStateSymbol, padStateSymbol, szSymbols, globppStructures[xGrammar]->dPercentage, dThresholdP, phtPasswords, &nBillions, &nGuesses); } DestroyHashTable(phtPasswords); free(pxStartLetterCombo); free(paxStateLetterCombo); free(pxSyntax); free(globppStructures); } double mcProbDigits(char *szSeq, double *pdProbStart, double (*padProbTransition)[N_DIGITS]) { int i, chPrev, chNext; double dP; if ( !szSeq[0] ) return 1.0; chPrev = szSeq[0] - '0'; dP = pdProbStart[chPrev]; for ( i = 1; szSeq[i]; ++i ) { chNext = szSeq[i] - '0'; dP *= padProbTransition[chPrev][chNext]; chPrev = chNext; } return dP; } double mcProbSymbols(char *szSeq, double *pdProbStart, double (*padProbTransition)[N_SYMBOLS], char *szSymbols) { int i, chPrev, chNext; char *pChar; double dP; if ( !szSeq[0] ) return 1.0; pChar = strchr(szSymbols, szSeq[0]); assert( pChar != NULL ); chPrev = pChar - szSymbols; dP = pdProbStart[chPrev]; for ( i = 1; szSeq[i]; ++i ) { pChar = strchr(szSymbols, szSeq[i]); assert ( pChar != NULL ); chNext = pChar - szSymbols; dP *= padProbTransition[chPrev][chNext]; chPrev = chNext; } return dP; } double mcProbLetters(char *szSeq, int nGrams, int nModReduce, double *pdProbStart, double (*padProbTransition)[N_LETTERS], double *pdProbSingle) { int i, ch, xNgram; double dP = 1.0; for ( i = xNgram = 0; i < nGrams && szSeq[i]; ++i ) { ch = szSeq[i]; ch = tolower(ch) - 'a'; dP *= pdProbSingle[ch]; xNgram *= N_LETTERS; xNgram += ch; } if ( i < nGrams ) return dP; for ( dP = pdProbStart[xNgram]; szSeq[i]; ++i ) { ch = szSeq[i]; ch = tolower(ch) - 'a'; dP *= padProbTransition[xNgram][ch]; xNgram %= nModReduce; xNgram *= N_LETTERS; xNgram += ch; } return dP; } double GuessNumber(char *szPwd, int nGrams, int nModReduce, double *pdStartLetterProb, double (*padNextLetterProb)[N_LETTERS], double *pdSingleLetterProb, double *pdStartDigitProb, double (*padNextDigitProb)[N_DIGITS], double *pdStartSymbolProb, double (*padNextSymbolProb)[N_SYMBOLS], char *szSymbols, HashTable *phtGrammar, double dTotalGrammars ) { char szTemp[MAX_LENGTH+1], *pSym; int i, xLetter1, xDigit1, xSymbol1, nExactSame, nSameClass, iLast, iThis, ch; double dTemp, dNGuesses; PwdStructure syntax, *pSyntax; dNGuesses = 1e-9; /* measure in billions */ for ( iThis = xLetter1 = xDigit1 = xSymbol1 = -1, i = 0; szPwd[i] >= ' '; ++i ) { ch = szPwd[i]; iLast = iThis; if ( isupper(ch) ) iThis = IS_UPPER; else if ( islower(ch) ) iThis = IS_LOWER; else if ( isdigit(ch) ) iThis = IS_DIGIT; else iThis = IS_SYMBOL; if ( i ) { if ( iLast == iThis ) { ++nSameClass; ++nExactSame; } else { sprintf(szTemp, "%c%d", iLast, nExactSame); strcat(syntax.szNonTerminals, szTemp); nExactSame = 1; if ( !( (iLast == IS_LOWER && iThis == IS_UPPER) || (iLast == IS_UPPER && iThis == IS_LOWER) ) ) { memcpy(szTemp, szPwd+i-nSameClass, nSameClass); szTemp[nSameClass] = '\0'; if ( iLast == IS_SYMBOL ) { dNGuesses /= mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols)); #endif } else if ( iLast == IS_DIGIT ) { dNGuesses /= mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb)); #endif } else { dNGuesses /= mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb)); #endif } nSameClass = 1; } else { ++nSameClass; } } } else { syntax.szNonTerminals[0] = '\0'; nSameClass = 1; nExactSame = 1; } if ( isalpha(ch) && xLetter1 < 0 ) xLetter1 = i; /* Begin new letter chain */ else if ( !isalpha(ch) ) xLetter1 = -1; /* Halt letter chain */ if ( isdigit(ch) && xDigit1 < 0 ) xDigit1 = i; /* Begin new digit chain */ else if ( !isdigit(ch) ) xDigit1 = -1; /* Halt digit chain */ pSym = strchr(szSymbols, ch); if ( pSym != NULL && xSymbol1 < 0 ) xSymbol1 = i; /* Begin new symbol chain */ else if ( pSym == NULL ) xSymbol1 = -1; /* Halt symbol chain */ } sprintf(szTemp, "%c%d", iThis, nExactSame); strcat(syntax.szNonTerminals, szTemp); memcpy(szTemp, szPwd+i-nSameClass, nSameClass); szTemp[nSameClass] = '\0'; if ( iThis == IS_SYMBOL ) { dNGuesses /= mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols)); #endif } else if ( iThis == IS_DIGIT ) { dNGuesses /= mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb)); #endif } else { dNGuesses /= mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb)); #endif } pSyntax = LookupHashTable(phtGrammar, syntax.szNonTerminals); dTemp = (pSyntax == NULL) ? 1.0/dTotalGrammars : pSyntax->dPercentage; /* probability of choosing this structure */ dNGuesses /= dTemp; #ifdef PRINT_DEBUG printf("p(%s) = %lf\n", syntax.szNonTerminals, dTemp); #endif return dNGuesses; } int main(int argc, char **argv) { char szBuf[2048], szSymbols[N_SYMBOLS+2]; int iMakeGuesses = 0; int nGrams, i, j, xFile, NLetters, xRow, NModReduce, nPwdChars, xState, nPCFG; double dTemp, dTotalLetters = 0, dTotalDigits = 0, dTotalSymbols = 0, dTotalGrammars = 0, dNGuesses; double *pdLetterPrefix, *pdLetterStart, (*padLetters)[N_LETTERS], *pdDigitPrefix, *pdDigitStart, (*padDigits)[N_DIGITS], *pdSymbolPrefix, *pdSymbolStart, (*padSymbols)[N_SYMBOLS], adSingleLetter[N_LETTERS]; FILE *fp; PwdStructure syntax, *pSyntax; HashTable *phtGrammar = CreateHashTable(177787, sizeof(syntax)); unsigned xBucket; HashTable_Element *pEl; srand((unsigned)time(NULL)); if ( argc < 4 ) { printf( "usage: %s nGrams FileToCrack TrainFile1 [TrainFile2 ...]\nIf 'nGrams' is < 0, the program will actually try to guess to the passwords in the cracking file.\nOtherwise, guess numbers are calculated for each password.", argv[0] ); return 0; } nGrams = atoi(argv[1]); if ( nGrams < 0 ) { iMakeGuesses = 1; nGrams *= -1; } if ( nGrams < 1 || nGrams > 4 ) { printf( "%s - nGram must be between 1 and 4, inclusive\n", argv[0] ); return 0; } NLetters = (int)pow((double)N_LETTERS, (double)nGrams); NModReduce = NLetters / N_LETTERS; pdLetterStart = malloc(sizeof(pdLetterStart[0]) * NLetters); if ( pdLetterStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdLetterStart!\n", argv[0] ); return 0; } pdDigitStart = malloc(sizeof(pdLetterStart[0]) * N_DIGITS); if ( pdDigitStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdDigitStart!\n", argv[0] ); free(pdLetterStart); return 0; } pdSymbolStart = malloc(sizeof(pdLetterStart[0]) * N_SYMBOLS); if ( pdSymbolStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdSymbolStart!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); return 0; } pdLetterPrefix = malloc(sizeof(pdLetterPrefix[0]) * NLetters); if ( pdLetterPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdLetterPrefix!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); return 0; } pdDigitPrefix = malloc(sizeof(pdDigitPrefix[0]) * N_DIGITS); if ( pdDigitPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdDigitPrefix!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); return 0; } pdSymbolPrefix = malloc(sizeof(pdSymbolPrefix[0]) * N_SYMBOLS); if ( pdSymbolPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdSymbolPrefix!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); return 0; } padLetters = malloc(sizeof(padLetters[0]) * NLetters); if ( padLetters == NULL ) { fprintf( stderr, "%s - can't malloc space for padLetters!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); free(pdSymbolPrefix); return 0; } padDigits = malloc(sizeof(padLetters[0]) * N_DIGITS); if ( padDigits == NULL ) { fprintf( stderr, "%s - can't malloc space for padDigits!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); free(pdSymbolPrefix); free(padLetters); return 0; } padSymbols = malloc(sizeof(padSymbols[0]) * N_SYMBOLS); if ( padSymbols == NULL ) { fprintf( stderr, "%s - can't malloc space for padSymbols!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); free(pdSymbolPrefix); free(padLetters); free(padDigits); return 0; } for ( i = 0; i < N_LETTERS; ++i ) { adSingleLetter[i] = 0.0; } for ( i = 0; i < NLetters; ++i ) { pdLetterStart[i] = 0.0; pdLetterPrefix[i] = 0.0; for ( j = 0; j < N_LETTERS; ++j ) { padLetters[i][j] = 0.0; } } for ( i = 0; i < N_DIGITS; ++i ) { pdDigitStart[i] = 0.0; pdDigitPrefix[i] = 0.0; for ( j = 0; j < N_DIGITS; ++j ) { padDigits[i][j] = 0.0; } } for ( i = 0; i < N_SYMBOLS; ++i ) { pdSymbolStart[i] = 0.0; pdSymbolPrefix[i] = 0.0; for ( j = 0; j < N_SYMBOLS; ++j ) { padSymbols[i][j] = 0.0; } } for ( xFile = 3; xFile < argc; ++xFile ) { fp = fopen(argv[xFile], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[xFile]); continue; } fprintf(stderr, "%s\n", argv[xFile]); /* read in the markov chain data for the letters */ fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ for ( xRow = 0; xRow < NLetters; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = nGrams; xState < N_LETTERS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / NLetters; /* add fraction so no row has a 0 probability of being chosen */ pdLetterStart[xRow] += dTemp; dTotalLetters += dTemp; adSingleLetter[xRow / NModReduce] += dTemp; } else if ( xState == -1 ) { pdLetterPrefix[xRow] += dTemp + 1.0; /* add fraction for each possible transition state */ } else { padLetters[xRow][xState] += dTemp + 1.0/(double)N_LETTERS; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } /* read in the markov chain data for the digits */ fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ for ( xRow = 0; xRow < N_DIGITS; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = 1; xState < N_DIGITS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / N_DIGITS; /* add fraction so no row has a 0 probability of being chosen */ pdDigitStart[xRow] += dTemp; dTotalDigits += dTemp; } else if ( xState == -1 ) { pdDigitPrefix[xRow] += dTemp + 1.0; /* add fraction for each possible transition state */ } else { padDigits[xRow][xState] += dTemp + 0.1; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } /* read in the markov chain data for the symbols */ fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ szBuf[strlen(szBuf)-1] = '\0'; assert(strlen(szBuf) == N_SYMBOLS); strcpy(szSymbols, szBuf); for ( xRow = 0; xRow < N_SYMBOLS; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = 1; xState < N_SYMBOLS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / N_SYMBOLS; /* add fraction so no row has a 0 probability of being chosen */ pdSymbolStart[xRow] += dTemp; dTotalSymbols += dTemp; } else if ( xState == -1 ) { pdSymbolPrefix[xRow] += dTemp + 1.0; /* add fraction for each possible transition state */ } else { padSymbols[xRow][xState] += dTemp + 1.0/N_SYMBOLS; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } /* last, read the sentence structures */ fgets(szBuf, sizeof(szBuf), fp); sscanf(szBuf, "%d", &nPCFG); syntax.dPercentage = 0.0; for ( xRow = 0; xRow < nPCFG; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); if ( sscanf(szBuf, "%lf %s", &dTemp, syntax.szNonTerminals) == 2 ) { pSyntax = InsertHashTable(phtGrammar, (void *)&syntax); pSyntax->dPercentage += dTemp; dTotalGrammars += dTemp; } else { fprintf( stderr, "%s - can't parse %s\n", argv[0], szBuf); } } assert(szBuf[i] == '\n'); fclose(fp); } /* Turn the counts into probabilities */ for ( j = 0; j < N_LETTERS; ++j ) { adSingleLetter[j] /= dTotalLetters; } for ( i = 0; i < NLetters; ++i ) { pdLetterStart[i] /= dTotalLetters; for ( j = 0; j < N_LETTERS; ++j ) { padLetters[i][j] /= pdLetterPrefix[i]; } } for ( i = 0; i < N_DIGITS; ++i ) { pdDigitStart[i] /= dTotalDigits; for ( j = 0; j < N_DIGITS; ++j ) { padDigits[i][j] /= pdDigitPrefix[i]; } } for ( i = 0; i < N_SYMBOLS; ++i ) { pdSymbolStart[i] /= dTotalSymbols; for ( j = 0; j < N_SYMBOLS; ++j ) { padSymbols[i][j] /= pdSymbolPrefix[i]; } } for ( xBucket = 0; xBucket < phtGrammar->nBuckets; ++xBucket ) { for ( pEl = phtGrammar->ppChain[xBucket]; pEl != NULL; pEl = pEl->pNext ) { pSyntax = (PwdStructure *)pEl->pData; pSyntax->dPercentage /= dTotalGrammars; } } /* Now open process the cracking file and get to work! */ fp = fopen(argv[2], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[2]); exit(0); } /* Either make guesses or compute guess numbers */ if ( iMakeGuesses ) { ThresholdGuessing(fp, nGrams, NLetters, NModReduce, phtGrammar, adSingleLetter, pdLetterStart, padLetters, pdDigitStart, padDigits, pdSymbolStart, padSymbols, szSymbols, 1e-13); } else { while ( fgets(szBuf, sizeof(szBuf), fp) ) { nPwdChars = strlen(szBuf) - 1; if (nPwdChars > MAX_LENGTH) continue; dNGuesses = GuessNumber(szBuf, nGrams, NModReduce, pdLetterStart, padLetters, adSingleLetter, pdDigitStart, padDigits, pdSymbolStart, padSymbols, szSymbols, phtGrammar, dTotalGrammars ); printf( "%9.3lf\t%s", dNGuesses, szBuf ); #ifdef PRINT_DEBUG //getchar(); #endif } } /* Clean up, go home */ fclose(fp); DestroyHashTable(phtGrammar); free(pdLetterPrefix); free(padLetters); free(pdLetterStart); free(pdDigitStart); free(pdDigitPrefix); free(padDigits); free(pdSymbolStart); free(pdSymbolPrefix); free(padSymbols); return 0; } <file_sep>/mangler.c #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <string.h> #include <assert.h> #include "hash.h" //#define PRINT_DEBUG //#define NDEBUG #define MAX_LENGTH 32 #define N_LETTERS 26 #define N_DIGITS 10 #define N_SYMBOLS 33 #define TARGET_MIN_GUESS 5e+6 #define N_NEW_ATTEMPTS 256 #define IS_UPPER 'U' #define IS_LOWER 'L' #define IS_DIGIT 'D' #define IS_SYMBOL 'S' typedef struct { char szNonTerminals[2*MAX_LENGTH+1]; double dPercentage; } PwdStructure; double mcProbDigits(char *szSeq, double *pdProbStart, double (*padProbTransition)[N_DIGITS]) { int i, chPrev, chNext; double dP; if ( !szSeq[0] ) return 1.0; chPrev = szSeq[0] - '0'; dP = pdProbStart[chPrev]; for ( i = 1; szSeq[i]; ++i ) { chNext = szSeq[i] - '0'; dP *= padProbTransition[chPrev][chNext]; chPrev = chNext; } return dP; } double mcProbSymbols(char *szSeq, double *pdProbStart, double (*padProbTransition)[N_SYMBOLS], char *szSymbols) { int i, chPrev, chNext; char *pChar; double dP; if ( !szSeq[0] ) return 1.0; pChar = strchr(szSymbols, szSeq[0]); assert( pChar != NULL ); chPrev = pChar - szSymbols; dP = pdProbStart[chPrev]; for ( i = 1; szSeq[i]; ++i ) { pChar = strchr(szSymbols, szSeq[i]); assert ( pChar != NULL ); chNext = pChar - szSymbols; dP *= padProbTransition[chPrev][chNext]; chPrev = chNext; } return dP; } double mcProbLetters(char *szSeq, int nGrams, int nModReduce, double *pdProbStart, double (*padProbTransition)[N_LETTERS], double *pdProbSingle) { int i, ch, xNgram; double dP = 1.0; for ( i = xNgram = 0; i < nGrams && szSeq[i]; ++i ) { ch = szSeq[i]; ch = tolower(ch) - 'a'; dP *= pdProbSingle[ch]; xNgram *= N_LETTERS; xNgram += ch; } if ( i < nGrams ) return dP; for ( dP = pdProbStart[xNgram]; szSeq[i]; ++i ) { ch = szSeq[i]; ch = tolower(ch) - 'a'; dP *= padProbTransition[xNgram][ch]; xNgram %= nModReduce; xNgram *= N_LETTERS; xNgram += ch; } return dP; } double GuessNumber(char *szPwd, int nGrams, int nModReduce, double *pdStartLetterProb, double (*padNextLetterProb)[N_LETTERS], double *pdSingleLetterProb, double *pdStartDigitProb, double (*padNextDigitProb)[N_DIGITS], double *pdStartSymbolProb, double (*padNextSymbolProb)[N_SYMBOLS], char *szSymbols, HashTable *phtGrammar, double dTotalGrammars ) { char szTemp[MAX_LENGTH+1], *pSym; int i, xLetter1, xDigit1, xSymbol1, nExactSame, nSameClass, iLast, iThis, ch; double dTemp, dNGuesses; PwdStructure syntax, *pSyntax; dNGuesses = 1e-9; /* measure in billions */ for ( iThis = xLetter1 = xDigit1 = xSymbol1 = -1, i = 0; szPwd[i] >= ' '; ++i ) { ch = szPwd[i]; iLast = iThis; if ( isupper(ch) ) iThis = IS_UPPER; else if ( islower(ch) ) iThis = IS_LOWER; else if ( isdigit(ch) ) iThis = IS_DIGIT; else iThis = IS_SYMBOL; if ( i ) { if ( iLast == iThis ) { ++nSameClass; ++nExactSame; } else { sprintf(szTemp, "%c%d", iLast, nExactSame); strcat(syntax.szNonTerminals, szTemp); nExactSame = 1; if ( !( (iLast == IS_LOWER && iThis == IS_UPPER) || (iLast == IS_UPPER && iThis == IS_LOWER) ) ) { memcpy(szTemp, szPwd+i-nSameClass, nSameClass); szTemp[nSameClass] = '\0'; if ( iLast == IS_SYMBOL ) { dNGuesses /= mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols)); #endif } else if ( iLast == IS_DIGIT ) { dNGuesses /= mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb)); #endif } else { dNGuesses /= mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb)); #endif } nSameClass = 1; } else { ++nSameClass; } } } else { syntax.szNonTerminals[0] = '\0'; nSameClass = 1; nExactSame = 1; } if ( isalpha(ch) && xLetter1 < 0 ) xLetter1 = i; /* Begin new letter chain */ else if ( !isalpha(ch) ) xLetter1 = -1; /* Halt letter chain */ if ( isdigit(ch) && xDigit1 < 0 ) xDigit1 = i; /* Begin new digit chain */ else if ( !isdigit(ch) ) xDigit1 = -1; /* Halt digit chain */ pSym = strchr(szSymbols, ch); if ( pSym != NULL && xSymbol1 < 0 ) xSymbol1 = i; /* Begin new symbol chain */ else if ( pSym == NULL ) xSymbol1 = -1; /* Halt symbol chain */ } sprintf(szTemp, "%c%d", iThis, nExactSame); strcat(syntax.szNonTerminals, szTemp); memcpy(szTemp, szPwd+i-nSameClass, nSameClass); szTemp[nSameClass] = '\0'; if ( iThis == IS_SYMBOL ) { dNGuesses /= mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbSymbols(szTemp, pdStartSymbolProb, padNextSymbolProb, szSymbols)); #endif } else if ( iThis == IS_DIGIT ) { dNGuesses /= mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbDigits(szTemp, pdStartDigitProb, padNextDigitProb)); #endif } else { dNGuesses /= mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb); #ifdef PRINT_DEBUG printf( "%s has prob %.12lf\n", szTemp, mcProbLetters(szTemp, nGrams, nModReduce, pdStartLetterProb, padNextLetterProb, pdSingleLetterProb)); #endif } pSyntax = LookupHashTable(phtGrammar, syntax.szNonTerminals); dTemp = (pSyntax == NULL) ? 1.0/dTotalGrammars : pSyntax->dPercentage; /* probability of choosing this structure */ dNGuesses /= dTemp; #ifdef PRINT_DEBUG printf("p(%s) = %lf; total %lf\n", syntax.szNonTerminals, dTemp, dNGuesses); #endif return dNGuesses; } int InsertChars(char *szMangled, char *szOriginal, int nCharsInsert, double dThreshold, int nPrefix, int nModReduce, double *pdLetterPrefix, double (*padLetterTrans)[N_LETTERS], double *pdSingleLetter, double *pdDigitPrefix, double (*padDigitTrans)[N_DIGITS], double *pdSymbolPrefix, double (*padSymbolTrans)[N_SYMBOLS], char *szSymbols, HashTable *phtGrammar, double dTotalGrammars ) { char szTemp[MAX_LENGTH+1], szBest[MAX_LENGTH+1], szMask[1+MAX_LENGTH]; int nTries, x, ch, nAdded; int iLength = strlen(szOriginal); int iHasLower = 0, iHasUpper = 0, iHasSymbol = 0, iHasDigit = 0; int iNewLower, iNewUpper, iNewSymbol, iNewDigit; double dGuesses, dBest = -1; strcpy(szMangled, szOriginal); for ( x = 0; szOriginal[x]; ++x ) { ch = szOriginal[x]; if ( islower(ch) ) { iHasLower++; szMask[x] = IS_LOWER; } else if ( isupper(ch) ) { iHasLower++; szMask[x] = IS_UPPER; } else if ( isdigit(ch) ) { iHasLower++; szMask[x] = IS_DIGIT; } else { iHasLower++; szMask[x] = IS_SYMBOL; } } if ( nCharsInsert == 1 && (iHasLower != 0) + (iHasUpper != 0) + (iHasDigit != 0) + (iHasSymbol != 0) == 1 ) nCharsInsert = 2; if ( iLength + nCharsInsert > MAX_LENGTH ) return 0; #ifdef PRINT_DEBUG dGuesses = GuessNumber(szOriginal, nPrefix, nModReduce, pdLetterPrefix, padLetterTrans, pdSingleLetter, pdDigitPrefix, padDigitTrans, pdSymbolPrefix, padSymbolTrans, szSymbols, phtGrammar, dTotalGrammars ); printf( "Password was \"%s\"\t%.3lf\t%lf\n", szOriginal, dGuesses, dThreshold); #endif strcpy(szBest, szOriginal); for ( nTries = 0; nTries < N_NEW_ATTEMPTS; ++nTries ) { do { strcpy(szMangled, szOriginal); iNewLower = iHasLower; iNewUpper = iHasUpper; iNewDigit = iHasDigit; iNewSymbol = iHasSymbol; for ( nAdded = 0; nAdded < nCharsInsert && iLength + nAdded < MAX_LENGTH; ++nAdded ) { x = rand() % (iLength+nAdded+1); ch = (rand() % ('~' - ' ' + 1)) + ' '; if ( islower(ch) ) ++iNewLower; else if ( isupper(ch) ) ++iNewUpper; else if ( isdigit(ch) ) ++iNewDigit; else ++iNewSymbol; sprintf(szTemp, "%.*s%c%s", x, szMangled, ch, szMangled+x); strcpy(szMangled, szTemp); } } while ( !((iNewLower != 0) + (iNewUpper != 0) + (iNewDigit != 0) + (iNewSymbol != 0) >= 3) && !(iNewLower + iNewUpper + iNewDigit >= 8 && iNewSymbol >= 2) ); dGuesses = GuessNumber(szMangled, nPrefix, nModReduce, pdLetterPrefix, padLetterTrans, pdSingleLetter, pdDigitPrefix, padDigitTrans, pdSymbolPrefix, padSymbolTrans, szSymbols, phtGrammar, dTotalGrammars ); if ( dGuesses > dBest ) { #ifdef PRINT_DEBUG printf( "Pword (%d) is \"%s\"\t%.3lf\n", nCharsInsert, szMangled, dBest); #endif strcpy(szBest, szMangled); dBest = dGuesses; } if ( dGuesses >= dThreshold ) return 1; } strcpy(szMangled, szBest); #ifdef PRINT_DEBUG printf( "Pword (%d) is \"%s\"\t%.3lf\n", nCharsInsert, szMangled, dBest); #endif return 0; //(dBest >= dThreshold) ? 1 : 0; } int ChangeChars(char *szMangled, char *szOriginal, int nCharsChange, double dThreshold, int nPrefix, int nModReduce, double *pdLetterPrefix, double (*padLetterTrans)[N_LETTERS], double *pdSingleLetter, double *pdDigitPrefix, double (*padDigitTrans)[N_DIGITS], double *pdSymbolPrefix, double (*padSymbolTrans)[N_SYMBOLS], char *szSymbols, HashTable *phtGrammar, double dTotalGrammars ) { char abModified[MAX_LENGTH], szBest[1+MAX_LENGTH], szMask[1+MAX_LENGTH]; int nTries, x, ch, nChanged; int iLength = strlen(szOriginal); int iHasLower = 0, iHasUpper = 0, iHasSymbol = 0, iHasDigit = 0; int iNewLower, iNewUpper, iNewSymbol, iNewDigit; double dGuesses, dBest = -1; if ( iLength > MAX_LENGTH || iLength < nCharsChange ) return 0; for ( x = 0; szOriginal[x]; ++x ) { ch = szOriginal[x]; if ( islower(ch) ) { iHasLower++; szMask[x] = IS_LOWER; } else if ( isupper(ch) ) { iHasLower++; szMask[x] = IS_UPPER; } else if ( isdigit(ch) ) { iHasLower++; szMask[x] = IS_DIGIT; } else { iHasLower++; szMask[x] = IS_SYMBOL; } } if ( nCharsChange == 1 && (iHasLower != 0) + (iHasUpper != 0) + (iHasDigit != 0) + (iHasSymbol != 0) == 1 ) nCharsChange = 2; #ifdef PRINT_DEBUG printf( "%s (%d %d %d %d) %d\n", szOriginal, iHasLower, iHasUpper, iHasDigit, iHasSymbol, nCharsChange ); dGuesses = GuessNumber(szOriginal, nPrefix, nModReduce, pdLetterPrefix, padLetterTrans, pdSingleLetter, pdDigitPrefix, padDigitTrans, pdSymbolPrefix, padSymbolTrans, szSymbols, phtGrammar, dTotalGrammars ); printf( "Password was \"%s\"\t%.3lf\t%lf\n", szOriginal, dGuesses, dThreshold); #endif strcpy(szBest, szOriginal); for ( nTries = 0; nTries < N_NEW_ATTEMPTS; ++nTries ) { do { strcpy(szMangled, szOriginal); for ( x = 0; x < MAX_LENGTH; ++x ) { abModified[x] = 0; } iNewLower = iHasLower; iNewUpper = iHasUpper; iNewDigit = iHasDigit; iNewSymbol = iHasSymbol; for ( nChanged = 0; nChanged < nCharsChange; ++nChanged ) { do { x = rand() % iLength; } while ( abModified[x] //|| (szMask[x] == IS_LOWER && iNewLower == 1) //|| (szMask[x] == IS_UPPER && iNewUpper == 1) //|| (szMask[x] == IS_DIGIT && iNewDigit == 1) //|| (szMask[x] == IS_SYMBOL && iNewSymbol == 1) // Don't take away only instance of a character class ); if ( szMask[x] == IS_LOWER ) --iNewLower; else if ( szMask[x] == IS_UPPER ) --iNewUpper; else if ( szMask[x] == IS_DIGIT ) --iNewDigit; else if ( szMask[x] == IS_SYMBOL ) --iNewSymbol; abModified[x] = 1; do { ch = (rand() % ('~' - ' ')) + ' '; } while ( ch == szMangled[x] || (szMask[x] == IS_LOWER && islower(ch)) || (szMask[x] == IS_UPPER && isupper(ch)) || (szMask[x] == IS_DIGIT && isdigit(ch)) || (szMask[x] == IS_SYMBOL && !islower(ch) && !isupper(ch) && !isdigit(ch)) // Must change character class ); szMangled[x] = ch; if ( islower(ch) ) ++iNewLower; else if ( isupper(ch) ) ++iNewUpper; else if ( isdigit(ch) ) ++iNewDigit; else ++iNewSymbol; } #ifdef PRINT_DEBUG printf( "%s (%d %d %d %d)\n", szMangled, iNewLower, iNewUpper, iNewDigit, iNewSymbol); #endif } while ( (iNewLower != 0) + (iNewUpper != 0) + (iNewDigit != 0) + (iNewSymbol != 0) < 3 ); dGuesses = GuessNumber(szMangled, nPrefix, nModReduce, pdLetterPrefix, padLetterTrans, pdSingleLetter, pdDigitPrefix, padDigitTrans, pdSymbolPrefix, padSymbolTrans, szSymbols, phtGrammar, dTotalGrammars ); if ( dGuesses > dBest ) { #ifdef PRINT_DEBUG printf( "Pword (%d) is \"%s\"\t%.3lf\n", nCharsChange, szMangled, dGuesses); #endif strcpy(szBest, szMangled); dBest = dGuesses; } if ( dGuesses >= dThreshold ) return 1; } strcpy(szMangled, szBest); #ifdef PRINT_DEBUG printf( "Pword (%d) is \"%s\"\t%.3lf\n", nCharsChange, szMangled, dBest); #endif return 0; //(dBest >= dThreshold) ? 1 : 0; } int main(int argc, char **argv) { char szBuf[2048], szSymbols[N_SYMBOLS+2], szNewPwd[1+MAX_LENGTH]; int nGrams, i, j, xFile, NLetters, xRow, NModReduce, nPwdChars, xState, nPCFG, iGotNew, nChanges, nChangesNow; double dTemp, dTotalLetters = 0, dTotalDigits = 0, dTotalSymbols = 0, dTotalGrammars = 0, dNGuesses, dThreshold; double *pdLetterPrefix, *pdLetterStart, (*padLetters)[N_LETTERS], *pdDigitPrefix, *pdDigitStart, (*padDigits)[N_DIGITS], *pdSymbolPrefix, *pdSymbolStart, (*padSymbols)[N_SYMBOLS], adSingleLetter[N_LETTERS]; FILE *fp; PwdStructure syntax, *pSyntax; HashTable *phtGrammar = CreateHashTable(177787, sizeof(syntax)); unsigned xBucket; HashTable_Element *pEl; srand((unsigned)time(NULL)); if ( argc < 4 ) { printf( "usage: %s nChanges nGrams FileToMangle TrainFile1 [TrainFile2 ...]\n", argv[0] ); return 0; } nChanges = atoi(argv[1]); if ( nChanges < 1 || nChanges > 8 ) { printf( "%s - nChanges must be between 1 and 8, inclusive\n", argv[0] ); return 0; } nGrams = atoi(argv[2]); if ( nGrams < 1 || nGrams > 4 ) { printf( "%s - nGram must be between 1 and 4, inclusive\n", argv[0] ); return 0; } NLetters = (int)pow((double)N_LETTERS, (double)nGrams); NModReduce = NLetters / N_LETTERS; pdLetterStart = malloc(sizeof(pdLetterStart[0]) * NLetters); if ( pdLetterStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdLetterStart!\n", argv[0] ); return 0; } pdDigitStart = malloc(sizeof(pdLetterStart[0]) * N_DIGITS); if ( pdDigitStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdDigitStart!\n", argv[0] ); free(pdLetterStart); return 0; } pdSymbolStart = malloc(sizeof(pdLetterStart[0]) * N_SYMBOLS); if ( pdSymbolStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdSymbolStart!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); return 0; } pdLetterPrefix = malloc(sizeof(pdLetterPrefix[0]) * NLetters); if ( pdLetterPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdLetterPrefix!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); return 0; } pdDigitPrefix = malloc(sizeof(pdDigitPrefix[0]) * N_DIGITS); if ( pdDigitPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdDigitPrefix!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); return 0; } pdSymbolPrefix = malloc(sizeof(pdSymbolPrefix[0]) * N_SYMBOLS); if ( pdSymbolPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdSymbolPrefix!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); return 0; } padLetters = malloc(sizeof(padLetters[0]) * NLetters); if ( padLetters == NULL ) { fprintf( stderr, "%s - can't malloc space for padLetters!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); free(pdSymbolPrefix); return 0; } padDigits = malloc(sizeof(padLetters[0]) * N_DIGITS); if ( padDigits == NULL ) { fprintf( stderr, "%s - can't malloc space for padDigits!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); free(pdSymbolPrefix); free(padLetters); return 0; } padSymbols = malloc(sizeof(padSymbols[0]) * N_SYMBOLS); if ( padSymbols == NULL ) { fprintf( stderr, "%s - can't malloc space for padSymbols!\n", argv[0] ); free(pdLetterStart); free(pdDigitStart); free(pdSymbolStart); free(pdLetterPrefix); free(pdDigitPrefix); free(pdSymbolPrefix); free(padLetters); free(padDigits); return 0; } for ( i = 0; i < N_LETTERS; ++i ) { adSingleLetter[i] = 0.0; } for ( i = 0; i < NLetters; ++i ) { pdLetterStart[i] = 0.0; pdLetterPrefix[i] = 0.0; for ( j = 0; j < N_LETTERS; ++j ) { padLetters[i][j] = 0.0; } } for ( i = 0; i < N_DIGITS; ++i ) { pdDigitStart[i] = 0.0; pdDigitPrefix[i] = 0.0; for ( j = 0; j < N_DIGITS; ++j ) { padDigits[i][j] = 0.0; } } for ( i = 0; i < N_SYMBOLS; ++i ) { pdSymbolStart[i] = 0.0; pdSymbolPrefix[i] = 0.0; for ( j = 0; j < N_SYMBOLS; ++j ) { padSymbols[i][j] = 0.0; } } for ( xFile = 4; xFile < argc; ++xFile ) { fp = fopen(argv[xFile], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[xFile]); continue; } fprintf(stderr, "%s\n", argv[xFile]); /* read in the markov chain data for the letters */ fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ for ( xRow = 0; xRow < NLetters; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = nGrams; xState < N_LETTERS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / NLetters; /* add fraction so no row has a 0 probability of being chosen */ pdLetterStart[xRow] += dTemp; dTotalLetters += dTemp; adSingleLetter[xRow / NModReduce] += dTemp; } else if ( xState == -1 ) { pdLetterPrefix[xRow] += dTemp + 1.0; /* add fraction for each possible transition state */ } else { padLetters[xRow][xState] += dTemp + 1.0/(double)N_LETTERS; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } /* read in the markov chain data for the digits */ fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ for ( xRow = 0; xRow < N_DIGITS; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = 1; xState < N_DIGITS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / N_DIGITS; /* add fraction so no row has a 0 probability of being chosen */ pdDigitStart[xRow] += dTemp; dTotalDigits += dTemp; } else if ( xState == -1 ) { pdDigitPrefix[xRow] += dTemp + 1.0; /* add fraction for each possible transition state */ } else { padDigits[xRow][xState] += dTemp + 0.1; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } /* read in the markov chain data for the symbols */ fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ szBuf[strlen(szBuf)-1] = '\0'; assert(strlen(szBuf) == N_SYMBOLS); strcpy(szSymbols, szBuf); for ( xRow = 0; xRow < N_SYMBOLS; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = 1; xState < N_SYMBOLS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / N_SYMBOLS; /* add fraction so no row has a 0 probability of being chosen */ pdSymbolStart[xRow] += dTemp; dTotalSymbols += dTemp; } else if ( xState == -1 ) { pdSymbolPrefix[xRow] += dTemp + 1.0; /* add fraction for each possible transition state */ } else { padSymbols[xRow][xState] += dTemp + 1.0/N_SYMBOLS; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } /* last, read the sentence structures */ fgets(szBuf, sizeof(szBuf), fp); sscanf(szBuf, "%d", &nPCFG); syntax.dPercentage = 0.0; for ( xRow = 0; xRow < nPCFG; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); if ( sscanf(szBuf, "%lf %s", &dTemp, syntax.szNonTerminals) == 2 ) { pSyntax = InsertHashTable(phtGrammar, (void *)&syntax); pSyntax->dPercentage += dTemp; dTotalGrammars += dTemp; } else { fprintf( stderr, "%s - can't parse %s\n", argv[0], szBuf); } } assert(szBuf[i] == '\n'); fclose(fp); } /* Turn the counts into probabilities */ for ( j = 0; j < N_LETTERS; ++j ) { adSingleLetter[j] /= dTotalLetters; } for ( i = 0; i < NLetters; ++i ) { pdLetterStart[i] /= dTotalLetters; for ( j = 0; j < N_LETTERS; ++j ) { padLetters[i][j] /= pdLetterPrefix[i]; } } for ( i = 0; i < N_DIGITS; ++i ) { pdDigitStart[i] /= dTotalDigits; for ( j = 0; j < N_DIGITS; ++j ) { padDigits[i][j] /= pdDigitPrefix[i]; } } for ( i = 0; i < N_SYMBOLS; ++i ) { pdSymbolStart[i] /= dTotalSymbols; for ( j = 0; j < N_SYMBOLS; ++j ) { padSymbols[i][j] /= pdSymbolPrefix[i]; } } for ( xBucket = 0; xBucket < phtGrammar->nBuckets; ++xBucket ) { for ( pEl = phtGrammar->ppChain[xBucket]; pEl != NULL; pEl = pEl->pNext ) { pSyntax = (PwdStructure *)pEl->pData; pSyntax->dPercentage /= dTotalGrammars; } } /* Now open process the cracking file and get to work! */ fp = fopen(argv[3], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[2]); exit(0); } // Let the mangling begin!! while ( fgets(szBuf, sizeof(szBuf), fp) ) { nPwdChars = strlen(szBuf); szBuf[--nPwdChars] = '\0'; if (nPwdChars > MAX_LENGTH) continue; iGotNew = 0; dNGuesses = GuessNumber(szBuf, nGrams, NModReduce, pdLetterStart, padLetters, adSingleLetter, pdDigitStart, padDigits, pdSymbolStart, padSymbols, szSymbols, phtGrammar, dTotalGrammars ); if ( dNGuesses < TARGET_MIN_GUESS ) { nChangesNow = nChanges; for ( dThreshold = TARGET_MIN_GUESS; !iGotNew; ) { iGotNew = InsertChars(szNewPwd, szBuf, nChangesNow, dThreshold, nGrams, NModReduce, pdLetterStart, padLetters, adSingleLetter, pdDigitStart, padDigits, pdSymbolStart, padSymbols, szSymbols, phtGrammar, dTotalGrammars ) || ChangeChars(szNewPwd, szBuf, nChangesNow, dThreshold, nGrams, NModReduce, pdLetterStart, padLetters, adSingleLetter, pdDigitStart, padDigits, pdSymbolStart, padSymbols, szSymbols, phtGrammar, dTotalGrammars ); dThreshold /= 2.0; } puts(szNewPwd); #ifdef PRINT_DEBUG getchar(); #endif } else { puts(szBuf); } } /* Clean up, go home */ fclose(fp); DestroyHashTable(phtGrammar); free(pdLetterPrefix); free(padLetters); free(pdLetterStart); free(pdDigitStart); free(pdDigitPrefix); free(padDigits); free(pdSymbolStart); free(pdSymbolPrefix); free(padSymbols); return 0; } <file_sep>/mcc.c #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <string.h> #include <assert.h> #include "hash.h" class CMarkovChain { private: int m_nGrams; int m_nPrefix; int m_nReduceModulus; }; /*#define NDEBUG*/ #define MAX_LENGTH 32 #define N_CHARS 96 /* 128 - ' ' */ int globintProcessor = 'a'; void BuildPassword(char *szPwd, int xPwd, int iLength, FILE *fp, int nModReduce, int xOriginalState, int (*paxState)[N_CHARS], double (*padState)[N_CHARS], double dProbSoFar, double dThresholdP, HashTable *phtPasswords, int *pnBillions, int *pnGuesses) { int i, iChar, xNewState, xPreState; if ( xPwd == iLength ) { if ( ++*pnGuesses == 1000000000 ) { ++*pnBillions; *pnGuesses = 0; } szPwd[xPwd] = '\0'; if ( DeleteHashElement(phtPasswords, szPwd) ) { printf( "%c\t%d.%09d\t%s\t%.03lf\n", globintProcessor, *pnBillions, *pnGuesses, szPwd, 1e-9/dProbSoFar ); fflush(stdout); } } else { xPreState = (xOriginalState % nModReduce) * N_CHARS; for ( i = 0; i < N_CHARS; ++i ) { iChar = paxState[xOriginalState][i]; xNewState = xPreState + iChar; if ( dProbSoFar * padState[xOriginalState][iChar] < dThresholdP ) break; szPwd[xPwd] = iChar + ' '; BuildPassword(szPwd, xPwd+1, iLength, fp, nModReduce, xNewState, paxState, padState, dProbSoFar * padState[xOriginalState][iChar], dThresholdP, phtPasswords, pnBillions, pnGuesses); } } } double *globpdSortMeUsingIndex; int IndirectSortDoubleDescending(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return (globpdSortMeUsingIndex[x] > globpdSortMeUsingIndex[y]) ? -1 : (globpdSortMeUsingIndex[x] != globpdSortMeUsingIndex[y]); } void ThresholdGuessing(FILE *fp, int nGrams, int NChars, int nModReduce, double *pdLengths, double *pdStart, double (*padState)[N_CHARS], double dThresholdP) { char szBuf[2048]; int nBillions = 0, nGuesses = 0, xPwd, xNGram, i, j, iLen, jStart, jEnd; int axLength[1+MAX_LENGTH], *pxStart, (*paxState)[N_CHARS]; HashTable *phtPasswords = CreateHashTable(5000011, 1+MAX_LENGTH); double dCumProb; pxStart = malloc(NChars * sizeof(pxStart[0])); paxState = malloc(NChars * sizeof(paxState[0])); while ( fgets(szBuf, sizeof(szBuf), fp) ) { iLen = strlen(szBuf) - 1; if ( iLen <= MAX_LENGTH ) { szBuf[iLen] = '\0'; InsertHashTable(phtPasswords, szBuf); } } for ( i = 0; i <= MAX_LENGTH; ++i ) { axLength[i] = i; } globpdSortMeUsingIndex = pdLengths; qsort(axLength, 1+MAX_LENGTH, sizeof(axLength[0]), IndirectSortDoubleDescending); for ( i = 0; i < NChars; ++i ) { pxStart[i] = i; for ( j = 0; j < N_CHARS; ++j ) { paxState[i][j] = j; } globpdSortMeUsingIndex = padState[i]; qsort(paxState[i], N_CHARS, sizeof(paxState[i][0]), IndirectSortDoubleDescending); } globpdSortMeUsingIndex = pdStart; qsort(pxStart, NChars, sizeof(pxStart[0]), IndirectSortDoubleDescending); //jStart = jEnd = 0; for ( dCumProb = 0.0, j = jStart = jEnd = 0; j < NChars; ++j ) { dCumProb += pdStart[pxStart[j]]; if ( dCumProb > 0.10 ) { jEnd = j+1; if ( !fork() ) break; jStart = jEnd; dCumProb = 0.0; ++globintProcessor; } } if ( jStart == jEnd ) { jEnd = NChars; } for ( j = jStart; j < jEnd; ++j ) { xNGram = pxStart[j]; if ( pdStart[xNGram] < dThresholdP ) break; for ( i = 0; i <= MAX_LENGTH; ++i ) { iLen = axLength[i]; if ( pdLengths[iLen] * pdStart[xNGram] < dThresholdP ) break; xPwd = 0; if ( nGrams == 1 ) { szBuf[xPwd++] = xNGram + ' '; } else if ( nGrams == 2 ) { szBuf[xPwd++] = xNGram / N_CHARS + ' '; szBuf[xPwd++] = xNGram % N_CHARS + ' '; } else if ( nGrams == 3 ) { szBuf[xPwd++] = xNGram / (N_CHARS * N_CHARS) + ' '; szBuf[xPwd++] = (xNGram / N_CHARS) % N_CHARS + ' '; szBuf[xPwd++] = xNGram % N_CHARS + ' '; } BuildPassword(szBuf, xPwd, iLen, fp, nModReduce, xNGram, paxState, padState, pdLengths[iLen] * pdStart[xNGram], dThresholdP, phtPasswords, &nBillions, &nGuesses); } } DestroyHashTable(phtPasswords); free(pxStart); free(paxState); } double dRand() { int x = ((rand() & 0x03ff) << 10) | (rand() & 0x03ff); return (double)x / (double)0x100000; /* returns 0.0 to < 1.0 */ } void ActuallyGuess(FILE *fp, int nGrams, int NChars, int nModReduce, double *pdLengths, double *pdStart, double (*padState)[N_CHARS]) { char szBuf[2048]; int iLen, i, j, xLo, xMid, xHi, nBillions = 0, nGuesses, nLength, xPwd, xNGram; double dGuess; HashTable *phtPasswords = CreateHashTable(5000011, 1+MAX_LENGTH); while ( fgets(szBuf, sizeof(szBuf), fp) ) { iLen = strlen(szBuf) - 1; if ( iLen <= MAX_LENGTH ) { szBuf[iLen] = '\0'; InsertHashTable(phtPasswords, szBuf); } } for ( i = 1; i <= MAX_LENGTH; ++i ) { pdLengths[i] += pdLengths[i-1]; } assert(pdLengths[MAX_LENGTH] = 1.0); for ( i = 0; i < NChars; ++i ) { if ( i ) pdStart[i] += pdStart[i-1]; for ( j = 1; j < N_CHARS; ++j ) { padState[i][j] += padState[i][j-1]; } assert(padState[i][N_CHARS-1] = 1.0); } assert(pdStart[NChars-1] = 1.0); for ( nGuesses = 0; nBillions < 2; ++nGuesses ) { if ( nGuesses == 1000000000 ) { nGuesses = 0; ++nBillions; } while ( (dGuess = dRand()) <= 0.0 ) ; for ( xLo = 0, xHi = MAX_LENGTH; xLo < xHi; ) { xMid = (xLo + xHi) / 2; if ( dGuess <= pdLengths[xMid] ) { xHi = xMid; } else { xLo = xMid + 1; } } assert( xLo > 0 && xLo <= MAX_LENGTH && pdLengths[xLo] > 0.0 ); assert( (!xLo || pdLengths[xLo-1] < dGuess) && dGuess <= pdLengths[xLo] ); nLength = xLo; dGuess = dRand(); for ( xLo = 0, xHi = NChars-1; xLo < xHi; ) { xMid = (xLo + xHi) / 2; if ( dGuess <= pdStart[xMid] ) { xHi = xMid; } else { xLo = xMid + 1; } } xPwd = 0; xNGram = xLo; assert( (!xLo || pdStart[xLo-1] < dGuess) && dGuess <= pdStart[xLo] ); if ( nGrams == 1 ) { szBuf[xPwd++] = xNGram + ' '; } else if ( nGrams == 2 ) { szBuf[xPwd++] = xNGram / N_CHARS + ' '; szBuf[xPwd++] = xNGram % N_CHARS + ' '; } else if ( nGrams == 3 ) { szBuf[xPwd++] = xNGram / (N_CHARS * N_CHARS) + ' '; szBuf[xPwd++] = (xNGram / N_CHARS) % N_CHARS + ' '; szBuf[xPwd++] = xNGram % N_CHARS + ' '; } while ( xPwd < nLength ) { assert( xNGram >= 0 && xNGram < NChars ); dGuess = dRand(); for ( xLo = 0, xHi = N_CHARS-1; xLo < xHi; ) { xMid = (xLo + xHi) / 2; if ( dGuess <= padState[xNGram][xMid] ) { xHi = xMid; } else { xLo = xMid + 1; } } assert( xLo >= 0 && xLo < N_CHARS ); assert( (!xLo || padState[xNGram][xLo-1] < dGuess) && dGuess <= padState[xNGram][xLo] ); szBuf[xPwd++] = xLo + ' '; xNGram %= nModReduce; xNGram *= N_CHARS; xNGram += xLo; } szBuf[xPwd] = '\0'; if ( DeleteHashElement(phtPasswords, szBuf) ) { if ( nBillions ) printf( "%d", nBillions ); printf( "%d\t", nGuesses ); printf( "%s\n", szBuf ); } } DestroyHashTable(phtPasswords); } int main(int argc, char **argv) { char szBuf[2048]; int iMakeGuesses = 0; int nGrams, i, j, xFile, NChars, xRow, iFoundNonZero, NModReduce, nLengths, xState; double dTemp, *pdStart, *pdPrefix, (*padState)[N_CHARS], *pdLengths, dTotalStart = 0, dTotalLength = 0, dNGuesses; FILE *fp; srand((unsigned)time(NULL)); if ( argc < 4 ) { printf( "usage: %s nGrams FileToCrack TrainFile1 [TrainFile2 ...]\nIf 'nGrams' is < 0, the program will actually try to guess to the passwords in the cracking file.\nOtherwise, guess numbers are calculated for each password.", argv[0] ); return 0; } nGrams = atoi(argv[1]); if ( nGrams < 0 ) { iMakeGuesses = 1; nGrams *= -1; } if ( nGrams < 1 || nGrams > 4 ) { printf( "%s - nGram must be between 1 and 4, inclusive\n", argv[0] ); return 0; } pdLengths = malloc(sizeof(pdLengths[0]) * (1 + MAX_LENGTH)); if ( pdLengths == NULL ) { fprintf( stderr, "%s - can't malloc space for pdLengths!\n", argv[0] ); return 0; } NChars = (int)pow((double)N_CHARS, (double)nGrams); NModReduce = NChars / N_CHARS; pdStart = malloc(sizeof(pdStart[0]) * NChars); if ( pdStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdStart!\n", argv[0] ); free(pdLengths); return 0; } pdPrefix = malloc(sizeof(pdPrefix[0]) * NChars); if ( pdPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdPrefix!\n", argv[0] ); free(pdLengths); free(pdStart); return 0; } padState = malloc(sizeof(padState[0]) * NChars); if ( padState == NULL ) { fprintf( stderr, "%s - can't malloc space for padState!\n", argv[0] ); free(pdLengths); free(pdStart); free(pdPrefix); return 0; } for ( i = 0; i <= MAX_LENGTH; ++i ) { pdLengths[i] = 0; } for ( i = 0; i < NChars; ++i ) { pdStart[i] = 0.0; pdPrefix[i] = 0.0; for ( j = 0; j < N_CHARS; ++j ) { padState[i][j] = 0.0; } } for ( xFile = 3; xFile < argc; ++xFile ) { fp = fopen(argv[xFile], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[xFile]); continue; } fprintf(stderr, "%s\n", argv[xFile]); fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ for ( xRow = 0; xRow < NChars; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = nGrams; xState < N_CHARS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / NChars; /* add fraction so no row has a 0 probability of being chosen */ pdStart[xRow] += dTemp; dTotalStart += dTemp; } else if ( xState == -1 ) { pdPrefix[xRow] += dTemp + N_CHARS/100.0; /* add fraction for each possible transition state */ } else { padState[xRow][xState] += dTemp + 0.01; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } fgets(szBuf, sizeof(szBuf), fp); /* length count */ sscanf(szBuf, "%d", &nLengths); if ( nLengths > MAX_LENGTH ) { fprintf( stderr, "%s - MAX_LENGTH not long enough for %s!!", argv[0], argv[xFile]); exit(0); } fgets(szBuf, sizeof(szBuf), fp); /* read lengths into szBuf */ for ( iFoundNonZero = 0, i = 0, xRow = 1; xRow <= nLengths; ++xRow ) { assert(szBuf[i] == ' '); sscanf(szBuf+i, "%lf", &dTemp); if ( !iFoundNonZero ) iFoundNonZero = dTemp > 0.0; if ( iFoundNonZero ) ++dTemp; /* add 1 so no length has a 0 probability of being chosen */ pdLengths[xRow] += dTemp; dTotalLength += dTemp; for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); fclose(fp); } /* Turn the counts into probabilities */ for ( i = 0; i < NChars; ++i ) { pdStart[i] /= dTotalStart; for ( j = 0; j < N_CHARS; ++j ) { padState[i][j] /= pdPrefix[i]; } } for ( i = 0; i <= nLengths; ++i ) { pdLengths[i] /= dTotalLength; } /* Now open process the cracking file and get to work! */ fp = fopen(argv[2], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[2]); exit(0); } /* Either make guesses or compute guess numbers */ if ( iMakeGuesses ) { ThresholdGuessing(fp, nGrams, NChars, NModReduce, pdLengths, pdStart, padState, 1e-13); /*ActuallyGuess(fp, nGrams, NChars, NModReduce, pdLengths, pdStart, padState);*/ } else { while ( fgets(szBuf, sizeof(szBuf), fp) ) { nLengths = strlen(szBuf) - 1; if (nLengths > MAX_LENGTH) continue; dNGuesses = 1e-9; /* measure in billions */ dNGuesses /= pdLengths[nLengths]; /* probability of choosing this length */ /*printf("p(len) = %lf\n", pdLengths[nLengths]);*/ for ( xRow = i = 0; i < nGrams; ++i ) { xRow *= N_CHARS; xRow += szBuf[i] - ' '; } dNGuesses /= pdStart[xRow]; /* probability of choosing this starting nGram */ /*printf("p(start) = %lf\n", pdStart[xRow]);*/ for ( ; szBuf[i] >= ' '; ++i ) { dNGuesses /= padState[xRow][szBuf[i] - ' ']; /* Probability of choosing this next state */ /*printf("p(trans) = %lf\n", padState[xRow][szBuf[i] - ' ']);*/ xRow %= NModReduce; /* throw out first char in old nGram */ xRow *= N_CHARS; /* and calculate the new nGram */ xRow += szBuf[i] - ' '; } printf( "%9.3lf\t%s", dNGuesses, szBuf ); /*getchar();*/ } } /* Clean up, go home */ fclose(fp); free(pdLengths); free(padState); free(pdStart); free(pdPrefix); return 0; } <file_sep>/MarkovCracker.c #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <string.h> #include <assert.h> #include "hash.h" /* #define NDEBUG */ #define MAX_LENGTH 32 #define N_CHARS 96 /* 128 - ' ' */ double dRand() { int x = ((rand() & 0x7fff) << 15) | (rand() & 0x7fff); return (double)x / (double)0x40000000; /* returns 0.0 to < 1.0 */ } void ActuallyGuess(FILE *fp, int nGrams, int NChars, int nModReduce, double *pdLengths, double *pdStart, double (*padState)[N_CHARS]) { char szBuf[2048]; int iLen, i, j, xLo, xMid, xHi, nBillions = 0, nGuesses, nLength, xPwd, xNGram; double dGuess; HashTable *phtPasswords = CreateHashTable(5000011, 1+MAX_LENGTH); while ( fgets(szBuf, sizeof(szBuf), fp) ) { iLen = strlen(szBuf) - 1; if ( iLen <= MAX_LENGTH ) { szBuf[iLen] = '\0'; InsertHashTable(phtPasswords, szBuf); } } for ( i = 1; i <= MAX_LENGTH; ++i ) { pdLengths[i] += pdLengths[i-1]; } for ( i = 0; i < NChars; ++i ) { if ( i ) pdStart[i] += pdStart[i-1]; for ( j = 1; j < N_CHARS; ++j ) { padState[i][j] += padState[i][j-1]; } } for ( nGuesses = 0; nBillions < 4; ++nGuesses ) { if ( nGuesses == 1000000000 ) { nGuesses = 0; ++nBillions; } dGuess = dRand(); for ( xLo = 0, xHi = MAX_LENGTH; xLo <= xHi; ) { xMid = (xLo + xHi) / 2; if ( dGuess < pdLengths[xMid] ) { xHi = xMid - 1; } else { xLo = xMid + 1; } } assert( xLo > 0 && xLo <= MAX_LENGTH && pdLengths[xLo] > 0.0 ); assert( (!xLo || pdLengths[xLo-1] < dGuess) && dGuess <= pdLengths[xLo] ); nLength = xLo; dGuess = dRand(); for ( xLo = 0, xHi = NChars-1; xLo <= xHi; ) { xMid = (xLo + xHi) / 2; if ( dGuess < pdStart[xMid] ) { xHi = xMid - 1; } else { xLo = xMid + 1; } } xPwd = 0; xNGram = xLo; assert( (!xLo || pdStart[xLo-1] < dGuess) && dGuess <= pdStart[xLo] ); if ( nGrams == 1 ) { szBuf[xPwd++] = xNGram + ' '; } else if ( nGrams == 2 ) { szBuf[xPwd++] = xNGram / N_CHARS + ' '; szBuf[xPwd++] = xNGram % N_CHARS + ' '; } else if ( nGrams == 3 ) { szBuf[xPwd++] = xNGram / (N_CHARS * N_CHARS) + ' '; szBuf[xPwd++] = (xNGram / N_CHARS) % N_CHARS + ' '; szBuf[xPwd++] = xNGram % N_CHARS + ' '; } while ( xPwd < nLength ) { assert( xNGram >= 0 && xNGram < NChars ); dGuess = dRand(); for ( xLo = 0, xHi = N_CHARS-1; xLo <= xHi; ) { xMid = (xLo + xHi) / 2; if ( dGuess < padState[xNGram][xMid] ) { xHi = xMid - 1; } else { xLo = xMid + 1; } } assert( xLo >= 0 && xLo < N_CHARS ); assert( (!xLo || padState[xNGram][xLo-1] < dGuess) && dGuess <= padState[xNGram][xLo] ); szBuf[xPwd++] = xLo + ' '; xNGram %= nModReduce; xNGram *= N_CHARS; xNGram += xLo; } szBuf[xPwd] = '\0'; if ( DeleteHashElement(phtPasswords, szBuf) ) { if ( nBillions ) printf( "%d", nBillions ); printf( "%d\t", nGuesses ); printf( "%s\n", szBuf ); } } } int main(int argc, char **argv) { char szBuf[2048]; int iMakeGuesses = 0; int nGrams, i, j, xFile, NChars, xRow, iFoundNonZero, NModReduce, nLengths, xState; double dTemp, *pdStart, *pdPrefix, (*padState)[N_CHARS], *pdLengths, dTotalStart = 0, dTotalLength = 0, dNGuesses; FILE *fp; if ( argc < 4 ) { printf( "usage: %s nGrams FileToCrack TrainFile1 [TrainFile2 ...]\nIf 'nGrams' is < 0, the program will actually try to guess to the passwords in the cracking file.\nOtherwise, guess numbers are calculated for each password.", argv[0] ); return 0; } nGrams = atoi(argv[1]); if ( nGrams < 0 ) { iMakeGuesses = 1; nGrams *= -1; } if ( nGrams < 1 || nGrams > 4 ) { printf( "%s - nGram must be between 1 and 4, inclusive\n", argv[0] ); return 0; } pdLengths = malloc(sizeof(pdLengths[0]) * (1 + MAX_LENGTH)); if ( pdLengths == NULL ) { fprintf( stderr, "%s - can't malloc space for pdLengths!\n", argv[0] ); return 0; } NChars = (int)pow((double)N_CHARS, (double)nGrams); NModReduce = NChars / N_CHARS; pdStart = malloc(sizeof(pdStart[0]) * NChars); if ( pdStart == NULL ) { fprintf( stderr, "%s - can't malloc space for pdStart!\n", argv[0] ); free(pdLengths); return 0; } pdPrefix = malloc(sizeof(pdPrefix[0]) * NChars); if ( pdPrefix == NULL ) { fprintf( stderr, "%s - can't malloc space for pdPrefix!\n", argv[0] ); free(pdLengths); free(pdStart); return 0; } padState = malloc(sizeof(padState[0]) * NChars); if ( padState == NULL ) { fprintf( stderr, "%s - can't malloc space for padState!\n", argv[0] ); free(pdLengths); free(pdStart); free(pdPrefix); return 0; } for ( i = 0; i <= MAX_LENGTH; ++i ) { pdLengths[i] = 0; } for ( i = 0; i < NChars; ++i ) { pdStart[i] = 0.0; pdPrefix[i] = 0.0; for ( j = 0; j < N_CHARS; ++j ) { padState[i][j] = 0.0; } } for ( xFile = 3; xFile < argc; ++xFile ) { fp = fopen(argv[xFile], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[xFile]); continue; } fprintf(stderr, "%s\n", argv[xFile]); fgets(szBuf, sizeof(szBuf), fp); /* list of chars */ for ( xRow = 0; xRow < NChars; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -2, i = nGrams; xState < N_CHARS; ++xState ) { assert(szBuf[i] == ' '); sscanf( szBuf+i, "%lf", &dTemp ); if ( xState == -2 ) { dTemp += 1.0 / NChars; /* add fraction so no row has a 0 probability of being chosen */ pdStart[xRow] += dTemp; dTotalStart += dTemp; } else if ( xState == -1 ) { pdPrefix[xRow] += dTemp + N_CHARS/100.0; /* add fraction for each possible transition state */ } else { padState[xRow][xState] += dTemp + 0.01; /* add fraction so no state has a 0 probability of being chosen */ } for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); } fgets(szBuf, sizeof(szBuf), fp); /* length count */ sscanf(szBuf, "%d", &nLengths); if ( nLengths > MAX_LENGTH ) { fprintf( stderr, "%s - MAX_LENGTH not long enough for %s!!", argv[0], argv[xFile]); exit(0); } fgets(szBuf, sizeof(szBuf), fp); /* read lengths into szBuf */ for ( iFoundNonZero = 0, i = 0, xRow = 1; xRow <= nLengths; ++xRow ) { assert(szBuf[i] == ' '); sscanf(szBuf+i, "%lf", &dTemp); if ( !iFoundNonZero ) iFoundNonZero = dTemp > 0.0; if ( iFoundNonZero ) ++dTemp; /* add 1 so no length has a 0 probability of being chosen */ pdLengths[xRow] += dTemp; dTotalLength += dTemp; for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } assert(szBuf[i] == '\n'); fclose(fp); } /* Turn the counts into probabilities */ for ( i = 0; i < NChars; ++i ) { pdStart[i] /= dTotalStart; for ( j = 0; j < N_CHARS; ++j ) { padState[i][j] /= pdPrefix[i]; } } for ( i = 0; i <= nLengths; ++i ) { pdLengths[i] /= dTotalLength; } /* Now open process the cracking file and get to work! */ fp = fopen(argv[2], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[2]); exit(0); } /* Either make guesses or compute guess numbers */ if ( iMakeGuesses ) { ActuallyGuess(fp, nGrams, NChars, NModReduce, pdLengths, pdStart, padState); } else { while ( fgets(szBuf, sizeof(szBuf), fp) ) { nLengths = strlen(szBuf) - 1; if (nLengths > MAX_LENGTH) continue; dNGuesses = 1e-9; /* measure in billions */ dNGuesses /= pdLengths[nLengths]; /* probability of choosing this length */ /*printf("p(len) = %lf\n", pdLengths[nLengths]);*/ for ( xRow = i = 0; i < nGrams; ++i ) { xRow *= N_CHARS; xRow += szBuf[i] - ' '; } dNGuesses /= pdStart[xRow]; /* probability of choosing this starting nGram */ /*printf("p(start) = %lf\n", pdStart[xRow]);*/ for ( ; szBuf[i] >= ' '; ++i ) { dNGuesses /= padState[xRow][szBuf[i] - ' ']; /* Probability of choosing this next state */ /*printf("p(trans) = %lf\n", padState[xRow][szBuf[i] - ' ']);*/ xRow %= NModReduce; /* throw out first char in old nGram */ xRow *= N_CHARS; /* and calculate the new nGram */ xRow += szBuf[i] - ' '; } printf( "%9.3lf\t%s", dNGuesses, szBuf ); /*getchar();*/ } } /* Clean up, go home */ fclose(fp); free(pdLengths); free(padState); free(pdStart); free(pdPrefix); return 0; } <file_sep>/pwdstats.c #include <stdlib.h> #include <stdio.h> #define MAX_LENGTH 32 #define MAX_N (1 << 24) // 16 million, give or take int SortDoubleAscending(const void *a, const void *b) { double p = *(const double *)a; double q = *(const double *)b; return (p < q) ? -1 : (p != q); } int main(int argc, char **argv) { char szBuf[2048]; double *pdGuessNumbers = malloc(sizeof(double) * MAX_N); int nNumbers = 0, i; while ( gets(szBuf) ) { if ( sscanf(szBuf, "%lf", pdGuessNumbers+nNumbers) == 1 ) ++nNumbers; } qsort(pdGuessNumbers, nNumbers, sizeof(*pdGuessNumbers), SortDoubleAscending); printf( "%d\tN\n", nNumbers); printf( "%.3lg\tMax\n", pdGuessNumbers[nNumbers-1] ); for ( i = 9; i; --i ) { double dTemp = pdGuessNumbers[(int)(nNumbers * i/10.0)]; printf( (dTemp >= 1e+6) ? "%.3le" : "%.3lf", dTemp ); if ( i == 5 ) puts("\tmedian"); else printf("\t%dth ptile\n", i*10 ); } printf( "%.3lg\tMin\n", pdGuessNumbers[0] ); free(pdGuessNumbers); return 0; } <file_sep>/locktest.c #include <stdlib.h> #include <stdio.h> #include <fcntl.h> int main(int argc, char **argv) { char szBuf[2048], chWho; int fd, x, y; struct flock lockIt; if ( argc != 2 ) { fprintf( stderr, "usage: %s outputFile\n", argv[0] ); return 0; } fd = open(argv[1], _O_CREAT | _O_WRONLY | _O_TEXT); if ( fd < 0 ) { fprintf( stderr, "%s: can't open %s\n", argv[0], argv[1]); return 0; } chWho = (fork() > 0) ? 'c' : 'p'; lockIt.l_whence = SEEK_CUR; lockIt.l_start = 0; lockIt.l_len = 16; lockIt.l_pid = getpid(); for ( x = 0; x < 10; ++x ) { sprintf(szBuf, "%c %4d\n", chWho, x); //lockIt.l_type = F_WRLCK; //fcntl(fd, F_SETLKW, &lockIt); write(fd, szBuf, strlen(szBuf)); //lockIt.l_type = F_UNLCK; //fcntl(fd, F_SETLKW, &lockIt); } close(fd); return 0; } <file_sep>/aaaa Do NOT copy new code here.cpp #include <stdafx.h> #include "classPCFG.h" //#define PRINT_DEBUG //#define TRY_MANGLED_WORD CPCFG::CPCFG(int nGrams) { m_bAreProbabilities = false; m_nGuesses = 0; m_nGuessed = 0; m_nBillions = 0; m_nProcessor = 'a'; m_dThresholdP = 1e-13; m_phtPasswords = NULL; //m_phtDictionary = NULL; m_nCaseMasks = 0; m_nStructures = 0; if ( nGrams ) { m_pmcAlphaN = new CMarkovChainAlpha(nGrams); m_pmcAlpha1 = new CMarkovChainAlpha(1); m_pmcDigits = new CMarkovChainDigit; m_pmcSymbols = new CMarkovChainSymbol; m_phtCaseMask = new CHashTable(3, sizeof(CBaseStructure)); //65537 m_phtStructures = new CHashTable(65537, sizeof(CBaseStructure)); } else { m_pmcAlphaN = NULL; m_pmcAlpha1 = NULL; m_pmcDigits = NULL; m_pmcSymbols = NULL; m_phtStructures = NULL; m_phtCaseMask = NULL; } for ( int i = 0; i <= MAX_LENGTH; ++i) { m_anCaseMaskLength[i] = 0; //m_anAlphaStringLengths[i] = 0; //m_anDigitStringLengths[i] = 0; //m_anSymbolStringLengths[i] = 0; //m_anMixedStringLengths[i] = 0; } } CPCFG::~CPCFG() { if ( m_pmcAlphaN != NULL ) delete m_pmcAlphaN; if ( m_pmcAlpha1 != NULL ) delete m_pmcAlpha1; if ( m_pmcDigits != NULL ) delete m_pmcDigits; if ( m_pmcSymbols != NULL ) delete m_pmcSymbols; if ( m_phtCaseMask != NULL ) delete m_phtCaseMask; if ( m_phtPasswords != NULL ) delete m_phtPasswords; //if ( m_phtDictionary != NULL ) delete m_phtDictionary; if ( m_phtStructures != NULL ) delete m_phtStructures; } void CPCFG::ConvertCountsToProb(bool bSmoothProbabilities) { m_bAreProbabilities = true; m_pmcAlphaN->ConvertCountsToProb(bSmoothProbabilities, false); m_pmcAlpha1->ConvertCountsToProb(bSmoothProbabilities, false); m_pmcDigits->ConvertCountsToProb(bSmoothProbabilities, false); m_pmcSymbols->ConvertCountsToProb(bSmoothProbabilities, false); } void CPCFG::AddCharacters(int nToAdd, int xOriginalState, char *szCharClass, int xPwd, char *szSyntax, CMarkovChain *pmc, double dProbSoFar) { int i, iChar, xPreState; #ifdef PRINT_DEBUG printf("Pwd = %.*s\n", xPwd, m_szGuessing); #endif if ( nToAdd <= 0 ) { BuildPassword(xPwd, szSyntax, dProbSoFar); } else { xPreState = (xOriginalState % pmc->m_nReduceModulus) * pmc->m_nChars; for ( i = 0; i < pmc->m_nChars; ++i ) { iChar = pmc->getTransitionProbabilityIndex(xOriginalState, i); if ( dProbSoFar * pmc->getTransitionProbability(xOriginalState, iChar) < m_dThresholdP ) break; m_szGuessing[xPwd] = pmc->ToCharacter(iChar); if ( *szCharClass == IS_UPPER ) m_szGuessing[xPwd] += 'A' - 'a'; AddCharacters(nToAdd-1, xPreState + iChar, szCharClass+1, xPwd+1, szSyntax, pmc, dProbSoFar * pmc->getTransitionProbability(xOriginalState, iChar)); } } } void CPCFG::BuildPassword(int xPwd, char *szSyntax, double dProbSoFar) { int xClass, i, iChar; char szClass[MAX_LENGTH+1]; CMarkovChain *pmc; if ( !*szSyntax ) { if ( ++m_nGuesses == 1000000000 ) { ++m_nBillions; m_nGuesses = 0; } m_szGuessing[xPwd] = '\0'; #ifdef PRINT_DEBUG printf("Guessing %s\n", m_szGuessing); #endif if ( m_phtPasswords->Delete(m_szGuessing) ) { ++m_nGuessed; //printf( "%c\t%d.%09d\t%s\t%.3lf\n", m_nProcessor, m_nBillions, m_nGuesses, m_szGuessing, 1e-9/dProbSoFar ); //fflush(stdout); #ifdef PRINT_DEBUG getchar(); #endif } } else { #ifdef PRINT_DEBUG printf("Pwd = %s\tSyntax = %s\n", m_szGuessing, szSyntax); #endif xClass = 0; do { szClass[xClass++] = *szSyntax++; } while ( (szClass[xClass-1] == *szSyntax) || (szClass[xClass-1] == IS_UPPER && *szSyntax == IS_LOWER) || (szClass[xClass-1] == IS_LOWER && *szSyntax == IS_UPPER) ); szClass[xClass] = '\0'; // Determine which MC we will use switch ( szClass[0] ) { case IS_DIGIT: pmc = m_pmcDigits; break; case IS_SYMBOL: pmc = m_pmcSymbols; break; case IS_UPPER: case IS_LOWER: pmc = (xClass < m_pmcAlphaN->m_nGrams) ? m_pmcAlpha1 : m_pmcAlphaN; break; default: //printf( "Unexpected token %c in grammatical structure!!!\n", szClass[0]); break; } #ifdef TRY_DICTIONARY_ATTACKS // First use the MC's dictionary to fill the slot if ( xClass > 1 ) { for ( CBaseStructure *p = pmc->m_apWordLists[xClass]; p != NULL; p = p->m_pNext ) { double dThisProb = (double)p->m_nCount / (double)pmc->m_anWordsSeen[xClass]; if ( dThisProb * dProbSoFar < m_dThresholdP ) break; for ( i = 0; i < xClass; ++i ) { m_szGuessing[xPwd+i] = p->m_szWord[i]; if ( szClass[i] == IS_UPPER ) m_szGuessing[xPwd+i] += 'A' - 'a'; } BuildPassword(xPwd+xClass, szSyntax, dThisProb * dProbSoFar); } } #endif // Now use the MC to build next part of the password for ( i = 0; i < pmc->m_nPrefix; ++i ) { iChar = pmc->m_pxStartProb[i]; if ( dProbSoFar * pmc->m_pdStartProb[iChar] < m_dThresholdP ) break; switch ( pmc->m_nGrams ) { case 1: m_szGuessing[xPwd] = pmc->ToCharacter(iChar); if ( szClass[0] == IS_UPPER ) m_szGuessing[xPwd] += 'A' - 'a'; break; case 2: m_szGuessing[xPwd] = pmc->ToCharacter(iChar / N_LETTERS); if ( szClass[0] == IS_UPPER ) m_szGuessing[xPwd] += 'A' - 'a'; m_szGuessing[xPwd+1] = pmc->ToCharacter(iChar % N_LETTERS); if ( szClass[1] == IS_UPPER ) m_szGuessing[xPwd+1] += 'A' - 'a'; break; case 3: m_szGuessing[xPwd] = pmc->ToCharacter(iChar / (N_LETTERS * N_LETTERS)); if ( szClass[0] == IS_UPPER ) m_szGuessing[xPwd] += 'A' - 'a'; m_szGuessing[xPwd+1] = pmc->ToCharacter((iChar / N_LETTERS) % N_LETTERS); if ( szClass[1] == IS_UPPER ) m_szGuessing[xPwd+1] += 'A' - 'a'; m_szGuessing[xPwd+2] = pmc->ToCharacter(iChar % N_LETTERS); if ( szClass[2] == IS_UPPER ) m_szGuessing[xPwd+2] += 'A' - 'a'; break; default: return; } AddCharacters(xClass-pmc->m_nGrams, iChar, szClass+pmc->m_nGrams, xPwd+pmc->m_nGrams, szSyntax, pmc, dProbSoFar * pmc->m_pdStartProb[iChar]); } } } static CBaseStructure **my_ppStructures; int SortStructureDescendingIndirectUsingIndex(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return my_ppStructures[y]->m_nCount - my_ppStructures[x]->m_nCount; } void CPCFG::ThresholdGuessing() { int xGrammar, j, n, jStart, jEnd; int *pxSyntax; double dCumProb; unsigned b; CHashTableElement *pEl; // Get the grammatical structures into an array for sorting pxSyntax = new int [m_phtStructures->Elements()]; my_ppStructures = new CBaseStructure * [m_phtStructures->Elements()]; for ( n = b = 0; b < m_phtStructures->TableSize(); ++b ) { for ( pEl = m_phtStructures->Bucket(b); pEl != NULL; pEl = pEl->m_pNext ) { my_ppStructures[n] = (CBaseStructure *)pEl->m_pData; pxSyntax[n] = n; ++n; } } #ifdef PRINT_DEBUG printf("nStructures = %d ; uCount = %d\n", n, m_phtStructures->m_uCount); #endif qsort(pxSyntax, n, sizeof(pxSyntax[0]), SortStructureDescendingIndirectUsingIndex); #ifdef PRINT_DEBUG printf("Most common structure is %s (%.6lf)\n", my_ppStructures[pxSyntax[0]]->szNonTerminals, my_ppStructures[pxSyntax[0]]->m_nCount / m_nStructures); #endif // Split the load across 10 different processors jStart = jEnd = 0; dCumProb = 1.0; #ifdef PRINT_DEBUG #else /* for ( dCumProb = 0.0, j = jStart = jEnd = 0; j < n; ++j ) { dCumProb += (double)my_ppStructures[pxSyntax[j]]->m_nCount / (double)m_nStructures; if ( dCumProb > 0.10 ) { jEnd = j+1; //if ( !fork() ) break; jStart = jEnd; dCumProb = 0.0; ++m_nProcessor; } } */ #endif if ( jStart == jEnd ) { jEnd = n; } //printf( "%c - %d to %d - %.4lf\n", globintProcessor, jStart, jEnd-1, dCumProb ); return; for ( j = jStart; j < jEnd; ++j ) { xGrammar = pxSyntax[j]; if ( (double)my_ppStructures[xGrammar]->m_nCount / (double)m_nStructures < m_dThresholdP ) break; BuildPassword(0, my_ppStructures[xGrammar]->m_szWord, (double)my_ppStructures[xGrammar]->m_nCount / (double)m_nStructures); } delete [] pxSyntax; delete [] my_ppStructures; } double CPCFG::GuessNumber(const char *szPwd) { char szTemp[MAX_LENGTH+1], *pSym; bool bCrackedIt = false, bAllAlpha = true, bAllDigits = true; int i, xLetter1, xDigit1, xSymbol1, nSameClass, iLast, iThis, ch; double dTemp, dNGuesses = 1.0, dFixedGuesses = 0.0; CBaseStructure syntax, *pSyntax; #ifdef PRINT_DEBUG printf( "Computing GuessNumber for %s\n", szPwd); #endif // Try dictionary attacks first #ifdef TRY_MANGLED_WORD if ( !bCrackedIt ) { double dWouldNeedToTry = 1.0; // Test for mangled dictionary word by stripping out all non-letters for ( xLetter1 = -1, i = 0; szPwd[i] >= ' '; ++i ) { if ( isalpha(szPwd[i]) ) { szTemp[++xLetter1] = szPwd[i]; bAllDigits = false; } else if ( isdigit(szPwd[i]) ) { dWouldNeedToTry *= N_DIGITS; bAllAlpha = false; } else { dWouldNeedToTry *= N_SYMBOLS; bAllDigits = false; bAllAlpha = false; } } szTemp[++xLetter1] = '\0'; if ( xLetter1 ) { dWouldNeedToTry *= m_pmcAlphaN->m_anUniqueWords[xLetter1] / 2; } #ifdef PRINT_DEBUG printf( "%s --> %.*s, requiring %.0lf tries (%d for words)\n", szPwd, xLetter1, szTemp, dWouldNeedToTry, m_anWordLengths[xLetter1] ); getchar(); #endif if ( dWouldNeedToTry <= 100e+9 && !bAllDigits ) //!iAllAlpha && { _strlwr(szTemp); dFixedGuesses += dWouldNeedToTry; if ( !xLetter1 || m_pmcAlphaN->m_phtDictionary->Lookup(szTemp) ) { bCrackedIt = true; #ifdef PRINT_DEBUG printf( "Cracked in %.3lf billion attempts\n", dFixedGuesses/1e+9 ); #endif } } } #endif // Dictionary attack failed - use grammar for ( iThis = xLetter1 = xDigit1 = xSymbol1 = -1, nSameClass = i = 0; szPwd[i] >= ' '; ++i ) { ch = szPwd[i]; iLast = iThis; if ( isupper(ch) ) iThis = IS_UPPER; else if ( islower(ch) ) iThis = IS_LOWER; else if ( isdigit(ch) ) iThis = IS_DIGIT; else iThis = IS_SYMBOL; syntax.m_szWord[i] = iThis; if ( !i || (iLast == iThis) || (iLast == IS_LOWER && iThis == IS_UPPER) || (iLast == IS_UPPER && iThis == IS_LOWER) ) { ++nSameClass; } else { memcpy(szTemp, szPwd+i-nSameClass, nSameClass); szTemp[nSameClass] = '\0'; if ( iLast == IS_SYMBOL ) { #ifdef PRINT_DEBUG printf( "Computing g# for >>%s<<\n", szTemp); #endif dNGuesses *= m_pmcSymbols->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcSymbols->GuessNumber(szTemp, 1.0)/1e+9); #endif } else if ( iLast == IS_DIGIT ) { #ifdef PRINT_DEBUG printf( "Computing g# for >>%s<<\n", szTemp); #endif dNGuesses *= m_pmcDigits->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcDigits->GuessNumber(szTemp, 1.0)/1e+9); #endif } else if ( nSameClass < m_pmcAlphaN->m_nGrams ) { #ifdef PRINT_DEBUG printf( "Computing g# for >>%s<<\n", szTemp); #endif dNGuesses *= m_pmcAlpha1->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcAlpha1->GuessNumber(szTemp, 1.0)/1e+9); #endif } else { #ifdef PRINT_DEBUG printf( "Computing g# for >>%s<<\n", szTemp); #endif dNGuesses *= m_pmcAlphaN->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcAlphaN->GuessNumber(szTemp, 1.0)/1e+9); #endif } nSameClass = 1; } if ( isalpha(ch) && xLetter1 < 0 ) xLetter1 = i; /* Begin new letter chain */ else if ( !isalpha(ch) ) xLetter1 = -1; /* Halt letter chain */ if ( isdigit(ch) && xDigit1 < 0 ) xDigit1 = i; /* Begin new digit chain */ else if ( !isdigit(ch) ) xDigit1 = -1; /* Halt digit chain */ pSym = strchr(m_pmcSymbols->m_szSymbols, ch); if ( pSym != NULL && xSymbol1 < 0 ) xSymbol1 = i; /* Begin new symbol chain */ else if ( pSym == NULL ) xSymbol1 = -1; /* Halt symbol chain */ } syntax.m_szWord[i] = '\0'; memcpy(szTemp, szPwd+i-nSameClass, nSameClass); szTemp[nSameClass] = '\0'; if ( iThis == IS_SYMBOL ) { dNGuesses *= m_pmcSymbols->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcSymbols->GuessNumber(szTemp, 1.0)/1e+9); #endif } else if ( iThis == IS_DIGIT ) { dNGuesses *= m_pmcDigits->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcDigits->GuessNumber(szTemp, 1.0)/1e+9); #endif } else if ( nSameClass < m_pmcAlphaN->m_nGrams ) { dNGuesses *= m_pmcAlpha1->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcAlpha1->GuessNumber(szTemp, 1.0)/1e+9); #endif } else { dNGuesses *= m_pmcAlphaN->GuessNumber(szTemp); #ifdef PRINT_DEBUG printf( "%s has g# %.3lf\n", szTemp, m_pmcAlphaN->GuessNumber(szTemp, 1.0)/1e+9); #endif } pSyntax = (CBaseStructure *)m_phtStructures->Lookup(syntax.m_szWord); dTemp = (pSyntax == NULL) ? 1.0/(1.0 + m_nStructures) : (double)pSyntax->m_nCount/(double)m_nStructures; // probability of choosing this structure if ( bCrackedIt ) dFixedGuesses /= dTemp; else dNGuesses /= dTemp; #ifdef PRINT_DEBUG printf("p(%s) = %lf\n", syntax.szNonTerminals, dTemp); #endif return dFixedGuesses + (bCrackedIt ? 0 : dNGuesses); } int CPCFG::LoadFromFile(const char *szPathPCFG, int nGrams, bool bUseDictionaries) { char szBuf[2048]; FILE *fp = fopen(szPathPCFG, "r"); CBaseStructure Word, *pWord; if ( fp == NULL ) return 0; if ( m_phtStructures == NULL ) { m_phtStructures = new CHashTable(65537, sizeof(CBaseStructure)); m_phtCaseMask = new CHashTable(3, sizeof(CBaseStructure)); //65537 m_pmcAlphaN = new CMarkovChainAlpha(nGrams); m_pmcAlpha1 = new CMarkovChainAlpha(1); m_pmcDigits = new CMarkovChainDigit; m_pmcSymbols = new CMarkovChainSymbol; } if ( !m_pmcAlpha1->LoadFromFile(fp, false, bUseDictionaries) // read in the markov chain data for the letter n-grams || !m_pmcAlphaN->LoadFromFile(fp, false, bUseDictionaries) // read in the markov chain data for the letter 1-grams || !m_pmcDigits->LoadFromFile(fp, false, bUseDictionaries) // read in the markov chain data for the digits || !m_pmcSymbols->LoadFromFile(fp, false, bUseDictionaries) // read in the markov chain data for the symbols ) { #ifdef PRINT_DEBUG printf("MC load failed - aborting"); #endif return 0; } // next, read the case masks while ( fgets(szBuf, sizeof(szBuf), fp) && szBuf[0] > ' ' ) { if ( sscanf(szBuf, "%s %d", Word.m_szWord, &Word.m_nCount) == 2 ) { pWord = (CBaseStructure *)m_phtCaseMask->Lookup(Word.m_szWord); if ( pWord == NULL ) { m_phtCaseMask->Insert((void *)&Word); } else { pWord->m_nCount += Word.m_nCount; } m_nCaseMasks += Word.m_nCount; } else { #ifdef PRINT_DEBUG fprintf( stderr, "can't parse %s\n", szBuf); getchar(); #endif } } // last, read the sentence structures while ( fgets(szBuf, sizeof(szBuf), fp) && szBuf[0] > ' ' ) { if ( sscanf(szBuf, "%s %d", Word.m_szWord, &Word.m_nCount) == 2 ) { pWord = (CBaseStructure *)m_phtStructures->Lookup(Word.m_szWord); if ( pWord == NULL ) { m_phtStructures->Insert((void *)&Word); } else { pWord->m_nCount += Word.m_nCount; } m_nStructures += Word.m_nCount; } else { #ifdef PRINT_DEBUG fprintf( stderr, "can't parse %s\n", szBuf); getchar(); #endif } } // All done! fclose(fp); return 1; } /* void CPCFG::AddWordToDictionary(char *szWord) { bool bIsAllAlpha = true; bool bIsAllDigits = true; bool bIsAllSymbols = true; int i; for ( i = 0; szWord[i]; ++i ) { if ( isalpha(szWord[i]) ) { bIsAllDigits = false; bIsAllSymbols = false; } else if ( isdigit(szWord[i]) ) { bIsAllAlpha = false; bIsAllSymbols = false; } else if ( szWord[i] >= ' ' && szWord[i] <= '~' ) { bIsAllAlpha = false; bIsAllDigits = false; } else { return; } } m_phtDictionary->Insert(strlwr(szWord)); if ( bIsAllAlpha ) m_anAlphaStringLengths[i]++; else if ( bIsAllDigits ) m_anDigitStringLengths[i]++; else if ( bIsAllSymbols ) m_anSymbolStringLengths[i]++; else m_anMixedStringLengths[i]++; } */ int CPCFG::LoadDictionary(const char *szPathDictionary) { return m_pmcAlphaN->LoadDictionary(szPathDictionary); /* char szBuf[2048]; FILE *fp = fopen(szPathDictionary, "r"); if ( fp == NULL ) return 0; if ( m_phtDictionary == NULL ) m_phtDictionary = new CHashTable(1500007, sizeof(CBaseStructure)); while ( fgets(szBuf, sizeof(szBuf), fp) ) { int n = strlen(szBuf) - 1; if ( n > 0 && n <= MAX_LENGTH ) { szBuf[n] = '\0'; AddWordToDictionary(szBuf); } } fclose(fp); return 1; */ } void CPCFG::ProcessWord(const char *szWord) { int xWord, xState, xBegin, x; char szBuf[1+MAX_LENGTH], szMask[1+MAX_LENGTH]; CBaseStructure Syntax, *pSyntax; for ( xWord = xBegin = xState = x = 0; szWord[xWord]; ++xWord ) { if ( isalpha(szWord[xWord]) ) { if ( xWord && xState != IS_ALPHA ) { szBuf[x] = '\0'; if ( xState == IS_SYMBOL ) { m_pmcSymbols->ProcessWord(szBuf); } else { m_pmcDigits->ProcessWord(szBuf); } xBegin = xWord; x = 0; } xState = IS_ALPHA; } else if ( isdigit(szWord[xWord]) ) { if ( xWord && xState != IS_DIGIT ) { szBuf[x] = '\0'; szMask[x] = '\0'; if ( xState == IS_SYMBOL ) { m_pmcSymbols->ProcessWord(szBuf); } else { if ( x < m_pmcAlphaN->m_nGrams ) m_pmcAlpha1->ProcessWord(szBuf); else m_pmcAlphaN->ProcessWord(szBuf); AddCaseMask(szMask); } xBegin = xWord; x = 0; } xState = IS_DIGIT; } else { if ( xWord && xState != IS_SYMBOL ) { szBuf[x] = '\0'; szMask[x] = '\0'; if ( xState == IS_DIGIT ) { m_pmcDigits->ProcessWord(szBuf); } else { if ( x < m_pmcAlphaN->m_nGrams ) m_pmcAlpha1->ProcessWord(szBuf); else m_pmcAlphaN->ProcessWord(szBuf); AddCaseMask(szMask); } xBegin = xWord; x = 0; } xState = IS_SYMBOL; } szBuf[x] = szWord[xWord]; szMask[x] = (xState == IS_ALPHA) ? (isupper(szWord[xWord]) ? IS_UPPER : IS_LOWER) : xState; Syntax.m_szWord[xWord] = szMask[x]; ++x; } szBuf[x] = '\0'; szMask[x] = '\0'; if ( xState == IS_ALPHA ) { if ( x < m_pmcAlphaN->m_nGrams ) m_pmcAlpha1->ProcessWord(szBuf); else m_pmcAlphaN->ProcessWord(szBuf); AddCaseMask(szMask); } else if ( xState == IS_DIGIT ) { m_pmcDigits->ProcessWord(szBuf); } else { m_pmcSymbols->ProcessWord(szBuf); } Syntax.m_szWord[xWord] = '\0'; Syntax.m_nCount = 0; pSyntax = (CBaseStructure *)m_phtStructures->Insert(&Syntax); pSyntax->m_nCount++; m_nStructures++; } void CPCFG::AddCaseMask(const char *szMask) { return; /* CBaseStructure Mask, *pMask; strcpy(Mask.m_szWord, szMask); Mask.m_nCount = 0; pMask = (CBaseStructure *)m_phtCaseMask->Insert(&Mask); pMask->m_nCount++; m_nCaseMasks++; m_anCaseMaskLength[strlen(szMask)]++; */ } void CPCFG::WriteToTextFile(const char *szPath) { unsigned x; FILE *fp = fopen(szPath, "w"); if ( fp == NULL ) return; m_pmcAlpha1->WriteToTextFile(fp); m_pmcAlphaN->WriteToTextFile(fp); m_pmcDigits->WriteToTextFile(fp); m_pmcSymbols->WriteToTextFile(fp); for ( x = 0; x < m_phtCaseMask->TableSize(); ++x ) { for ( CHashTableElement *pEl = m_phtCaseMask->Bucket(x); pEl != NULL; pEl = pEl->m_pNext ) { CBaseStructure *p = (CBaseStructure *)pEl->m_pData; fprintf(fp, "%s %d\n", p->m_szWord, p->m_nCount); } } fputc('\n', fp); for ( x = 0; x < m_phtStructures->TableSize(); ++x ) { for ( CHashTableElement *pEl = m_phtStructures->Bucket(x); pEl != NULL; pEl = pEl->m_pNext ) { CBaseStructure *p = (CBaseStructure *)pEl->m_pData; fprintf(fp, "%s %d\n", p->m_szWord, p->m_nCount); } } fputc('\n', fp); fclose(fp); } <file_sep>/README.md # PasswordGeneration CSE 543 - Fall 2016 - Assignment 1: Password Generation <file_sep>/Makefile # # File : Makefile # Environment Setup LIBDIRS=-L. -L/usr/local/lib -L/usr/lib64 INCLUDES=-I. -I/usr/local/include CC=gcc CFLAGS=-c $(INCLUDES) -g -Wall LINK=g++ -g LDFLAGS=$(LIBDIRS) AR=ar rc RANLIB=ranlib # Suffix rules .cpp.o : ${CC} ${CFLAGS} $< -o $@ .c.o : ${CC} ${CFLAGS} $< -o $@ mangler2 : mangler2.o hash.o chash.o classPCFG.o MarkovChain.o $(LINK) $(LDFLAGS) mangler2.o hash.o chash.o MarkovChain.o classPCFG.o $(LIBS) -o $@ mangler : mangler.o hash.o chash.o $(LINK) $(LDFLAGS) mangler.o hash.o chash.o $(LIBS) -o $@ pwdstats : pwdstats.o $(LINK) $(LDFLAGS) pwdstats.o $(LIBS) -o $@ splitpwd : splitpwd.o $(LINK) $(LDFLAGS) splitpwd.o $(LIBS) -o $@ pcfgc : pcfgc.o hash.o chash.o $(LINK) $(LDFLAGS) pcfgc.o hash.o $(LIBS) -o $@ pcfgc2 : pcfgc2.o hash.o chash.o MarkovChain.o classPCFG.o $(LINK) $(LDFLAGS) pcfgc2.o hash.o chash.o MarkovChain.o classPCFG.o $(LIBS) -o $@ locktest : locktest.o $(LINK) $(LDFLAGS) locktest.o $(LIBS) -o $@ mcc2 : mcc2.o chash.o hash.o MarkovChain.o $(LINK) $(LDFLAGS) mcc2.o hash.o chash.o MarkovChain.o $(LIBS) -o $@ MarkovCracker : MarkovCracker.o hash.o chash.o $(LINK) $(LDFLAGS) MarkovCracker.o hash.o chash.o $(LIBS) -o $@ markov : markov.o hash.o chash.o $(LINK) $(LDFLAGS) markov.o hash.o chash.o $(LIBS) -o $@ markov2 : markov2.o hash.o chash.o $(LINK) $(LDFLAGS) markov2.o hash.o chash.o $(LIBS) -o $@ BASENAME=p1-crypto tar: tar cvfz $(BASENAME).tgz -C ..\ $(BASENAME)/Makefile \ $(BASENAME)/cse543-gcrypt.c \ $(BASENAME)/cse543-gcrypt.h \ $(BASENAME)/cse543-util.c \ $(BASENAME)/cse543-util.h <file_sep>/chash.cpp #include "chash.h" #include <cstring> /* #include <stdafx.h> */ /* ** Hash routines ** ** Assume item to hash is null-terminated string at start of structure ** */ CHashTable::CHashTable(unsigned uTableSize, unsigned uSizeOfData) { unsigned i; m_uBuckets = uTableSize; m_uDatumSize = uSizeOfData; m_uCount = 0; m_ppChain = new CHashTableElement * [uTableSize]; for ( i = 0; i < uTableSize; ++i ) { m_ppChain[i] = NULL; } } CHashTable::~CHashTable() { unsigned x; CHashTableElement *p, *q; for ( x = 0; x < m_uBuckets; ++x ) { for ( p = m_ppChain[x]; p != NULL; p = q ) { q = p->m_pNext; delete p; } } delete [] m_ppChain; return; } CHashTableElement::CHashTableElement(const void *pCopyIt, unsigned uSize) { #ifdef HASH_SUPPORTS_DELETE m_pPrev = NULL; #endif m_pNext = NULL; m_pData = new char [uSize]; memcpy(m_pData, pCopyIt, uSize); } CHashTableElement::~CHashTableElement() { delete [] m_pData; } unsigned CHashTable::Hash(const char *szSearchFor) { unsigned uHashValue = 2166136261u; unsigned uPrimeFNV = (1 << 24) + (1 << 8) + 0x93; while ( *szSearchFor ) { uHashValue ^= *szSearchFor++; uHashValue *= uPrimeFNV; } return uHashValue % m_uBuckets; } void * CHashTable::Lookup(const char *szSearchFor) { unsigned xBucket = Hash(szSearchFor); CHashTableElement *pEl; for ( pEl = m_ppChain[xBucket]; pEl != NULL && strcmp(szSearchFor, (char *)pEl->m_pData) != 0; pEl = pEl->m_pNext ) { } return *szSearchFor && pEl != NULL ? pEl->m_pData : NULL; } void * CHashTable::Insert(const void *pItem) { void *p = Lookup((char *)pItem); unsigned xBucket; CHashTableElement *pEl; if ( p != NULL ) return p; pEl = new CHashTableElement(pItem, m_uDatumSize); xBucket = Hash((char *)pItem); pEl->m_pNext = m_ppChain[xBucket]; #ifdef HASH_SUPPORTS_DELETE if ( pEl->m_pNext != NULL ) pEl->m_pNext->m_pPrev = pEl; pEl->m_pPrev = NULL; #endif m_ppChain[xBucket] = pEl; ++m_uCount; return pEl->m_pData; } int CHashTable::Delete(const char *szSearchFor) { unsigned xBucket = Hash(szSearchFor); CHashTableElement *pEl; for ( pEl = m_ppChain[xBucket]; pEl != NULL && strcmp(szSearchFor, (char *)pEl->m_pData) != 0; pEl = pEl->m_pNext ) { } if ( pEl != NULL ) { if ( pEl->m_pNext != NULL ) pEl->m_pNext->m_pPrev = pEl->m_pPrev; if ( pEl->m_pPrev != NULL ) pEl->m_pPrev->m_pNext = pEl->m_pNext; else m_ppChain[xBucket] = pEl->m_pNext; delete pEl; return 1; } return 0; } <file_sep>/classPCFG.h #include "MarkovChain.h" #define IS_ALPHA 'A' #define IS_UPPER 'U' #define IS_LOWER 'L' #define IS_DIGIT 'D' #define IS_SYMBOL 'S' class CPCFG { private: CMarkovChainAlpha *m_pmcAlphaN; CMarkovChainAlpha *m_pmcAlpha1; CMarkovChainDigit *m_pmcDigits; CMarkovChainSymbol *m_pmcSymbols; bool m_bAreProbabilities; int m_nStructures; // non-unique: sum of counts of all structures seen int m_nCaseMasks; int m_anCaseMaskLength[1+MAX_LENGTH]; //int m_anAlphaStringLengths[1+MAX_LENGTH]; //int m_anDigitStringLengths[1+MAX_LENGTH]; //int m_anSymbolStringLengths[1+MAX_LENGTH]; //int m_anMixedStringLengths[1+MAX_LENGTH]; //CHashTable *m_phtDictionary; CHashTable *m_phtStructures; CHashTable *m_phtCaseMask; CBaseStructure *m_apStructures; int m_nBillions; int m_nGuesses; int m_nGuessed; int m_nProcessor; void AddCharacters(int nToAdd, int xOriginalState, char *szCharClass, int xPwd, char *szSyntax, CMarkovChain *pmc, double dProbSoFar); void BuildPassword(int xPwd, char *szNonTerminals, double dProbSoFar); public: CPCFG(int nGrams = 0); ~CPCFG(); int nGrams() const { return m_pmcAlphaN->m_nGrams; } void ProcessWord(const char *szWord); void AddCaseMask(const char *szMask); int LoadFromFile(const char *szPath, int nGrams, bool bUseDictionaries = true); int LoadDictionary(const char *szPathDictionary); int Guessed() const { return m_nGuessed; } //void AddWordToDictionary(char *szWord); void ConvertCountsToProb(bool bSmoothProbabilities); void ThresholdGuessing(); double GuessNumber(const char *szPassword); CHashTable *m_phtPasswords; char m_szGuessing[1+MAX_LENGTH]; int m_nLengthToGuess; double m_dThresholdP; void WriteToTextFile(const char *szPath); }; <file_sep>/PCFGmfc.h #include "MarkovChain.h" #define IS_UPPER 'U' #define IS_LOWER 'L' #define IS_DIGIT 'D' #define IS_SYMBOL 'S' typedef struct { char szNonTerminals[2*MAX_LENGTH+1]; double dPercentage; } PwdStructure; class CPCFG { private: CMarkovChainAlpha *m_pmcAlphaN; CMarkovChainAlpha *m_pmcAlpha1; CMarkovChainDigit *m_pmcDigits; CMarkovChainSymbol *m_pmcSymbols; int m_nStructures; double m_dAvgWordLength; int m_anWordLengths[MAX_LENGTH+1]; int m_anAndShorter[MAX_LENGTH+1]; CHashTable *m_phtDictionary; CHashTable *m_phtStructures; int m_nBillions; int m_nGuesses; int m_nProcessor; void AddCharacters(int nToAdd, int xOriginalState, char *szCharClass, int xPwd, char *szSyntax, CMarkovChain *pmc, double dProbSoFar); void BuildPassword(int xPwd, char *szNonTerminals, double dProbSoFar); public: CPCFG(); ~CPCFG(); int LoadFromFile(char *szPath, int nGrams); int LoadDictionary(char *szPathDictionary); void ConvertCountsToProb(); void ThresholdGuessing(); double GuessNumber(char *szPassword); CHashTable *m_phtPasswords; char m_szGuessing[1+MAX_LENGTH]; int m_nLengthToGuess; double m_dThresholdP; }; <file_sep>/modTest.sh #!/usr/bin/env bash # <NAME> 2016 # remove existing output files rm -f crack-file rm -f mod-crack-file rm -f *.pcfg1 rm -f *.mc1 echo "Strengthening Lists" # My strengthen program takes an an existing file # and the name of the output file # You should modify this for however you generate # stregthened training and test data strengthen.py rockyou.txt.6.1.a modOutTrain.txt strengthen.py rockyou.txt.6.1.b modOutTest.txt echo "Generated Strengthened Lists" # Train the markov models, we don't need the output # file name so redirect it to /dev/null markov 1 modOutTrain.txt > /dev/null markov 1 rockyou.txt.6.1.a > /dev/null echo "Generated Markov Models" # Run the pcfgc program and specify the output files pcfgc 1 modOutTest.txt modOutTrain.txt.pcfg1 > mod-crack-file pcfgc 1 rockyou.txt.6.1.b rockyou.txt.6.1.a.pcfg1 > crack-file echo "Ran PCFGS" # I'm choosing to show both the modified and unmodified lists' # cracking data printf "\nModified Passwords\n" pwdstats < mod-crack-file printf "\nUnmodified Passwords\n" pwdstats < crack-file <file_sep>/mangler2.cpp #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <string.h> #include <assert.h> #include <time.h> #include "classPCFG.h" //#define PRINT_DEBUG //#define NDEBUG #define MAX_PCFG 12 #define MAX_MC 12 #define TARGET_MIN_GUESS 10e+6 #define MIN_ORIGINAL_GUESS 100 #define N_NEW_ATTEMPTS 32 int InsertChars(char *szAddToMe) { char szTemp[MAX_LENGTH*2+1]; int x, ch; int iLength = strlen(szAddToMe); if ( iLength >= MAX_LENGTH ) return 0; x = rand() % (iLength+1); ch = (rand() % ('~' - ' ' + 1)) + ' '; sprintf(szTemp, "%.*s%c%s", x, szAddToMe, ch, szAddToMe+x); strcpy(szAddToMe, szTemp); return 1; } int ChangeChars(char *szAddToMe) { int x, ch; int iLength = strlen(szAddToMe); x = rand() % iLength; ch = (rand() % ('~' - ' ' + 1)) + ' '; szAddToMe[x] = ch; return 1; } int main(int argc, char **argv) { char szBuf[2048], szStrong[1+MAX_LENGTH], *pszDictionary = NULL, *pszInputFile = NULL; int nChangesMin = 1, iFilter = 0, iMangle = 1, iMCfile = 0, iPCFGfile = 0, nToDo; int nGrams, i, nAttempts, xArg, nPwdChars, nPCFG = 0, nMC = 0; double dNGuesses; double dLowThreshold = MIN_ORIGINAL_GUESS; double dRequiredGuesses = TARGET_MIN_GUESS; FILE *fp; CPCFG apcfg[MAX_PCFG]; CMarkovChain *apmc[MAX_MC]; srand((unsigned)time(NULL)); if ( argc == 1 ) { printf( "usage: %s -i InputFile -g MinGuess# -l LowerGuess# -d DictionaryFile -c MinChanges -M|-F -m[123] MCfile1 ... -p[123] PCFGfile ... \n", argv[0] ); return 0; } for ( xArg = 1; xArg < argc; ++xArg ) { if ( argv[xArg][0] == '-' ) { iMCfile = 0; iPCFGfile = 0; switch( argv[xArg][1] ) { case 'd': pszDictionary = argv[++xArg]; break; case 'c': nChangesMin = argv[xArg][2] ? atoi(&argv[xArg][2]) : atoi(argv[++xArg]); break; case 'g': dRequiredGuesses = argv[xArg][2] ? atof(&argv[xArg][2]) : atof(argv[++xArg]); break; case 'l': dLowThreshold = argv[xArg][2] ? atof(&argv[xArg][2]) : atof(argv[++xArg]); break; case 'M': iMangle = 1; iFilter = 0; break; case 'F': iMangle = 0; iFilter = 1; break; case 'i': pszInputFile = argv[++xArg]; break; case 'm': iMCfile = 1; if ( argv[xArg][2] < '1' || argv[xArg][2] > '3' ) { printf( "%s: unknown argument %s \n", argv[0], argv[xArg] ); return 0; } nGrams = argv[xArg][2] - '0'; break; case 'p': iPCFGfile = 1; if ( argv[xArg][2] < '1' || argv[xArg][2] > '3' ) { printf( "%s: unknown argument %s \n", argv[0], argv[xArg] ); return 0; } nGrams = argv[xArg][2] - '0'; break; default: printf( "%s: unknown argument %s \n", argv[0], argv[xArg] ); return 0; } } else if ( iMCfile ) { if ( nMC == MAX_MC ) { printf( "%s: too many markov chain files; %d max\n", argv[0], MAX_MC ); return 0; } fprintf(stderr, "Loading %s\n", argv[xArg]); apmc[nMC] = new CMarkovChain(N_CHARS, nGrams); if ( !apmc[nMC]->LoadFromFile(argv[xArg]) ) { printf( "%s: Load of %s failed!\n", argv[0], argv[xArg] ); return 0; } else { apmc[nMC]->ConvertCountsToProb(true); } if ( pszDictionary != NULL && !apmc[nMC]->LoadDictionary(pszDictionary) ) { printf( "%s: Load of dictionary %s failed!\n", argv[0], pszDictionary ); } ++nMC; } else if ( iPCFGfile ) { if ( nPCFG == MAX_PCFG ) { printf( "%s: too many PCFG files; %d max\n", argv[0], MAX_PCFG ); return 0; } fprintf(stderr, "Loading %s\n", argv[xArg]); if ( !apcfg[nPCFG].LoadFromFile(argv[xArg], nGrams) ) { printf( "%s: Load of %s failed!\n", argv[0], argv[xArg] ); return 0; } else { apcfg[nPCFG].ConvertCountsToProb(true); } if ( pszDictionary != NULL && !apcfg[nPCFG].LoadDictionary(pszDictionary) ) { printf( "%s: Load of dictionary %s failed!\n", argv[0], pszDictionary ); } ++nPCFG; } else { printf( "%s: unknown argument %s \n", argv[0], argv[xArg] ); return 0; } } if ( !nMC && !nPCFG ) { printf( "%s: must specify at least one MC or PCFG file\n", argv[0] ); return 0; } else if ( !pszInputFile ) { printf( "%s: must specify input file\n", argv[0] ); return 0; } fp = fopen(pszInputFile, "r"); if ( fp == NULL ) { printf( "%s: can't open input file %s\n", argv[0], pszInputFile ); return 0; } while ( fgets(szBuf, sizeof(szBuf), fp) ) { #ifdef PRINT_DEBUG fprintf(stderr, "%s", szBuf); #endif nPwdChars = strlen(szBuf); szBuf[--nPwdChars] = '\0'; if (nPwdChars > MAX_LENGTH) continue; strcpy(szStrong, szBuf); for ( dNGuesses = 1e+99, i = 0; i < nMC; ++i ) { double dNewN = apmc[i]->GuessNumber(szStrong) / 1e+9; #ifdef PRINT_DEBUG fprintf(stderr, "mcg#[%d] = %lg\n", i, dNewN); #endif if ( dNewN < dNGuesses ) dNGuesses = dNewN; } for ( i = 0; i < nPCFG; ++i ) { double dNewN = apcfg[i].GuessNumber(szStrong) / 1e+9; #ifdef PRINT_DEBUG fprintf(stderr, "pcfgg#[%d] = %lg\n", i, dNewN); #endif if ( dNewN < dNGuesses ) dNGuesses = dNewN; } if ( dNGuesses < dLowThreshold ) continue; if ( iFilter ) { puts(szBuf); continue; } #ifdef PRINT_DEBUG fprintf(stderr, "Original g# = %lf\n", dNGuesses); //getchar(); #endif for ( nToDo = nChangesMin; dNGuesses < dRequiredGuesses; ++nToDo ) { for ( nAttempts = 0; nAttempts < N_NEW_ATTEMPTS && dNGuesses < dRequiredGuesses; ++nAttempts ) { strcpy(szStrong, szBuf); #ifdef PRINT_DEBUG printf("%s - making %d changes\n", szStrong, nToDo); #endif for ( i = 0; i < nToDo; ) { i += (rand() & 1) ? ChangeChars(szStrong) : InsertChars(szStrong); #ifdef PRINT_DEBUG printf("%s - after %d changes\n", szStrong, i); #endif } for ( dNGuesses = 1e+99, i = 0; i < nMC; ++i ) { double dNewN = apmc[i]->GuessNumber(szStrong) / 1e+9; #ifdef PRINT_DEBUG fprintf(stderr, "mcg#[%d] = %lf\n", i, dNewN); #endif if ( dNewN < dNGuesses ) dNGuesses = dNewN; } for ( i = 0; i < nPCFG; ++i ) { double dNewN = apcfg[i].GuessNumber(szStrong) / 1e+9; #ifdef PRINT_DEBUG fprintf(stderr, "pcfgg#[%d] = %lg\n", i, dNewN); #endif if ( dNewN < dNGuesses ) dNGuesses = dNewN; } #ifdef PRINT_DEBUG printf( "%s --> --|%s|-- ; %d changes; g# now %lg\n", szBuf, szStrong, nToDo, dNGuesses ); #endif } } printf("%s\n", szStrong); #ifdef PRINT_DEBUG //getchar(); #endif } fclose(fp); /* Clean up, go home */ for ( i = 0; i < nMC; ++i ) { delete apmc[i]; } return 0; } <file_sep>/Markovmfc.h #ifndef MARKOVCHAIN_H_INCLUDED #define MARKOVCHAIN_H_INCLUDED #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #include <stdlib.h> #define N_CHARS 95 #define MAX_LENGTH 32 #define N_LETTERS 26 #define N_DIGITS 10 #define N_SYMBOLS 33 #include "hash.h" class CMarkovChain { public: CMarkovChain(int nChars, int nGrams); virtual ~CMarkovChain(); int m_nChars; int m_nGrams; int m_nPrefix; int m_nReduceModulus; int m_nBillions; int m_nGuesses; int m_nProcessor; int m_nTotalCount; double m_adLengthProb[1+MAX_LENGTH]; double m_dStartCount; double *m_pdTransitionCount; double (*m_padTransitionProb)[N_CHARS]; int (*m_paxTransitionProb)[N_CHARS]; double *m_pdStartProb; int *m_pxStartProb; virtual int ToCharacter(int x) { return x + ' '; } virtual int ToIndex(int ch) { return ch - ' '; } void AddStartCount(int xPrefix, int n); void AddTransitionCount(int xFrom, int xTo, int n); void BuildPassword(int xPwd, int xOriginalState, double dProbSoFar); int LoadFromFile(char *szPath); int LoadFromFile(FILE *fp, CMarkovChain *p1 = NULL); void ConvertCountsToProb(); int LoadDictionary(char *szPathDictionary); void ThresholdGuessing(); double GuessNumber(char *szPassword); char *m_pszCharacters; int *m_pnWordLengths; CHashTable *m_phtDictionary; CHashTable *m_phtPasswords; char m_szGuessing[1+MAX_LENGTH]; int m_nLengthToGuess; double m_dThresholdP; }; class CMarkovChainAll : public CMarkovChain { public: CMarkovChainAll(int nGrams); }; class CMarkovChainAlpha : public CMarkovChain { public: CMarkovChainAlpha(int nGrams); int ToCharacter(int x) { return x + 'a'; } int ToIndex(int ch) { return isupper(ch) ? (ch - 'A') : (ch - 'a'); } }; class CMarkovChainDigit : public CMarkovChain { public: CMarkovChainDigit(); int ToCharacter(int x) { return x + '0'; } int ToIndex(int ch) { return ch - '0'; } }; class CMarkovChainSymbol : public CMarkovChain { public: CMarkovChainSymbol(); char m_szSymbols[1+N_SYMBOLS]; int ToCharacter(int x) { return m_szSymbols[x]; } int ToIndex(int ch) { return strchr(m_szSymbols, ch) - m_szSymbols; } }; #endif <file_sep>/MarkovChain.cpp /* #include <stdafx.h> */ #include "MarkovChain.h" #include<ctype.h> inline char* strlwr( char* str ) { char* orig = str; // process the string for ( ; *str != '\0 '; str++ ) *str = tolower(*str); return orig; } //#define PRINT_DEBUG CBaseStructure::CBaseStructure() { m_szWord[0] = '\0'; m_nCount = 0; m_pNext = NULL; } static double *my_pdSortMeUsingIndex; static CBaseStructure **my_ppSortMeUsingIndex; static int IndirectSortDoubleDescending(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return (my_pdSortMeUsingIndex[x] > my_pdSortMeUsingIndex[y]) ? -1 : (my_pdSortMeUsingIndex[x] != my_pdSortMeUsingIndex[y]); } static int IndirectSortByCountDescending(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return (my_ppSortMeUsingIndex[x]->m_nCount > my_ppSortMeUsingIndex[y]->m_nCount) ? -1 : (my_ppSortMeUsingIndex[x]->m_nCount != my_ppSortMeUsingIndex[y]->m_nCount); } CMarkovChainAll::CMarkovChainAll(int nGrams) : CMarkovChain(N_CHARS, nGrams) { //m_phtDictionary = new CHashTable(1500007, sizeof(CBaseStructure)); m_phtDictionary = NULL; } CMarkovChainWords::CMarkovChainWords(int nGrams) : CMarkovChain(N_LETTERS+1, nGrams) { m_phtDictionary = NULL; m_dStartCount = 0.0; for ( int i = 0; i < m_nPrefix; ++i ) { m_pdStartProb[i] = 0.0; m_pxStartProb[i] = i; m_pdTransitionCount[i] = 0.0; for ( int j = 0; j < m_nChars; ++j ) { setTransitionProbability(i, j, 0.0); } } } CMarkovChainAlpha::CMarkovChainAlpha(int nGrams) : CMarkovChain(N_LETTERS, nGrams) { m_phtDictionary = new CHashTable(1500007, sizeof(CBaseStructure)); } CMarkovChainDigit::CMarkovChainDigit() : CMarkovChain(N_DIGITS, 1) { m_phtDictionary = new CHashTable(65537, sizeof(CBaseStructure)); } CMarkovChainSymbol::CMarkovChainSymbol() : CMarkovChain(N_SYMBOLS, 1) { int n, x; for ( x = 0, n = ' '; n <= '~'; ++n ) { if ( !isdigit(n) && !isalpha(n) ) m_szSymbols[x++] = n; } m_szSymbols[x] = '\0'; assert(x == N_SYMBOLS); m_pszCharacters = m_szSymbols; m_phtDictionary = new CHashTable(65537, sizeof(CBaseStructure)); } CMarkovChain::CMarkovChain(int nChars, int nGrams) { int i, j; m_nGuesses = 0; m_nBillions = 0; m_nProcessor = 'a'; m_dThresholdP = 1e-13; m_phtPasswords = NULL; m_phtDictionary = NULL; m_bAreProbabilities = false; m_nChars = nChars; m_nGrams = nGrams; m_nPrefix = (int)pow((double)m_nChars, (double)nGrams); m_nReduceModulus = m_nPrefix / m_nChars; m_pszCharacters = NULL; for ( i = 0; i <= MAX_LENGTH; ++i ) { m_adLengthProb[i] = 1.0; m_anUniqueWords[i] = 0; m_anWordsSeen[i] = 0; m_apWordLists[i] = NULL; } #ifdef PRINT_DEBUG puts("Allocating memory"); #endif m_pdStartProb = new double [m_nPrefix]; m_pxStartProb = new int [m_nPrefix]; m_pdTransitionCount = new double [m_nPrefix]; m_pdTransitionProb = new double [m_nPrefix * m_nChars]; m_pxTransitionProb = NULL; //new int [m_nPrefix * m_nChars]; #ifdef PRINT_DEBUG puts("Done allocating memory"); #endif m_dStartCount = 1.0; for ( i = 0; i < m_nPrefix; ++i ) { m_pdStartProb[i] = 1.0 / m_nPrefix; m_pxStartProb[i] = i; m_pdTransitionCount[i] = 1.0; for ( j = 0; j < m_nChars; ++j ) { setTransitionProbability(i, j, 1.0 / m_nChars); //setTransitionProbabilityIndex(i, j, j); } } } CMarkovChain::~CMarkovChain() { delete [] m_pdStartProb; delete [] m_pxStartProb; delete [] m_pdTransitionProb; if ( m_pdTransitionCount != NULL ) delete [] m_pdTransitionCount; if ( m_pxTransitionProb != NULL ) delete [] m_pxTransitionProb; if ( m_phtDictionary != NULL ) delete m_phtDictionary; if ( m_phtPasswords != NULL ) delete m_phtPasswords; } void CMarkovChain::AddStartCount(int xPrefix, int n) { m_dStartCount += n; m_pdStartProb[xPrefix] += n; } void CMarkovChain::AddTransitionCount(int xFrom, int xTo, int n) { m_pdTransitionCount[xFrom] += n; increaseTransitionCount(xFrom, xTo, n); } void CMarkovChain::ConvertCountsToProb(bool bSmoothProbabilities, bool bDoLengths) { int i, j; double dStartEqual = 1.0 / (double)m_nPrefix; double dTransEqual = 1.0 / (double)m_nChars; double dStartCountLess = 0.0, dStartTotalLess = 0.0; m_pxTransitionProb = new int [m_nPrefix * m_nChars]; for ( i = 0; i < m_nPrefix; ++i ) { for ( j = 0; j < m_nChars; ++j ) { setTransitionProbabilityIndex(i, j, j); } } m_bAreProbabilities = true; for ( i = 0; i < m_nPrefix; ++i ) { double dTransCountLess = 0.0, dTransTotalLess = 0.0; m_pdStartProb[i] /= m_dStartCount; if ( m_pdStartProb[i] < dStartEqual ) { dStartCountLess += 1.0; dStartTotalLess += m_pdStartProb[i]; } for ( j = 0; j < m_nChars; ++j ) { setTransitionProbability(i, j, getTransitionProbability(i, j) / m_pdTransitionCount[i]); if ( getTransitionProbability(i, j) < dTransEqual ) { dTransCountLess += 1.0; dTransTotalLess += getTransitionProbability(i, j); } } for ( j = 0; bSmoothProbabilities && j < m_nChars; ++j ) { if ( getTransitionProbability(i, j) < dTransEqual ) setTransitionProbability(i, j, dTransTotalLess / dTransCountLess); } my_pdSortMeUsingIndex = &m_pdTransitionProb[i * m_nChars]; qsort(&m_pxTransitionProb[i * m_nChars], m_nChars, sizeof(m_pxTransitionProb[0]), IndirectSortDoubleDescending); } delete [] m_pdTransitionCount; m_pdTransitionCount = NULL; for ( i = 0; bSmoothProbabilities && i < m_nPrefix; ++i ) { if ( m_pdStartProb[i] < dStartEqual ) m_pdStartProb[i] = dStartTotalLess / dStartCountLess; } my_pdSortMeUsingIndex = m_pdStartProb; qsort(m_pxStartProb, m_nPrefix, sizeof(m_pxStartProb[0]), IndirectSortDoubleDescending); if ( bDoLengths ) { for ( i = 1; i <= MAX_LENGTH; ++i ) { m_adLengthProb[i] /= (m_dStartCount - m_nPrefix + MAX_LENGTH); } } // Sort word lists if ( m_apWordLists != NULL ) { for ( i = 1; i <= MAX_LENGTH; ++i ) { int j, nWords = m_anUniqueWords[i], *px; CBaseStructure *p = m_apWordLists[i]; if ( nWords <= 1 ) continue; my_ppSortMeUsingIndex = new CBaseStructure * [nWords]; px = new int [nWords]; for ( j = 0; p != NULL; ++j ) { px[j] = j; my_ppSortMeUsingIndex[j] = p; p = p->m_pNext; } qsort(px, nWords, sizeof(px[0]), IndirectSortByCountDescending); m_apWordLists[i] = my_ppSortMeUsingIndex[px[0]]; for ( j = 1; j < nWords; ++j ) { my_ppSortMeUsingIndex[px[j-1]]->m_pNext = my_ppSortMeUsingIndex[px[j]]; } my_ppSortMeUsingIndex[px[j-1]]->m_pNext = NULL; delete [] my_ppSortMeUsingIndex; delete [] px; } } } void CMarkovChain::BuildPassword(int xPwd, int xOriginalState, double dProbSoFar) { int i, iChar, xPreState; if ( xPwd == m_nLengthToGuess ) { if ( ++m_nGuesses == 1000000000 ) { ++m_nBillions; m_nGuesses = 0; } m_szGuessing[xPwd] = '\0'; if ( m_phtPasswords->Delete(m_szGuessing) ) { printf( "%c\t%d.%09d\t%s\t%.03lf\n", m_nProcessor, m_nBillions, m_nGuesses, m_szGuessing, 1e-9/dProbSoFar ); fflush(stdout); } } else { xPreState = (xOriginalState % m_nReduceModulus) * m_nChars; for ( i = 0; i < m_nChars; ++i ) { iChar = getTransitionProbabilityIndex(xOriginalState, i); if ( dProbSoFar * getTransitionProbability(xOriginalState, iChar) < m_dThresholdP ) break; m_szGuessing[xPwd] = this->ToCharacter(iChar); BuildPassword(xPwd+1, xPreState + iChar, dProbSoFar * getTransitionProbability(xOriginalState, iChar)); } } } double CMarkovChain::GuessNumber(const char *szPwd, bool bUseDictionary) { int i, xRow; int nPwdChars = strlen(szPwd); char szTemp[1+MAX_LENGTH]; double dFixedGuesses = 0, dNGuesses = 1.0; double dLengthProb = m_bAreProbabilities ? m_adLengthProb[nPwdChars] : (m_adLengthProb[nPwdChars] / m_dStartCount); #ifdef TRY_DICTIONARY_ATTACKS if ( m_phtDictionary != NULL && bUseDictionary ) { strcpy(szTemp, szPwd); // Try dictionary attacks first dFixedGuesses += m_anUniqueWords[nPwdChars] / 2; if ( m_phtDictionary->Lookup(szTemp) ) { #ifdef PRINT_DEBUG printf( "Cracked %s in %lf attempts - word\n", szPwd, dFixedGuesses ); #endif return dFixedGuesses / dLengthProb; } else { dFixedGuesses += m_anUniqueWords[nPwdChars] / 2; #ifdef PRINT_DEBUG printf( "%s not in dictionary\n", szTemp ); #endif } #ifdef TRY_DELETING_1 for ( i = 0; szPwd[i]; ++i ) { dFixedGuesses += nPwdChars * m_anUniqueWords[nPwdChars-1] * m_nChars / 2; sprintf(szTemp, "%.*s%s", i, szPwd, &szPwd[i+1]); if ( m_phtDictionary->Lookup(szTemp) ) { #ifdef PRINT_DEBUG printf( "Cracked %s in %lf attempts - delete 1\n", szPwd, dFixedGuesses ); #endif return dFixedGuesses / dLengthProb; } else { dFixedGuesses += nPwdChars * m_anUniqueWords[nPwdChars-1] * m_nChars / 2; #ifdef PRINT_DEBUG printf( "%s not in dictionary\n", szTemp ); #endif } } #endif } #endif if ( nPwdChars < m_nGrams ) { return 0.5 * (dFixedGuesses + pow((double)m_nChars, nPwdChars)) / dLengthProb; } // Dictionary attacks failed - go to the chain! for ( xRow = i = 0; i < m_nGrams; ++i ) { xRow *= m_nChars; xRow += this->ToIndex(szPwd[i]); } if ( m_bAreProbabilities ) dNGuesses /= m_pdStartProb[xRow]; // probability of choosing this starting nGram else dNGuesses /= m_pdStartProb[xRow] / m_dStartCount; // probability of choosing this starting nGram #ifdef PRINT_DEBUG printf("p(start %d) = %lf (%lf)\n", xRow, m_pdStartProb[xRow], dNGuesses); #endif for ( ; szPwd[i] >= ' '; ++i ) { if ( m_bAreProbabilities ) dNGuesses /= getTransitionProbability(xRow, this->ToIndex(szPwd[i])); // Probability of choosing this next state else dNGuesses /= getTransitionProbability(xRow, this->ToIndex(szPwd[i])) / m_pdTransitionCount[xRow]; // Probability of choosing this next state #ifdef PRINT_DEBUG printf("p(trans: [%d,%d]) = %lf (%lf)\n", xRow, this->ToIndex(szPwd[i]), getTransitionProbability(xRow, this->ToIndex(szPwd[i])), dNGuesses); #endif xRow %= m_nReduceModulus; // throw out first char in old nGram xRow *= m_nChars; // and calculate the new nGram xRow += this->ToIndex(szPwd[i]); } #ifdef PRINT_DEBUG getchar(); #endif #ifdef PRINT_DEBUG printf("p(len) = %lf\n", dLengthProb); #endif return (dFixedGuesses + dNGuesses) / dLengthProb; } void CMarkovChain::ThresholdGuessing() { int xPwd, xNGram, i, j, iLen, jStart, jEnd; int axLength[1+MAX_LENGTH]; //double dCumProb; for ( i = 0; i <= MAX_LENGTH; ++i ) { axLength[i] = i; } my_pdSortMeUsingIndex = m_adLengthProb; qsort(axLength, 1+MAX_LENGTH, sizeof(axLength[0]), IndirectSortDoubleDescending); jStart = jEnd = 0; /* for ( dCumProb = 0.0, j = jStart = jEnd = 0; j < m_nPrefix; ++j ) { dCumProb += m_pdStartProb[m_pxStartProb[j]]; if ( dCumProb > 0.10 ) { jEnd = j+1; //if ( !fork() ) break; jStart = jEnd; dCumProb = 0.0; ++m_nProcessor; } } */ if ( jStart == jEnd ) { jEnd = m_nChars; } for ( j = jStart; j < jEnd; ++j ) { xNGram = m_pxStartProb[j]; if ( m_pdStartProb[xNGram] < m_dThresholdP ) break; for ( i = 0; i <= MAX_LENGTH; ++i ) { iLen = axLength[i]; if ( m_adLengthProb[iLen] * m_pdStartProb[xNGram] < m_dThresholdP ) break; xPwd = 0; if ( m_nGrams == 1 ) { m_szGuessing[xPwd++] = this->ToCharacter(xNGram); } else if ( m_nGrams == 2 ) { m_szGuessing[xPwd++] = this->ToCharacter(xNGram / m_nChars); m_szGuessing[xPwd++] = this->ToCharacter(xNGram % m_nChars); } else if ( m_nGrams == 3 ) { m_szGuessing[xPwd++] = this->ToCharacter(xNGram / (m_nChars * m_nChars)); m_szGuessing[xPwd++] = this->ToCharacter((xNGram / m_nChars) % m_nChars); m_szGuessing[xPwd++] = this->ToCharacter(xNGram % m_nChars); } else if ( m_nGrams == 4 ) { m_szGuessing[xPwd++] = this->ToCharacter(xNGram / (m_nChars * m_nChars * m_nChars)); m_szGuessing[xPwd++] = this->ToCharacter((xNGram / (m_nChars * m_nChars)) % m_nChars); m_szGuessing[xPwd++] = this->ToCharacter((xNGram / m_nChars) % m_nChars); m_szGuessing[xPwd++] = this->ToCharacter(xNGram % m_nChars); } BuildPassword(xPwd, xNGram, m_adLengthProb[iLen] * m_pdStartProb[xNGram]); } } } int CMarkovChain::LoadDictionary(const char *szPathDictionary) { char szBuf[2048]; int n; FILE *fp = fopen(szPathDictionary, "r"); if ( fp == NULL ) return 0; if ( m_phtDictionary == NULL ) m_phtDictionary = new CHashTable(1500007, sizeof(CBaseStructure)); while ( fgets(szBuf, sizeof(szBuf), fp) ) { n = strlen(szBuf) - 1; if ( n <= MAX_LENGTH ) { szBuf[n] = '\0'; AddToDictionary(szBuf); } } #ifdef PRINT_DEBUG printf("%d words in dictionary\n", m_phtDictionary->m_uCount); #endif fclose(fp); return 1; } int CMarkovChain::LoadFromFile(const char *szPath) { int iOK; FILE *fp = fopen(szPath, "r"); if ( fp != NULL ) { iOK = LoadFromFile(fp, true); fclose(fp); } else { iOK = 0; } return iOK; } int CMarkovChain::LoadFromFile(FILE *fp, bool bReadLengths, bool bUseDictionaries) { char szBuf[2048]; int i, xRow, xState, nLengths, n; fgets(szBuf, sizeof(szBuf), fp); // list of letters if ( m_pszCharacters != NULL ) { szBuf[strlen(szBuf) - 1] = '\0'; strcpy(m_pszCharacters, szBuf); #ifdef PRINT_DEBUG printf( "m_pszCharacters is now %s\n", m_pszCharacters); #endif } else { #ifdef PRINT_DEBUG printf( "%sm_pszCharacters is NULL\n", szBuf); #endif } for ( xRow = 0; xRow < m_nPrefix; ++xRow ) { fgets(szBuf, sizeof(szBuf), fp); for ( xState = -1, i = m_nGrams; xState < m_nChars; ++xState ) { if ( szBuf[i] != ' ' && szBuf[i] != '\t' ) { #ifdef PRINT_DEBUG printf("szBuf[i] != ' '\n%s[%d] = %d", szBuf, i, szBuf[i]); getchar(); #endif return 0; } sscanf( szBuf+i, "%d", &n ); if ( xState == -1 ) { AddStartCount(xRow, n); } else { AddTransitionCount(xRow, xState, n); } for ( ; szBuf[i] == ' ' || szBuf[i] == '\t'; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } if (szBuf[i] != '\n') { #ifdef PRINT_DEBUG printf("szBuf[i] != '\n'\n%s[%d] = %d", szBuf, i, szBuf[i]); getchar(); #endif return 0; } } // Write the length distributions, if requested -- yes for stand-alone MC, no if part of PCFG if ( bReadLengths ) { fgets(szBuf, sizeof(szBuf), fp); /* length count */ sscanf(szBuf, "%d", &nLengths); if ( nLengths > MAX_LENGTH ) { #ifdef PRINT_DEBUG fprintf( stderr, "MAX_LENGTH not long enough for %s!!", szPath); #endif return 0; } else { fgets(szBuf, sizeof(szBuf), fp); /* read lengths into szBuf */ for ( i = 0, xRow = 1; xRow <= nLengths; ++xRow ) { if ( szBuf[i] != ' ') { return 0; } sscanf(szBuf+i, "%d", &n); m_adLengthProb[xRow] += n; #ifdef PRINT_DEBUG printf( "m_adLengthProb[%d] = %lf\n", xRow, m_adLengthProb[xRow]); #endif for ( ; szBuf[i] == ' '; ++i ) { } for ( ; szBuf[i] > ' '; ++i ) { } } if ( szBuf[i] != '\n' ) { #ifdef PRINT_DEBUG printf( "szBuf[i] != '\n');" ); #endif return 0; } } } while ( fgets(szBuf, sizeof(szBuf), fp) && szBuf[0] > ' ' ) { char szWord[1+MAX_LENGTH]; int nCount; //if ( m_phtDictionary == NULL ) m_phtDictionary = new CHashTable(1500007, sizeof(CBaseStructure)); if ( bUseDictionaries && sscanf(szBuf, "%s %d", szWord, &nCount) == 2 ) { if ( nCount <= 0 ) continue; for ( i = 0; szWord[i]; ++i ) { if ( szWord[i] == 0x7f ) szWord[i] = ' '; } AddToDictionary(szWord, nCount); } } return 1; } void CMarkovChain::ProcessWord(const char *szWord) { int xFrom = 0, i; for ( i = 0; szWord[i] && i < m_nGrams; ++i ) { xFrom *= m_nChars; xFrom += this->ToIndex(szWord[i]); } if ( i == m_nGrams ) { m_pdStartProb[xFrom]++; m_dStartCount++; m_adLengthProb[strlen(szWord)]++; AddToDictionary(szWord); } for ( ; szWord[i]; ++i ) { m_pdTransitionCount[xFrom]++; increaseTransitionCount(xFrom, this->ToIndex(szWord[i]), 1); xFrom %= m_nReduceModulus; xFrom *= m_nChars; xFrom += this->ToIndex(szWord[i]); } } void CMarkovChain::AddToDictionary(const char *szWord, int nTimes) { CBaseStructure Word, *pWord; int nChars = strlen(szWord); if ( m_phtDictionary != NULL ) { strcpy(Word.m_szWord, szWord); strlwr(Word.m_szWord); Word.m_nCount = 0; Word.m_pNext = NULL; pWord = (CBaseStructure *)m_phtDictionary->Insert(&Word); if ( !pWord->m_nCount ) { m_anUniqueWords[nChars]++; pWord->m_pNext = m_apWordLists[nChars]; m_apWordLists[nChars] = pWord; } pWord->m_nCount += nTimes; m_anWordsSeen[nChars] += nTimes; } } void CMarkovChain::WriteToTextFile(const char *szPath) { FILE *fp = fopen(szPath, "w"); if ( fp != NULL ) { WriteToTextFile(fp, true); fclose(fp); } } void CMarkovChain::WriteToTextFile(FILE *fp, bool bWriteLengths) { int i, j; for ( i = 0; i < m_nChars; ++i ) { fprintf(fp, "%c", this->ToCharacter(i)); } fputc('\n', fp); for ( i = 0; i < m_nPrefix; ++i ) { for ( int k1 = m_nGrams - 1; k1 >= 0; --k1 ) { j = i; for ( int k2 = k1; k2; --k2 ) { j /= m_nChars; } fprintf(fp, "%c", this->ToCharacter(j % m_nChars)); } fprintf(fp, "\t%.*lf", m_bAreProbabilities ? 9 : 0, m_pdStartProb[i]); for ( j = 0; j < m_nChars; ++j ) { fprintf(fp, "\t%.*lf", m_bAreProbabilities ? 9 : 0, getTransitionProbability(i,j)); } fputc('\n', fp); } if ( bWriteLengths ) { fprintf(fp, "%d word lengths\n", MAX_LENGTH); for ( i = 1; i <= MAX_LENGTH; ++i ) { fprintf(fp, " %.*lf", m_bAreProbabilities ? 9 : 0, m_adLengthProb[i]); } fputc('\n', fp); } if ( m_phtDictionary != NULL ) { for ( unsigned x = 0; x < m_phtDictionary->TableSize(); ++x ) { for ( CHashTableElement *pEl = m_phtDictionary->Bucket(x); pEl != NULL; pEl = pEl->m_pNext ) { CBaseStructure *p = (CBaseStructure *)pEl->m_pData; for ( i = 0; p->m_szWord[i]; ++i ) { if ( p->m_szWord[i] == ' ' ) p->m_szWord[i] = 0x7f; } fprintf(fp, "%s %d\n", p->m_szWord, p->m_nCount); } } } fputc('\n', fp); } void CMarkovChainWords::BuildAWord(char *szWord, int nMaxChars) { int xNGram, xChar, xWord = 0; double dThisProb, dCumProb; dThisProb = (double)(rand() & 0x7fff) / (double)0x7fff; for ( xNGram = 0, dCumProb = 0.0; (dCumProb += m_pdStartProb[m_pxStartProb[xNGram]]) < dThisProb; ++xNGram ) { } xNGram = m_pxStartProb[xNGram]; if ( m_nGrams == 1 ) { szWord[xWord++] = this->ToCharacter(xNGram); } else if ( m_nGrams == 2 ) { szWord[xWord++] = this->ToCharacter(xNGram / m_nChars); szWord[xWord++] = this->ToCharacter(xNGram % m_nChars); } else if ( m_nGrams == 3 ) { szWord[xWord++] = this->ToCharacter(xNGram / (m_nChars * m_nChars)); szWord[xWord++] = this->ToCharacter((xNGram / m_nChars) % m_nChars); szWord[xWord++] = this->ToCharacter(xNGram % m_nChars); } else if ( m_nGrams == 4 ) { szWord[xWord++] = this->ToCharacter(xNGram / (m_nChars * m_nChars * m_nChars)); szWord[xWord++] = this->ToCharacter((xNGram / (m_nChars * m_nChars)) % m_nChars); szWord[xWord++] = this->ToCharacter((xNGram / m_nChars) % m_nChars); szWord[xWord++] = this->ToCharacter(xNGram % m_nChars); } do { dThisProb = (double)(rand() & 0x7fff) / (double)0x7fff; for ( xChar = 0, dCumProb = 0.0; (dCumProb += getTransitionProbability(xNGram, getTransitionProbabilityIndex(xNGram, xChar))) < dThisProb; ++xChar ) { } xChar = getTransitionProbabilityIndex(xNGram, xChar); if ( xChar != N_LETTERS ) { szWord[xWord++] = this->ToCharacter(xChar); xNGram %= m_nReduceModulus; xNGram *= m_nChars; xNGram += xChar; } } while ( xWord < nMaxChars && xChar != N_LETTERS ); szWord[xWord] = '\0'; } <file_sep>/hash.c #include <stdio.h> #include <malloc.h> #include <string.h> #include "hash.h" /* ** Hash routines ** ** Assume item to hash is null-terminated string at start of structure ** */ HashTable *CreateHashTable(unsigned uTableSize, unsigned uSizeOfData) { unsigned i; HashTable *pTable = (HashTable *)malloc(sizeof(HashTable)); if ( pTable != NULL ) { pTable->nBuckets = uTableSize; pTable->uDatumSize = uSizeOfData; pTable->uCount = 0; pTable->ppChain = (HashTable_Element **)malloc(uTableSize * sizeof(HashTable_Element *)); if ( pTable->ppChain == NULL ) { free(pTable); pTable = NULL; } else { for ( i = 0; i < uTableSize; ++i ) { pTable->ppChain[i] = NULL; } } } return pTable; } static unsigned Hash(HashTable *pTable, char *szSearchFor) { unsigned uHashValue = 2166136261u; unsigned uPrimeFNV = (1 << 24) + (1 << 8) + 0x93; while ( *szSearchFor ) { uHashValue ^= *szSearchFor++; uHashValue *= uPrimeFNV; } return uHashValue % pTable->nBuckets; } void *LookupHashTable(HashTable *pTable, char *szSearchFor) { unsigned xBucket = Hash(pTable, szSearchFor); HashTable_Element *pEl; for ( pEl = pTable->ppChain[xBucket]; pEl != NULL && strcmp(szSearchFor, (char *)pEl->pData) != 0; pEl = pEl->pNext ) { } return pEl != NULL ? pEl->pData : NULL; } void *InsertHashTable(HashTable *pTable, void *pItem) { void *p = LookupHashTable(pTable, (char *)pItem); unsigned xBucket; HashTable_Element *pEl; if ( p != NULL ) return p; pEl = (HashTable_Element *)malloc(sizeof(HashTable_Element)); if ( pEl != NULL ) { pEl->pData = malloc(pTable->uDatumSize); if ( pEl->pData == NULL ) { free((void *)pEl); pEl = NULL; } else { memcpy(pEl->pData, pItem, pTable->uDatumSize); xBucket = Hash(pTable, (char *)pItem); pEl->pNext = pTable->ppChain[xBucket]; #ifdef HASH_SUPPORTS_DELETE if ( pEl->pNext != NULL ) pEl->pNext->pPrev = pEl; pEl->pPrev = NULL; #endif pTable->ppChain[xBucket] = pEl; ++pTable->uCount; } } return pEl->pData; } void DestroyHashTable(HashTable *pTable) { unsigned x; HashTable_Element *p, *q; for ( x = 0; x < pTable->nBuckets; ++x ) { for ( p = pTable->ppChain[x]; p != NULL; p = q ) { free(p->pData); q = p->pNext; free((void *)p); } } free((void *)pTable); return; } double HashEfficiency(HashTable *pTable) { int nHit = 0; unsigned i; HashTable_Element *p; for ( i = 0; i < pTable->nBuckets; ++i ) { nHit += (pTable->ppChain[i] != NULL); for ( p = pTable->ppChain[i]; p != NULL; p = p->pNext ) { } } return (double)nHit / (double)(pTable->nBuckets < pTable->uCount ? pTable->nBuckets : pTable->uCount); } #ifdef HASH_SUPPORTS_DELETE int DeleteHashElement(HashTable *pTable, char *szSearchFor) { unsigned xBucket = Hash(pTable, szSearchFor); HashTable_Element *pEl; for ( pEl = pTable->ppChain[xBucket]; pEl != NULL && strcmp(szSearchFor, (char *)pEl->pData) != 0; pEl = pEl->pNext ) { } if ( pEl != NULL ) { free(pEl->pData); if ( pEl->pNext != NULL ) pEl->pNext->pPrev = pEl->pPrev; if ( pEl->pPrev != NULL ) pEl->pPrev->pNext = pEl->pNext; else pTable->ppChain[xBucket] = pEl->pNext; return 1; } return 0; } #endif <file_sep>/markov.c #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <string.h> #include "hash.h" #define MAX_LENGTH 32 #define N_LETTERS 26 #define N_DIGITS 10 #define N_SYMBOLS 33 #define N_CHARS 96 /* 128 - ' ' */ #define IS_UPPER 'U' #define IS_LOWER 'L' #define IS_DIGIT 'D' #define IS_SYMBOL 'S' inline char* strlwr( char* str ) { char* orig = str; // process the string for ( ; *str != '\0 '; str++ ) *str = tolower(*str); return orig; } typedef struct { char szNonTerminals[2*MAX_LENGTH+1]; unsigned uCount; } PwdStructure; int main(int argc, char **argv) { int nGrams, i, j, xFile, xLetter1, xDigit1, xSymbol1, xCurrent, xPrior, xGram, NLetters, NChars, ch; int nSame, iLast, iThis; int (*panLetters)[2+N_LETTERS], (*panDigits)[2+N_DIGITS], (*panSymbols)[2+N_SYMBOLS], (*panChars)[2+N_CHARS], *pnLength; char szBuf[2048]; FILE *fpIn; FILE *fpPCFG, *fpMC; char szTemp[8]; char szSymbols[] = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ", *pSym; PwdStructure syntax, *pSyntax, *pMost; HashTable *phtPCFG; unsigned x; HashTable_Element *pEl; if ( strlen(szSymbols) != N_SYMBOLS ) { printf( "%s - szSymbols wrong length\n", argv[0] ); return 0; } else if ( argc < 3 ) { printf( "usage: %s nGram file1 [file2 ...]\n", argv[0] ); return 0; } pnLength = malloc(sizeof(pnLength[0]) * (1 + MAX_LENGTH)); if ( pnLength == NULL ) { printf( "%s - can't malloc space for pnLength!\n", argv[0] ); return 0; } nGrams = atoi(argv[1]); if ( nGrams < 1 || nGrams > 4 ) { printf( "%s - nGram must be between 1 and 4, inclusive\n", argv[0] ); return 0; } NLetters = (int)pow((double)N_LETTERS, (double)nGrams); panLetters = malloc(sizeof(panLetters[0]) * NLetters); if ( panLetters == NULL ) { free(pnLength); printf( "%s - can't malloc space for panLetters!\n", argv[0] ); return 0; } panDigits = malloc(sizeof(panDigits[0]) * N_DIGITS); if ( panDigits == NULL ) { printf( "%s - can't malloc space for panDigits!\n", argv[0] ); free(pnLength); free(panLetters); return 0; } panSymbols = malloc(sizeof(panSymbols[0]) * N_SYMBOLS); if ( panSymbols == NULL ) { printf( "%s - can't malloc space for panSymbols!\n", argv[0] ); free(pnLength); free(panLetters); free(panDigits); return 0; } NChars = (int)pow((double)N_CHARS, (double)nGrams); panChars = malloc(sizeof(panChars[0]) * NChars); if ( panChars == NULL ) { printf( "%s - can't malloc space for panChars!\n", argv[0] ); free(pnLength); free(panLetters); free(panDigits); free(panSymbols); return 0; } for ( xFile = 2; xFile < argc; ++xFile ) { for ( i = 0; i <= MAX_LENGTH; ++i ) { pnLength[i] = 0; } for ( i = 0; i < NLetters; ++i ) { for ( j = 0; j < 2+N_LETTERS; ++j ) { panLetters[i][j] = 0; } } for ( i = 0; i < N_DIGITS; ++i ) { for ( j = 0; j < 2+N_DIGITS; ++j ) { panDigits[i][j] = 0; } } for ( i = 0; i < N_SYMBOLS; ++i ) { for ( j = 0; j < 2+N_SYMBOLS; ++j ) { panSymbols[i][j] = 0; } } for ( i = 0; i < NChars; ++i ) { for ( j = 0; j < 2+N_CHARS; ++j ) { panChars[i][j] = 0; } } fpIn = fopen(argv[xFile], "r"); if ( fpIn == NULL ) { printf( "%s - can't open %s for reading\n", argv[0], argv[xFile]); continue; } sprintf(szBuf, "%s.pcfg%d", argv[xFile], nGrams); fpPCFG = fopen(szBuf, "w"); if ( fpPCFG == NULL ) { printf( "%s - can't open %s for writing\n", argv[0], szBuf); fclose(fpIn); continue; } sprintf(szBuf, "%s.mc%d", argv[xFile], nGrams); fpMC = fopen(szBuf, "w"); if ( fpMC == NULL ) { printf( "%s - can't open %s for writing\n", argv[0], szBuf); fclose(fpIn); fclose(fpPCFG); continue; } phtPCFG = CreateHashTable(177787, sizeof(syntax)); pMost = NULL; syntax.uCount = 0; printf( "%s\n", argv[xFile] ); fflush(stdout); while ( fgets(szBuf, sizeof(szBuf), fpIn) ) { j = strlen(szBuf) - 1; /* -1 due to trailing \n */ if ( j > MAX_LENGTH ) continue; pnLength[j]++; /* Scan password, first producing stats for the 'total' Markov chain */ for ( iThis = -1, i = 0; szBuf[i] >= ' '; ++i ) { /* First parse into the grammatical structure */ iLast = iThis; if ( isupper((int)szBuf[i]) ) iThis = IS_UPPER; else if ( islower((int)szBuf[i]) ) iThis = IS_LOWER; else if ( isdigit((int)szBuf[i]) ) iThis = IS_DIGIT; else iThis = IS_SYMBOL; if ( i ) { if ( iLast == iThis ) { ++nSame; } else { sprintf(szTemp, "%c%d", iLast, nSame); strcat(syntax.szNonTerminals, szTemp); nSame = 1; } } else { syntax.szNonTerminals[0] = '\0'; nSame = 1; } if ( i+1 == nGrams ) { /* Chain is exactly 'n' chars long; update start count */ for ( xGram = 0, j = 0; j <= i; ++j ) /* Calculate index into table */ { xGram *= N_CHARS; xGram += szBuf[j] - ' '; } panChars[xGram][0]++; /* Keep track of how frequently nGram used at start of password */ } else if ( i >= nGrams ) { for ( xGram = 0, j = i-nGrams; j < i; ++j ) /* Calculate index into table */ { xGram *= N_CHARS; xGram += szBuf[j] - ' '; } panChars[xGram][1]++; /* Keep track of how frequently nGram used */ panChars[xGram][szBuf[i] - ' ' + 2]++; /* Track frequency of letters following nGram */ } } sprintf(szTemp, "%c%d", iThis, nSame); strcat(syntax.szNonTerminals, szTemp); pSyntax = (PwdStructure *)InsertHashTable(phtPCFG, &syntax); pSyntax->uCount++; if ( pMost == NULL || pSyntax->uCount > pMost->uCount ) pMost = pSyntax; /* For sub-chains, processing is case-insensitive, so set to lowercase */ strlwr(szBuf); /* Make second pass, producing the chains for similar-character sequences */ for ( xLetter1 = xDigit1 = xSymbol1 = -1, i = 0; szBuf[i] >= ' '; ++i ) { ch = szBuf[i]; if ( islower(ch) && xLetter1 < 0 ) xLetter1 = i; /* Begin new letter chain */ else if ( !islower(ch) ) xLetter1 = -1; /* Halt letter chain */ if ( isdigit(ch) && xDigit1 < 0 ) xDigit1 = i; /* Begin new digit chain */ else if ( !isdigit(ch) ) xDigit1 = -1; /* Halt digit chain */ pSym = strchr(szSymbols, ch); if ( pSym != NULL && xSymbol1 < 0 ) xSymbol1 = i; /* Begin new symbol chain */ else if ( pSym == NULL ) xSymbol1 = -1; /* Halt symbol chain */ if ( xLetter1 >= 0 && i-xLetter1+1 >= nGrams ) /* In chain of required length */ { if ( i-xLetter1+1 == nGrams ) { /* Chain is exactly 'n' letters long; update start count */ for ( xGram = 0, j = xLetter1; j <= i; ++j ) /* Calculate index into table */ { xGram *= N_LETTERS; xGram += szBuf[j] - 'a'; } panLetters[xGram][0]++; /* Keep track of how frequently nGram used at start of chain */ } else { for ( xGram = 0, j = i-nGrams; j < i; ++j ) /* Calculate index into table */ { xGram *= N_LETTERS; xGram += szBuf[j] - 'a'; } panLetters[xGram][1]++; /* Keep track of how frequently nGram used */ panLetters[xGram][ch - 'a' + 2]++; /* Track frequency of letters following nGram */ } } else if ( xDigit1 >= 0 ) { if ( i == xDigit1 ) { panDigits[ch-'0'][0]++; /* Keep track of how frequently digit used at start of chain */ } else { panDigits[szBuf[i-1]-'0'][1]++; /* Keep track of how frequently digit used */ panDigits[szBuf[i-1]-'0'][ch - '0' + 2]++; /* Track frequency of the subsequent digit */ } } else if ( xSymbol1 >= 0 ) { if ( i == xSymbol1 ) { xCurrent = pSym - szSymbols; panSymbols[xCurrent][0]++; /* Keep track of how frequently symbol used at start of chain */ } else { xPrior = xCurrent; xCurrent = pSym - szSymbols; panSymbols[xPrior][1]++; /* Keep track of how frequently symbol used */ panSymbols[xPrior][xCurrent + 2]++; /* Track frequency of the subsequent symbol */ } } } } fclose(fpIn); if ( pMost != NULL ) printf( "Most common structure: %s (%u)\n", pMost->szNonTerminals, pMost->uCount ); /* Dump the letters */ fprintf( fpPCFG, "abcdefghijklmnopqrstuvwxyz\n" ); for ( i = 0; i < NLetters; ++i ) { if ( nGrams == 4 ) fprintf(fpPCFG, "%c%c%c%c", 'a' + (i/(N_LETTERS*N_LETTERS*N_LETTERS)), 'a' + ((i/(N_LETTERS*N_LETTERS))%N_LETTERS), 'a' + ((i/N_LETTERS)%N_LETTERS), 'a' + (i%N_LETTERS)); else if ( nGrams == 3 ) fprintf(fpPCFG, "%c%c%c", 'a' + (i/(N_LETTERS*N_LETTERS)), 'a' + ((i/N_LETTERS)%N_LETTERS), 'a' + (i%N_LETTERS)); else if ( nGrams == 2 ) fprintf(fpPCFG, "%c%c", 'a' + i/N_LETTERS, 'a'+ (i%N_LETTERS)); else fprintf(fpPCFG, "%c", 'a' + i); for ( j = 0; j < N_LETTERS + 2; ++j ) { fprintf( fpPCFG, " %d", panLetters[i][j] ); } fprintf(fpPCFG, "\n"); } /* Dump the digits */ fprintf( fpPCFG, "0123456789\n" ); for ( i = 0; i < N_DIGITS; ++i ) { fprintf(fpPCFG, "%c", '0' + i); for ( j = 0; j < N_DIGITS + 2; ++j ) { fprintf( fpPCFG, " %d", panDigits[i][j] ); } fprintf(fpPCFG, "\n"); } /* Dump the symbols */ fprintf( fpPCFG, "%s\n", szSymbols ); for ( i = 0; i < N_SYMBOLS; ++i ) { fprintf(fpPCFG, "%c", szSymbols[i]); for ( j = 0; j < N_SYMBOLS + 2; ++j ) { fprintf( fpPCFG, " %d", panSymbols[i][j] ); } fprintf(fpPCFG, "\n"); } /* Dump the sentence structures */ fprintf( fpPCFG, "%d sentence structures\n", phtPCFG->uCount); for ( x = 0; x < phtPCFG->nBuckets; ++x ) { for ( pEl = phtPCFG->ppChain[x]; pEl != NULL; pEl = pEl->pNext ) { pSyntax = (PwdStructure *)pEl->pData; fprintf( fpPCFG, "%6d %s\n", pSyntax->uCount, pSyntax->szNonTerminals ); } } fclose(fpPCFG); DestroyHashTable(phtPCFG); /* Dump the big table */ for ( i = 0; i < N_CHARS; ++i ) { fprintf( fpMC, "%c", ' ' + i ); } fprintf(fpMC, "\n"); for ( i = 0; i < NChars; ++i ) { if ( nGrams == 4 ) fprintf(fpMC, "%c%c%c%c", ' ' + (i/(N_CHARS*N_CHARS*N_CHARS)), ' ' + ((i/(N_CHARS*N_CHARS))%N_CHARS), ' ' + ((i/N_CHARS)%N_CHARS), ' ' + (i%N_CHARS)); else if ( nGrams == 3 ) fprintf(fpMC, "%c%c%c", ' ' + (i/(N_CHARS*N_CHARS)), ' ' + ((i/N_CHARS)%N_CHARS), ' ' + (i%N_CHARS)); else if ( nGrams == 2 ) fprintf(fpMC, "%c%c", ' ' + i/N_CHARS, ' '+ (i%N_CHARS)); else fprintf(fpMC, "%c", ' ' + i); for ( j = 0; j < N_CHARS + 2; ++j ) { fprintf( fpMC, " %d", panChars[i][j] ); } fprintf(fpMC, "\n"); } fprintf( fpMC, "%d password lengths\n", MAX_LENGTH ); for ( j = 1; j <= MAX_LENGTH; ++j ) { fprintf( fpMC, " %d", pnLength[j] ); } fprintf(fpMC, "\n"); fclose(fpMC); } free(pnLength); free(panLetters); free(panDigits); free(panSymbols); free(panChars); return 0; } <file_sep>/splitpwd.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <ctype.h> #include <string.h> int main(int argc, char **argv) { char szBuf[2048]; FILE *aafp[5][5]; int x, i, j, nMinChars, nClasses, nLower, nUpper, nDigit, nSymbol, nBad; srand((unsigned long)time(NULL)); if ( argc < 3 ) { printf( "usage: %s MinimumLength file1 [file2 ...]\n", argv[0] ); exit(0); } nMinChars = atoi(argv[1]); if ( nMinChars < 6 || nMinChars > 16 ) { printf( "%s - MinimumLength parameter must be between 6 and 16, inclusive\n", argv[0] ); exit(0); } for ( x = 2; x < argc; ++x ) { aafp[0][0] = fopen(argv[x], "r"); if ( aafp[0][0] == NULL ) { printf( "error opening %s\n", argv[x]); continue; } for ( i = 1; i <= 4; ++i ) { for ( j = 0; j < 5; ++j ) { if ( j == 4 ) { sprintf( szBuf, "%s.%d.%d", argv[x], nMinChars, i ); } else { sprintf( szBuf, "%s.%d.%d.%c", argv[x], nMinChars, i, j + 'a' ); } aafp[i][j] = fopen(szBuf, "w"); if ( aafp[i][j] == NULL ) { printf( "%s - can't open %s, bailing out!!\n", argv[0], szBuf ); exit(0); } } } while ( fgets(szBuf, sizeof(szBuf), aafp[0][0]) != NULL ) { nClasses = 0; nLower = 0; nUpper = 0; nDigit = 0; nSymbol = 0; nBad = 0; for ( i = 0; szBuf[i]; ++i ) { if ( szBuf[i] == '\n' ) { break; } else if ( (szBuf[i] < ' ') || (szBuf[i] & 0x80) ) { ++nBad; } else if ( islower(szBuf[i]) ) { nClasses += !nLower; ++nLower; } else if ( isupper(szBuf[i]) ) { nClasses += !nUpper; ++nUpper; } else if ( isdigit(szBuf[i]) ) { nClasses += !nDigit; ++nDigit; } else { nClasses += !nSymbol; ++nSymbol; } } if ( !nBad && (nLower + nUpper + nDigit + nSymbol >= nMinChars) ) { for ( i = 1; i < 5; ++i ) { if ( nClasses >= i ) { fprintf(aafp[i][rand() & 3], "%s", szBuf); fprintf(aafp[i][4], "%s", szBuf); } } } } for ( i = 0; i < 5; ++i ) { if ( i ) { for ( j = 0; j < 5; ++j ) { fclose(aafp[i][j]); } } else { fclose(aafp[i][0]); } } } return 0; } <file_sep>/pcfgc2.cpp #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <string.h> #include <assert.h> #include "hash.h" #include "classPCFG.h" /*#define NDEBUG*/ //#define PRINT_DEBUG int main(int argc, char **argv) { char szBuf[2048]; int iMakeGuesses = 0; int nGrams, n, xFile, nPwdChars; FILE *fp; CPCFG pcfg; srand((unsigned)time(NULL)); if ( argc < 5 ) { printf( "usage: %s nGrams FileToCrack Dictionary TrainFile1 [TrainFile2 ...]\nIf 'nGrams' is < 0, the program will actually try to guess to the passwords in the cracking file.\nOtherwise, guess numbers are calculated for each password.", argv[0] ); return 0; } nGrams = atoi(argv[1]); if ( nGrams < 0 ) { iMakeGuesses = 1; nGrams *= -1; } if ( nGrams < 1 || nGrams > 3 ) { printf( "%s - nGram must be between 1 and 3, inclusive\n", argv[0] ); return 0; } // Read in the training files and accumulate statistics for ( xFile = 4; xFile < argc; ++xFile ) { pcfg.LoadFromFile(argv[xFile], nGrams); } pcfg.ConvertCountsToProb(); pcfg.LoadDictionary(argv[3]); // Now open process the cracking file and get to work! fp = fopen(argv[2], "r"); if ( fp == NULL ) { fprintf( stderr, "%s - can't open %s for reading\n", argv[0], argv[2]); exit(0); } // Either make guesses or compute guess numbers if ( iMakeGuesses ) { pcfg.m_phtPasswords = new CHashTable(5000011, 1+MAX_LENGTH); while ( fgets(szBuf, sizeof(szBuf), fp) ) { n = strlen(szBuf) - 1; if ( n <= MAX_LENGTH ) { szBuf[n] = '\0'; pcfg.m_phtPasswords->Insert(szBuf); } } pcfg.ThresholdGuessing(); } else { while ( fgets(szBuf, sizeof(szBuf), fp) ) { nPwdChars = strlen(szBuf) - 1; if ( nPwdChars <= MAX_LENGTH ) { printf( "%9.3lf\t%s", pcfg.GuessNumber(szBuf) / 1e+9, szBuf ); } #ifdef PRINT_DEBUG //getchar(); #endif } } // Clean up, go home fclose(fp); return 0; } <file_sep>/strengthen.py #!/usr/bin/env python import sys import random #letterOptions = ['|', '}', '{', '>', '`', '^', '[', ':', '~', '%', ']', '<', '"', ';', "'", '(', 'Q', '?', ')', '=', '&', '+', '\\', ',', 'X', '$', '#', '/', 'Z', 'W', 'V', 'F', '@', 'J', '*', 'G', 'P', '-', 'U', '!', 'K', 'Y', 'H', 'q', 'B', '_', 'D', 'C', 'T', '.', 'M', 'S', 'N', 'R', 'O', 'L', 'I', 'E', 'x', 'A', 'z', 'w', 'f', 'v', 'j'] def replace(word, replacements, r): toReplace = r.sample(xrange(len(word)-1), replacements) for i in toReplace: word = word[:i] + r.choice(letterOptions) + word[i+1:] return word def main(): with open(sys.argv[2], 'w') as w: with open(sys.argv[1], 'r') as f: r = random.Random() for line in f.readlines(): w.write(replace(line, 3, r)) if __name__ == "__main__": letterOptions = ['|', '}', '{', '>', '`', '^', '[', ':', '~', '%', ']', '<', '"', ';', "'", '(', 'Q', '?', ')', '=', '&', '+', '\\', ',', 'X', '$', '#', '/', 'Z', 'W', 'V', 'F', '@', 'J', '*', 'G', 'P', '-', 'U', '!', 'K', 'Y', 'H', 'q', 'B', '_', 'D', 'C', 'T', '.', 'M', 'S', 'N', 'R', 'O', 'L', 'I', 'E', 'x', 'A', 'z', 'w', 'f', 'v', 'j'] main() <file_sep>/MarkovChain.h #ifndef MARKOVCHAIN_H_INCLUDED #define MARKOVCHAIN_H_INCLUDED #define _CRT_SECURE_NO_WARNINGS #define TRY_DICTIONARY_ATTACKS //#define TRY_DELETING_1 #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> #include <cstring> #define N_CHARS 95 // == '~' - ' ' + 1 #define MAX_LENGTH 23 #define N_LETTERS 26 #define N_DIGITS 10 #define N_SYMBOLS 33 #include "chash.h" class CBaseStructure { public: CBaseStructure(); char m_szWord[MAX_LENGTH+1]; int m_nCount; CBaseStructure *m_pNext; }; class CMarkovChain { public: int m_nChars; int m_nGrams; int m_nPrefix; int m_nReduceModulus; int m_nBillions; int m_nGuesses; int m_nProcessor; double m_adLengthProb[1+MAX_LENGTH]; bool m_bAreProbabilities; double m_dStartCount; double *m_pdTransitionCount; double *m_pdTransitionProb; int *m_pxTransitionProb; double getTransitionProbability(int i, int j) { return m_pdTransitionProb[i * m_nChars + j]; } void increaseTransitionCount(int i, int j, double n) { m_pdTransitionProb[i * m_nChars + j] += n; } void setTransitionProbability(int i, int j, double p) { m_pdTransitionProb[i * m_nChars + j] = p; } int getTransitionProbabilityIndex(int i, int j) { return m_pxTransitionProb[i * m_nChars + j]; } void setTransitionProbabilityIndex(int i, int j, int x) { m_pxTransitionProb[i * m_nChars + j] = x; } double *m_pdStartProb; int *m_pxStartProb; virtual int ToCharacter(int x) { return x + ' '; } virtual int ToIndex(int ch) { return ch - ' '; } char *m_pszCharacters; CHashTable *m_phtPasswords; char m_szGuessing[1+MAX_LENGTH]; int m_nLengthToGuess; double m_dThresholdP; public: CMarkovChain(int nChars, int nGrams); virtual ~CMarkovChain(); int m_anUniqueWords[MAX_LENGTH+1]; int m_anWordsSeen[MAX_LENGTH+1]; CBaseStructure *m_apWordLists[MAX_LENGTH+1]; CHashTable *m_phtDictionary; void AddToDictionary(const char *szWord, int nTimes = 1); void AddStartCount(int xPrefix, int n); void AddTransitionCount(int xFrom, int xTo, int n); void AddOneTransition(const char *achFrom, char chTo); void ProcessWord(const char *szWord); void BuildPassword(int xPwd, int xOriginalState, double dProbSoFar); int LoadFromFile(const char *szPath); int LoadFromFile(FILE *fp, bool bReadLengths = false, bool bUseDictionaries = true); void ConvertCountsToProb(bool bSmoothProbabilities, bool bDoLengths = true); int LoadDictionary(const char *szPathDictionary); void ThresholdGuessing(); double GuessNumber(const char *szPassword, bool bUseDictionary = true); void WriteToTextFile(const char *szPath); void WriteToTextFile(FILE *fp, bool bWriteLengths = false); }; class CMarkovChainAll : public CMarkovChain { public: CMarkovChainAll(int nGrams); }; class CMarkovChainWords : public CMarkovChain { public: CMarkovChainWords(int nGrams); int ToCharacter(int x) { return (x == N_LETTERS) ? '.' : (x + 'a'); } int ToIndex(int ch) { return isalpha(ch) ? (isupper(ch) ? (ch - 'A') : (ch - 'a')) : N_LETTERS; } void BuildAWord(char *szNewWord, int nMaxChar); }; class CMarkovChainAlpha : public CMarkovChain { public: CMarkovChainAlpha(int nGrams); int ToCharacter(int x) { return x + 'a'; } int ToIndex(int ch) { return isupper(ch) ? (ch - 'A') : (ch - 'a'); } }; class CMarkovChainDigit : public CMarkovChain { public: CMarkovChainDigit(); int ToCharacter(int x) { return x + '0'; } int ToIndex(int ch) { return ch - '0'; } }; class CMarkovChainSymbol : public CMarkovChain { public: CMarkovChainSymbol(); char m_szSymbols[1+N_SYMBOLS]; int ToCharacter(int x) { return m_szSymbols[x]; } int ToIndex(int ch) { return strchr(m_szSymbols, ch) - m_szSymbols; } }; #endif
1e49b453aebbe7fed3fa383ce1f75b2b88514ae8
[ "Markdown", "Makefile", "Python", "C", "C++", "Shell" ]
22
C
michaelwheatman/PasswordGeneration
75c62a49b220e1ba3e6378d56d5d2ce8cdd8bfcf
af555072a4813f98f05c61daa1bb41a9ae4dbf2b
refs/heads/master
<file_sep>class ValidateLogin def initialize(session) @session = session end def call return false unless @session.valid? # Call an API here return @session if validate_login_api false end private def validate_login_api # TODO: Document a validate_login API true end end<file_sep>require 'rails_helper' RSpec.describe Roll, type: :model do let(:play) { Play.new(flybuys_number: '6014012345678912', points: 10_000, bet: 20) } let(:result) { 2 } subject(:roll) { Roll.new(result: result, play: play) } describe "#successful?" do context "when a 2 is rolled" do it "is successful" do expect(roll).to be_successful end end context "when not 2 is rolled" do it "is unsuccessful when 1 is rolled" do roll.result = 1 expect(roll).not_to be_successful expect(roll).to be_unsuccessful end it "is unsuccessful when 6 is rolled" do roll.result = 6 expect(roll).not_to be_successful expect(roll).to be_unsuccessful end end end end <file_sep>json.extract! roll, :id, :result, :created_at, :updated_at <file_sep>class PlaysController < ApplicationController # GET /plays/1 # GET /plays/1.json def show end # GET /plays/new def new flybuys_number = session[:flybuys_number] current_points = GetPoints.new(flybuys_number).call @play = Play.new(points: current_points) end # POST /plays # POST /plays.json def create @play = CreateNewPlay.new( flybuys_number: session[:flybuys_number], current_play: current_play, bet: params['bet'] ).call respond_to do |format| if @play format.html { redirect_to play_path, notice: 'Play was successfully created.' } format.json { render :show, status: :created, location: @play } else format.html { render :new } format.json { render json: @play.errors, status: :unprocessable_entity } end end end end <file_sep>require 'rails_helper' RSpec.describe "rolls/edit", type: :view do before(:each) do @roll = assign(:roll, Roll.create!( :result => 1 )) end it "renders the edit roll form" do render assert_select "form[action=?][method=?]", roll_path(@roll), "post" do assert_select "input[name=?]", "roll[result]" end end end <file_sep>module ApplicationHelper def authenticated? return true if session[:flybuys_number] end def flybuys_number session[:flybuys_number] end end <file_sep>require 'rails_helper' RSpec.describe "plays/edit", type: :view do before(:each) do @play = assign(:play, Play.create!( :flybuys_number => "MyString", :points => 1, :bet => 1 )) end it "renders the edit play form" do render assert_select "form[action=?][method=?]", play_path(@play), "post" do assert_select "input[name=?]", "play[flybuys_number]" assert_select "input[name=?]", "play[points]" assert_select "input[name=?]", "play[bet]" end end end <file_sep>class Play < ApplicationRecord has_many :rolls def current_points if lost? points - bet else points - bet + ((2 ** count_wins) * bet) end end def game_over? finished_at || rolls.count >= 3 || lost? end def lost? rolls.any?(&:unsuccessful?) end def points_difference current_points - points end def data { flybuys_number: flybuys_number, bet: bet, start_points: points, current_points: current_points, finished: !!finished_at, rolls: rolls.map { |roll| { result: roll.result, success: roll.successful? } } } end private def count_wins rolls.select(&:successful?).count end end <file_sep>require 'rails_helper' RSpec.describe "plays/show", type: :view do before(:each) do @play = assign(:play, Play.create!( :flybuys_number => "Flybuys Number", :points => 2, :bet => 3 )) end it "renders attributes in <p>" do render expect(rendered).to match(/Flybuys Number/) expect(rendered).to match(/2/) expect(rendered).to match(/3/) end end <file_sep>class CreateNewPlay attr_accessor :flybuys_number, :current_play, :bet def initialize(flybuys_number:, current_play: , bet:) @flybuys_number = flybuys_number @current_play = current_play @bet = bet end def call return false if current_play && !current_play.game_over? current_points = GetPoints.new(flybuys_number).call ActiveRecord::Base.transaction do # Close off the current play as finished before we create a new play if current_play && current_play.finished_at.nil? current_play.update!(finished_at: Time.current) end @play = Play.create!(bet: bet, flybuys_number: flybuys_number, points: current_points) end @play end end<file_sep>require "application_system_test_case" class RollsTest < ApplicationSystemTestCase # test "visiting the index" do # visit rolls_url # # assert_selector "h1", text: "Roll" # end end <file_sep>class Session include ActiveModel::AttributeMethods include ActiveModel::Conversion include ActiveModel::Validations include ActiveModel::Model extend ActiveModel::Naming attr_accessor :flybuys_number, :password validates :flybuys_number, presence: true, format: { with: /\A6014\d{12}/} validates :password, presence: true def persisted? false end end <file_sep>require 'rails_helper' RSpec.describe ValidateLogin, type: :service do let(:flybuys_number) { '6014012345678912' } let(:password) { '<PASSWORD>' } let(:session) { Session.new(flybuys_number: flybuys_number, password: <PASSWORD>) } subject(:validate_login) { ValidateLogin.new(session) } context "with a valid session" do it "returns the session" do expect(subject.call).to eq session end end context "when session is invalid" do it "is also not valid" do expect(session).to receive(:valid?).and_return(false) expect(subject.call).to be_falsey end end end<file_sep>class SessionsController < ApplicationController skip_before_action :authenticate # GET /sessions/new def new @session = Session.new end # POST /sessions # POST /sessions.json def create flybuys_number = params[:session][:flybuys_number] @session = Session.new( flybuys_number: flybuys_number, password: params[:session][:password], ) validate_login = ValidateLogin.new(@session) respond_to do |format| if validate_login.call session[:flybuys_number] = flybuys_number format.html { redirect_to root_path, notice: 'Login successful' } format.json { render :show, status: :created, location: @session } else format.html { render :new, notice: 'Invaild login' } format.json { render json: @session.errors, status: :unprocessable_entity } end end end # DELETE /sessions/1 # DELETE /sessions/1.json def destroy session[:flybuys_number] = nil respond_to do |format| format.html { redirect_to root_path, notice: 'Session was successfully destroyed.' } format.json { head :no_content } end end end <file_sep>require 'rails_helper' def create_roll(play, win) if win Roll.create!(play: play, result: 2) else Roll.create!(play: play, result: 1) end end RSpec.describe Play, type: :model do let(:flybuys_number) { '6014012345678912' } let(:points) { 10_000 } let(:bet) { 20 } subject(:play) { Play.new(flybuys_number: flybuys_number, points: points, bet: bet) } describe "#lost?" do context "when there is only one unsuccessful roll" do it "is lost" do create_roll(play, false) expect(play).to be_lost end end context "when there are a mix of rolls with a losing roll" do it "is lost" do create_roll(play, true) create_roll(play, false) expect(play).to be_lost end end context "when there are no losing rolls" do it "isn't lost" do create_roll(play, true) create_roll(play, true) create_roll(play, true) expect(play).not_to be_lost end end end describe "#game_over?" do context "when there are 3 rolls" do it "is game over" do create_roll(play, true) create_roll(play, true) create_roll(play, true) expect(play).to be_game_over end end context "when the game is finished" do it "is game over" do play.finished_at = Time.now expect(play).to be_game_over end end context "when there is an unsuccessful roll" do it "is game over" do create_roll(play, true) create_roll(play, false) expect(play).to be_game_over end end end describe "#current_points" do context "when you have lost" do it "subtracts your bet from your points" do create_roll(play, false) expect(play.current_points).to eq(play.points - play.bet) end end context "when you haven't lost (yet)" do it "is the same when you haven't rolled" do expect(play.current_points).to eq(play.points) end it "doubles when you have rolled successfully" do create_roll(play, true) expect(play.current_points).to eq(play.points - play.bet + 2 * play.bet) end it "doubles agains when you have rolled successfully again" do create_roll(play, true) create_roll(play, true) expect(play.current_points).to eq(play.points - play.bet + (play.bet * 2) * 2) end end end end <file_sep>class CreditPoints attr_accessor :flybuys_number, :points def initialize(flybuys_number:, points:) @flybuys_number = flybuys_number @points = points end def call true end end<file_sep>json.extract! play, :id, :flybuys_number, :points, :bet, :created_at, :updated_at json.url play_url(play, format: :json) <file_sep>class RollsController < ApplicationController # GET /rolls/new def new @roll = Roll.new end # POST /rolls # POST /rolls.json def create roll = Roll.new(play: current_play) @roll = RollDice.new(play: current_play, roll: roll).call respond_to do |format| if @roll format.html { redirect_to play_path, notice: 'Roll was successfully created.' } format.json { render :show, status: :created, location: @roll } else format.html { render :new } format.json { render json: @roll.errors, status: :unprocessable_entity } end end end # DELETE /rolls/1 # DELETE /rolls/1.json def destroy @roll.destroy respond_to do |format| format.html { redirect_to rolls_url, notice: 'Roll was successfully destroyed.' } format.json { head :no_content } end end end <file_sep>class AddFinishedAtToPlay < ActiveRecord::Migration[5.1] def change add_column :plays, :finished_at, :datetime end end <file_sep>require 'rails_helper' RSpec.describe "rolls/index", type: :view do before(:each) do assign(:rolls, [ Roll.create!( :result => 2 ), Roll.create!( :result => 2 ) ]) end it "renders a list of rolls" do render assert_select "tr>td", :text => 2.to_s, :count => 2 end end <file_sep>class Roll < ApplicationRecord belongs_to :play validates :result, numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 6} def successful? # 2 means to double the points result == 2 end def unsuccessful? !successful? end end <file_sep>require "application_system_test_case" class PlaysTest < ApplicationSystemTestCase # test "visiting the index" do # visit plays_url # # assert_selector "h1", text: "Play" # end end <file_sep>class GetPoints def initialize(flybuys_number) @flybuys_number = flybuys_number end def call get_points_api end private def get_points_api # TODO: document a points API 10000 end end <file_sep># README * Ruby version 2.4.2 * Node version v8.4.0 * Database creation Setup and migrate - uses sqlite * How to run the test suite Run individual tests - mostly unit tests for services and models * Dev environment `rails s` AND `./bin/webpack-dev-server` <file_sep>require 'rails_helper' RSpec.describe RollDice, type: :service do let(:flybuys_number) { '6014012345678912' } let(:play) { Play.create!(flybuys_number: flybuys_number, points: 10_000, bet: 20) } let(:roll) { Roll.new(play: play) } let(:result) { 2 } subject(:roll_dice) { RollDice.new(play: play, roll: roll, result: result) } before do allow(SecureRandom).to receive(:random_number).and_return(result) end describe "#call" do it "sets a result on a roll" do roll_dice.call expect(roll.result).to be_present end it "saves roll" do roll_dice.call expect(roll).to be_persisted end it "returns false if we can't play anymore" do expect(play).to receive(:game_over?).and_return(true) expect(roll_dice.call).to be_falsey end context "when the first roll is unsuccessful" do let(:result) { 1 } it "debits points from your acount" do expect(DebitPoints).to receive(:new).with(hash_including(flybuys_number: flybuys_number, points: 20)).and_return(-> { true }) roll_dice.call end it "sets finished at" do roll_dice.call play.reload expect(play.finished_at).to be_truthy end end context "when the first roll is successful" do it "credits points to your account" do expect(CreditPoints).to receive(:new).with(hash_including(flybuys_number: flybuys_number, points: 20)).and_return(-> { true }) roll_dice.call end end context "when the second roll is also successful" do before do play.save! Roll.create!(play: play, result: 2) end it "credits you the difference in points between rolls" do expect(CreditPoints).to receive(:new).with(hash_including(flybuys_number: flybuys_number, points: 40)).and_return(-> { true }) roll_dice.call end end context "when the third roll is also successful" do before do play.save! Roll.create!(play: play, result: 2) Roll.create!(play: play, result: 2) end it "credits you the difference in points between rolls" do expect(CreditPoints).to receive(:new).with(hash_including(flybuys_number: flybuys_number, points: 80)).and_return(-> { true }) roll_dice.call end end end end<file_sep>class ApplicationController < ActionController::Base helper_method :current_play protect_from_forgery with: :exception before_action :authenticate # Redirect to login page? private def authenticate redirect_to new_session_path unless authenticated? end def authenticated? return true if session[:flybuys_number] end def current_play Play.where(flybuys_number: session[:flybuys_number]).order(created_at: :desc).first end end <file_sep>class RollDice attr_accessor :play, :roll, :result def initialize(play:, roll:, result: nil) @play = play @roll = roll @result = result || SecureRandom.random_number(6) + 1 end def call return false if play.game_over? ActiveRecord::Base.transaction do old_points = play.points_difference roll.result = result roll.save! play.reload play.update!(finished_at: Time.current) if play.game_over? points_delta = play.points_difference - old_points # TODO don't really want to be making API calls within a database transaction balance_account(points_delta) end roll end private def balance_account(points_delta) if points_delta > 0 CreditPoints.new(flybuys_number: play.flybuys_number, points: points_delta.abs).call elsif points_delta < 0 DebitPoints.new(flybuys_number: play.flybuys_number, points: points_delta.abs).call end end end<file_sep>require 'rails_helper' RSpec.describe Session, type: :model do let(:flybuys_number) { '6014012345678912' } let(:password) { '<PASSWORD>' } subject(:session) { Session.new(flybuys_number: flybuys_number, password: <PASSWORD>) } it { is_expected.to be_valid } context "when the password is blank" do let(:password) { nil } it { is_expected.to be_invalid } end context "when the flybuys number is blank" do let(:flybuys_number) { nil } it { is_expected.to be_invalid } end context "when flybuys number doesn't start with 6014" do let(:flybuys_number) { '1111012345678912' } it { is_expected.to be_invalid } end context "when flybuys number isn't 16 digits long" do let(:flybuys_number) { '601401234' } it { is_expected.to be_invalid } end context "when flybuys number isn't made of digits" do let(:flybuys_number) { '601401234567891a' } it { is_expected.to be_invalid } end end<file_sep>Rails.application.routes.draw do resource :roll resource :play resource :session root 'plays#show' end <file_sep>import React from "react" import PropTypes from "prop-types" import Roll from './Roll' import NewPlay from './NewPlay' class Play extends React.Component { rolls() { return this.props.rolls.map(roll => { return ( <Roll result={roll.result} success={roll.success} /> ); }); } point_difference() { return this.props.current_points - this.props.start_points; } roll() { console.log('clicked roll'); let data = {}; Rails.ajax({ type: "POST", url: "/roll.json", data: data, success: function(response){ //console.log("SUCCESS!!"); window.location.reload(); }, error: function(repsonse){ console.log("There was an error"); console.log(response); } }) } finished() { if(this.props.finished) { return( <div> <div>Game Over</div> <NewPlay/> </div> ); } else { return( <button onClick={() => this.roll() } >Roll me</button> ); } } render () { console.log(this.props); if(this.props.current_points){ return ( <div> <div>Flybuys Number: {this.props.flybuys_number}</div> <div>Start points: {this.props.start_points}</div> <div>Current points: {this.props.current_points}</div> <div>Points difference: {this.point_difference()}</div> <div>Bet: {this.props.bet}</div> {this.rolls()} {this.finished()} </div> ); } else { return ( <NewPlay/> ) } } } Play.propTypes = { flybuysNumber: PropTypes.string }; export default Play
364aee5000217ea8c732259dfeeb27a4b9e01e21
[ "Markdown", "JavaScript", "Ruby" ]
30
Ruby
akampjes/lucky-dice-roll
ae87b5a195f43a590b59e74740ec82c7487d4d08
f070073d9563ed1657fcc62225a35567657fb3e0
refs/heads/master
<file_sep>package com.fiskra.atm.finder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fiskra.atm.finder.model.Atm; public class RestConsume { private static final char[] protectingCharacters = {')', ']', '}', '\'', ','}; public static void main(String[] args) throws IOException { System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,TLSv1"); testWithJackson(); } public static void testWithJackson() throws IOException { URL url = new URL("https://www.ing.nl/api/locator/atms/"); try ( final Reader reader = stripProtection(new InputStreamReader(url.openStream())) ) { final ObjectMapper objectMapper = new ObjectMapper(); final JsonNode jsonNode = objectMapper.readTree(reader); List<Atm> atms = objectMapper.convertValue(jsonNode, new TypeReference<List<Atm>>(){}); Set<String> cities = new HashSet<>(); for (Atm atm : atms) { cities.add(atm.getAddress().getCity().getCityName()); } String[] cityArray = cities.toArray(new String[cities.size()]); for (int i = 1; i < cityArray.length; i++) { System.out.println("INSERT INTO City (city_id,city_name) VALUES("+i+",'"+ cityArray[i] +"');" ); } for (int i = 1; i<atms.size();i++) { System.out.println("INSERT INTO GeoLocation(geo_id,lat,lng,address_id) VALUES ("+i+","+atms.get(i).getAddress().getGeoLocation().getLat()+","+atms.get(i).getAddress().getGeoLocation().getLng()+");"); System.out.println("INSERT INTO Address (address_id,street,house_number,postal_code,city_id,geo_id) VALUES ("+i+",'"+atms.get(i).getAddress().getStreet()+"','"+atms.get(i).getAddress().getHousenumber()+"','"+atms.get(i).getAddress().getPostalcode()+"',(select city_id from City where city_name='"+atms.get(i).getAddress().getCity()+"'),"+i+");"); System.out.println("INSERT INTO Atm(atm_id,distance,atm_type,address_id) VALUES ("+i+","+atms.get(i).getDistance()+",'"+atms.get(i).getType().name()+"',"+i+");"); } } } public static Reader stripProtection(final Reader reader) throws IOException { final char[] buffer = new char[protectingCharacters.length]; final Reader normalizedReader = reader.markSupported() ? reader : new BufferedReader(reader); normalizedReader.mark(protectingCharacters.length); normalizedReader.read(buffer, 0, protectingCharacters.length); if (!Arrays.equals(protectingCharacters, buffer)) { normalizedReader.reset(); } return normalizedReader; } } <file_sep>package com.fiskra.atm.finder.controller; import java.util.List; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; 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.fiskra.atm.finder.exception.AtmException; import com.fiskra.atm.finder.exception.ExceptionCodes; import com.fiskra.atm.finder.model.Address; import com.fiskra.atm.finder.model.City; import com.fiskra.atm.finder.repository.AddressRepository; import com.fiskra.atm.finder.repository.CityRepository; @RestController @RequestMapping("/city") public class CityController { @Autowired ServletContext context; @Autowired private CityRepository cityRepository; @Autowired private AddressRepository addressRepository; @RequestMapping(method = RequestMethod.GET, value = "/all") public List<City> getAllCityList(){ System.out.println(context.getRealPath("uploads")); return cityRepository.findAllByOrderByCityNameAsc(); } @RequestMapping(method = RequestMethod.GET) public City findCityByName(@RequestParam(value="name") String name) throws AtmException{ City c = cityRepository.findByCityName(name); if(c == null) throw new AtmException(ExceptionCodes.CITY_NOT_FOUND); return c; } @RequestMapping(method = RequestMethod.GET, value = "/top") public List<City> getTopOrderBy(){ return cityRepository.findTop10ByOrderByCityNameAsc(); } @RequestMapping(method = RequestMethod.GET, value = "/{name}/addresses") public List<Address> getAddressesByCity(@PathVariable String name){ return addressRepository.findByCityCityName(name); } } <file_sep># ATM FINDER PROJECT [![MIT Licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/fiskra/AtmFinder/master/LICENSE) This project aims to show all atms in Netherlands on Google Map. There is also a filter feature by city. ## Getting Started This project is developed by using Spring-Boot so it has tomcat container already and no need to deploy. ### Infrastructure ##### JAVA 8 ##### Maven ##### Spring-Boot and other dependencies(data-rest,data-jpa, security, test) ##### H2 in-memory db ##### Angular.js ##### Bootstrap ### Prerequisites The data is used in this application consumed a rest service and create insert queries. `RestConsume.java` class represents client codes of that rest service and parse the data and prepare insert queries. Given rest service has a protection against called ** JSON highjacking exploit **, it starts ** )]}', ** so first needed to remove invalid characters then convert json data to java object. After prepared insert queries, they must be in data.sql because h2 in-memory db is selected for this project and Spring-Boot recognise **data.sql** and **schema.sql** files and run them when server starts up. ## Installing Just clone the project and run `Application.java` class. ### JPA Queries There are many ways to create queries in Spring world. I implemented repository interface and explained how to configure it in our application. It's so simple, let's dive into :) #### What is Spring repository? The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. #### How we use Spring repository? The ex below for repository service: ``` public interface RepositoryName extends Repository<T, ID> { … } ``` Type should be our Entity and Id is an entity id. There are additional Repository interface that we can extend : CrudRepository,PagingAndSortingRepository. Spring also provides persistence technology-specific abstractions like JpaRepository or MongoRepository. These repositories have some useful methods like findAll(),T findOne(ID primaryKey),count(),void delete(T entity),etc...If we want to get all values from an entity we don't need to write additional code just call **findAll()** method. ##### Creating Database Queries With Query Methods * 1 If we need to create specific query like find city from city name we can just write a method in interface which named findByCityName ``` City findByCityName(String cityname); ``` This query generation method gives us to create queries by using method name strategy. There are some rules to create these queries : * Query method name should start and end with these words: find…By, read…By, query…By, count…By, and get…By. * If we want to limit the number of returned query results, we can add first of top keyword like findTopBy, findTop1By, findFirstBy * For unique results : findTitleDistinctBy or findDistinctTitleBy The result set can be entry, Optional<Entry>, List<Entry>,Stream<Entry> . This query generation strategy is used to when we need simple queries. For the complex queries it might seem ugly and long besides the query keywords must provide our needs. The disadvantage of this method it does not have dynamic query support. * 2 We can use @Query annotation to write custom queries : ``` @Query("SELECT * FROM City c where c.city_name = :name") City findByCityName(@Param("name") String name); ``` We can also use @Async annotation to execute queries asynchronously. In addition, there is one way to set parameters to query other than @Query annotation ``` @Query("SELECT t FROM Address t where t.street = ?1 AND t.house_number = ?2") public Optional<Address> findByStreetAndHouseNumber(String street, String houseNumber); ``` Or we can write query in Entity class with @NamedQuery annotation : ``` @Entity @NamedQuery(name = "City.findByCityName", query = "select c from City c where c.city_name = ?1") public class City { } ``` ``` public interface CityRepository extends JpaRepository<City, Long> { City findByCityName(String cityName); } ``` The next two approach should be considered more convenient than static one if we work on real-life applications and requirements might be more complex. [Spring Boot Jpa doc](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#dependencies.spring-boot) ##### Creating Database Queries With the JPA Criteria API ##### Creating Database Queries With Querydsl Querydsl is a framework which enables to build dynamic and complex queries but we need to add it' dependency in pom.xml ### Securing the Rest Service Spring security provides to secure application access. We should apply at least the most important best practices for our application that we can say it's done. Authentication, authorization, CSRF protection. There are numerous approaches that could be used here, with numerous tradeoffs. The rest api we built on can be used by all manner of HTML, native mobile, desktop clients, etc. The security approach we picked up should cover all. You can check here for more details : [Rest Cheat Sheet](https://www.owasp.org/index.php/REST_Security_Cheat_Sheet) Active Directory, LDAP, pam, CAAS, Spring Social(OAuth based services like Facebook,Twitter,Github) for authentication providers. HTTPS is important to prevent Man-in-the-Middle Attacks. Spring boot has easy steps to apply this protection. First create this resource file : ``` security/src/main/resources/application-https.properties ``` Second add these properties : ``` server.port = 8443 server.ssl.key-store = classpath:tomcat.keystore server.ssl.key-store-password = <PASSWORD> server.ssl.key-password = <PASSWORD> ``` To setup Spring security we have to add spring security dependency to maven ``` <dependencies> ... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ... </dependencies> ``` `WebSecurityConfig.java` class is annotated with `@EnableWebSecurity` and `@Configuration` to enable Spring security supports and provide MVC integration.`configure(HttpSecurity)` method defines which URL paths are configured to not require any authentication. We can also make secure our application from CSRF attacks by adding `.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())` ` httpBasic()` provides basic authentication `configureGlobal(AuthenticationManagerBuilder)` method sets up an in-memory user store with a single user.It can be configured to login by many users. Spring Security provides many implementations of authentication contract that adapt existing identity providers, like Active Directory, LDAP, pam, CAAS, etc. Spring Social even provides a nice integration that delegates to different OAuth-based services like Facebook, Twitter, etc., for authentication. ### Exception Handling in Spring There are three approaches to handle exceptions : Controller Based Exception Handling, Global Exception Handling, Exception Based Exception Handling I believe to present http status codes, message, exception code when exception occurs in REST API. There are many(nearly 70) http status code but we shouldn't use all of them just some of them that covers basic status like : everything works, the application did something wrong, the api did something wrong. I prefer to implement global exception mechanism approach to manage exceptions from one source. But all approaches deal with separation of concerns very well. ``` @RestControllerAdvice public class GlobalExceptionHandler { } ``` ** @RestControllerAdvice ** annotation provides global exception mechanism to handle exceptions and reduce boilerplate codes in Spring(after 4.3 version) by removing ** @ResponseBody ** annotation on each method in controller advice. It says in the documentation : annotation that is itself annotated with ** @ControllerAdvice ** and ** @ResponseBody ** For handling 404 errors, we need to add `@EnableWebMvc` annotation in Spring Boot Application class and `spring.mvc.throw-exception-if-no-handler-found=true`in application.properties ## Running the tests To test our application we add `spring-boot-starter-test` and it includes some test libraries like : JUnit, Spring Test, AssertJ, Hamcrest, Mockito, JSONAssert, JsonPath `@SpringBootTest` annotation is used for regular tests, `@RunWith(SpringRunner.class)` tells JUnit to run using Spring’s testing support. `@DataJpaTest` provides to test jpa part. It configures an in-memory database, configure hibernate, spring data, datasource automatically and performs `@EntityScan` <file_sep>app = angular.module('mapApp', []); app.controller('cityController', function($scope, $http) { $http.get('/city/all/').then(function(response) { $scope.cities = response.data; }); $http.get('/atm/all').then(function(response) { $scope.atms = response.data; console.log($scope.atms); }); $scope.myFunc = function(menu) { $http({ method : "GET", url : "/city/all/", }).success(function(data) { $scope.cities = data; }); var cityId = document.getElementById('menu'); var netherlands = { lat : 52.1326, lng : 5.2913 }; var mapOptions = { zoom : 8, center : netherlands, mapTypeId : google.maps.MapTypeId.ROADMAP } $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions); $scope.markers = []; $scope.cities = []; var infoWindow = new google.maps.InfoWindow(); $http.get('/atm?name=' + menu.cityName).success(function(data) { $scope.atms = data; angular.forEach($scope.atms, function(atm) { createMarker(atm); }); }); var createMarker = function(atm) { var marker = new google.maps.Marker({ map : $scope.map, position : new google.maps.LatLng(atm.address.geoLocation.lat, atm.address.geoLocation.lng), title : atm.address.street + " " + atm.address.housenumber + " " + atm.address.postalcode }); marker.content = '<div class="infoWindowContent">' + "Atm_" + atm.id + '</div>'; google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content); infoWindow.open($scope.map, marker); }); $scope.markers.push(marker); }; } }); <file_sep>package com.fiskra.atm.finder.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.fiskra.atm.finder.model.Address; public interface AddressRepository extends JpaRepository<Address,Long> { /** * Retrieves all atm addresses in city * * @param cityname * @return */ public List<Address> findByCityCityName(String cityname); } <file_sep>CREATE TABLE IF NOT EXISTS `City` ( `city_id` bigint(20) NOT NULL auto_increment, `city_name` varchar(200) NOT NULL, PRIMARY KEY (`city_id`) ); CREATE TABLE IF NOT EXISTS `GeoLocation`( `geo_id` bigint(20) NOT NULL auto_increment, `lat` decimal(10,6) NOT NULL, `lng` decimal(10,6) NOT NULL, PRIMARY KEY (`geo_id`) ); CREATE TABLE IF NOT EXISTS `Address` ( `address_id` bigint(20) NOT NULL auto_increment, `street` varchar(200) NOT NULL, `house_number` varchar(200) NOT NULL, `postal_code` varchar(100) NOT NULL, `city_id` bigint(20) NOT NULL, `geo_id` bigint(20) NOT NULL, PRIMARY KEY (`address_id`), FOREIGN KEY (`city_id`) REFERENCES CITY(`city_id`), FOREIGN KEY (`geo_id`) REFERENCES GEOLOCATION(`geo_id`) ); CREATE TABLE IF NOT EXISTS `Atm` ( `atm_id` BIGINT(20) NOT NULL AUTO_INCREMENT , `distance` BIGINT(20) NOT NULL, `atm_type` VARCHAR(100) NOT NULL, `address_id` BIGINT(20) NOT NULL, PRIMARY KEY (`atm_id`), FOREIGN KEY (`address_id`) REFERENCES ADDRESS (`address_id`) ); <file_sep>package com.fiskra.atm.finder; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) public class TestMe { /*public TestMe() { System.setProperty("spring.profiles.active", "dev"); }*/ } <file_sep>package com.fiskra.atm.finder.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "Address") public class Address { @Id @GeneratedValue @Column(name = "address_id") private Long id; @Column(name = "street") private String street; @Column(name = "house_number") private String housenumber; @Column(name = "postal_code") private String postalcode; @OneToOne @JoinColumn(name = "city_id") private City city; @OneToOne @JoinColumn(name = "geo_id") private GeoLocation geoLocation; protected Address() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getHousenumber() { return housenumber; } public void setHousenumber(String housenumber) { this.housenumber = housenumber; } public String getPostalcode() { return postalcode; } public void setPostalcode(String postalcode) { this.postalcode = postalcode; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public GeoLocation getGeoLocation() { return geoLocation; } public void setGeoLocation(GeoLocation geoLocation) { this.geoLocation = geoLocation; } @Override public String toString() { return String.format( "Address[id=%d, street='%s', house_number ='%s', postal_code ='%s', city= '%s']", id, street, housenumber, postalcode, city.getCityName()); } } <file_sep>package com.fiskra.atm.finder.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="geolocation") public class GeoLocation { @Id @GeneratedValue @Column(name = "geo_id") private Long geoId; @Column(name = "lat") private double lat; @Column(name = "lng") private double lng; 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 Long getGeoId() { return geoId; } public void setGeoId(Long geoId) { this.geoId = geoId; } }
398925f3b5f27ed2218147aafd6996d2d4723f7e
[ "Markdown", "Java", "JavaScript", "SQL" ]
9
Java
fiskra-zz/AtmFinder
3b73fea0f837c5f2e01319dc37719c646feafff4
5eb1af3a7ae92eb66c1355703f8f17f10e0efe86
refs/heads/master
<repo_name>AdamBolfik/Grid_detector<file_sep>/Tracker/Tracker/Tracker/A_Star.cpp // // A_Star.cpp // OpenCV // // Created by Dustin on 7/28/13. // Copyright (c) 2013 Dustin. All rights reserved. // #include "A_Star.h" #include <iostream> #include <vector> using namespace std; // Determine priority (in the priority queue) bool operator<(const Node & a, const Node & b) { return a.getPriority() > b.getPriority(); } vector<vector<int> > A_Star::get_path_vectors(){ if (vect_path.size() == 0) { vect_path = vector<vector<int> >(path.size(), vector<int>(2)); for(int i = 0; i < path.size(); i++) { vect_path[i][0] = path[i].x; vect_path[i][1] = path[i].y; } } return vect_path; } vector<cv::Point2i> A_Star::get_path_points(){ return path; } A_Star::A_Star(int width, int height, int start_x, int start_y, int end_x, int end_y, map<int, vector<int> > obst_map, int dir) { n = width; m = height; this->dir = dir; if (dir == 8) { dx.push_back(1); dx.push_back(1); dx.push_back(0); dx.push_back(-1); dx.push_back(-1); dx.push_back(-1); dx.push_back(0); dx.push_back(1); dy.push_back(0); dy.push_back(1); dy.push_back(1); dy.push_back(1); dy.push_back(0); dy.push_back(-1); dy.push_back(-1); dy.push_back(-1); } else{ dx.push_back(1); dx.push_back(0); dx.push_back(-1); dx.push_back(0); dy.push_back(0); dy.push_back(1); dy.push_back(0); dy.push_back(-1); } base_map = vector<vector<int> >(n, vector<int>(m, 0)); closed_nodes_map = vector<vector<int> >(n, vector<int>(m)); open_nodes_map = vector<vector<int> >(n, vector<int>(m)); dir_map = vector<vector<int> >(n, vector<int>(m)); for(map<int, vector<int> >::iterator map_it = obst_map.begin(); map_it != obst_map.end(); map_it++) { if (map_it->first < n) { for (vector<int>::iterator vect_it = (map_it->second).begin() ; vect_it != (map_it->second).end(); vect_it++){ if (*vect_it < m) { base_map[n][m] = 1; } } } } // get the route string route = pathFind(start_x, start_y, end_x, end_y); // follow the route on the map and display it if(route.length() > 0){ int j; char c; int x = start_x; int y = start_y; base_map[x][y] = 2; path.push_back(cv::Point2i(x, y)); for(int i = 0;i < route.length(); i++){ c = route.at(i); j = atoi(&c); x = x + dx[j]; y = y + dy[j]; path.push_back(cv::Point2i(x, y)); base_map[x][y] = 3; } base_map[x][y] = 4; path.push_back(cv::Point2i(x, y)); // // display the map with the route // for(int y = 0; y < m; y++){ // for(int x = 0; x < n; x++) // if(base_map[x][y] == 0) // cout << "."; // else if(base_map[x][y] == 1) // cout << "O"; //obstacle // else if(base_map[x][y] == 2) // cout << "S"; //start // else if(base_map[x][y] == 3) // cout << "R"; //route // else if(base_map[x][y] == 4) // cout << "F"; //finish // cout << endl; // } } } // A-star algorithm. // The route returned is a string of direction digits. string A_Star::pathFind( const int & xStart, const int & yStart, const int & xFinish, const int & yFinish ){ priority_queue<Node> pq[2]; // list of open (not-yet-tried) nodes int pqi = 0; // pq index Node* n0; Node* m0; static int j, x, y, xdx, ydy; char c; // reset the node maps for(y = 0; y < m; y++){ for(x = 0; x < n; x++){ closed_nodes_map[x][y] = 0; open_nodes_map[x][y] = 0; } } // create the start node and push into list of open nodes n0 = new Node(xStart, yStart, 0, 0); n0->updatePriority(xFinish, yFinish); pq[pqi].push(*n0); open_nodes_map[xStart][yStart]= (n0->getPriority()); // mark it on the open nodes map // A* search while(!pq[pqi].empty()){ // get the current node w/ the highest priority // from the list of open nodes n0 = new Node( pq[pqi].top().getxPos(), pq[pqi].top().getyPos(), pq[pqi].top().getLevel(), pq[pqi].top().getPriority()); x = n0->getxPos(); y = n0->getyPos(); pq[pqi].pop(); // remove the node from the open list open_nodes_map[x][y]=0; // mark it on the closed nodes map closed_nodes_map[x][y]=1; // quit searching when the goal state is reached //if((*n0).estimate(xFinish, yFinish) == 0) if(x == xFinish && y == yFinish){ // generate the path from finish to start // by following the directions string path = ""; while(!(x == xStart && y == yStart)){ j = dir_map[x][y]; c = '0' + (j + dir / 2) % dir; path = c + path; x += dx[j]; y += dy[j]; } // garbage collection delete n0; // empty the leftover nodes while(!pq[pqi].empty()) pq[pqi].pop(); return path; } // generate moves (child nodes) in all possible directions for(int i = 0; i < dir ; i++){ xdx = x + dx[i]; ydy = y + dy[i]; if(!(xdx < 0 || xdx > n - 1 || ydy < 0 || ydy > m - 1 || base_map[xdx][ydy] == 1 || closed_nodes_map[xdx][ydy] == 1)){ // generate a child node m0 = new Node(xdx, ydy, n0->getLevel(), n0->getPriority()); m0->nextLevel(i); m0->updatePriority(xFinish, yFinish); // if it is not in the open list then add into that if(open_nodes_map[xdx][ydy] == 0){ open_nodes_map[xdx][ydy] = m0->getPriority(); pq[pqi].push(*m0); // mark its parent node direction dir_map[xdx][ydy] = (i + dir / 2) % dir; } else if(open_nodes_map[xdx][ydy] > m0->getPriority()){ // update the priority info open_nodes_map[xdx][ydy] = m0->getPriority(); // update the parent direction info dir_map[xdx][ydy] = (i + dir / 2) % dir; // replace the node // by emptying one pq to the other one // except the node to be replaced will be ignored // and the new node will be pushed in instead while(!(pq[pqi].top().getxPos() == xdx && pq[pqi].top().getyPos() == ydy)){ pq[1 - pqi].push(pq[pqi].top()); pq[pqi].pop(); } pq[pqi].pop(); // remove the wanted node // empty the larger size pq to the smaller one if(pq[pqi].size() > pq[1 - pqi].size()) pqi = 1 - pqi; while(!pq[pqi].empty()){ pq[1 - pqi].push(pq[pqi].top()); pq[pqi].pop(); } pqi = 1 - pqi; pq[pqi].push(*m0); // add the better node instead } else delete m0; // garbage collection } } delete n0; // garbage collection } return ""; // no route found }<file_sep>/Tracker/Tracker/Tracker/Tracker.h // // Tracker.h // Grid // // Created by Dustin on 9/6/13. // Copyright (c) 2013 Dustin. All rights reserved. // #ifndef __Grid__Tracker__ #define __Grid__Tracker__ #include <sstream> #include <string> #include <iostream> #include <opencv2/highgui.hpp> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv/cv.h> using namespace std; using namespace cv; class Tracker{ private: //initial min and max HSV filter values. //these will be changed using trackbars int H_MIN; int H_MAX; int S_MIN; int S_MAX; int V_MIN; int V_MAX; //default capture width and height int FRAME_WIDTH; int FRAME_HEIGHT; //max number of objects to be detected in frame int MAX_NUM_OBJECTS; //minimum and maximum object area int MIN_OBJECT_AREA; int MAX_OBJECT_AREA; //names that will appear at the top of each window string windowName; string windowName1; string windowName2; string windowName3; string trackbarWindowName; Mat HSV, threshold; public: static const int RED = 0; static const int ORANGE = 1; static const int YELLOW = 2; static const int GREEN = 3; static const int BLUE = 4; static const int VIOLET = 5; Tracker(); ~Tracker(); vector<Point2f> get_positions(Mat &img, const int color); void morphOps(Mat &thresh); void trackFilteredObject(int &x, int &y, Mat threshold, Mat &cameraFeed); void drawObject(int x, int y,Mat &frame); static void on_trackbar( int, void* ); string intToString(int number); void createTrackbars(); }; #endif /* defined(__Grid__Tracker__) */ <file_sep>/Tracker/Tracker/Tracker/Grid.h // // Grid.h // OpenCV // // Created by Dustin on 7/21/13. // Copyright (c) 2013 Dustin. All rights reserved. // #ifndef __OpenCV__Grid__ #define __OpenCV__Grid__ #include <opencv2/highgui.hpp> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv/cv.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <set> #include "A_Star.h" using namespace cv; using namespace std; class Grid{ private: Mat starter_image, skeleton, straightened_image, perspective_transform_matrix; string source_window; vector<Point> grid_intersections; vector<Point2f> warped_corners, straightened_corners; map<int, vector<int> > grid_intersections_map, obst_map; /** * removes redundancy from a vector of points (removes clusters) * parameter: vector<Point2f> &points * int tolerance */ void remove_redundant_points(vector<Point2f> &points, int tolerance); /** * recursively merges entries of map whose keys are within a tolerance of one another * parameters: map< int, vector<Point2f> > &in_map * int tolerance: this represents a percentage; ex: 10 means ± 10% */ void merge_close_elements_of_map(map< int, vector<int> > &in_map, float tolerance = 10); /** * returns the essential points from a vector of points by removing redundancy * (removes clusters) * */ vector<Point2f> get_essential_points(vector<Point2f> points, int tolerance); public: // constructors Grid(Mat &src); Grid(); ~Grid(); /** * locates a "blob" (the difference between the source and new image) */ vector<Point2f> get_blob_location(Mat &new_img); Mat get_contoured_image(Mat img); // returns basic grid from grid image Mat get_skeleton(Mat contoured_img); /** * sorts the vector according to x then y */ void sort_points(vector<Point2f> &points); /** * this returns a map that is */ map<int, vector<int> > get_sorted_point_map(vector<Point2f> &points, float tolerance = 10); /** * Returns a vector points for the shortest path to dst * * ^ * | —–> * * * * * *>F * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * S * * parameters: Point2f start_pt * Point2f end_point * vector<Point2f> points */ vector<Point2f> get_shortest_path_points(Point2i start_pt, Point2i end_point, map<int, vector<int> > grid); /** * returns vector of floating-point "Points" * Parameter: Mat skeleton: a skeleton-like(bare-bones) representation of image * */ vector<Point2f> get_intersections(Mat skeleton); // gets intersection point of two lines Point2f get_intersection(Point2f o1, Point2f o2, Point2f p1, Point2f p2); void set_image_straighting(vector<Point2f> &input_corners); void straighten_image(Mat &img); Mat get_straightened_image(); void sort_corners(std::vector<cv::Point2f>& corners, cv::Point2f center); /** * creates an image with points/ circles, and lines overlayed onto a given image */ void show_image(vector<Point2f> points, Mat img, vector<Point2f> path, int thickness = -1, int radius = 20, Scalar color = Scalar(255,255,0)); void set_obstacle(Point p); /** * returns the essential points from a vector of points by removing redundancy * (removes clusters) * */ vector<Point2f> get_essential_points(); /** * Returns a vector points for the shortest path to dst * * ^ * | —–> * * * * * *>F * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * S */ vector<Point2f> get_shortest_path_points(Point2i start_pt, Point2i end_point); /** * returns vector of floating-point "Points" * */ vector<Point2f> get_intersections(); // gets intersection point of two lines Mat get_contours(); // returns basic grid from grid image Mat get_skeleton(); /** * returns a map of containg the corners of: source image * straightened image * vector<points> | key * ———————————————|——————— * source | "src" * straightened | "dst" * Procedure: -Use HoughLines to get distinctive lines in image * -merge the lines that are close to on another/ similar * -use process of elimination discover the edges of main object * -get intercepts of edges * -get endpoints of edges * -get intersections of edges * -approximate new dimensions of straightened image * -return map of both source and straightened endpoints */ map<string, vector<Point2f> > get_corner_points(); map<string, vector<Point2f> > get_corner_points(vector<Point2f> corners); }; #endif /* defined(__OpenCV__Grid__) */ <file_sep>/mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; delete qcd; } void MainWindow::on_sp_progress_bar_valueChanged(int value) { } void MainWindow::on_detect_bot_button_clicked() { qcd = new QColorDialog(); qcd->show(); } <file_sep>/Tracker/Tracker/Tracker/A_Star.h // // A_Star.h // OpenCV // // Created by Dustin on 7/28/13. // Copyright (c) 2013 Dustin. All rights reserved. // #ifndef __OpenCV__A_Star__ #define __OpenCV__A_Star__ #include <iostream> #include <iomanip> #include <queue> #include <string> #include <math.h> #include <ctime> #include <map> #include "Node.h" #include "opencv2/imgproc/imgproc.hpp" using namespace std; class A_Star{ private: int n; // horizontal size of the map int m; // vertical size size of the map vector<vector<int> > base_map; vector<vector<int> > closed_nodes_map; vector<vector<int> > open_nodes_map; vector<vector<int> > dir_map; vector<vector<int> > vect_path; vector<cv::Point2i> path; map<string, vector<int> > point_map; int dir; // number of possible directions to go at any position vector<int> dx, dy; // A-star algorithm. // The route returned is a string of direction digits. string pathFind( const int & xStart, const int & yStart, const int & xFinish, const int & yFinish ); bool is_neighbor(vector<int> pt); public: A_Star(int width, int height, int start_x, int start_y, int end_x, int end_y, map<int, vector<int> > obst_map, int dir = 4); A_Star(int width, int height, cv::Point2i start_pt, cv::Point2i end_pt, map<int, vector<int> > obst_map, int dir = 4); vector<vector<int> > get_path_vectors(); vector<cv::Point2i> get_path_points(); }; #endif /* defined(__OpenCV__A_Star__) */ <file_sep>/Tracker/Tracker/Tracker/Robot.h // // Robot.h // Grid // // Created by Dustin on 9/1/13. // Copyright (c) 2013 Dustin. All rights reserved. // #ifndef __Grid__Robot__ #define __Grid__Robot__ #include <iostream> #include <opencv2/highgui.hpp> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv/cv.h> using namespace std; using namespace cv; class Robot{ private: vector<Point2f> path; Scalar color; RNG rng; string name; public: Robot(); Robot(string name); Robot(Point2f point, string name); Robot(Point2f point); ~Robot(); void update_current_position(Point2f point); vector<Point2f> get_path(); string get_name(); Point2f get_nearest_bot(vector<Point2f> bot_locations); void show_bot_location(Mat &image); void show_bot_path(Mat &image); Scalar get_bot_color(); }; #endif /* defined(__Grid__Robot__) */ <file_sep>/Tracker/Tracker/Tracker/Junk.cpp ////#include "opencv2/highgui/highgui.hpp" ////#include "opencv2/imgproc/imgproc.hpp" ////#include <opencv2/objdetect/objdetect.hpp> ////#include <iostream> ////#include <stdio.h> ////#include <stdlib.h> ////#include "Grid.h" ////#include "time.h" ////using namespace cv; ////using namespace std; ////#define num_robots 1 //// ////Mat src; // source image ////Mat rob_source; ////VideoCapture vcap; ////String src_window = "source"; ////vector<Point2f> corners; //// ////Grid grid; //// ////static void on_mouse(int event,int x, int y, int, void* ); //// /////** @function main */ ////int main( int argc, char** argv ){ //// cout << "hello" << endl; //// // src = imread( "/Users/Dustin/Desktop/2013-06-18 11.49.35.jpg", 1 ); //// // resize(src, src, Size(src.size().width / 3, src.size().height / 3)); //// // namedWindow(src_window); //// // grid = Grid(src); //// // rob_source = imread("/Users/Dustin/Documents/Robot Stuff/srcnot.jpg", 1); //// // //// // setMouseCallback(src_window, on_mouse); //// // imshow(src_window, src); //// // //// // waitKey(0); //// //// ////// VideoCapture cap = VideoCapture(-1); // open the default camera ////// ////// if(!cap.isOpened()) // check if we succeeded ////// return -1; ////// ////// Mat edges; ////// namedWindow("edges",1); ////// for(;;) ////// { ////// Mat frame; ////// cap >> frame; // get a new frame from camera ////// cout << frame.cols << " " << frame.rows << endl; ////// cvtColor(frame, edges, CV_BGR2GRAY); ////// GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5); ////// Canny(edges, edges, 0, 30, 3); ////// imshow("edges", edges); ////// if(waitKey(30) >= 0) break; ////// } ////// // the camera will be deinitialized automatically in VideoCapture destructor ////// return 0; ////// Mat back, fore, ref; ////// int iter = 20; ////// vector<vector<Point> > contours; ////// RNG rng(12345); ////// ////// vcap = VideoCapture("http://admin:robotcam1@172.16.58.3/video.cgi?.mjpg"); ////// vcap = VideoCapture(-1); ////// vcap.set(CV_CAP_PROP_FPS, 10); ////// vcap >> src; ////// grid = Grid(src); ////// imshow(src_window, src); ////// setMouseCallback(src_window, on_mouse); ////// imshow(src_window, src); ////// ////// waitKey(0); ////// // grid.set_image_straighting(corners); ////// ////// while (1) { ////// if (!vcap.isOpened()) { ////// return -1; ////// } ////// ////// vcap >> src; ////// ////// grid.straighten_image(src); ////// vector<Point2f> blobs = grid.get_blob_location(src); ////// int robots_found = num_robots; ////// for (vector<Point2f>::iterator blob_it = blobs.begin(); blob_it != blobs.end(); blob_it++) { ////// if(robots_found >= 0){ ////// circle(src, *blob_it, 20, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), 5); ////// robots_found--; ////// } ////// } ////// ////// imshow("straightened", src); ////// if (waitKey(30) > 0) { ////// break; ////// } ////// } //// ////// for (int i = 0; ; i++) { ////// vcap = VideoCapture(i); ////// ////// if (vcap.isOpened()) { ////// cout << "cam open " << i << endl; ////// } ////// else{ ////// cout << "not open " << i << endl; ////// } ////// } //// //// vcap = VideoCapture(500); //// while (1) { //// Mat frame; //// vcap >> frame; //// imshow("hello", frame); //// //// if (waitKey(30) >= 0) { //// break; //// } //// } //// return 0; ////} //// ////// mouse event ////static void on_mouse(int event,int x, int y, int, void* ){ //// Mat temp_image; //// src.copyTo(temp_image); //// Point2f p(x, y); //// if (corners.size() == 4) { //// destroyWindow(src_window); //// grid.set_image_straighting(corners); //// vector<Point2f> intersections = grid.get_intersections(); //// vector<Point2f> path; //// grid.show_image(intersections, grid.get_straightened_image(), path, 2); //// } //// else{ //// for (vector<Point2f>::iterator it = corners.begin(); it != corners.end(); it++) { //// circle(temp_image, *it, 20, Scalar(255, 255, 0), 3); //// stringstream ss; //// ss << "(" << it->x << " , " << it->y << ")"; //// string location = ss.str(); //// putText(temp_image, location, Point((it ->x) -40, (it->y) + 30), FONT_HERSHEY_PLAIN, 1, Scalar(255, 100, 200)); //// if (it != corners.begin()) { //// line(temp_image, *it, *(it - 1) , Scalar(255, 100, 200), 3); //// } //// if (it == corners.end() - 1) { //// line(temp_image, *it, *(corners.begin()) , Scalar(255, 100, 200), 3); //// } //// } //// switch (event) { //// case EVENT_LBUTTONDOWN: //// corners.push_back(p); //// cout << p << endl; //// break; //// case EVENT_RBUTTONDOWN: //// if (corners.size() > 0) { //// for (vector<Point2f>::iterator it = corners.begin(); it != corners.end();) { //// Point2f diff = p - *it; //// int dist = cv::sqrt(::pow(diff.x, 2) + ::pow(diff.y, 2)); //// if (dist < 40) { //// corners.erase(it); //// } //// else{ //// it++; //// } //// } //// } //// break; //// case EVENT_MOUSEMOVE: //// circle(temp_image, Point(x,y), 20, Scalar(100, 100, 255), 3); //// circle(temp_image, Point(x,y), 3, Scalar(100, 255, 255), 3); //// stringstream ss; //// ss << "(" << x << " , " << y << ")"; //// string location = ss.str(); //// putText(temp_image, location, Point(x - 40, y - 30), FONT_HERSHEY_PLAIN, 1, Scalar(255, 255, 100)); //// break; //// //// } //// //// imshow(src_window, temp_image); } ////} //// // ////objectTrackingTutorial.cpp // ////Written by <NAME> 2013 // ////Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software") ////, to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, ////and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // ////The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // ////THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ////FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ////LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS ////IN THE SOFTWARE. // //#include <sstream> //#include <string> //#include <iostream> //#include <opencv2/highgui.hpp> //#include <opencv2/core.hpp> //#include <opencv2/imgproc.hpp> //#include <opencv/cv.h> // ////#include <opencv2/imgproc/imgproc_c.h> ////#include <opencv2/imgproc/imgproc_c.h> // //using namespace cv; //using namespace std; ////initial min and max HSV filter values. ////these will be changed using trackbars ////int H_MIN = 0; ////int H_MAX = 256; ////int S_MIN = 0; ////int S_MAX = 256; ////int V_MIN = 0; ////int V_MAX = 256; // //// GREEN ////int H_MIN = 45; ////int H_MAX = 80; // //// GREEN-BLUE ////int H_MIN = 80; ////int H_MAX = 90; // //// BLUE //int H_MIN = 90; //int H_MAX = 135; // //// PINK ////int H_MIN = 135; ////int H_MAX = 165; // //// RED ////int H_MIN = 165; ////int H_MAX = 180; // //// ORANGE ////int H_MIN = 0; ////int H_MAX = 20; // //// YELLOW ////int H_MIN = 20; ////int H_MAX = 35; // //// YELLOW-GREEN ////int H_MIN = 35; ////int H_MAX = 45; // ////int H_MIN = 90; ////int H_MAX = H_MIN; // //int S_MIN = 75; //int S_MAX = 256; //int V_MIN = 0; //int V_MAX = 256; // //// BLACK -------------------- NOT WORKING ---------------------- ////int H_MIN = 165; ////int H_MAX = 180; ////int S_MIN = 255; ////int S_MAX = 256; ////int V_MIN = 0; ////int V_MAX = 5; // ////default capture width and height //const int FRAME_WIDTH = 640; //const int FRAME_HEIGHT = 480; ////max number of objects to be detected in frame //const int MAX_NUM_OBJECTS=50; ////minimum and maximum object area //const int MIN_OBJECT_AREA = 20*20; //const int MAX_OBJECT_AREA = FRAME_HEIGHT*FRAME_WIDTH/1.5; ////names that will appear at the top of each window //vector<Point> points; //const string windowName = "Original Image"; //const string windowName1 = "HSV Image"; //const string windowName2 = "Thresholded Image"; //const string windowName3 = "After Morphological Operations"; //const string trackbarWindowName = "Trackbars"; //Point2f mouse_point; ////Matrix to store each frame of the webcam feed //Mat cameraFeed, bgr_mat, hsv_mat, HSV; //matrix storage for HSV image //Mat1b mask; //int b, g, r, h, s, v; //Scalar color; //Vec3b pixel; // //void on_trackbar( int, void* ) //{//This function gets called whenever a // // trackbar position is changed // // // //} //string intToString(int number){ // // // std::stringstream ss; // ss << number; // return ss.str(); //} //void createTrackbars(){ // //create window for trackbars // // // namedWindow(trackbarWindowName,0); // //create memory to store trackbar name on window // char TrackbarName[50]; // sprintf( TrackbarName, "H_MIN", H_MIN); // // sprintf( TrackbarName, "H_MAX", H_MAX); // // sprintf( TrackbarName, "S_MIN", S_MIN); // // sprintf( TrackbarName, "S_MAX", S_MAX); // // sprintf( TrackbarName, "V_MIN", V_MIN); // // sprintf( TrackbarName, "V_MAX", V_MAX); // //create trackbars and insert them into window // //3 parameters are: the address of the variable that is changing when the trackbar is moved(eg.H_LOW), // //the max value the trackbar can move (eg. H_HIGH), // //and the function that is called whenever the trackbar is moved(eg. on_trackbar) // // ----> ----> ----> // createTrackbar( "H_MIN", trackbarWindowName, &H_MIN, H_MAX, on_trackbar ); // createTrackbar( "H_MAX", trackbarWindowName, &H_MAX, H_MAX, on_trackbar ); // // createTrackbar( "S_MIN", trackbarWindowName, &S_MIN, S_MAX, on_trackbar ); // // createTrackbar( "S_MAX", trackbarWindowName, &S_MAX, S_MAX, on_trackbar ); // // createTrackbar( "V_MIN", trackbarWindowName, &V_MIN, V_MAX, on_trackbar ); // // createTrackbar( "V_MAX", trackbarWindowName, &V_MAX, V_MAX, on_trackbar ); // // //} // //void drawObject(int x, int y,Mat &frame){ // // //use some of the openCV drawing functions to draw crosshairs // //on your tracked image! // // //UPDATE:JUNE 18TH, 2013 // //added 'if' and 'else' statements to prevent // //memory errors from writing off the screen (ie. (-25,-25) is not within the window!) // // circle(frame,Point(x,y),20,Scalar(0,255,0),2); // if(y-25>0) // line(frame,Point(x,y),Point(x,y-25),Scalar(0,255,0),2); // else line(frame,Point(x,y),Point(x,0),Scalar(0,255,0),2); // if(y+25<FRAME_HEIGHT) // line(frame,Point(x,y),Point(x,y+25),Scalar(0,255,0),2); // else line(frame,Point(x,y),Point(x,FRAME_HEIGHT),Scalar(0,255,0),2); // if(x-25>0) // line(frame,Point(x,y),Point(x-25,y),Scalar(0,255,0),2); // else line(frame,Point(x,y),Point(0,y),Scalar(0,255,0),2); // if(x+25<FRAME_WIDTH) // line(frame,Point(x,y),Point(x+25,y),Scalar(0,255,0),2); // else line(frame,Point(x,y),Point(FRAME_WIDTH,y),Scalar(0,255,0),2); // // putText(frame,intToString(x)+","+intToString(y),Point(x,y+30),1,1,Scalar(0,255,0),2); // //} //void morphOps(Mat &thresh){ // // //create structuring element that will be used to "dilate" and "erode" image. // //the element chosen here is a 3px by 3px rectangle // // Mat erodeElement = getStructuringElement( CV_SHAPE_RECT,Size(3,3)); // //dilate with larger element so make sure object is nicely visible // Mat dilateElement = getStructuringElement( CV_SHAPE_RECT,Size(8,8)); // // erode(thresh,thresh,erodeElement); // erode(thresh,thresh,erodeElement); // // // dilate(thresh,thresh,dilateElement); // dilate(thresh,thresh,dilateElement); // // // //} //void trackFilteredObject(int &x, int &y, Mat threshold, Mat &cameraFeed){ // // Mat temp; // threshold.copyTo(temp); // //these two vectors needed for output of findContours // vector< vector<Point> > contours; // vector<Vec4i> hierarchy; // //find contours of filtered image using openCV findContours function // findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE ); // //use moments method to find our filtered object // double refArea = 30; // bool objectFound = false; // if (hierarchy.size() > 0) { // long numObjects = hierarchy.size(); // //if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter // if(numObjects < MAX_NUM_OBJECTS){ // for (int index = 0; index >= 0; index = hierarchy[index][0]) { // // Moments moment = moments((cv::Mat)contours[index]); // double area = moment.m00; // // //if the area is less than 20 px by 20px then it is probably just noise // //if the area is the same as the 3/2 of the image size, probably just a bad filter // //we only want the object with the largest area so we safe a reference area each // //iteration and compare it to the area in the next iteration. // if(area>MIN_OBJECT_AREA && area<MAX_OBJECT_AREA && area > refArea){ // x = moment.m10/area; // y = moment.m01/area; // // objectFound = true; // // }else objectFound = false; // // // } // //let user know you found an object // if(objectFound ==true){ // putText(cameraFeed,"Tracking Object",Point(0,50),2,1,Scalar(0,255,0),2); // //draw object location on screen // drawObject(x,y,cameraFeed);} // // }else putText(cameraFeed,"TOO MUCH NOISE! ADJUST FILTER",Point(0,50),1,2,Scalar(0,0,255),2); // } //} // //void trackFilteredObject(vector<Point> &points, Mat threshold, Mat &cameraFeed){ // // Mat temp; // threshold.copyTo(temp); // //these two vectors needed for output of findContours // vector< vector<Point> > contours; // vector<Vec4i> hierarchy; // //find contours of filtered image using openCV findContours function // findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE ); // //use moments method to find our filtered object // double refArea = 20; // bool objectFound = false; // if (hierarchy.size() > 0) { // long numObjects = hierarchy.size(); // //if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter // if(numObjects < MAX_NUM_OBJECTS){ // for (int index = 0; index >= 0; index = hierarchy[index][0]) { // // Moments moment = moments((cv::Mat)contours[index]); // double area = moment.m00; // // //if the area is less than 20 px by 20px then it is probably just noise // //if the area is the same as the 3/2 of the image size, probably just a bad filter // //we only want the object with the largest area so we safe a reference area each // //iteration and compare it to the area in the next iteration. // if(area > MIN_OBJECT_AREA && area < MAX_OBJECT_AREA && area > refArea){ // int x = moment.m10 / area; // int y = moment.m01 / area; // points.push_back(Point(x,y)); // // objectFound = true; // // }else objectFound = false; // // // } // //let user know you found an object // if(objectFound ==true){ // putText(cameraFeed,"Tracking Object",Point(0,50),2,1,Scalar(0,255,0),2); // //draw object location on screen // for (vector<Point>::iterator it = points.begin(); it != points.end(); it++) { // drawObject(it->x,it->y,cameraFeed); // } // } // // }else putText(cameraFeed,"TOO MUCH NOISE! ADJUST FILTER",Point(0,50),1,2,Scalar(0,0,255),2); // } //} // //static void on_mouse(int event,int x, int y, int, void* ){ // switch (event) { // // get the "most important" Color of the area selected // case EVENT_LBUTTONDOWN: // // break; // case EVENT_RBUTTONDOWN: // break; // // Tracks mouse // case EVENT_MOUSEMOVE: // mouse_point.x = x; // mouse_point.y = y; // break; // // default: // // imshow(windowName, cameraFeed); // // } // imshow(windowName, cameraFeed); // // //} // //int main(int argc, char* argv[]) //{ // //some boolean variables for different functionality within this // //program // bool trackObjects = true; // bool useMorphOps = true; // // // //matrix storage for binary threshold image // Mat threshold; // //x and y values for the location of the object // int x = 0, // y = 0; // //create slider bars for HSV filtering // createTrackbars(); // //video capture object to acquire webcam feed // VideoCapture capture; // //open capture object at location zero (default location for webcam) // // capture.open("http://admin:robotcam1@172.16.58.3/video.cgi?.mjpg"); // capture.open(0); // //set height and width of capture frame // capture.set(CAP_PROP_FRAME_WIDTH,FRAME_WIDTH); // capture.set(CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT); // //start an infinite loop where webcam feed is copied to cameraFeed matrix // //all of our operations will be performed within this loop // //store image to matrix // capture.read(cameraFeed); // // cvtColor(cameraFeed, color_mat,CV_BGR2HSV); // // imshow("color" , color_mat); // // imshow(windowName,cameraFeed); // // // while(1){ // // //store image to matrix // capture.read(cameraFeed); // //convert frame from BGR to HSV colorspace // cvtColor(cameraFeed,HSV,COLOR_BGR2HSV); // /** // * filter HSV image between values and store filtered image to // * threshold matrix // */ // inRange(HSV,Scalar(H_MIN,S_MIN,V_MIN),Scalar(H_MAX,S_MAX,V_MAX),threshold); // // /** // * perform morphological operations on thresholded image to eliminate noise // * and emphasize the filtered object(s) // */ // setMouseCallback(windowName, on_mouse); // if(useMorphOps) // morphOps(threshold); // /** // * pass in thresholded frame to our object tracking function // * this function will return the x and y coordinates of the // * filtered object // */ // if(trackObjects) // // trackFilteredObject(x,y,threshold,cameraFeed); // // trackFilteredObject(points,threshold,cameraFeed); // points.clear(); // // //show frames // imshow(windowName2,threshold); // // imshow(windowName,cameraFeed); // imshow(windowName1,HSV); // // // //delay 30ms so that screen can refresh. // //image will not appear without this waitKey() command // if (waitKey(30) >= 0) { // break; // } // } // // return 0; //} <file_sep>/Tracker/Tracker/Tracker/Background_Subtractor.cpp // // Background_Subtractor.cpp // Tracker // // Created by Dustin on 10/7/13. // Copyright (c) 2013 Dustin. All rights reserved. // #include "Background_Subtractor.h" <file_sep>/Tracker/Tracker/Tracker/Background_Subtractor.h // // Background_Subtractor.h // Tracker // // Created by Dustin on 10/7/13. // Copyright (c) 2013 Dustin. All rights reserved. // #ifndef __Tracker__Background_Subtractor__ #define __Tracker__Background_Subtractor__ #include <iostream> #include <opencv/cv.h> #include <vector> #include <opencv2/highgui.hpp> #include <opencv2/core.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/objdetect.hpp> #include <opencv2/opencv_modules.hpp> using namespace cv; using namespace std; class Background_subtractor: public BackgroundSubtractorMOG2{ // default parameters of gaussian background detection algorithm // static const int defaultHistory2 = 500; // Learning rate; alpha = 1/defaultHistory2 // static const float defaultVarThreshold2 = 4.0*4.0; // static const int defaultNMixtures2 = 5; // maximal number of Gaussians in mixture // static const float defaultBackgroundRatio2 = 0.9; // threshold sum of weights for background test // static const float defaultVarThresholdGen2 = 3.0*3.0; // static const float defaultVarInit2 = 15.0; // initial variance for new components // static const float defaultVarMax2 = 5 * defaultVarInit2; // static const float defaultVarMin2 = 4.0; }; #endif /* defined(__Tracker__Background_Subtractor__) */ <file_sep>/Tracker/Tracker/Tracker/Grid.cpp // // Grid.cpp // OpenCV // // Created by Dustin on 7/21/13. // Copyright (c) 2013 Dustin. All rights reserved. // #include "Grid.h" #include <vector> #include <ctime> #include <unistd.h> #include <opencv2/opencv.hpp> #include <opencv2/opencv_modules.hpp> #include <opencv2/imgproc/imgproc_c.h> #include <opencv2/imgproc/imgproc_c.h> int da_thresh = 100, max_length = 0, count = 0; // maximum length of image // random number generator set at a state of 12345 //RNG rng = RNG(12345); Grid::~Grid(){ } Grid::Grid(){ } Grid::Grid(Mat &src){ clock_t start_time = clock(); starter_image = src; clock_t end_time = clock(), ticks = end_time - start_time; cout << ticks / (double)CLOCKS_PER_SEC << endl; cout << "done" << endl; } Mat Grid::get_straightened_image(){ return straightened_image; } /** * sorts the vector according to x then y */ void Grid::sort_points(vector<Point2f> &points){ map<int, vector<int> > sorted_map = get_sorted_point_map(points); grid_intersections_map = sorted_map; map<int, vector<int> >::iterator map_it = sorted_map.begin(); points.clear(); while (map_it != sorted_map.end()) { vector<int>::iterator vect_it = map_it->second.begin(); while (vect_it != map_it->second.end()) { points.push_back(Point2f(map_it->first, *vect_it)); vect_it++; } map_it++; } } /** * locates a "blob" (the difference between the source and new image) */ vector<Point2f> Grid::get_blob_location(Mat &new_img){ Mat output, temp; bilateralFilter(new_img, output, 5, 150, 150); Mat kernel_circle = (Mat_<uchar>(3, 3) << 1,1,1,1,0,1,1,1,1); vector<Point2f> centers; vector<Scalar> colors; // cout << straightened_image.rows << " " << straightened_image.cols << endl; // cout << output.rows << " " << output.cols << endl; // cvtColor(ref, ref, CV_BGR2GRAY); // cvtColor(input, input, CV_BGR2GRAY); temp = straightened_image - output; // GaussianBlur(temp, temp, Size(15, 15), KERNEL_GENERAL); // input.copyTo(frame); // GaussianBlur(frame, frame, Size(15, 15), KERNEL_GENERAL); cvtColor(temp, temp, CV_BGR2GRAY); Canny(temp, temp, 50, 200); // dilate(temp, temp, kernel_circle, Point(-1, -1), 10); // medianBlur(input, input, 9); vector<vector<Point> > contours; findContours(temp,contours,RETR_EXTERNAL,CHAIN_APPROX_NONE); for(int i = 0; i < contours.size(); i++){ Point p; for(int j = 0; j < contours[i].size(); j++){ p += contours[i][j]; } p.x /= contours[i].size(); p.y /= contours[i].size(); // Scalar color(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); // colors.push_back(color); centers.push_back(p); } remove_redundant_points(centers, 40); // for(int i = 0; i < centers.size(); i++){ // circle(new_img, centers[i], 40, colors[1], -1); // } // cvtColor(temp, temp, CV_GRAY2BGR); // drawContours(new_img,contours,-1,Scalar(0,0,255),2); // imshow("this", temp); return centers; } /** * recursively merges entries of map whose keys are within a tolerance of one another * parameters: map< int, vector<Point2f> > &in_map * int tolerance: this represents a percentage; ex: 10 means ± 10% */ void Grid::merge_close_elements_of_map(map< int, vector<int> > &in_map, float tolerance){ map<int, vector<int> > current_map = in_map; map<int, vector<int> >::iterator it = in_map.begin(), beater_it; float new_tol = 1 + tolerance / 100.0; pair<int, vector<int> > current_pair = *it; it++; for (; it != in_map.end(); it++) { if ((it->first) * new_tol >= (current_pair.first) && (it->first) / new_tol <= (current_pair.first)) { int avg_key = (it->first + current_pair.first) / 2; vector<int> merged; merged.reserve((it->second).size() + (current_pair.second).size()); merged.insert(merged.end(), (it->second).begin(), (it->second).end()); merged.insert(merged.end(), (current_pair.second).begin(), (current_pair.second).end()); beater_it = current_map.find(current_pair.first); current_map.erase(beater_it); beater_it = current_map.find(it->first); current_map.erase(beater_it); current_pair = pair<int, vector<int> >(avg_key, merged); current_map.insert(current_pair); break; } else current_pair = *it; } if (in_map.size() != current_map.size()) { merge_close_elements_of_map(current_map, tolerance); } in_map = current_map; } /** * * returns map: key: xs from points * value: vector of correspoing ys from points * */ map<int, vector<int> > Grid::get_sorted_point_map(vector<Point2f> &points, float tolerance){ map<int, vector<int> > sorted_map; vector<int> ys; // set of xs (keys) that will be deleted from the map set<int> keys; int count = 0; /** * this is where macrosorting takes place. * this does not handle 'off' lines. (points that do not exactly align */ vector<Point2f> ::iterator it = points.begin(); while(it != points.end()){ if (sorted_map.find(static_cast<int>((*it).x)) == sorted_map.end()) { sorted_map.insert(pair<int, vector<int> >(static_cast<int>((*it).x), ys)); } sorted_map[static_cast<int>((*it).x)].push_back(static_cast<int>((*it).y)); keys.insert(static_cast<int>((*it).x)); it++; } if(sorted_map.begin()->first == 0){ vector<int> values = sorted_map.begin()->second; sorted_map.erase(0); keys.erase(0); (sorted_map.begin()->second).insert((sorted_map.begin()->second).end(),values.begin(), values.end()); } /** * are there any keys that are of a 10% proximity of one another? * let's recursively find out */ merge_close_elements_of_map(sorted_map, tolerance); map<int, vector<int> >::iterator map_it = sorted_map.begin(); if(sorted_map.begin()->first == 0){ vector<int> values = sorted_map.begin()->second; sorted_map.erase(0); // cout << "\t\t" << (sorted_map.begin()->second).size() << endl; // cout << "\t\tnext: " << sorted_map.begin()->first << "\t" << (sorted_map.begin()->second).size() << " -> "; (sorted_map.begin()->second).insert((sorted_map.begin()->second).end(),values.begin(), values.end()); // cout << "\t" << (sorted_map.begin()->second).size() << endl; } map_it = sorted_map.begin(); count = 1; while (map_it != sorted_map.end()) { // cout << "\n" << count << ".\t" << (map_it->first) << " # "; // count++; std::sort((map_it->second).begin(),(map_it->second).end()); // for (int i = 0; i < (map_it->second).size(); i++) { // cout <<(map_it->second)[i] << " , "; // } // cout << endl; map_it++; } return sorted_map; } void Grid::set_obstacle(Point p){ if (obst_map.find(p.x) != obst_map.end()) { obst_map[p.x].push_back(p.y); } else{ obst_map.insert(pair<int, vector<int> >(p.x , vector<int>(p.y))); } } /** * Returns a vector points for the shortest path to dst * * ^ * | —–> * * * * * *>F * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * S */ vector<Point2f> Grid::get_shortest_path_points(Point2i start_pt, Point2i end_point){ return get_shortest_path_points(start_pt, end_point, grid_intersections_map); } /** * Returns a vector points for the shortest path to dst * A* algm * ^ * | —–> * * * * * *>F * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * | | | | | * *|—-—-|—-—-|—-—-|—-—-| * S * * parameters: Point2f start_pt * Point2f end_point * map<int. vector<int> > grid */ vector<Point2f> Grid::get_shortest_path_points(Point2i start_pt, Point2i end_pt, map<int, vector<int> > grid){ /** * In order to use the A* (A Star) algorithm, the points need to simplified. * appendix holds the value of all x values; example |0| : 3 * |1| : 17 * |2| : 32 * .... * the indexes of appendix are the new "simplified" x values from grid; */ vector<int> appendix; for (map<int, vector<int> >::iterator it = grid.begin(); it != grid.end(); it++) { appendix.push_back(it->first); } // create simplified int simp_sx = (int)distance(appendix.begin(), find(appendix.begin(), appendix.end(), start_pt.x)), simp_sy = (int)distance(grid[start_pt.x].begin(), find(grid[start_pt.x].begin(), grid[start_pt.x].end(), start_pt.y)), simp_ex = (int)distance(appendix.begin(), find(appendix.begin(), appendix.end(), end_pt.x)), simp_ey = (int)distance(grid[end_pt.x].begin(), find(grid[end_pt.x].begin(), grid[end_pt.x].end(), end_pt.y)); Point2i simple_start(simp_sx, simp_sy), simple_end(simp_ex, simp_ey); // create object that hold the shortest path A_Star path = A_Star((int)grid.size(), (int)grid.begin()->second.size(), simp_sx, simp_sy, simp_ex, simp_ey, obst_map); vector<Point2i> simp_path = path.get_path_points(); vector<Point2f> path_points(simp_path.size()); for (int i = 0; i < simp_path.size(); i++) { int old_x = simp_path[i].x, old_y = simp_path[i].y, new_x = appendix[old_x], new_y = grid[new_x][old_y]; path_points[i] = Point2f(new_x, new_y); } return path_points; } /** * returns vector of floating-point "Points" * */ vector<Point2f> Grid::get_intersections(){ Mat temp; straightened_image.copyTo(temp); temp = get_contoured_image(temp); imshow("contour", temp); temp = get_skeleton(temp); imshow("skeleton", temp); vector<Point2f> intersections = get_intersections(temp); sort_points(intersections); return intersections; } Mat Grid::get_contours(){ Mat contours; return contours; } // returns basic grid from grid image Mat Grid::get_skeleton(){ return skeleton; } /** * returns a map of containg the corners of: source image * straightened image * vector<points> | key * ———————————————|——————— * source | "src" * straightened | "dst" * Procedure: -Use HoughLines to get distinctive lines in image * -merge the lines that are close to on another/ similar * -use process of elimination discover the edges of main object * -get intercepts of edges * -get endpoints of edges * -get intersections of edges * -approximate new dimensions of straightened image * -return map of both source and straightened endpoints */ map<string, vector<Point2f> > Grid::get_corner_points(){ map<string, vector<Point2f> > corner_points; return corner_points; } /** * creates an image with points/ circles overlayed onto a given image * Parameters: vector<Point2f> points: vector of points * Mat img: an image * Scalar color: color of circles */ void Grid::show_image(vector<Point2f> points, Mat img, vector<Point2f> path, int thickness, int radius, Scalar color){ Mat new_img; img.copyTo(new_img); for (int i = 0; i < path.size(); i++) { if (i + 1 < path.size()) { line(new_img, path[i], path[i + 1], color); } } for(vector<Point2f>::iterator it = points.begin(); it != points.end(); ++it){ circle(new_img, (*it), radius, color, thickness); stringstream ss; ss << "(" << it->x << " , " << it->y << ")"; string location = ss.str(); putText(new_img, location, Point((it ->x), (it->y) + 10), FONT_HERSHEY_PLAIN, 0.75, Scalar(0,0,255)); } imshow("Points", new_img); waitKey(30); } /** * removes redundancy from a vector of points (removes clusters) * parameter: vector<Point2f> &points * int tolerance */ void Grid::remove_redundant_points(vector<Point2f> &points, int tolerance = 90){ vector<Point2f> new_intersections, temp_intersections; new_intersections = get_essential_points(points, tolerance); points.clear(); points = new_intersections; } /** * returns the essential points from a vector of points by removing redundancy * (removes clusters) * */ vector<Point2f> Grid::get_essential_points(vector<Point2f> points, int tolerance){ vector<Point2f> points_remaining, points_final; unsigned long num_of_points = points.size(); if (num_of_points >= 1) { vector<Point2f>::iterator it = points.begin(); Point2f head = (*it); it++; for(; it != points.end(); it++){ int diff_x = abs(abs((*it).x) - abs(head.x)), diff_y = abs(abs((*it).y) - abs(head.y)); if(diff_x > tolerance || diff_y > tolerance){ points_remaining.push_back((*it)); } } points_final = get_essential_points(points_remaining, tolerance); points_final.push_back(head); return points_final; } return points; } /** * returns vector of floating-point "Points" * Parameter: Mat skeleton: a skeleton-like(bare-bones) representation of image * */ vector<Point2f> Grid::get_intersections(Mat skeleton){ Mat kernel = (Mat_<uchar>(3,3) << 1,1,1,1,0,1,1,1,1); // dilate(skeleton, skeleton, kernel, Point(-1,-1), 2); // // thickness of border/ edges // int top = (int)(skeleton.rows * 0.01), // bottom = top, // left = (int)skeleton.cols * 0.01, // right = left; // // put a border around image (makes sure it still has one) // copyMakeBorder(skeleton, skeleton, top, bottom, left, right, BORDER_CONSTANT, Scalar(255,255,255)); Mat cannied_image; Canny(skeleton, cannied_image, 50, 200, 3); cvtColor(cannied_image, cannied_image, CV_GRAY2BGR); vector<Point2f> intersections; vector<Vec4i> lines; // get the lines in the image HoughLinesP(skeleton, lines, 1, CV_PI / 180, 180, 30, 10); // gets the inserctions points of all the lines. Size skel_size = skeleton.size(); for(int i = 0; i < lines.size(); i++){ for(int j = 0; j < lines.size();j++){ Point p1 = Point(lines[i][0], lines[i][1]), p2 = Point(lines[i][2], lines[i][3]), p3 = Point(lines[j][0], lines[j][1]), p4 = Point(lines[j][2], lines[j][3]); if(i != j){ Point2f intersection = get_intersection(p1, p2, p3, p4); if(intersection.x >= 0 && intersection.y >= 0 && intersection.x <= skel_size.width * 1.1 && intersection.y <= skel_size.height * 1.1) intersections.push_back(intersection); } } } // remove some of the redudandant points from the above process. remove_redundant_points(intersections); return intersections; } // gets intersection point of two lines Point2f Grid::get_intersection(Point2f o1, Point2f o2, Point2f p1, Point2f p2){ Point2f x = p1 - o1; Point2f d1 = o2 - o1; Point2f d2 = p2 - p1; Point2f r(-1,-1); float cross = d1.x*d2.y - d1.y*d2.x; if(abs(cross) >= 1e-8){ double t1 = (x.x * d2.y - x.y * d2.x) / cross; r = o1 + d1 * t1; } return r; } void Grid::set_image_straighting(vector<Point2f> &input_corners){ warped_corners = input_corners; straightened_corners.push_back(cv::Point2f(0, 0)); straightened_corners.push_back(cv::Point2f(600, 0)); straightened_corners.push_back(cv::Point2f(600, 600)); straightened_corners.push_back(cv::Point2f(0, 600)); Point2f center(0,0); for (int i = 0; i < input_corners.size(); i++) { center += input_corners[i]; } center.x /= warped_corners.size(); center.y /= warped_corners.size(); sort_corners(warped_corners, center); perspective_transform_matrix = getPerspectiveTransform(warped_corners, straightened_corners); straightened_image = Mat::zeros(600, 600, CV_8UC3); warpPerspective(starter_image, straightened_image, perspective_transform_matrix, straightened_image.size()); // int top = (int)straightened_image.rows * 0.01, // bottom = top, // left = (int)straightened_image.cols * 0.01, // right = left; // copyMakeBorder(straightened_image, straightened_image, top, bottom, left, right, BORDER_CONSTANT, Scalar(0,0,0)); } void Grid::straighten_image(Mat &img){ Mat quad = Mat::zeros(600, 600, CV_8UC3); warpPerspective(img, quad, perspective_transform_matrix, quad.size()); // int top = (int)quad.rows * 0.01, // bottom = top, // left = (int)quad.cols * 0.01, // right = left; // copyMakeBorder(quad, quad, top, bottom, left, right, BORDER_CONSTANT, Scalar(0,0,0)); img = quad; } Mat Grid::get_contoured_image(Mat img){ Mat img_gray, canny_output; img.copyTo(img_gray); vector<vector<Point> > contours; vector<Vec4i> hierarchy; cvtColor(img_gray, img_gray, CV_BGR2GRAY); dilate(img_gray, img_gray, KERNEL_GENERAL, Point(-1,-1)); // erode(img_gray, img_gray, KERNEL_GENERAL); // detect edges Canny(img_gray, canny_output, da_thresh, da_thresh * 2, 3); imshow("img gray", img_gray); // find countours findContours(canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0,0)); Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3); for( int i = 0; i< contours.size(); i++ ){ // Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); Scalar color = Scalar(255, 255, 0); drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point() ); } return drawing; } // returns basic grid from grid image Mat Grid::get_skeleton(Mat contoured_img){ Mat mask = Mat::zeros(contoured_img.rows + 2, contoured_img.cols + 2, CV_8U); floodFill(contoured_img, mask, Point(0,0), 255, 0, Scalar(),Scalar(), 4 + (255 << 8) + FLOODFILL_MASK_ONLY); Mat kernel = (Mat_<uchar>(3,3) << 1,1,1,1,0,1,1,1,1); dilate(mask, mask, kernel); erode(mask, mask, kernel, Point(-1, -1), 2); return mask; } /** * Determine top-left, bottom-left, top-right, and bottom-right corner * Given the four corner points, we have to determine the top-left, bottom-left, top-right, and bottom-right corner so we can apply the perspective * correction. * To determine the top-left, bottom-left, top-right, and bottom right corner, we’ll use the simplest method: * Get the mass center. * Points that have lower y-axis than mass center are the top points, otherwise they are bottom points. * Given two top points, the one with lower x-axis is the top-left. The other is the top-right. * Given two bottom points, the one with lower x-axis is the bottom-left. The other is the bottom-right. */ void Grid::sort_corners(std::vector<cv::Point2f>& corners, cv::Point2f center){ std::vector<cv::Point2f> top, bot; for (int i = 0; i < corners.size(); i++) { if (corners[i].y < center.y) top.push_back(corners[i]); else bot.push_back(corners[i]); } cv::Point2f tl = top[0].x > top[1].x ? top[1] : top[0]; cv::Point2f tr = top[0].x > top[1].x ? top[0] : top[1]; cv::Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0]; cv::Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1]; corners.clear(); corners.push_back(tl); corners.push_back(tr); corners.push_back(br); corners.push_back(bl); }<file_sep>/Tracker/Tracker/Tracker/Node.h // // Node.h // OpenCV // // Created by Dustin on 7/28/13. // Copyright (c) 2013 Dustin. All rights reserved. // #ifndef __OpenCV__Node__ #define __OpenCV__Node__ #include <iostream> #include "math.h" class Node { // current position int xPos; int yPos; // total distance already travelled to reach the node int level; // priority=level+remaining distance estimate int priority; // smaller: higher priority int dir; public: Node(int xp, int yp, int d, int p, int dir = 8); int getxPos() const; int getyPos() const; int getLevel() const; int getPriority() const; void updatePriority(const int & xDest, const int & yDest); // give better priority to going strait instead of diagonally void nextLevel(const int & i); // i: direction // Estimation function for the remaining distance to the goal. const int & estimate(const int & xDest, const int & yDest) const; }; #endif /* defined(__OpenCV__Node__) */ <file_sep>/Tracker/Tracker/Tracker/Robot.cpp // // Robot.cpp // Grid // // Created by Dustin on 9/1/13. // Copyright (c) 2013 Dustin. All rights reserved. // #include "Robot.h" vector<Point2f> path; string name; Robot::Robot(){ this->name = "bot"; rng = RNG(12345); color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); } Robot::Robot(string name){ this->name = name; rng = RNG(12345); color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); } Robot::Robot(Point2f point, string name){ this->name = name; path.push_back(point); rng = RNG(12345); color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); } Robot::Robot(Point2f point){ name = "bot"; path.push_back(point); rng = RNG(12345); color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); } Robot::~Robot(){ } void Robot::update_current_position(Point2f point){ path.push_back(point); } vector<Point2f> Robot::get_path(){ return path; } string Robot::get_name(){ return name; } Point2f Robot::get_nearest_bot(vector<Point2f> bot_locations){ Point2f this_bot = *path.rbegin(), closest_bot = *bot_locations.begin(), diff_point; diff_point = this_bot - closest_bot; diff_point.x *= diff_point.x; diff_point.y *= diff_point.y; double dist = sqrt(diff_point.x + diff_point.y); for (vector<Point2f>::iterator it = (bot_locations.begin() + 1); it != bot_locations.end(); it++) { diff_point = this_bot - *it; diff_point = this_bot - closest_bot; diff_point.x *= diff_point.x; diff_point.y *= diff_point.y; double temp_dist = sqrt(diff_point.x + diff_point.y); if (temp_dist < dist) { dist = temp_dist; } } return this_bot; } void Robot::show_bot_location(Mat &image){ circle(image, *(path.rbegin()), 10, color); } void Robot::show_bot_path(Mat &image){ for (vector<Point2f>::iterator it = path.begin(); it != path.end() - 1; it++) { line(image, *it, *(it + 1), color); } } Scalar Robot::get_bot_color(){ return color; }
0226a63d85d8f15a03d5afb9779dca455ebd28e9
[ "C++" ]
12
C++
AdamBolfik/Grid_detector
2f748c0b61e1bef96b45228056266a5ced6e21d9
933026f0f3f3cb5128d447ff36d8ac4801e6f813
refs/heads/master
<file_sep># Multi-repo `app` > POC of using a remote package dependency `core` in a JavaScript (ES6) project `app`. **Install** 1. `npm install` 1. Go to [`core`](https://github.com/serbanghita/multirepo-core-js) repo; Run `npm link` 1. Come back to `app`; Run `npm link multirepo-core` 1. `npm run transpile` 1. `node dist/index.js`<file_sep>"use strict"; var _babelRegister = require("babel-register"); var _babelRegister2 = _interopRequireDefault(_babelRegister); var _Actor = require("multirepo-core/src/entity/Actor"); var _Actor2 = _interopRequireDefault(_Actor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // import * as core from "multirepo-core"; // const Actor = core.entity.Actor; const a = new _Actor2.default("sghita", 10, 20, "<NAME>"); // babelRegister({ // ignore: /node_modules\/(?!multirepo-core)/, // extensions: [".js"] // }); console.log(a.getName(), a.spawn());
4cd59932c05207cd23d09f7b1f0837197f51d8ce
[ "Markdown", "JavaScript" ]
2
Markdown
serbanghita/multirepo-app-js
7e74995ba2fda2ce7078c6128b39ef96fd21b9df
b56ac8432580b2189a3526c6a7a76e7423ee7460
refs/heads/main
<repo_name>domison/JS_Cave-Automata<file_sep>/src/js/Display.js import { game, loop } from './gol-oop.js'; export default class Display { constructor() { // canvas setup this.canvas = document.querySelector('canvas'); this.context = this.canvas.getContext('2d'); this.width = this.canvas.width = window.innerWidth * (9 / 10); this.height = this.canvas.height = window.innerHeight * (9 / 10); this.height <= this.width ? (this.width = this.height) : (this.height = this.width); this.resolution = Math.floor(this.width / 64); this.cols = Math.floor(this.width / this.resolution); this.rows = Math.floor(this.height / this.resolution); // other DOM elements // div this.container = document.getElementById('container'); // btn this.btnNames = [ 'Play', 'Undo', 'Conway', 'Caive', 'Aisle', 'Terrain', 'Clear', 'Random', 'Instant Cave', 'Instant Isles', 'Instant Worms', ]; this.buttons = this.addButtons(this.btnNames); this.buttons = document.querySelectorAll('button'); this.buttons.forEach((btn) => { return btn.addEventListener('click', (event) => { switch (event.target) { case this.buttons[0]: // play game.board.algorithm.setRule([[2, 3], [3]]); game.notGOL = false; if (btn.textContent != 'Play') { btn.textContent = 'Play'; game.isLooped = false; } else { btn.textContent = 'Stop'; game.isLooped = true; } loop(); break; case this.buttons[1]: // undo game.regressBoard(); this.render(game.board.grid); btn.toggleAttribute('disabled'); break; case this.buttons[2]: // conway game.notGOL = false; game.board.algorithm.setRule([[2, 3], [3]]); game.progressBoard(1); this.render(game.board.grid); break; case this.buttons[3]: // caveAI game.notGOL = true; // apply B678/S345678 game.board.algorithm.setRule([ // [2, 3, 4, 5, 6, 7, 8], // [5, 6, 7, 8], [3, 4, 5, 6, 7, 8], [6, 7, 8], ]); game.progressBoard(1); this.render(game.board.grid); break; case this.buttons[4]: // AIsland game.board.algorithm.setRule([ [5, 6, 7, 8], [5, 6, 7, 8], ]); game.progressBoard(1); this.render(game.board.grid); break; case this.buttons[5]: // Terrain game.terrainOn = !game.terrainOn; game.board.toggleTerrain(); game.board.terrain = true; this.render(game.board.grid); break; case this.buttons[6]: // clear game.board.resetGrid(); this.render(game.board.grid); break; case this.buttons[7]: // randomize game.board.randomizeGrid(); this.render(game.board.grid); break; case this.buttons[8]: // instant cave game.board.randomizeGrid(); game.board.algorithm.setRule([ [3, 4, 5, 6, 7, 8], [6, 7, 8], ]); game.progressBoard(1); game.board.algorithm.setRule([ [5, 6, 7, 8], [5, 6, 7, 8], ]); game.progressBoard(1); game.board.algorithm.setRule([ [3, 4, 5, 6, 7, 8], [6, 7, 8], ]); game.progressBoard(10); game.board.toggleTerrain(); this.render(game.board.grid); break; case this.buttons[9]: // instant isles game.notGOL = false; game.board.randomizeGrid(); game.board.algorithm.setRule([ [2, 3, 4, 5, 6, 7, 8], [6, 7, 8], ]); game.progressBoard(1); game.board.algorithm.setRule([ [5, 6, 7, 8], [5, 6, 7, 8], ]); game.progressBoard(8); game.board.algorithm.setRule([ [3, 4, 5, 6, 7, 8], [5, 6, 7, 8], ]); game.progressBoard(10); game.board.toggleTerrain(); this.render(game.board.grid); break; case this.buttons[10]: // instant worms game.board.randomizeGrid(); game.board.algorithm.setRule([ [2, 3, 4, 5, 6, 7, 8], [6, 7, 8], ]); game.progressBoard(Math.ceil(Math.random() * 20)); game.board.algorithm.setRule([ [5, 6, 7, 8], [5, 6, 7, 8], ]); game.progressBoard(Math.ceil(Math.random() * 10) + 2); game.board.algorithm.setRule([ [3, 4, 5, 6, 7, 8], [5, 6, 7, 8], ]); game.progressBoard(10); game.board.toggleTerrain(); this.render(game.board.grid); break; } }); }); } addButtons(names) { for (const i in names) { if (names.hasOwnProperty(i)) { const btn = names[i]; this.createDOMElement({ content: `${btn}`, type: 'button', parent: this.container, CSSClasses: { btn: `btn-${+i + 1}` }, }); } } return document.querySelectorAll('btn'); } render(grid) { for (let col = 0; col < grid.length; col++) { for (let row = 0; row < grid[col].length; row++) { const cell = grid[col][row]; this.context.beginPath(); this.context.fillStyle = cell.state === 0 ? 'white' : cell.state === 3 ? 'brown' : 'blue'; this.context.rect( col * this.resolution, row * this.resolution, this.resolution, this.resolution ); this.context.strokeStyle = 'white'; this.context.fill(); this.context.stroke(); } } this.context.strokeStyle = 'blue'; this.context.stroke; } createDOMElement({ content = '', type = 'div', parent = document.body, CSSClasses = {}, attributes = {}, }) { let newElement = document.createElement(type); if (content) newElement.innerText = content; for (const key in CSSClasses) { if (CSSClasses.hasOwnProperty(key)) { newElement.classList.add(key, CSSClasses[key]); } } for (const key in attributes) { if (attributes.hasOwnProperty(key)) { newElement.setAttribute(key, attributes[key]); } } parent.append(newElement); } } <file_sep>/src/js/gol-oop.js 'use strict'; import Display from './Display.js'; import Game from './Game.js'; import Board from './Board.js'; import Algorithm from './Algorithm.js'; let display = new Display(); let game = new Game(new Board(new Algorithm())); game.board.grid = game.board.randomizeGrid(); display.render(game.board.grid); // requestAnimationFrame(loop); function loop() { if (game.isLooped) { game.progressBoard(1); display.render(game.board.grid); requestAnimationFrame(loop); } } export { game, display, loop }; <file_sep>/src/js/Algorithm.js export default class Algorithm { constructor() { this.current = [[2, 3], [3]]; // standard rule-set } // lives 2,3 - revives 3 - dies setRule(rule = [[2, 3], [3]]) { this.current = rule; } } <file_sep>/README.md # JS_Cave-Automata A cellular automaton that can create cave systems, and isles, based on the famous Game of Life algorithm ## This was a week long project to conclude a 2-month-long training as JavaScript Developer ### Written purely in Javascript using only minimal static html and css ### Inspired by the famous game of life cellular automata by Conway ### Has been giving a twist to extend its functionality to something aking to a cave- or map-builder
905fd6cdeedde6bd530d04987dd96293c734ae2a
[ "JavaScript", "Markdown" ]
4
JavaScript
domison/JS_Cave-Automata
f3045733bca3ee6d966cc276c9a553f4f6530c7c
c1af47ff267ff145848376bf208acb590498f6a5
refs/heads/master
<repo_name>yakaolife/goToBeach<file_sep>/README.md Go To Beach and Stay Hydrate 😎<br> Playing with React Native with a little funky project. ### Using: * React Native (create-react-native-app) * Native Base (react native ui components) * React Native Navigation (?) <file_sep>/App.js import React from 'react'; import { AsyncStorage, View, Animated } from 'react-native'; import { StyleProvider, Container, Header, Content, Button, Footer, Text, Fab, Icon } from 'native-base'; import moment from 'moment'; export default class App extends React.Component { constructor() { super(); this.state = { active: false, water: 0, error: null, animate: new Animated.Value(0), }; this.setWater = this.setWater.bind(this); this.moveWater = this.moveWater.bind(this); } componentDidMount() { AsyncStorage.getItem("water").then((water) => this.setState({water: parseInt(water)})); } setWater(reset) { const water = reset ? 0 : this.state.water+1; this.setState({ water: water }); AsyncStorage.setItem("water", `${water}`); this.moveWater(water-1, water); } moveWater(from, to) { } render() { const date = moment().format("MMM Do"); const water = `${this.state.water} cups`; return ( <Container> <Header> <Text style={styles.headerTitle}>😎 Go To Beach and Stay Hydrate 😎</Text> </Header> <Content> <View style={styles.content}> <Text style={styles.date}>{date}</Text> <Text style={styles.cupText}>{water}</Text> </View> </Content> {/* <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }}> <View style={{width: '100%', height: 400, backgroundColor: 'powderblue'}} /> <View style={{width: '100%', height: 50, backgroundColor: 'skyblue'}} /> <View style={{width: '100%', height: 50, backgroundColor: 'steelblue'}} /> </View> */} <Fab active={this.state.active} direction="right" style={styles.fabStyle} position="bottomLeft" onPress={() => this.setWater()} onLongPress={() => this.setWater(true)} > <Icon type='Entypo' name='drop' /> </Fab> </Container> ); } } const styles = { content: { flex: 1, alignItems: 'center', justifyContent: 'center', }, headerTitle: { paddingTop: 10, }, date: { fontSize: 20, paddingTop: 50, position: 'absolute', }, cupText: { fontSize: 40, color: '#aaa', paddingTop: 150, position: 'absolute', }, zIndexTop: { zIndex: 1000, }, fabStyle: { backgroundColor: '#00b2f9', zIndex: 1000, } };
2befbf3186ec9e9ead9a864de90036042a55d6be
[ "Markdown", "JavaScript" ]
2
Markdown
yakaolife/goToBeach
99c70b79bc5f0d5c22d6b584fb65854456b5043e
31d5e63ab8345c8fe8d7c1e9fce89576b5074d55
refs/heads/master
<repo_name>creatone1996/edp12<file_sep>/lesson2/src/Exercise2/System_out_print.java package Exercise2; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; public class System_out_print { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("QUESTION 1"); int i = 5; System.out.println(i); System.out.println("QUESTION 2"); int i1 = 100000000; System.out.printf(Locale.US,"%,d%n" ,i1); System.out.println("QUESTION 3"); float i2 = 5.567098f; System.out.printf("%5.4f%n",i2); System.out.println("QUESTION 4"); String i3 = "<NAME>"; System.out.printf("Ho va Ten: " + i3 + " Va toi dang doc than"); System.out.println("QUESTION 5"); String pattern = "24/04/2020 11:16:20"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat.format(new Date()); System.out.println(date); } } <file_sep>/lesson2/src/vti/com/railway12/Group.java package vti.com.railway12; public class Group { int id; String groupName; Account [] accounts; } <file_sep>/lesson2/src/vti/com/railway12/Lesson2.java package vti.com.railway12; import java.util.Date; public class Lesson2 { public static void main(String[] args) { // TODO Auto-generated method stub Department department0 = new Department(); department0.id = 1; department0.departmentName = "Phong Sale"; System.out.println("id: " + department0.id); System.out.println("departmentName:" + department0.departmentName); Department department1 = new Department(); department1.id = 2; department1.departmentName = "Phong MKT"; System.out.println("id: " + department1.id); System.out.println("departmentName:" + department1.departmentName); Department department3 = new Department(); department3.id = 3; department3.departmentName = "<NAME>"; System.out.println("id: " + department3.id); System.out.println("departmentName:" + department3.departmentName); Position position = new Position(); position.id = 1; position.PositionName = PositionName.DEV; System.out.println("id: " + position.id); System.out.println("PositionName:" + position.PositionName); Position position1 = new Position(); position1.id = 2; position1.PositionName = PositionName.TEST; System.out.println("id: " + position1.id); System.out.println("PositionName:" + position1.PositionName); Position position2 = new Position(); position2.id = 3; position2.PositionName = PositionName.PM; System.out.println("id: " + position2.id); System.out.println("PositionName:" + position2.PositionName); Group group1 = new Group(); group1.id = 1; group1.groupName = "nhom1"; Group group2 = new Group(); group2.id = 2; group2.groupName = "nhom2"; Group group3 = new Group(); group3.id = 3; group3.groupName = "nhom3"; Account account0 = new Account(); account0.id = 1; account0.email = "<EMAIL>"; account0.fullName = "<NAME>"; account0.userName = "Hieupt0807"; account0.department = department0; account0.position = position; Date date = new Date(); account0.createDate = date; Group[] accountgroups = {group1, group2}; account0.groups = accountgroups; System.out.println("ID nhan vien: " + account0.id); System.out.println("Email nhan vien: " + account0.email); System.out.println("Ten nhan vien: " + account0.fullName); System.out.println("Ten dang nhap nhan vien: " + account0.userName); System.out.println("Phong Ban Nhan Vien: " + account0.department.departmentName); System.out.println("Chuc vu nhan vien: " + account0.position.PositionName); System.out.println("Ngay tao Nhan Vien: " + account0.createDate); Account account1 = new Account(); account1.id = 2; account1.email = "<EMAIL>"; account1.fullName = "<NAME>"; account1.userName = "Hieupt08072"; account1.department = department1; account1.position = position1; Date date1 = new Date(); account1.createDate = date1; Group [] groupaccount1 = new Group[] {group1, group3}; account1.groups = groupaccount1 ; System.out.println("ID nhan vien: " + account1.id); System.out.println("Email nhan vien: " + account1.email); System.out.println("Ten nhan vien: " + account1.fullName); System.out.println("Ten dang nhap nhan vien: " + account1.userName); System.out.println("Phong Ban Nhan Vien: " + account1.department.departmentName); System.out.println("Chuc vu nhan vien: " + account1.position.PositionName); System.out.println("Ngay tao Nhan Vien: " + account1.createDate); Account account2 = new Account(); account2.id = 3; account2.email = "<EMAIL>"; account2.fullName = "<NAME>"; account2.userName = "Hieupt08071"; account2.department = department3; account2.position = position2; Date date2 = new Date(); account2.createDate = date2; account2.groups = new Group[] {group1, group2, group3}; System.out.println("ID nhan vien: " + account2.id); System.out.println("Email nhan vien: " + account2.email); System.out.println("Ten nhan vien: " + account2.fullName); System.out.println("Ten dang nhap nhan vien: " + account2.userName); System.out.println("Phong Ban Nhan Vien: " + account2.department.departmentName); System.out.println("Chuc vu nhan vien: " + account2.position.PositionName); System.out.println("Ngay tao Nhan Vien: " + account2.createDate); group1.accounts = new Account [] {account0, account1, account2}; group2.accounts = new Account [] {account0, account2}; group3.accounts = new Account [] {account1, account2}; System.out.println("kiem tra nhan vien thu 2"); if( account1.department == null) { System.out.println("nhan vien nay chua co phong ban"); } else { System.out.println("phong ban cua nhan vien nay la: " + account1.department.departmentName); }; System.out.println("kiem tra nhan vien thu 2"); if( account1.groups == null) { System.out.println("nhan vien nay chua co nhom"); } else { int countgroups = account1.groups.length; if (countgroups == 1 || countgroups == 2) { System.out.println("Group cua nhan vien nay la Java\r\n" + "Fresher, C# Fresher"); } if (countgroups == 3) { System.out.println("nhan vien nay la nguoi quan trong, tham gia nhieu group"); } if (countgroups >= 4) { System.out.println("Nhan vien nay la nguoi hong chuyen, tham gia tat ca group"); } }; System.out.println("kiem tra nhan vien thu 2 (cau 3)"); System.out.println(account2.department == null ? "Nhan vien nay chua co phong ban" : "Phong ban cua nhan vien nay la: " + account2.department.departmentName); System.out.println("kiem tra nhan vien thu 1 (cau 4)"); System.out.println(account0.position.PositionName.toString() == "DEV" ? "Day la Deverloper" : "Nguoi nay khong phai developer"); System.out.println("cau 5"); int countgroupaccount1 = group1.accounts.length; switch (countgroupaccount1) { case 1: System.out.println("nhom co 1 thanh vien"); break; case 2: System.out.println("nhom co 2 thanh vien"); break; case 3: System.out.println("nhom co 3 thanh vien"); break; default: System.out.println("nhom co nhieu thanh vien"); }; System.out.println("cau 6"); int countgroupaccount2 = account2.groups.length; switch (countgroupaccount2) { case 1: System.out.println("Group cua nhan vien nay la Java\\r\\n\" + \"Fresher, C# Fresher"); break; case 2: System.out.println("Group cua nhan vien nay la Java\\r\\n\" + \"Fresher, C# Fresher"); break; case 3: System.out.println("nhan vien nay la nguoi quan trong, tham gia nhieu group"); break; default: System.out.println("Nhan vien nay la nguoi hong chuyen, tham gia tat ca group"); }; System.out.println("cau 7"); String account1Name = account0.position.PositionName.toString(); switch (account1Name) { case "DEV": System.out.println("Nhan vien nay la developer"); break; default: System.out.println("nhan vien nay khong phai developer"); }; System.out.println("cau 8"); Account[] acccounts1 = { account0,account1, account2 }; for (Account account : acccounts1) { System.out.println("AccountID: " + account.id + " Email: " + account.email + " Name: " + account.fullName); }; System.out.println("cau 9"); Department[] departmentArray = { department0, department1, department3 }; for ( Department department : departmentArray) { System.out.println("DepartmentID: " + department.id + " Name: " + department.departmentName); }; System.out.println("cau 10"); Account[] accArray1 = { account0, account1 }; for (int i = 0 ; i < accArray1.length; i ++) { System.out.println("Thông tin account " + (i+1)); System.out.println("Email: " + accArray1[i].email); System.out.println("Full name: " + accArray1[i].fullName); System.out.println("Pḥng ban: " + accArray1[i].department.departmentName); }; System.out.println("cau 11"); Department[] departmentArray1 = { department0, department1, department3 }; for ( int i = 0; i < departmentArray1.length; i++) { System.out.println("ID: " + (i+1)); System.out.println("Name: " + departmentArray1[i].departmentName); }; System.out.println("cau 12"); Department[] departmentArray2 = { department0, department1,department3 }; for ( int i = 0; i < 2; i++) { System.out.println("ID: " + (i+1)); System.out.println("Name: " + departmentArray2[i].departmentName); }; System.out.println("cau 13"); Account[] accArray2 = { account0, account1, account2 }; for (int i = 0 ; i < accArray2.length; i ++) { if (i != 1) { System.out.println("Thông tin account " + (i+1)); System.out.println("Email: " + accArray2[i].email); System.out.println("Full name: " + accArray2[i].fullName); System.out.println("Pḥng ban: " + accArray2[i].department.departmentName); } }; System.out.println("cau 14"); Account[] accArray3 = { account0, account1, account2 }; for (int i = 0 ; i < accArray2.length; i ++) { if (accArray3[i].id < 4) { System.out.println("Thông tin account " + (i+1)); System.out.println("Email: " + accArray3[i].email); System.out.println("Full name: " + accArray3[i].fullName); System.out.println("Pḥng ban: " + accArray3[i].department.departmentName); } }; System.out.println("cau 15"); for (int i = 0; i <= 20; i++) { if (i%2 == 0) { System.out.println(i); } } System.out.println("cau 16"); Account[] accArray4 = { account0, account1, account2 }; { int i = 0; while (i < accArray4.length) { System.out.println("Thông tin account " + (i+1)); System.out.println("Email: " + accArray4[i].email); System.out.println("Full name: " + accArray4[i].fullName); System.out.println("Pḥng ban: " + accArray4[i].department.departmentName); i++; } }; System.out.println("cau 17"); Department[] departmentArray3 = { department0, department1, department3 }; { int j = 0; while ( j < departmentArray3.length) { System.out.println("ID: " + (j+1)); System.out.println("Name: " + departmentArray3[j].departmentName); j++; } }; System.out.println("cau 18"); Department[] departmentArray4 = { department0, department1, department3 }; { int j = 0; while ( j < departmentArray4.length) { if (j < 2) { System.out.println("ID: " + (j+1)); System.out.println("Name: " + departmentArray3[j].departmentName); j++;} } }; // System.out.println("cau 19"); // Account[] accArray5 = { account0, account1, account2}; // // int i = 0; // while (i < accArray5.length) { // if (i != 1 ) { // System.out.println("Thông tin account " + (i+1)); // System.out.println("Email: " + accArray5[i].email); // System.out.println("Full name: " + accArray5[i].fullName); // System.out.println("Pḥng ban: " + accArray5[i].department.departmentName); // } // i++; // }; // // System.out.println("cau 20"); // Account[] accArray6 = { account0, account1, account2 }; // // int i1 = 0; // while ( i1 < accArray6.length ) { // if (accArray6[i1].id < 4) { // System.out.println("Thông tin account " + (i1+1)); // System.out.println("Email: " + accArray6[i1].email); // System.out.println("Full name: " + accArray6[i1].fullName); // System.out.println("Pḥng ban: " + accArray6[i1].department.departmentName); // } // i1++; // }; // System.out.println("cau 21"); // Account[] accArray9 = { account0, account1, account2 }; // int i2 = 0; // do { // System.out.println("Thông tin account " + (i2+1)); // System.out.println("Email: " + accArray9[i2].email); // System.out.println("Full name: " + accArray9[i2].fullName); // System.out.println("Pḥng ban: " + accArray9[i2].department.departmentName); // i2++; // } while ( i2 < accArray9.length); // // // System.out.println("cau 22"); // Department[] departmentArray5 = { department0, department1, department3 }; // int j = 0; // do { // System.out.println("ID: " + (j+1)); // System.out.println("Name: " + departmentArray5[j].departmentName); // j++; // } while ( j < departmentArray5.length); // // System.out.println("cau 23"); // Department[] departmentArray6 = { department0, department1, department3 }; // int j1 = 0; // do { // if (j1 < 2) { // System.out.println("ID: " + (j1+1)); // System.out.println("Name: " + departmentArray6[j1].departmentName); // j1++; // } // } while ( j1 < departmentArray6.length); // System.out.println("cau 24"); // Account[] accArray7 = { account0, account1, account2}; // // int i3 = 0; // do { // if (i3 != 1 ) { // System.out.println("Thông tin account " + (i3+1)); // System.out.println("Email: " + accArray7[i3].email); // System.out.println("Full name: " + accArray7[i3].fullName); // System.out.println("Pḥng ban: " + accArray7[i3].department.departmentName); // } // i3++; // } while (i3 < accArray7.length); // // System.out.println("cau 25"); // Account[] accArray8 = { account0, account1, account2 }; // // int i4 = 0; // do { // if (accArray8[i4].id < 4) { // System.out.println("Thông tin account " + (i4+1)); // System.out.println("Email: " + accArray8[i4].email); // System.out.println("Full name: " + accArray8[i4].fullName); // System.out.println("Pḥng ban: " + accArray8[i4].department.departmentName); // } // i4++; // } while ( i4 < accArray8.length ); System.out.println("QUESTION 1"); System.out.println(" cau 1"); int i = 5; System.out.println(i); } } <file_sep>/lesson2/src/BTthem/BT1.java package BTthem; import java.util.Scanner; public class BT1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); System.out.println("Moi ban nhap vao chieu dai"); int cd = scanner.nextInt(); System.out.println("Moi ban nhap vao chieu rong"); int cr = scanner.nextInt(); int ChuVi = cvhcn(cr,cd); System.out.println("Dien tich hinh chu nhat co chieu dai: " + cd + "cm" + " chieu rong " + cr + "cm la " + ChuVi ); } public static int cvhcn (int cr, int cd) { int ChuVi = (cr + cd)*2; return ChuVi; } } <file_sep>/lesson2/src/Exercise5/Question2.java package Exercise5; import java.util.Scanner; public class Question2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner st = new Scanner(System.in); System.out.println("Moi ban nhap vao 2 so thuc"); System.out.println("Moi ban nhap vao so thuc thu 1"); float a0 = st.nextFloat(); System.out.println("Moi ban nhap vao so thuc thu 2"); float a1 = st.nextFloat(); System.out.println("Ban vua nhap vao 2 so thuc " + a0 + " " + a1); } } <file_sep>/lesson2/src/vti/com/railway12/Lesson2_1.java package vti.com.railway12; import java.util.Date; public class Lesson2_1 { public static void main(String[] args) { // TODO Auto-generated method stub Department department0 = new Department(); department0.id = 1; department0.departmentName = "Phong Sale"; System.out.println("id: " + department0.id); System.out.println("departmentName:" + department0.departmentName); Department department1 = new Department(); department1.id = 2; department1.departmentName = "Phong MKT"; System.out.println("id: " + department1.id); System.out.println("departmentName:" + department1.departmentName); Department department3 = new Department(); department3.id = 3; department3.departmentName = "<NAME>"; System.out.println("id: " + department3.id); System.out.println("departmentName:" + department3.departmentName); Position position = new Position(); position.id = 1; position.PositionName = PositionName.DEV; System.out.println("id: " + position.id); System.out.println("PositionName:" + position.PositionName); Position position1 = new Position(); position1.id = 2; position1.PositionName = PositionName.TEST; System.out.println("id: " + position1.id); System.out.println("PositionName:" + position1.PositionName); Position position2 = new Position(); position2.id = 3; position2.PositionName = PositionName.PM; System.out.println("id: " + position2.id); System.out.println("PositionName:" + position2.PositionName); Group group1 = new Group(); group1.id = 1; group1.groupName = "nhom1"; Group group2 = new Group(); group2.id = 2; group2.groupName = "nhom2"; Group group3 = new Group(); group3.id = 3; group3.groupName = "nhom3"; Account account0 = new Account(); account0.id = 1; account0.email = "<EMAIL>"; account0.fullName = "<NAME>"; account0.userName = "Hieupt0807"; account0.department = department0; account0.position = position; Date date = new Date(); account0.createDate = date; Group[] accountgroups = {group1, group2}; account0.groups = accountgroups; System.out.println("ID nhan vien: " + account0.id); System.out.println("Email nhan vien: " + account0.email); System.out.println("Ten nhan vien: " + account0.fullName); System.out.println("Ten dang nhap nhan vien: " + account0.userName); System.out.println("Phong Ban Nhan Vien: " + account0.department.departmentName); System.out.println("Chuc vu nhan vien: " + account0.position.PositionName); System.out.println("Ngay tao Nhan Vien: " + account0.createDate); Account account1 = new Account(); account1.id = 2; account1.email = "<EMAIL>"; account1.fullName = "<NAME>"; account1.userName = "Hieupt08072"; account1.department = department1; account1.position = position1; Date date1 = new Date(); account1.createDate = date1; Group [] groupaccount1 = new Group[] {group1, group3}; account1.groups = groupaccount1 ; System.out.println("ID nhan vien: " + account1.id); System.out.println("Email nhan vien: " + account1.email); System.out.println("Ten nhan vien: " + account1.fullName); System.out.println("Ten dang nhap nhan vien: " + account1.userName); System.out.println("Phong Ban Nhan Vien: " + account1.department.departmentName); System.out.println("Chuc vu nhan vien: " + account1.position.PositionName); System.out.println("Ngay tao Nhan Vien: " + account1.createDate); Account account2 = new Account(); account2.id = 3; account2.email = "<EMAIL>"; account2.fullName = "<NAME>"; account2.userName = "Hieupt08071"; account2.department = department3; account2.position = position2; Date date2 = new Date(); account2.createDate = date2; account2.groups = new Group[] {group1, group2, group3}; System.out.println("ID nhan vien: " + account2.id); System.out.println("Email nhan vien: " + account2.email); System.out.println("Ten nhan vien: " + account2.fullName); System.out.println("Ten dang nhap nhan vien: " + account2.userName); System.out.println("Phong Ban Nhan Vien: " + account2.department.departmentName); System.out.println("Chuc vu nhan vien: " + account2.position.PositionName); System.out.println("Ngay tao Nhan Vien: " + account2.createDate); group1.accounts = new Account [] {account0, account1, account2}; group2.accounts = new Account [] {account0, account2}; group3.accounts = new Account [] {account1, account2}; // System.out.println("cau 19"); // Account[] accArray5 = { account0, account1, account2}; // // int i = 0; // while (i < accArray5.length) { // if (i != 1 ) { // System.out.println("Thông tin account " + (i+1)); // System.out.println("Email: " + accArray5[i].email); // System.out.println("Full name: " + accArray5[i].fullName); // System.out.println("Pḥng ban: " + accArray5[i].department.departmentName); // } // i++; // }; // // System.out.println("cau 20"); // Account[] accArray6 = { account0, account1, account2 }; // // int i1 = 0; // while ( i1 < accArray6.length ) { // if (accArray6[i1].id < 4) { // System.out.println("Thông tin account " + (i1+1)); // System.out.println("Email: " + accArray6[i1].email); // System.out.println("Full name: " + accArray6[i1].fullName); // System.out.println("Pḥng ban: " + accArray6[i1].department.departmentName); // } // i1++; // }; // // // // System.out.println("cau 21"); // Account[] accArray4 = { account0, account1, account2 }; // int i2 = 0; // do { // System.out.println("Thông tin account " + (i2+1)); // System.out.println("Email: " + accArray4[i2].email); // System.out.println("Full name: " + accArray4[i2].fullName); // System.out.println("Pḥng ban: " + accArray4[i2].department.departmentName); // i2++; // } while ( i2 < accArray4.length); // // // System.out.println("cau 22"); // Department[] departmentArray3 = { department0, department1, department3 }; // int j = 0; // do { // System.out.println("ID: " + (j+1)); // System.out.println("Name: " + departmentArray3[j].departmentName); // j++; // } while ( j < departmentArray3.length); // // System.out.println("cau 23"); // Department[] departmentArray4 = { department0, department1, department3 }; // int j1 = 0; // do { // if (j1 < 2) { // System.out.println("ID: " + (j1+1)); // System.out.println("Name: " + departmentArray3[j1].departmentName); // j1++; // } // } while ( j1 < departmentArray4.length); // System.out.println("cau 24"); // Account[] accArray7 = { account0, account1, account2}; // // int i3 = 0; // do { // if (i3 != 1 ) { // System.out.println("Thông tin account " + (i3+1)); // System.out.println("Email: " + accArray7[i3].email); // System.out.println("Full name: " + accArray7[i3].fullName); // System.out.println("Pḥng ban: " + accArray7[i3].department.departmentName); // } // i3++; // } while (i3 < accArray7.length); // // System.out.println("cau 25"); // Account[] accArray8 = { account0, account1, account2 }; // // int i4 = 0; // do { // if (accArray8[i4].id < 4) { // System.out.println("Thông tin account " + (i4+1)); // System.out.println("Email: " + accArray8[i4].email); // System.out.println("Full name: " + accArray8[i4].fullName); // System.out.println("Pḥng ban: " + accArray8[i4].department.departmentName); // } // i4++; // } while ( i4 < accArray8.length ); } } <file_sep>/lesson2/src/BTthem/BT5.java package BTthem; import java.util.Scanner; public class BT5 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); System.out.println("Moi ban nhap vao cac he so a bac 2"); float a = scanner.nextFloat(); System.out.println("Moi ban nhap vao cac he so b bac 1"); float b = scanner.nextFloat(); System.out.println("Moi ban nhap vao cac he so c bac 0"); float c = scanner.nextFloat(); ketqua(a,b,c); } public static void ketqua (float a, float b, float c) { if (a == 0) { if ( b== 0) { System.out.println("Phuong Trinh Vo Nghiem"); } else { System.out.println("Phuong trinh co nghiem" + (-b)/c); } }; if (a != 0) { float Delta = (b*b) - 4*a*c; if (Delta < 0) { System.out.println("Phuong Trinh Vo Nghiem"); } else if (Delta == 0) { System.out.println("Phuong trinh co 1 nghiem " + (-b)/(2*a)); } else { float x1= (float) ((-b) + Math.sqrt(Delta)/(2*a)); float x2= (float) ((-b) - Math.sqrt(Delta)/(2*a)); System.out.println("Phuong trinh co 2 Nghiem " + "x1 = " + x1 + " va x2= " + x2); } }; } } <file_sep>/lesson2/src/BTthem/BT2.java package BTthem; import java.util.Scanner; public class BT2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); System.out.println("Moi ban nhap vao canh"); int ca = scanner.nextInt(); int Dientich = DTHV(ca); System.out.println("Dien tich hinh vuong co canh " + ca + "cm la: " + Dientich); } public static int DTHV (int ca) { int Dientich = ca*ca; return Dientich; } } <file_sep>/lesson2/src/Exercise5/Department.java package Exercise5; public class Department { int id; String departmentName; } <file_sep>/.metadata/version.ini #Wed Jun 09 20:34:18 GMT+07:00 2021 org.eclipse.core.runtime=2 org.eclipse.platform=4.19.0.v20210303-1800 <file_sep>/.metadata/.plugins/org.eclipse.pde.core/.cache/clean-cache.properties #Cached timestamps #Tue Jun 08 15:50:58 GMT+07:00 2021 <file_sep>/lesson2/src/Exercise5/Question3.java package Exercise5; import java.util.Scanner; public class Question3 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner ten = new Scanner(System.in); System.out.println("Moi Ban Nhap Vao Ho Ten"); System.out.println("Moi ban nhap vao Ho"); String a0 = ten.next(); System.out.println("Moi ban nhap vao Ten"); String a1 = ten.next(); System.out.println("Ho Va Ten Cua Ban " + a0 + " " + a1); } }
f116b8e3f0c8b7f62a07ce883ae81ff8d720584d
[ "Java", "INI" ]
12
Java
creatone1996/edp12
8cc2fea2f412f3a78b27b8b9aadb97f706af1eec
a01d7dc80391f2276704ff2c9e07f3c034f34879
refs/heads/master
<repo_name>raji2007/flipkart<file_sep>/src/org/samp/Flipkart1.java package org.samp; public class Flipkart1 { public static void main(String[] args) { System.out.println("First Flipkart Class"); System.out.println("Second Flipkart Class"); } }
104c22a59cf0fcf39c394b14f987bce336500a31
[ "Java" ]
1
Java
raji2007/flipkart
9b103fb2b8cb179f83a306e3c1ca0b496679e50d
d090cec7ddb997747cbcd454424ffa22ecf5a4a7