branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>rohitgaonkar/ty-practicals<file_sep>/fragmentation.c #include<stdio.h> /*#include<conio.h>*/ int main() { long dsize,mtusize,oset,psize,ndsize; int flag=1,mf=1,i; char ident='x'; FILE *f; f=fopen("out.txt","wt"); printf("Enter the size of the data\n"); scanf("%ld",&dsize); while(flag==1) { printf("Eter the size of the maximum tranfer unit\n"); scanf("%ld",&mtusize); if((mtusize-20)%8==0) flag=0; } oset=0; psize=mtusize-20; for(i=1;oset<dsize;i++) { fprintf(f,"%d\t%c\t%d\t%ld\t%ld\n",i,ident,mf,oset,psize); oset=oset+psize; } if(oset>=dsize) { mf=0; ndsize=oset-dsize; if(oset==dsize) ndsize=psize; fprintf(f,"%d\t%c\t%d\t%ld\t%ld\n",i,ident,mf,dsize,ndsize); } fclose(f); return 0; } <file_sep>/README.md # ty-practicals use for practicals
6c628a1a4b918dc703261d0698914d350b4355f3
[ "Markdown", "C" ]
2
C
rohitgaonkar/ty-practicals
ce544691c75c419301e2e44e8a7e4a9bfce468d8
05ad116c48eaed7d1dccd7d1e8fa8933d84a11a6
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { Router } from "@angular/router"; import { AuthService } from '../../services/auth.service'; @Component({ selector: 'app-company-register', templateUrl: './company-register.component.html', styleUrls: ['./company-register.component.css'] }) export class CompanyRegisterComponent implements OnInit { invalidRegister: boolean; company: any; unexpectedError: boolean = false; registerSuccess: boolean = false; existingUser: boolean = false; registerForm = new FormGroup({ webUrl: new FormControl('', [ Validators.required, Validators.minLength(5), Validators.maxLength(15), Validators.pattern('[a-z0-9._%+-]+\.[a-z]{2,3}$') ]), personName: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), companyName: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), phone: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), email: new FormControl('', [Validators.required, Validators.email, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]), password: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(15)]) }); get personName() { return this.registerForm.get('personName'); } get companyName() { return this.registerForm.get('companyName'); } get webUrl() { return this.registerForm.get('webUrl'); } get phone() { return this.registerForm.get('phone'); } get email() { return this.registerForm.get('email'); } get password() { return this.registerForm.get('password'); } constructor( private router: Router, private authService: AuthService ) { } onFormSubmit() { if (this.registerForm.valid) { this.company = this.registerForm.value; this.authService.companyRegister(this.company) .subscribe(result => { if (result.message == "success") { this.registerSuccess = true; setTimeout(() => this.router.navigate(['c/login']), 2000 ); } else if (result.message == "alreadyRegistered") { this.invalidRegister = true; this.existingUser = true; } else { this.invalidRegister = true; } }, error => { this.unexpectedError = true; }); } else { this.company = this.registerForm.value; } } ngOnInit() { if (this.authService.isLoggedIn()) { this.router.navigate(['c/dashboard']); } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { AuthService } from '../../services/auth.service'; import { CompanyService } from '../../services/company.service'; import { Router } from "@angular/router"; @Component({ selector: 'app-company-profile', templateUrl: './company-profile.component.html', styleUrls: ['./company-profile.component.css'] }) export class CompanyProfileComponent implements OnInit { formValues: any; companyData: any; updateForm: FormGroup; updateStatus: Object = { active: null, message: null, css: null }; companyImageData: String; imgSize: Number; imgType: String; companyId: any = this.authService.currentCompany._id; constructor( private router: Router, private companyService: CompanyService, private authService: AuthService ) { } companyDetails() { this.companyService.getCompany(this.companyId) .subscribe( data => { this.companyData = data.json(); } ); } imageUpload(event) { this.companyImageData = event.src; this.imgSize = event.file.size; this.imgType = event.file.type; } profileImageUpate() { if (this.imgSize > 204800) { this.updateStatus["message"] = "Please select an image less tha 200 KB"; this.updateStatus["active"] = false; } else if (this.imgType == 'image/jpeg' || this.imgType == 'image/png') { this.companyService.updateProfileImage({ companyId: this.companyId, logo: this.companyImageData }) .subscribe(response => { let result = response.json(); if (result.message == "success") { this.messageReturn("Logo uploaded Successfully", true); } else if (result.message == "invalid company") { this.messageReturn("Logo update failed", false); } else { this.messageReturn("Logo update failed", false); } }, error => { this.messageReturn("Server Error", false); }); } else { this.messageReturn("Please select an valid image type .jpg or .png", false); } } messageReturn(message, status){ this.updateStatus["message"] = message; this.updateStatus["active"] = status; } updateFormSubmit() { this.formValues = this.updateForm.value; this.companyService.updateCompany(this.formValues) .subscribe(response => { let result = response.json(); if (result.message == "success") { this.messageReturn("Profile updated successfully", true); } else if (result.message == "invalid password") { this.messageReturn("Invalid Password", false); } else { this.messageReturn("Profile update failed", false); } }, error => { this.messageReturn("Server Error", false); }); } ngOnInit() { this.companyDetails(); this.updateForm = new FormGroup({ 'companyId': new FormControl(this.companyId), 'personName': new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), 'webUrl': new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(25)]), 'companyName': new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), 'email': new FormControl(null), 'facebook': new FormControl(null), 'googlePlus': new FormControl(null), 'twitter': new FormControl(null), 'linkedin': new FormControl(null), 'description': new FormControl(null), 'phone': new FormControl('', [Validators.minLength(3), Validators.maxLength(15)]), 'country': new FormControl(null), 'category': new FormControl(null), 'password': new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), }); } } <file_sep>import { Component, OnInit, ElementRef, ClassProvider } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { UserService } from '../../services/user.service'; import { AuthService } from '../../services/auth.service'; import { ReviewService } from '../../services/review.service'; import { CompanyService } from '../../services/company.service'; @Component({ selector: 'app-show-review', templateUrl: './show-review.component.html', styleUrls: ['./show-review.component.css'] }) export class ShowReviewComponent implements OnInit { user:any; reResult:object[]; reviewresult:object[]; cresult:object[]; htmlToAdd:any; assignedUser:any; title:any; constructor( private userService: UserService, private authService: AuthService, private revService: ReviewService, private cmpService: CompanyService, private elementRef: ElementRef ) { } showReview(){ this.user=this.authService.currentUser._id; this.userService.getUser(this.user) .subscribe( data => { this.reResult=data.json(); } ); } showDetailReview(){ var cmpId=[]; var cmpName=[]; var len, i, cn; var rateHtml = document.getElementsByClassName('add-rating')[0].outerHTML; console.log(rateHtml) this.user=this.authService.currentUser._id; this.userService.userAllReview() .subscribe(data => { this.reviewresult=data.json(); var htmlResult=""; var cmpResult=""; var starValue=""; for(let i in this.reviewresult){ if(this.user == this.reviewresult[i]['assignedUser']){ var ratingNum = this.reviewresult[i]['rate']; switch(ratingNum){ case 1: starValue="star-rating-1"; break; case 1.5: starValue="star-rating-1half"; break; case 2: starValue="star-rating-2"; break; case 2.5: starValue="star-rating-2half"; break; case 3: starValue="star-rating-3"; break; case 3.5: starValue="star-rating-3half"; break; case 4: starValue="star-rating-4"; break; case 4.5: starValue="star-rating-4half"; break; default: starValue="star-rating-5"; } cmpId.push(this.reviewresult[i]['assignedCompany']); htmlResult+="<div class='card'><div class='reviewComp'>Review of <a class='reviewForComp'></a></div>"; htmlResult+="<div><div class='star-review "+ starValue +"'><span>"+ this.reviewresult[i]['rate'] +"</span></div><div class='reviewTitle'>"+ this.reviewresult[i]['title'] +"</div><div class='reviewText'>"+ this.reviewresult[i]['review'] +"</div></div>"; htmlResult+="</div>"; } } this.cmpService.getAllCompany() .subscribe( data =>{ this.cresult= data.json(); for(let c in this.cresult){ for(let m in cmpId){ if(this.cresult[c]['_id'] == cmpId[m]){ cmpResult= this.cresult[c]['companyName']; cmpName[m] = cmpResult; var t1 = this.elementRef.nativeElement.querySelector('.card-area'); var divs = t1.querySelectorAll(".reviewForComp"); for(var i = 0; i < divs.length; i++){ divs[i].innerHTML = cmpName[i]; } } } } } ); var d1 = this.elementRef.nativeElement.querySelector('.card-area'); d1.insertAdjacentHTML('beforeend', htmlResult); var rateText = this.elementRef.nativeElement.querySelectorAll('.card .star-review'); console.log(rateText.length); for(var r=0;r<rateText.length;r++){ rateText[r].insertAdjacentHTML('beforeend', rateHtml); } } ); } ngOnInit() { this.showReview(); this.showDetailReview(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { CompanySearchService } from '../../services/search/company-search.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { results; constructor( private companySearch: CompanySearchService ) { } searchCompany(queryString) { if(this.results == undefined){ this.companySearch.search() .subscribe( data => { this.results = data.json(); localStorage.setItem('companyData', JSON.stringify(this.results)); } ); } else { this.results = JSON.parse(localStorage.getItem('companyData')); } } ngOnInit() { } } <file_sep>import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Router } from "@angular/router"; import { ApiUrlService } from '../config/api-url.service'; @Injectable() export class ReviewService { url = this.apiUrl.url; port = this.apiUrl.port; serverUrl = this.url+':'+this.port; constructor( private http: Http, private router: Router, private apiUrl: ApiUrlService ) { } addReview(reviewData){ return this.http.post(this.serverUrl+'/api/review/add', reviewData); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { AuthService } from '../../services/auth.service'; import { UserService } from '../../services/user.service'; import { Router } from "@angular/router"; @Component({ selector: 'app-user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.css'] }) export class UserProfileComponent implements OnInit { formValues: any; userData: any; updateForm: FormGroup; updateStatus: Object = { active: null, message: null, css: null }; userImageData: String; imgSize: Number; imgType: String; userId: any = this.authService.currentUser._id; private base64textString: String = ""; constructor( private router: Router, private userService: UserService, private authService: AuthService ) { } userDetails() { this.userService.getUser(this.userId) .subscribe( data => { this.userData = data.json(); } ); } imageUpload(event) { this.userImageData = event.src; this.imgSize = event.file.size; this.imgType = event.file.type; } profileImageUpate() { if (this.imgSize > 204800) { this.updateStatus["message"] = "Please select an image less tha 200 KB"; this.updateStatus["active"] = false; } else if (this.imgType == 'image/jpeg' || this.imgType == 'image/png') { this.userService.updateProfileImage({ userId: this.userId, profile_image: this.userImageData }) .subscribe(result => { if (result.message == "success") { this.updateStatus["message"] = "Profile image uploaded Successfully"; this.updateStatus["active"] = true; } else if (result.message == "invalid user") { this.updateStatus["message"] = "Profile image uploaded failed"; this.updateStatus["active"] = false; } else { this.updateStatus["message"] = "Profile image uploaded failed"; this.updateStatus["active"] = false; } }, error => { this.updateStatus["message"] = "Server Error"; this.updateStatus["active"] = false; }); } else { this.updateStatus["message"] = "Please select an valid image type .jpg or .png"; this.updateStatus["active"] = false; } } updateFormSubmit() { this.formValues = this.updateForm.value; this.userService.updateUser(this.formValues) .subscribe(result => { if (result.message == "success") { this.updateStatus["message"] = "Profile updated successfully"; this.updateStatus["active"] = true; } else if (result.message == "invalid password") { this.updateStatus["message"] = "Invalid Password"; this.updateStatus["active"] = false; } else { this.updateStatus["message"] = "Profile update failed"; this.updateStatus["active"] = false; } }, error => { this.updateStatus["message"] = "Server Error"; this.updateStatus["active"] = false; }); } ngOnInit() { this.userDetails(); this.updateForm = new FormGroup({ 'userId': new FormControl(this.userId), 'name': new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), 'email': new FormControl(null), 'phone': new FormControl('', [Validators.minLength(3), Validators.maxLength(15)]), 'gender': new FormControl(null), 'country': new FormControl(null), 'password': new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]), }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from "@angular/router"; import { AuthService } from '../../services/auth.service'; import { UserService } from '../../services/user.service'; @Component({ selector: 'app-user-dashboard', templateUrl: './user-dashboard.component.html', styleUrls: ['./user-dashboard.component.css'] }) export class UserDashboardComponent implements OnInit { user: any; results: Object[]; count: any; constructor( private userService: UserService, private authService: AuthService ) { } chartOptions = { responsive: true // THIS WILL MAKE THE CHART RESPONSIVE (VISIBLE IN ANY DEVICE). } labels = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']; chartData = [ { label: '1st Year', data: [21, 56, 4, 31, 45, 15, 57, 61, 9, 17, 24, 59] }, { label: '2nd Year', data: [47, 9, 28, 54, 77, 51, 24] } ]; colors = [ { // 1st Year. backgroundColor: 'rgba(77,83,96,0.2)' }, { // 2nd Year. backgroundColor: 'rgba(30, 169, 224, 0.8)' } ] onChartClick(event) { console.log(event); } userDetails(){ this.user = this.authService.currentUser._id; //console.log(this.user); this.userService.getUser(this.user) .subscribe( data => { this.results = data.json(); } ); //this.count = (this.user).length; //console.log(this.user); //console.log(this.count); } userReviewCount(){ var i; var totalreview = 0; this.user = this.authService.currentUser._id; console.log(this.user); this.userService.userAllReview() .subscribe(results => { this.count = results.json(); console.log(this.count); var len = this.count.length; for(i =0; i<len;i++){ console.log(this.count[i].assignedUser); if(this.count[i].assignedUser == this.user){ totalreview++; } } console.log(totalreview); }); } ngOnInit() { this.userDetails(); this.userReviewCount(); } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { CompanyFrontComponent } from './company-front.component'; describe('CompanyFrontComponent', () => { let component: CompanyFrontComponent; let fixture: ComponentFixture<CompanyFrontComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ CompanyFrontComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CompanyFrontComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { HttpModule } from '@angular/http'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { NavbarComponent } from './components/navbar/navbar.component'; import { FooterComponent } from './components/footer/footer.component'; import { UserRegisterComponent } from './components/user-register/user-register.component'; import { UserProfileComponent } from './components/user-profile/user-profile.component'; import { AuthService } from './services/auth.service'; import { UserLoginComponent } from './components/user-login/user-login.component'; import { UserDashboardComponent } from './components/user-dashboard/user-dashboard.component'; import { HomeComponent } from './components/home/home.component'; import { AuthGaurdService } from './services/auth-gaurd.service'; import { DashboardHeaderComponent } from './common/dashboard-header/dashboard-header.component'; import { DashboardFooterComponent } from './common/dashboard-footer/dashboard-footer.component'; import { UserService } from './services/user.service'; import { ApiUrlService } from './config/api-url.service'; import { CompanyRegisterComponent } from './components/company-register/company-register.component'; import { CompanyLoginComponent } from './components/company-login/company-login.component'; import { CompanyDashboardComponent } from './components/company-dashboard/company-dashboard.component'; import { CompanyService } from './services/company.service'; import { CompanyAuthGaurdService } from './services/company-auth-gaurd.service'; import { NoAccessComponent } from './common/no-access/no-access.component'; import { UserAuthGaurdService } from './services/user-auth-gaurd.service'; import { Error404Component } from './common/error-404/error-404.component'; import { ChartsModule } from 'ng2-charts'; import { CompanyProfileComponent } from './components/company-profile/company-profile.component' import { ImageUploadModule } from "angular2-image-upload"; import { CompanyFrontComponent } from './components/company-front/company-front.component'; import { AddReviewComponent } from './components/add-review/add-review.component'; import { NoCompanyComponent } from './common/no-company/no-company.component'; import { MiddlewareService } from './services/middleware.service'; import { ReviewService } from './services/review.service'; import { CompanySearchService } from './services/search/company-search.service'; import { CompanySearchPipe } from './filters/company-search.pipe'; import { ShowReviewComponent } from './components/show-review/show-review.component'; const appRoutes: Routes = [ {path: '', component: HomeComponent}, {path: 'u/register', component: UserRegisterComponent}, {path: 'u/login', component: UserLoginComponent}, {path: 'c/register', component: CompanyRegisterComponent}, {path: 'c/login', component: CompanyLoginComponent}, {path: 'no-access', component: NoAccessComponent}, {path: 'company/add-review/:webUrl', component: AddReviewComponent}, {path: 'company-not-found', component: NoCompanyComponent}, { path: 'company/:webUrl', component: CompanyFrontComponent }, { path: 'u/profile', component: UserProfileComponent, canActivate: [AuthGaurdService, UserAuthGaurdService] }, { path: 'u/dashboard', component: UserDashboardComponent, canActivate: [AuthGaurdService, UserAuthGaurdService] }, { path: 'c/profile', component: CompanyProfileComponent, canActivate: [AuthGaurdService, CompanyAuthGaurdService] }, { path: 'c/dashboard', component: CompanyDashboardComponent, canActivate: [AuthGaurdService, CompanyAuthGaurdService] }, {path:'show-review', component: ShowReviewComponent}, {path: '404', component: Error404Component}, {path: '**', redirectTo: '404'}, ] @NgModule({ declarations: [ AppComponent, NavbarComponent, FooterComponent, UserLoginComponent, UserDashboardComponent, HomeComponent, DashboardHeaderComponent, DashboardFooterComponent, UserProfileComponent, UserRegisterComponent, CompanyRegisterComponent, CompanyLoginComponent, CompanyDashboardComponent, NoAccessComponent, Error404Component, CompanyProfileComponent, CompanyFrontComponent, AddReviewComponent, NoCompanyComponent, CompanySearchPipe, ShowReviewComponent ], imports: [ BrowserModule, HttpModule, FormsModule, ReactiveFormsModule, HttpClientModule, RouterModule.forRoot(appRoutes), ImageUploadModule.forRoot(), ChartsModule ], providers: [ AuthService, AuthGaurdService, UserService, CompanyService, CompanyAuthGaurdService, UserAuthGaurdService, ApiUrlService, MiddlewareService, ReviewService, CompanySearchService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { TestBed, inject } from '@angular/core/testing'; import { CompanyAuthGaurdService } from './company-auth-gaurd.service'; describe('CompanyAuthGaurdService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [CompanyAuthGaurdService] }); }); it('should be created', inject([CompanyAuthGaurdService], (service: CompanyAuthGaurdService) => { expect(service).toBeTruthy(); })); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { CompanyService } from '../../services/company.service'; import { MiddlewareService } from '../../services/middleware.service'; @Component({ selector: 'app-company-front', templateUrl: './company-front.component.html', styleUrls: ['./company-front.component.css'] }) export class CompanyFrontComponent implements OnInit { results: any; constructor( private route: ActivatedRoute, private router: Router, private companyService: CompanyService, private middleWareService: MiddlewareService ) {} addReview(){ this.middleWareService.reviewUrl = this.results[0].webUrl; this.middleWareService.currentUrlId = this.results[0]._id; this.middleWareService.currentCompanyName = this.results[0].companyName; this.router.navigate(['/company/add-review/'+this.results[0].webUrl]); } getCompanyDetails(){ this.route.paramMap .subscribe(paramas =>{ var companyUrl = paramas['params'].webUrl; this.companyService.getCompanyByUrl(companyUrl) .subscribe( data => { this.results = data.json(); if(this.results.length == 0){ this.router.navigate(['company-not-found']); } } ); }); } ngOnInit() { this.getCompanyDetails(); } } <file_sep>var demo1 = new autoComplete({ selector: '#autoComp9', minChars: 1, source: function (term, suggest) { term = term.toLowerCase(); var choices = ['ActionScript', 'AppleScript', 'Asp', 'Assembly', 'BASIC', 'Batch', 'C', 'C++', 'CSS', 'Clojure', 'COBOL', 'ColdFusion', 'Erlang', 'Fortran', 'Groovy', 'Haskell', 'HTML', 'Java', 'JavaScript', 'Lisp', 'Perl', 'PHP', 'PowerShell', 'Python', 'Ruby', 'Scala', 'Scheme', 'SQL', 'TeX', 'XML']; var suggestions = []; for (i = 0; i < choices.length; i++) if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]); suggest(suggestions); console.log(suggestions); } }); //demo1(); //console.log(demo1); var demo2 = new autoComplete({ selector: '#advanced-demo', minChars: 0, source: function (term, suggest) { term = term.toLowerCase(); var choices = [['Australia', 'au'], ['Austria', 'at'], ['Brasil', 'br'], ['Bulgaria', 'bg'], ['Canada', 'ca'], ['China', 'cn'], ['Czech Republic', 'cz'], ['Denmark', 'dk'], ['Finland', 'fi'], ['France', 'fr'], ['Germany', 'de'], ['Hungary', 'hu'], ['India', 'in'], ['Italy', 'it'], ['Japan', 'ja'], ['Netherlands', 'nl'], ['Norway', 'no'], ['Portugal', 'pt'], ['Romania', 'ro'], ['Russia', 'ru'], ['Spain', 'es'], ['Swiss', 'ch'], ['Turkey', 'tr'], ['USA', 'us']]; var suggestions = []; for (i = 0; i < choices.length; i++) if (~(choices[i][0] + ' ' + choices[i][1]).toLowerCase().indexOf(term)) suggestions.push(choices[i]); suggest(suggestions); }, renderItem: function (item, search) { search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&amp;'); var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); return '<div class="autocomplete-suggestion" data-langname="' + item[0] + '" data-lang="' + item[1] + '" data-val="' + search + '"><img src="img/' + item[1] + '.png"> ' + item[0].replace(re, "<b>$1</b>") + '</div>'; }, onSelect: function (e, term, item) { console.log('Item "' + item.getAttribute('data-langname') + ' (' + item.getAttribute('data-lang') + ')" selected by ' + (e.type == 'keydown' ? 'pressing enter' : 'mouse click') + '.'); document.getElementById('advanced-demo').value = item.getAttribute('data-langname') + ' (' + item.getAttribute('data-lang') + ')'; } }); <file_sep>import { Component, OnInit } from '@angular/core'; import { MiddlewareService } from '../../services/middleware.service'; import { ActivatedRoute, Router } from '@angular/router'; import { ReviewService } from '../../services/review.service'; import { AuthService } from '../../services/auth.service'; import { CompanyService } from '../../services/company.service'; import { UserService } from '../../services/user.service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-add-review', templateUrl: './add-review.component.html', styleUrls: ['./add-review.component.css'] }) export class AddReviewComponent implements OnInit { formValues: any; results: any; companyVerified: Boolean; userSelectedUrl: String; currentCompanyId: String; currentCompanyName: String; currentUser: String; updateStatus: Object = { active: null, message: null, css: null }; isCompany: any; constructor( private route: ActivatedRoute, private router: Router, private middleWareService: MiddlewareService, private reviewService: ReviewService, private authService: AuthService, private companyService: CompanyService, private userService: UserService ) { } messageReturn(message, status) { this.updateStatus["message"] = message; this.updateStatus["active"] = status; } reviewData = new FormGroup({ 'companyId': new FormControl(this.currentCompanyId), 'userId': new FormControl(this.currentUser), 'reviewText': new FormControl('', [Validators.minLength(12), Validators.maxLength(455)]), 'reviewTitle': new FormControl('', [Validators.minLength(12), Validators.maxLength(455)]), 'rating': new FormControl('', [Validators.required]) }); selectedRating(rating: number): void { this.reviewData.controls['rating'].setValue(rating); } addReview() { this.formValues = this.reviewData.value; if (this.companyVerified == true && this.currentUser != 'not-loggedin') { if (this.isCompany == 0) { this.messageReturn("A company can't add a review", false); } else { console.log(this.formValues); this.reviewService.addReview(this.formValues) .subscribe(response => { let result = response.json(); if (result.message == "success") { this.messageReturn("Review added successfully", true); setTimeout(() => this.router.navigate(['u/dashboard']), 1500 ); let companyReviewData = { companyId: this.currentCompanyId, reviewId: result.review._id } this.companyService.assignReview(companyReviewData) .subscribe(companyReviewResponse => { companyReviewResponse = companyReviewResponse.json(); }); let userReviewData = { userId: this.currentUser, reviewId: result.review._id } this.userService.assignReview(userReviewData) .subscribe(companyReviewResponse => { companyReviewResponse = companyReviewResponse.json(); }); } else { this.messageReturn("Please enter the fields", false); } }, error => { this.messageReturn("Server Error", false); console.log(error); }); } } else { this.messageReturn("Please log in first to post a review, redirecting...", false); setTimeout(() => this.router.navigate(['u/login']), 2000 ); } } verifyCompany() { this.route.paramMap .subscribe(paramas => { var companyUrl = paramas['params'].webUrl; if (this.userSelectedUrl == companyUrl) { this.reviewData.controls['companyId'].setValue(this.middleWareService.currentUrlId); this.companyVerified = true; } else { this.companyService.getCompanyByUrl(companyUrl) .subscribe( data => { this.results = data.json(); if (this.results.length == 0) { this.router.navigate(['company-not-found']); } else { this.currentCompanyName = this.results['0'].companyName; this.currentCompanyId = this.results['0']._id; this.reviewData.controls['companyId'].setValue(this.currentCompanyId); this.companyVerified = true; } } ); } }); } ngOnInit() { this.userSelectedUrl = this.middleWareService.reviewUrl; this.currentCompanyId = this.middleWareService.currentUrlId; this.currentCompanyName = this.middleWareService.currentCompanyName; if (this.authService.isLoggedIn() == false) { this.currentUser = 'not-loggedin'; } else { this.currentUser = this.authService.currentUser['_id']; this.reviewData.controls['userId'].setValue(this.currentUser); this.isCompany = this.authService.currentCompany.activePlan; } this.verifyCompany(); } } <file_sep>import { Injectable } from '@angular/core'; @Injectable() export class ApiUrlService { url: any = 'http://172.16.31.10'; port: Number = 3200; constructor() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from '../../services/auth.service'; import { CompanyService } from '../../services/company.service'; @Component({ selector: 'app-company-dashboard', templateUrl: './company-dashboard.component.html', styleUrls: ['./company-dashboard.component.css'] }) export class CompanyDashboardComponent implements OnInit { company: any; results: Object[]; constructor( private authService: AuthService, private companyService: CompanyService ) { } companyDetails(){ this.company = this.authService.currentCompany._id; this.companyService.getCompany(this.company) .subscribe( data => { this.results = data.json(); } ); } ngOnInit() { this.companyDetails(); } } <file_sep>import { Injectable } from '@angular/core'; @Injectable() export class MiddlewareService { reviewUrl: String; currentUrlId: String; currentCompanyName: String; constructor() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { Router } from "@angular/router"; import { AuthService } from '../../services/auth.service'; @Component({ selector: 'app-company-login', templateUrl: './company-login.component.html', styleUrls: ['./company-login.component.css'] }) export class CompanyLoginComponent implements OnInit { invalidLogin: boolean; company: any; unexpectedError: boolean = false; loginSuccess: boolean = false; loginForm = new FormGroup({ email: new FormControl('', [Validators.required, Validators.email, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]), password: new FormControl('', [Validators.required]) }); get email() { return this.loginForm.get('email'); } get password() { return this.loginForm.get('password'); } constructor( private router: Router, private authService: AuthService ) { } onFormSubmit() { if (this.loginForm.valid) { this.company = this.loginForm.value; this.authService.companyLogin(this.company) .subscribe(result => { if ((result.message == "success") && (result.token)) { localStorage.setItem('token', result.token) this.loginSuccess = true; setTimeout(() => this.router.navigate(['c/dashboard']), 2000 ); } else if (result.message == "Unauthorized Access") { this.invalidLogin = true; } else { this.invalidLogin = true; console.log(result); } }, error=>{ this.unexpectedError = true; }); } else { this.company = this.loginForm.value; } } ngOnInit() { if (this.authService.isLoggedIn()) { this.router.navigate(['c/dashboard']); } } } <file_sep>import { Injectable } from '@angular/core'; import { JwtHelper, tokenNotExpired } from 'angular2-jwt'; import { Http } from '@angular/http'; import { Router } from "@angular/router"; import { ApiUrlService } from '../config/api-url.service'; @Injectable() export class CompanyService { url = this.apiUrl.url; port = this.apiUrl.port; serverUrl = this.url+':'+this.port; constructor( private http: Http, private router: Router, private apiUrl: ApiUrlService ) { } getCompany(company){ return this.http.get(this.serverUrl+'/api/company/'+company); } getCompanyByUrl(webUrl){ return this.http.get(this.serverUrl+'/api/company/url/'+webUrl); } updateCompany(company){ return this.http.post(this.serverUrl+'/api/company/profile/update', company); } updateProfileImage(imageData){ return this.http.post(this.serverUrl+'/api/company/profile/image/update', imageData); } assignReview(reviewId){ return this.http.post(this.serverUrl+'/api/company/profile/review/add', reviewId); } getAllCompany(){ return this.http.get(this.serverUrl+'/api/company/all'); } } <file_sep>import { Injectable } from '@angular/core'; import { JwtHelper, tokenNotExpired } from 'angular2-jwt'; import { Http } from '@angular/http'; import { Router } from "@angular/router"; import 'rxjs/add/operator/map'; import { ApiUrlService } from '../config/api-url.service'; @Injectable() export class AuthService { url = this.apiUrl.url; port = this.apiUrl.port; serverUrl = this.url+':'+this.port; constructor( private http: Http, private router: Router, private apiUrl: ApiUrlService ) { } userRegister(user){ return this.http.post(this.serverUrl+'/api/user/register', user) .map(response => response.json()); } userLogin(user){ return this.http.post(this.serverUrl+'/api/user/login', user) .map(response => response.json()); } companyRegister(company){ return this.http.post(this.serverUrl+'/api/company/register', company) .map(response => response.json()); } companyLogin(company){ this.url = this.apiUrl.url; this.port = this.apiUrl.port; return this.http.post(this.serverUrl+'/api/company/login', company) .map(response => response.json()); } logout(){ localStorage.removeItem('token'); this.router.navigate(['']); } isLoggedIn(){ return tokenNotExpired(); } get currentUser(){ let token = localStorage.getItem('token'); if(!token) return null; let jwtHelper = new JwtHelper(); return jwtHelper.decodeToken(token); } get currentCompany(){ let token = localStorage.getItem('token'); if(!token) return null; let jwtHelper = new JwtHelper(); return jwtHelper.decodeToken(token); } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchPipe' }) export class SearchFilterPipe implements PipeTransform { transform(value: any[], searchText: string): any { if(!searchText) {return value;} let solution = value.filter(v=>{ if(!v){return;} return v.toString().toLowerCase().indexOf(searchText.toLowerCase())!==-1; }) return solution; // if (searchText) { // searchText = searchText.toLowerCase(); // return value.filter(function (el: any) { // return el.toString().toLowerCase().indexOf(searchText) > -1; // }) // } // return value; } } <file_sep>import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import { ApiUrlService } from '../../config/api-url.service'; @Injectable() export class CompanyService { url = this.apiUrl.url; port = this.apiUrl.port; serverUrl = this.url+':'+this.port; constructor( private http: Http, private apiUrl: ApiUrlService ) { } search(queryString: string){ return this.http.get(this.serverUrl+'/api/company/search'+queryString); } } <file_sep>import { Injectable } from '@angular/core'; import { JwtHelper, tokenNotExpired } from 'angular2-jwt'; import { Http } from '@angular/http'; import { Router } from "@angular/router"; import { ApiUrlService } from '../config/api-url.service'; @Injectable() export class UserService { url = this.apiUrl.url; port = this.apiUrl.port; serverUrl = this.url+':'+this.port; constructor( private http: Http, private router: Router, private apiUrl: ApiUrlService ) { } getUser(user){ return this.http.get(this.serverUrl+'/api/user/'+user); } updateUser(user){ return this.http.post(this.serverUrl+'/api/user/profile/update', user) .map(response => response.json() ); } updateProfileImage(imageData){ return this.http.post(this.serverUrl+'/api/user/profile/image/update', imageData) .map(response => response.json() ); } assignReview(reviewId){ return this.http.post(this.serverUrl+'/api/user/profile/review/add', reviewId); } userReviewCount(assignedUser){ return this.http.get(this.serverUrl+'/api/review/all', assignedUser); } userAllReview(){ // this.user = this.authService.currentUser._id; // this.count=(this.user).length; return this.http.get(this.serverUrl+'/api/review/all'); } }
2bb99b74299b6c45bb0164e1c46ce967deeade92
[ "JavaScript", "TypeScript" ]
22
TypeScript
Gaurav2214/Angular4-Review-App
e2cb4ab6c953d675c3fae19f4b6a37c23bea01af
70425f9529b136987b4d44bd2c577ee8bde12002
refs/heads/master
<file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package colorextractor.utils; import java.awt.Font; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.Enumeration; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; public class TweakUI { private static Point initialClick; public static void centerParent(JDialog parent) { parent.setLocationRelativeTo(null); } public static void centerParent(JFrame parent) { parent.setLocationRelativeTo(null); } public static void onMouseDragged(JFrame parent, MouseEvent evt) { // get location of Window int thisX = parent.getLocation().x; int thisY = parent.getLocation().y; // Determine how much the mouse moved since the initial click int xMoved = (thisX + evt.getX()) - (thisX + initialClick.x); int yMoved = (thisY + evt.getY()) - (thisY + initialClick.y); // Move window to this position int X = thisX + xMoved; int Y = thisY + yMoved; parent.setLocation(X, Y); } public static void onMousePressed(JFrame parent, MouseEvent evt) { initialClick = evt.getPoint(); parent.getComponentAt(initialClick); } public static void onMouseDragged(JDialog parent, MouseEvent evt) { // get location of Window int thisX = parent.getLocation().x; int thisY = parent.getLocation().y; // Determine how much the mouse moved since the initial click int xMoved = (thisX + evt.getX()) - (thisX + initialClick.x); int yMoved = (thisY + evt.getY()) - (thisY + initialClick.y); // Move window to this position int X = thisX + xMoved; int Y = thisY + yMoved; parent.setLocation(X, Y); } public static void onMousePressed(JDialog parent, MouseEvent evt) { initialClick = evt.getPoint(); parent.getComponentAt(initialClick); } public static void onMouseDragged(JPanel parent, MouseEvent evt) { // get location of Window int thisX = parent.getLocation().x; int thisY = parent.getLocation().y; // Determine how much the mouse moved since the initial click int xMoved = (thisX + evt.getX()) - (thisX + initialClick.x); int yMoved = (thisY + evt.getY()) - (thisY + initialClick.y); // Move window to this position int X = thisX + xMoved; int Y = thisY + yMoved; parent.setLocation(X, Y); } public static void onMousePressed(JPanel parent, MouseEvent evt) { initialClick = evt.getPoint(); parent.getComponentAt(initialClick); } /** * Sets the whole UI to use a custom font * * @param f Font resource to use on the UI */ public static void setUIFont(javax.swing.plaf.FontUIResource f) { java.util.Enumeration keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = UIManager.get(key); if (value != null && value instanceof javax.swing.plaf.FontUIResource) { UIManager.put(key, f); } } } public static void setGlobalFont(Font font) { Enumeration enume = UIManager.getDefaults().keys(); while (enume.hasMoreElements()) { Object key = enume.nextElement(); Object value = UIManager.get(key); if (value instanceof Font) { UIManager.put(key, font); } } } } <file_sep>IMAGE COLOR EXTRACTOR. -------RUN INSTRUCTIONS------ Requires a minimum of Java RTE 1.2 installed on the clien machine. Just double on the .jar file to launch the application. Email <EMAIL> for sources S.Karanja (c)2015 <file_sep># ImageColorExtractor A Java SE application that extracts per pixel based RGB and Hex color values from an image, by hoving the mouse cursor over the desired region of an image. Below is a typical screen of the application running, on Windows 7. The L&F may differ depending on how your OS renders the UI components. </p> <p> <img src="https://www.dropbox.com/s/wd4wku6j0kp407w/color_extractor_shot_1.png?raw=1"> </p> # How to use the application (.jar) / (Running the binaries) <p> A JRE 1.6 or later is required to run the application. Download the zip and unzip dist folder to a convinient folder. Ensure tha the following directories are present in the dist folder : .jar:- If everyting is okay double clicking on the .jar file will launch the application. Enjoy </p> # Setting up the project in Netbeans/Eclipse or any other IDE / (Compiling the sources) Clone the sources to a convinient directory & simply point netbeans project browser to that location. Enjoy <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. */ package colorextractor.ui; import colorextractor.utils.TweakUI; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.FontFormatException; import java.awt.Graphics; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.border.LineBorder; /** * * @author RESEARCH2 */ public class JFrameMainUI extends javax.swing.JFrame { private BufferedImage image; private final MyImagePanel canvas; private final JScrollPane jscp; private final JPopupMenu appMenu; private final JPanelMenu jpm; /** * Creates new form JFrameMainUI * * @throws java.io.IOException * @throws java.awt.FontFormatException */ public JFrameMainUI() throws IOException, FontFormatException { Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("/colorextractor/fonts/OpenSans-Light.ttf")).deriveFont(Font.PLAIN, 11); TweakUI.setGlobalFont(font); initComponents(); TweakUI.centerParent(this); jPanelWrapper.setLayout(new BorderLayout()); jscp = new JScrollPane(); canvas = new MyImagePanel(); jscp.setViewportView(canvas); jscp.setPreferredSize(new Dimension(700, 500)); jPanelWrapper.add(jscp); appMenu = new JPopupMenu(); appMenu.setBorder(new LineBorder(jButtonAppAbout.getBackground())); jpm = new JPanelMenu(); this.setSize(700, 600); } public void setImage(BufferedImage bi) { image = bi; } public void setCanvasSize(int x, int y) { jscp.setPreferredSize(new Dimension(x, y)); jPanelWrapper.setPreferredSize(new Dimension(x, y)); canvas.setPreferredSize(new Dimension(x, y)); this.repaint(); this.revalidate(); } public void setImageUploadPath(String path) { jTextFieldImagePath.setText(path); } public void addBtnUploadActionListener(ActionListener al) { jButtonUpload.addActionListener(al); } public void setLocX(int x) { jTextFieldLocX.setText(String.valueOf(x)); } public void setLocY(int y) { jTextFieldLocY.setText(String.valueOf(y)); } public void setR(int r) { jTextFieldR.setText(String.valueOf(r)); } public void setG(int g) { jTextFieldG.setText(String.valueOf(g)); } public void setB(int b) { jTextFieldB.setText(String.valueOf(b)); } public void setHex(String hex) { jTextFieldHex.setText(hex); } public MyImagePanel getCanvas() { return canvas; } public void addCanvasMouseListener(MouseListener ml) { canvas.addMouseListener(ml); } public void addCanvasMouseMotionListener(MouseMotionListener mml) { canvas.addMouseMotionListener(mml); } /** * Add mouse listener to app menu button * * @param ml */ public void addAppMenuBtnMouseListener(MouseListener ml) { jButtonAppAbout.addMouseListener(ml); } /** * Add mouse listener to popup menu * * @param ml */ public void addJPoupMouseListener(MouseListener ml) { appMenu.addMouseListener(ml); } public JPopupMenu getAppMenu() { return appMenu; } /** * Get the Menu panel * * @return */ public JPanelMenu getMenuPanel() { return jpm; } // This method does it all! public void showPopup(MouseEvent ae) { // Create a JPopupMenu // Add JMenuItems to JPopupMenu appMenu.add(jpm); // Get the event source Component b = (Component) ae.getSource(); // Get the location of the point 'on the screen' Point p = b.getLocationOnScreen(); // Show the JPopupMenu via program // Parameter desc // ---------------- // this - represents current frame // 0,0 is the co ordinate where the popup // is shown appMenu.show(this, 0, 0); // Now set the location of the JPopupMenu // This location is relative to the screen appMenu.setLocation(p.x + b.getWidth() - jpm.getWidth() - 2, p.y - jpm.getHeight()); } public BufferedImage getImage() { return image; } public JPanel getjPanelWrapper() { return jPanelWrapper; } public void setPreviewColor(int r, int g, int b) { jPanelColorPreview.setBackground(new Color(r, g, b)); } class MyImagePanel extends JPanel { MyImagePanel() throws IOException { image = ImageIO.read(getClass().getResource("/colorextractor/resources/demo.PNG"));//new File("demo.png")); int w = image.getWidth(); int h = image.getHeight(); setPreferredSize(new Dimension(w, h)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (image != null) { g.drawImage(image, 0, 0, this); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanelWrapper = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jSeparator1 = new javax.swing.JSeparator(); jPanel6 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jTextFieldHex = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jTextFieldG = new javax.swing.JTextField(); jTextFieldR = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextFieldB = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jTextFieldLocY = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jTextFieldLocX = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jPanelColorPreview = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); jLabel8 = new javax.swing.JLabel(); jButtonAppAbout = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jTextFieldImagePath = new javax.swing.JTextField(); jButtonUpload = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jSeparator3 = new javax.swing.JSeparator(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout jPanelWrapperLayout = new javax.swing.GroupLayout(jPanelWrapper); jPanelWrapper.setLayout(jPanelWrapperLayout); jPanelWrapperLayout.setHorizontalGroup( jPanelWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 623, Short.MAX_VALUE) ); jPanelWrapperLayout.setVerticalGroup( jPanelWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 136, Short.MAX_VALUE) ); getContentPane().add(jPanelWrapper, java.awt.BorderLayout.CENTER); jLabel6.setText("HEX"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldHex, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(42, 42, 42) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jTextFieldHex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel3.setText("B"); jLabel2.setText("G"); jLabel1.setText("R"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldB, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldG, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldR, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextFieldG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextFieldB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTextFieldLocY.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldLocYActionPerformed(evt); } }); jLabel4.setText("Color Pixel X"); jLabel5.setText("Color Pixel Y"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldLocX, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldLocY, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextFieldLocX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextFieldLocY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanelColorPreviewLayout = new javax.swing.GroupLayout(jPanelColorPreview); jPanelColorPreview.setLayout(jPanelColorPreviewLayout); jPanelColorPreviewLayout.setHorizontalGroup( jPanelColorPreviewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jPanelColorPreviewLayout.setVerticalGroup( jPanelColorPreviewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(0, 0, 0) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelColorPreview, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanelColorPreview, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jLabel7.setText("EXTRACTION SUMMARY"); jLabel8.setText("COLOR PREVIEW"); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jPanel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel8)) .addGap(7, 7, 7) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 1, Short.MAX_VALUE) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(1, 1, 1)) ); jButtonAppAbout.setBackground(new java.awt.Color(255, 153, 0)); jButtonAppAbout.setText("About"); jButtonAppAbout.setBorderPainted(false); jButtonAppAbout.setContentAreaFilled(false); jButtonAppAbout.setFocusPainted(false); jButtonAppAbout.setOpaque(true); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(62, Short.MAX_VALUE) .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE) .addComponent(jButtonAppAbout)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(51, 51, 51) .addComponent(jButtonAppAbout, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, 0)) ); getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END); jTextFieldImagePath.setEditable(false); jButtonUpload.setText("Upload Image"); jLabel9.setText("UPLOAD IMAGE TO EXTRACT"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jTextFieldImagePath, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE) .addGap(39, 39, 39) .addComponent(jButtonUpload)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jSeparator3)) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 1, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldImagePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonUpload)) .addContainerGap()) ); getContentPane().add(jPanel5, java.awt.BorderLayout.PAGE_START); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextFieldLocYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldLocYActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldLocYActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAppAbout; private javax.swing.JButton jButtonUpload; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanelColorPreview; private javax.swing.JPanel jPanelWrapper; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JTextField jTextFieldB; private javax.swing.JTextField jTextFieldG; private javax.swing.JTextField jTextFieldHex; private javax.swing.JTextField jTextFieldImagePath; private javax.swing.JTextField jTextFieldLocX; private javax.swing.JTextField jTextFieldLocY; private javax.swing.JTextField jTextFieldR; // End of variables declaration//GEN-END:variables }
f7801a9c65a9ad0b9900cab5d5f24d04cbfa9a2c
[ "Markdown", "Java", "Text" ]
4
Java
5oldman/ImageColorExtractor
fd1864419348232e3cd373fe26bf29a711c9da9a
7d463126ec9e4defc8b357df4cb1f4c475185a3f
refs/heads/master
<repo_name>AilinShen/wbdv-sp21-recipe-planner-server-java<file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/services/RecipeIngredientService.java package com.example.wbdvsp21recipeplannerserverjava.services; import com.example.wbdvsp21recipeplannerserverjava.models.Recipe; import com.example.wbdvsp21recipeplannerserverjava.models.RecipeIngredient; import com.example.wbdvsp21recipeplannerserverjava.repositories.RecipeIngredientRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.NoSuchElementException; @Service public class RecipeIngredientService { @Autowired RecipeIngredientRepository repository; @Autowired RecipeService recipeService; public List<RecipeIngredient> findAllRecipeIngredients(){ return (List<RecipeIngredient>) repository.findAll(); } public void deleteRecipeIngredientById(Integer id){ repository.deleteById(id); } public Integer updateRecipeIngredient(Integer id, RecipeIngredient newRecipeIngredient){ if(repository.existsById(id)){ newRecipeIngredient.setId(id); repository.save(newRecipeIngredient); return 1; }else { return -1; } } public RecipeIngredient createRecipeIngredient(String recipeId, RecipeIngredient r){ try { r.setRecipeId(recipeId); return repository.save(r); }catch (NoSuchElementException e){ return null; } } public RecipeIngredient findRecipeIngredientById(Integer id){ try { return repository.findById(id).get(); }catch (NoSuchElementException e){ return null; } } public List<RecipeIngredient> findIngredientsForRecipe(String id){ return repository.findIngredientsForRecipe(id); } } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/controllers/UserControllers.java package com.example.wbdvsp21recipeplannerserverjava.controllers; import com.example.wbdvsp21recipeplannerserverjava.models.Recipe; import com.example.wbdvsp21recipeplannerserverjava.models.User; import com.example.wbdvsp21recipeplannerserverjava.security.ApiResponse; import com.example.wbdvsp21recipeplannerserverjava.services.ApplicationUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @CrossOrigin(origins = "http://localhost:3000") public class UserControllers { @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired ApplicationUserService userService; @GetMapping("/api/users") public List<User> findAllUsers(){ List<User> users = userService.findAllUsers(); ArrayList<User> results = new ArrayList<>(); for(User user: users){ results.add(new User(user.getId(), user.getEmail(), user.getName(), user.getRole())); } return results; } @GetMapping("/api/users/{uid}") public User findUserById( @PathVariable("uid") Integer id){ User user = userService.findUserById(id); return new User(user.getId(), user.getEmail(), user.getName(), user.getRole()); } @GetMapping("/shopper") public String shopper() { return "SHOPPER: Successfully logged in"; } @GetMapping("/creator") public String creator() { return "CREATOR: Successfully logged in"; } // { // "username": "shopper", // "password": "<PASSWORD>", // "role": "SHOPPER" //} @PostMapping(value = "/register") public ApiResponse processRegister(@RequestBody User requestUser) { if (userService.findIdByEmail(requestUser.getEmail()) == null){ String encodedPassword = bCryptPasswordEncoder.encode(requestUser.getPassword()); User user = new User(requestUser.getEmail(), requestUser.getName(), encodedPassword, requestUser.getRole()); User saveUser = userService.createUser(user); return new ApiResponse(200, "Success"); } return new ApiResponse(403, "Email already exists"); } @PutMapping("/api/users/{uid}") public User updateUser( @PathVariable("uid") Integer id, @RequestBody User newUser ){ if(newUser.getPassword() != null) { String encodedPassword = bCryptPasswordEncoder.encode(newUser.getPassword()); newUser.setPassword(encodedPassword); } else { User origin = userService.findUserById(id); newUser.setPassword(origin.getPassword()); System.out.println(newUser.getPassword()); } User user = userService.updateUser(id, newUser); return new User(user.getId(), user.getEmail(), user.getName(), user.getRole()); } @DeleteMapping("/api/users/{uid}") public void deleteUser( @PathVariable("uid") Integer id ){ userService.deleteUserById(id); } } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/models/Cart.java package com.example.wbdvsp21recipeplannerserverjava.models; import javax.persistence.*; @Entity @Table(name="carts") public class Cart { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer Id; private Integer userId; private String recipeId; public Cart(){ } public Cart(Integer userId, String recipeId) { this.userId = userId; this.recipeId = recipeId; } public Integer getId() { return Id; } public void setId(Integer id) { this.Id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getRecipeId() { return recipeId; } public void setRecipeId(String recipeId) { this.recipeId = recipeId; } } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/repositories/UserRepository.java package com.example.wbdvsp21recipeplannerserverjava.repositories; import com.example.wbdvsp21recipeplannerserverjava.models.User; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface UserRepository extends CrudRepository<User, Integer> { @Query(value="SELECT * FROM users WHERE email=:e", nativeQuery = true) public List<User> findUserByEmail(String e); @Query(value="SELECT id FROM users WHERE email=:e", nativeQuery = true) public Integer findIdByEmail(String e); @Query(value="SELECT name FROM users WHERE email=:e", nativeQuery = true) public String findNameByEmail(String e); @Query(value="SELECT * FROM users WHERE id=:i", nativeQuery = true) public User findUserById(Integer i); } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/services/CartService.java package com.example.wbdvsp21recipeplannerserverjava.services; import com.example.wbdvsp21recipeplannerserverjava.models.Cart; import com.example.wbdvsp21recipeplannerserverjava.repositories.CartRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CartService { @Autowired CartRepository cartRepository; public Cart createCartItemForUser(Cart cart){ return cartRepository.save(cart); } public List<Cart> findCartForUser(Integer userId){ return cartRepository.findCartForUser(userId); } public Integer deleteCartItem(Integer cartId){ cartRepository.deleteById(cartId); return 1; } } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/models/RecipeIngredient.java package com.example.wbdvsp21recipeplannerserverjava.models; import javax.persistence.*; @Entity @Table(name="recipe_ingredients") public class RecipeIngredient { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private Integer amount; private String unit; private String recipeId; // { // "recipeId": "rep_123", // "name": "cocoa", // "amount": "1", // "unit": "cup" // } public RecipeIngredient() { } public RecipeIngredient(String name, Integer amount, String unit, String recipeId) { this.name = name; this.amount = amount; this.unit = unit; this.recipeId = recipeId; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRecipeId() { return recipeId; } public void setRecipeId(String recipeId) { this.recipeId = recipeId; } public String toString(){ return "{\"id\": \"" + this.id + "\", \"recipeId\": \"" + this.recipeId + "\", \"name\": \"" + this.name + "\", \"amount\": \"" + this.amount + "\", \"unit\": \"" + this.unit + "\" }"; } } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/repositories/RecipeIngredientRepository.java package com.example.wbdvsp21recipeplannerserverjava.repositories; import com.example.wbdvsp21recipeplannerserverjava.models.RecipeIngredient; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.List; public interface RecipeIngredientRepository extends CrudRepository<RecipeIngredient, Integer> { @Query(value="SELECT * FROM recipe_ingredients WHERE recipe_id=:rid", nativeQuery = true) public List<RecipeIngredient> findIngredientsForRecipe(@Param("rid") String recipeId); } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/services/RecipeService.java package com.example.wbdvsp21recipeplannerserverjava.services; import com.example.wbdvsp21recipeplannerserverjava.models.Recipe; import com.example.wbdvsp21recipeplannerserverjava.models.RecipeIngredient; import com.example.wbdvsp21recipeplannerserverjava.repositories.RecipeIngredientRepository; import com.example.wbdvsp21recipeplannerserverjava.repositories.RecipeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; @Service public class RecipeService { @Autowired RecipeRepository repository; @Autowired RecipeIngredientService ingredientService; public Recipe createRecipe(Recipe recipe){ List<RecipeIngredient> ingredientList = new ArrayList<RecipeIngredient>(); for(RecipeIngredient r: recipe.getExtendedIngredients()){ RecipeIngredient ingredient = ingredientService.createRecipeIngredient(recipe.getId(),r); ingredientList.add(ingredient); } recipe.setExtendedIngredients(ingredientList); return repository.save(recipe); } public List<Recipe> findAllRecipes(){ return (List<Recipe>) repository.findAll(); } public void deleteRecipeById(String id) { repository.deleteById(id); } public Integer updateRecipe(String recipeId, Recipe newRecipe){ if (repository.existsById(recipeId)){ newRecipe.setId(recipeId); for(RecipeIngredient r: newRecipe.getExtendedIngredients()){ if (r.getId()!=null){ ingredientService.updateRecipeIngredient(r.getId(), r); }else { ingredientService.createRecipeIngredient(recipeId, r); } } repository.save(newRecipe); return 1; }else { return -1; } } public Recipe findRecipeById(String id){ try { return repository.findById(id).get(); }catch (NoSuchElementException e){ return null; } } public List<Recipe> findRecipeById(List<String> ids){ ArrayList<Recipe> recipes = new ArrayList<>(); for (String id: ids) { recipes.add(findRecipeById(id)); } return recipes; } public List<Recipe> findRecipesForUser(Integer userId){ return repository.findRecipeForUser(userId); } } <file_sep>/README.md # wbdv-sp21-recipe-planner-server-java ## [Heroku App](https://wbdv-recipe-planner-server.herokuapp.com/) <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/WbdvSp21RecipePlannerServerJavaApplication.java package com.example.wbdvsp21recipeplannerserverjava; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.UUID; @SpringBootApplication public class WbdvSp21RecipePlannerServerJavaApplication { public static void main(String[] args) { SpringApplication.run(WbdvSp21RecipePlannerServerJavaApplication.class, args); } } <file_sep>/src/main/java/com/example/wbdvsp21recipeplannerserverjava/repositories/CartRepository.java package com.example.wbdvsp21recipeplannerserverjava.repositories; import com.example.wbdvsp21recipeplannerserverjava.models.Cart; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.List; public interface CartRepository extends CrudRepository<Cart, Integer>{ @Query(value="SELECT * FROM carts WHERE user_id=:uid", nativeQuery = true) List<Cart> findCartForUser(@Param("uid") Integer userId); }
2fffe4936e4aec16a0bcddd7004fc974bc61c764
[ "Markdown", "Java" ]
11
Java
AilinShen/wbdv-sp21-recipe-planner-server-java
20e29373c492524721bfc9a6011c84ab83c5b5a4
5e7399bacf44d0175f994821b0842ae9a7ba8a91
refs/heads/master
<file_sep>;(function(){ function $(id){ return document.getElementById(id); } var size = $('size'), bgColor = $('bgColor'), fgColor = $('fgColor'), direction = $('direction'), btn = document.getElementsByClassName('btn'), showTri = $('showTri'), codeAreaH = $('codeAreaH'), codeAreaC = $('codeAreaC'), ch1 = '<i class="bor-c"></i>', ch2 = '<i class="bor-c"><span class="bor-i"></span></i>', borC = $('borC'), borI = $('borI'), tip = $('tip'), triCommonCss = 'width:0; height:0; font-size:0; display:inline-block; position:absolute;', bgCSS = '', fgCSS = '', sizeVal = 10, bgColorVal = '#000', fgColorVal = '#000', directionVal = 'up', isBorder = false, colorReg = /^#([0-9a-fA-F]{3}){1,2}$/, updateCss = function(){ isBorder = bgColor.value; triWidth = 'border-width:' + sizeVal + 'px;'; if(directionVal === 'up'){ bgCSS = 'border-color:transparent transparent ' + bgColorVal + ' transparent; border-style: dashed dashed solid dashed; left: 0px; top: 0px;'; fgCSS = 'border-color:transparent transparent ' + fgColorVal + ' transparent; border-style: dashed dashed solid dashed; left: ' + -sizeVal + 'px; top: ' + (-sizeVal+1) + 'px;'; }else if(directionVal === 'down'){ bgCSS = 'border-color:' + bgColorVal + ' transparent transparent transparent; border-style:solid dashed dashed dashed; left: 0px; top: 0px;'; fgCSS = 'border-color:' + fgColorVal + ' transparent transparent transparent; border-style:solid dashed dashed dashed; left: ' + -sizeVal + 'px; top: ' + (-sizeVal-1) + 'px;'; }else if(directionVal === 'left'){ bgCSS = 'border-color: transparent ' + bgColorVal + ' transparent transparent; border-style: dashed solid dashed dashed; left: 0px; top: 0px;'; fgCSS = 'border-color: transparent ' + fgColorVal + ' transparent transparent; border-style: dashed solid dashed dashed; left: ' + (-sizeVal+1) + 'px; top: ' + -sizeVal + 'px;'; }else{ bgCSS = 'border-color:transparent transparent transparent ' + bgColorVal + '; border-style: dashed dashed dashed solid; left: 0px; top: 0px;'; fgCSS = 'border-color:transparent transparent transparent ' + fgColorVal + '; border-style: dashed dashed dashed solid; left: ' + (-sizeVal-1) + 'px; top: ' + -sizeVal + 'px;'; } }; direction.onchange = function(){ reset(); directionVal = this.value; create(); } size.onchange = function(){ reset(); if(!checkSize() ) return; create(); } bgColor.onchange = function(){ reset(); bgColorVal = bgColor.value; bgColorVal = bgColorVal ? '#' + bgColorVal : '#000'; if(!checkColor(bgColorVal)) return; create(); } fgColor.onchange = function(){ reset(); fgColorVal = fgColor.value; if(fgColorVal == ''){ tip.innerHTML = '骚年,三角不能没有颜色哦!'; return; } fgColorVal = '#' + fgColorVal; if(!checkColor(fgColorVal)) return; create(); } function checkSize(){ sizeVal = +size.value; if(isNaN(sizeVal)){ tip.innerHTML = '骚年,大小只能是数字哦!'; return false; } if(sizeVal > 100 && sizeVal <= 200){ tip.innerHTML = '嘿哟,骚年,这个三角有够大的哦!'; }else if(sizeVal > 200 && sizeVal <= 250){ tip.innerHTML = '可以了孩子,三角够大了!'; }if(sizeVal > 250){ showTri.style.cssText = ''; tip.innerHTML = '设这么大?你是来捣乱的吧,信不信我抽你!'; return false; } return true; } function checkColor(val){ if(!colorReg.test(val)){ showTri.style.cssText = ''; tip.innerHTML = '骚年,颜色只能是0-9a-fA-F字符且只能是3位或者6位哦!'; return false; } return true; } for(var i = 0, len = btn.length; i < len; i++){ (function(i){ btn[i].onclick = function(){ this.nextSibling.select(); } })(i); } function reset(){ showTri.style.cssText = ''; borC.style.cssText = ''; borI.style.cssText = ''; tip.innerHTML = ''; codeAreaC.value = ''; } function create(){ updateCss(); if(isBorder){ codeAreaH.value = ch2; codeAreaC.value = '.bor-c{' + triCommonCss + bgCSS + triWidth + '}\n.bor-i{' + triCommonCss + fgCSS + triWidth + '}'; borC.style.cssText = triCommonCss + bgCSS + triWidth; borI.style.cssText = triCommonCss + fgCSS + triWidth; }else{ codeAreaH.value = ch1; fgCSS = fgCSS.replace(/left:(.*)px; top: (.*)px/, 'left: 0px; top: 0px;'); codeAreaC.value = '.bor-c{' + triCommonCss + fgCSS + triWidth + '}'; showTri.style.cssText = triCommonCss + fgCSS + triWidth + 'left: 0px; top: 0px'; } } create(); })();<file_sep>;(function(){ function $(id){ return document.getElementById(id); } var inputr = $('inputr'), inputg = $('inputg'), inputb = $('inputb'), inputsix = $('inputsix'), changer = $('changer'), changel = $('changel'), tip = $('tip'), rgb = $('rgb'), six = $('six'), sixReg = /^#([0-9a-fA-F]{3}){1,2}$/; changer.addEventListener('click', function(){ var vr = +inputr.value, vg = +inputg.value, vb = +inputb.value, result; if(!checkRGB(vr) || !checkRGB(vg) || !checkRGB(vb)) return; result = toColorSix(vr, vg, vb); inputsix.value = result; six.style.background = result; inputsix.select(); tip.innerHTML = ''; }); changel.addEventListener('click', function(){ var vsix = inputsix.value, result; if(!checkSix(vsix)) return; result = toColorRGB(vsix); inputr.value = result.r; inputg.value = result.g; inputb.value = result.b; rgb.style.background = vsix; inputr.select(); tip.innerHTML = ''; }); function toColorRGB(val){ var length = val.length, r, g, b; if(length === 7){ r = parseInt(val.slice(1, 3), 16); g = parseInt(val.slice(3, 5), 16); b = parseInt(val.slice(5, 7), 16); }else{ r = val.substr(1, 1); g = val.substr(2, 1); b = val.substr(3, 1); r = parseInt(r + r, 16); g = parseInt(g + g, 16); b = parseInt(b + b, 16); } return { r: r, g: g, b: b } } function toColorSix(vr, vg, vb){ var r, g, b; r = vr.toString(16); g = vg.toString(16); b = vb.toString(16); if(r.length === 1) r = '0' + r; if(g.length === 1) g = '0' + g; if(b.length === 1) b = '0' + b; return '#' + r + g + b; } function checkSix(val){ if(!sixReg.test(val)){ tip.innerHTML = '骚年,16进制只能是0-9a-fA-F字符且只能是3位或者6位哦!'; inputr.value = ''; inputg.value = ''; inputb.value = ''; return false; } return true; } function checkRGB(val){ if(val == ''){ tip.innerHTML = '骚年,RGB要填完整哦!'; inputsix.value = ''; return false; } if(isNaN(val)){ tip.innerHTML = '骚年,大小只能是数字哦!'; inputsix.value = ''; return false; } if(val < 0 || val > 255){ tip.innerHTML = '骚年,RGB值只能在0-255之间哦!'; inputsix.value = ''; return false; } return true; } })();
669fbda48934e91585715c87b9bfafa1f7a6e9ad
[ "JavaScript" ]
2
JavaScript
littledu/chrome-csstools
c8a063986abe4ad461e3598916e4fb21997b3bd1
d89b2d491284abe77e5a2f71456cdda670fd373d
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="utf-8"> <title>Oficina PHPWomen</title> </head> <body> <?php ini_set('display_errors', 1); /*$cor = "amarelo"; //nome de uma cor $cor = "vermelho"; //onutra variavel echo $cor; //chamar a cor var_dump(array(32,"julie")). "<br>"; var_dump("julie"). "<br>"; $a = "Olá"; $b = "mundo"; echo $a ." ". $b; $nome = "Julie"; echo "Olá " . $nome . "!"; $a = 3; $b = 5; $resultado = $a % $b; echo $resultado $a = 5; $b = 2; if ($a > $b) { echo "a é maior que b"; } else if ($a < $b) { echo " b é maior que a"; } else { echo "a e b são iguais"; } $a = 1; $b = "1"; if ($a == $b) { //verifica se valores são iguaiis independente do tipo string,integer. echo " a igual a b"; } else { " a diferente de b"; } $i = 1; while ($i < 10) { $i = $i + 1; echo $i. "<br>"; echo "o valor de $i é par<br>" // não precisa concatenar quando temos aspas duplo } $i = 1; while ($i < 10) { $i = $i + 1; if ($i % 2 == 0) { echo $i . " é número par". "<br>"; } else { echo $i . " é número ímpar". "<br>"; } } for($i = 1; $i < 10; $i++) { echo "O valor de i é $i<br>"; } for($i = 1; $i <=10; $i++) { if($i % 2 == 0) { echo $i . " é número par". "<br>"; } else { echo $i . " é número ímpar". "<br>"; } } $nome = "Julie"; switch ($nome) { case "Julie": echo "Bem vinda Julie!"; break; case "Julia": echo "Bem vinda Julia!"; break; default: echo "Bem vindo(a)!"; } function soma($a, $b) { $resultado = $a + $b; return $resultado; } $numero1 = 10.2; $numero2 = 6; $resultfuncao = soma($numero1, $numero2); echo $resultfuncao; $cores = array("vermelho", "azul"); // ou $cores = ["vermelho", "azul"]; echo $cores[1]; //contagem de arrays começa do 0 $pessoas = ["nome" => "Ana", "idade" => 23]; echo $pessoas["nome"] . " " . $pessoas["idade"]; $numeros = [1, 2, 3, 4]; array_push($numeros, 5); echo $numeros[4]; $frutas = array("banana", "laranja", "melancia"); foreach($frutas as $fruta) { echo "A fruta é $fruta<br>"; } echo "<br>adicionei abacaxi<br><br>"; array_push($frutas, "abacaxi"); foreach($frutas as $fruta) { echo "A fruta é $fruta<br>"; } echo "<br>retirei abacaxi<br><br>"; array_pop($frutas); foreach($frutas as $fruta) { echo "A fruta é $fruta<br>"; }*/ ?> </body> </html>
2f9c35428049d60cb0f7709d248b8e9cf57f7622
[ "PHP" ]
1
PHP
juliesarvasi/oficina_php_iniciante
a55d1b83a98263c752e5d2327fe95c76d39b3a0a
e7badc6d6bf3c928f1bd847ebc52e39dd219736f
refs/heads/master
<repo_name>Edelbauer/c--socket-server<file_sep>/ConsoleApplication2/ConsoleApplication2/Program.cs using System; using System.Collections.Generic; using System.Linq; using Fleck; using System.Diagnostics; using System.Threading; namespace ConsoleApplication2 { class Program { private static PerformanceCounter cpuCounter; static void Main(string[] args) { cpuCounter = new PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; var allSockets = new List<IWebSocketConnection>(); var server = new WebSocketServer("ws://0.0.0.0:8181"); server.Start(socket => { socket.OnOpen = () => { allSockets.Add(socket); }; socket.OnClose = () => { allSockets.Remove(socket); }; }); var input = Console.ReadLine(); while (input != "exit") { foreach (var socket in allSockets.ToList()) { socket.Send(cpuCounter.NextValue().ToString().Replace(',','.')); Thread.Sleep(50); } } } } }
a065de0238f069ea6ffc400499dbb9f763306b46
[ "C#" ]
1
C#
Edelbauer/c--socket-server
884e56e73a08094121f507b03831044e3f6c9ad6
12c142b362ad62d4b346f99a9ea9880cd65ff5e7
refs/heads/master
<file_sep> #define __LIBRARY__ #include<unistd.h> #include<linux/kernel.h> #include<fcntl.h> _syscall2(sem_t, opensem, char*, name, int, value); _syscall1(int, unlinksem, char*, name); _syscall1(int, waitsem, sem_t, s); _syscall1(int, postsem, sem_t, s); #define BUFFER_SIZE 30 #define CUSTOMER 5 #define PRODUCT 1000 #define SEM_PRODUCT "product" #define SEM_MUTEX "mutex" #define SEM_FREE "free" #define FILE_MODE S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP sem_t *sem_open(char* name, int value) { char sem_name[20] = { 0 }; int i = 0; sem_t* s = (sem_t*)malloc(sizeof(sem_t)); while (name[i]) { sem_name[i] = name[i]; i++; } sem_name[i] = '\0'; *s = opensem(sem_name, value); return s; } int sem_wait(sem_t* sem) { return waitsem(*sem); } int sem_post(sem_t* sem) { return postsem(*sem); } int sem_unlink(char* name) { return unlinksem(name); } /* int main() { sem_t* sem = sem_open("sem_open", 2); sem_t* sem2 = sem_open("sem_open:)", 1); printf("sem = %d, and sem2 = %d!\n", *sem, *sem2); sem_unlink("sem_open:)"); sem_post(sem); sem_wait(sem); sem_wait(sem); sem_wait(sem); sem_wait(sem); sem_wait(sem); sem_wait(sem); sem_unlink("sem_open"); } */ int read_4byte(int fd) { int res = 0; char *buf = (char*) malloc(sizeof(char)); int i; for (i = 0; i < 4; i++) { read(fd, buf, 1); res <<= 8; res += *buf; } return res; } void write_4byte(int fd, int val) { char stack[4] = { 0 }; int stack_idx = 0; int i; for (i = 0; i < 4; i++) { stack[stack_idx++] = (val >> (8 * i)) & 0x0ff; } for (i = 0; i < 4; i++) { char data = stack[--stack_idx]; write(fd, &data, 1); } } int poll(int fd) { int pos; int res; lseek(fd, 4, SEEK_SET); pos = read_4byte(fd); lseek(fd, pos * 4, SEEK_SET); res = read_4byte(fd); lseek(fd, 4, SEEK_SET); write_4byte(fd, (pos - 1) % BUFFER_SIZE + 2); return res; } void offer(int fd, int val) { int pos; lseek(fd, 0, SEEK_SET); pos = read_4byte(fd); lseek(fd, pos * 4, SEEK_SET); write_4byte(fd, val); lseek(fd, 0, SEEK_SET); write_4byte(fd, (pos - 1) % BUFFER_SIZE + 2); } void customer(int fd, int id) { int i; sem_t *product = sem_open(SEM_PRODUCT, 0); sem_t *empty = sem_open(SEM_FREE, 0); sem_t *mutex = sem_open(SEM_MUTEX, 0); printf("customer %d!\n", id); for (i = 0; i < PRODUCT / CUSTOMER; i++) { int val; sem_wait(product); sem_wait(mutex); val = poll(fd); printf("%d:\t%d\n", id, val); sem_post(mutex); sem_post(empty); } } void producter(int fd) { int i; sem_t *product = sem_open(SEM_PRODUCT, 0); sem_t *empty = sem_open(SEM_FREE, 0); sem_t *mutex = sem_open(SEM_MUTEX, 0); for (i = 0; i < PRODUCT; i++) { sem_wait(empty); sem_wait(mutex); offer(fd, i); printf("make a [%d]\n", i); sem_post(mutex); sem_post(product); } } int main() { int fd; int i; sem_t *product = sem_open(SEM_PRODUCT, 0); sem_t *empty = sem_open(SEM_FREE, BUFFER_SIZE); sem_t *mutex = sem_open(SEM_MUTEX, 1); fd = open("filebuf", O_RDWR | O_CREAT); write_4byte(fd, 2); write_4byte(fd, 2); if (!fork()) { producter(fd); } else if (!fork()) { customer(fd, 0); } else if (!fork()) { customer(fd, 1); } else if (!fork()) { customer(fd, 1); } else if (!fork()) { customer(fd, 1); } else if (!fork()) { customer(fd, 1); } else { for (i = 0; i <= CUSTOMER; i++) wait(NULL); sem_unlink(SEM_PRODUCT); sem_unlink(SEM_FREE); sem_unlink(SEM_MUTEX); } } <file_sep>## 多级页表和快表 - 单纯的分页机制有什么问题? - 页表太大!!! - 页表的放置就是个问题 - 把不使用的逻辑页号从页表中去掉? - 可以是可以 - 但是会产生新的问题 - 页表中的页号不连续, 就需要"二分查找", 约需要20次查询比较 - 既要连续存放(找起来快), 而且要存储的空间小 ### 多级页表的操作: - 类比章和节 - 我们放在内存中的页表项, 可以很少, 因为我们不用用到 - 在一级页表中依然要"占位", 保证连续, 我们可以按需加载二级页表, 二级页表每个也就4K, 因此同时具备访问快和存储空间小的两个特点! - 每多增加一级页表会多增加一次访问内存 ### TLB是一组相联快速存储, 是寄存器 - 首先会去TLB中查询, 一次查询全部 - 如果TLB命中直接返回 - 如果未命中才到分级页表中查询, 并且要缓存到TLB中 ### 为什么TLB条目在64-1024之间? - 程序存在局部性, 存在循环之类的 ### 续20.寻址方式 - 我们已经找到了线性地址 1. 通过cr3(存储页目录表起始地址)找到页目录表 2. 线性地址通过位运算得知页目录表项的编号, 找到对应页表起始地址 3. 通过页表起始地址来到页表处, 同样位运算得出页表项, 通过页表项找出页框号 4. 通过页框号 * 页面大小找到物理起始地址 5. 物理起始地址 + 页内偏移值 = 物理地址!!! <file_sep>#include <unistd.h> int shmget(key_t key, size_t size, int flag); void *shmat(int shmid, void *addr, int flag);<file_sep>## 内存的使用和分段 ### 如何让内存用起来??? - 取指执行, 从内存取!!! - 将程序放到内存中, pc指向开始的地址 - 实现逻辑地址和物理地址的转换 - 找一段空闲的内存把程序放进来, 并且实现逻辑地址到物理地址的转换, 程序就能顺利执行. (重定位) - 什么时候做重定位? - 编译的时候 - 载入的时候(灵活, 根据内存中哪一段是空闲的, 再处理) - 很多时候, 程序载入之后还需要移动 - 交换(swap): 进程换入内存和换出内存. 当内存空间不足的时候会将一些进程换出内存, 这些进程可能是阻塞或者睡眠状态, 当他们换入内存的时候, 可能原本的物理地址就被占有了, 因此我们要分配新的物理地址(偏移量)给它们 - 因此重定位的最佳时机: 运行时重定位 - 每一条执行指令都要从逻辑地址计算出物理地址----地址翻译!!!! - 基地址(base)放在哪里? - PCB - 怎么让程序运行起来? 1. 程序编译好, 地址不需要任何修改 2. 接着我们想让程序执行起来, 要先创建进程, PCB. 在内存中找一段空闲的内存, 然后把空闲地址找到(1000), 然后把1000赋给pcb, 把这段程序载入内存中 3. pc置好初始地址, 然后开始执行, 每次执行一条指令都要进行地址翻译 ### 引入分段: 是将整个程序一起载入内存中吗? - 分治思想: 可能程序段只读, 数据段可写 - 提升了内存的效率: 不用移动全部程序! ### 什么是GDT/LDT? - LDT表是进程的表: - 进程的数据/代码段的起始地址保存在这个表中(采用段选择子的方式保存) - 而这个表保存在进程PCB之中 - 每次执行一条指令查询这个表然后找到真实的物理地址去执行 - 怎么找? 通过选择子进行匹配可以知道很多信息! ### 寻址方式(P148) 1. 通过ds(段选择子, 通过一定的位运算可以得知各种信息包括段的物理起始地址) + gdtr(存储段描述符表起始地址)找到相应的段描述符表项 通过表项得出ldt表起始地址 找到ldt表, 找到对应段起始地址 + 偏移 => 这样我们就找到线性地址了 => 如果没有采用分页, 我们这种地址就是实际物理地址 1. 每个进程都有一个ldt表 2. 通过ldtr获取ldt表的位置 1. ldtr是一个寄存器, 存储一个段选择子 2. 通过该段选择子在gdt表中一查, 得出ldt表的位置 3. 前往ldt表在内存的位置, 得知各个段的位置~<file_sep># 内核级别线程的实现(代码实现) - 关键在于栈之间的切换(什么叫做五段论) ### 从进入内核开始 -- 靠的是中断 - 当使用fork()的时候, 会引起中断. - fork() 对应的代码就是创建线程的代码 -- 制造出能切的样子 ``` main() { A(); B(); } A() { fork(); } ``` ``` // 在A中执行, 遇到fork(); mov %eax, __NR_fork INT 0x80 mov res, %eax <---- 跳到系统中断后的 PC // 执行int的时候: 还是在用户态, 会做这几件事(自动) 压栈ss:sp 压栈eflags 压栈ret(cs:ip) system_call: push %ds...%fs // 刚进入核心态, cpu的寄存器还是用户态的 // 将来在弹出 // 一个系统调用最多有三个参数 pushl %edx movl $0x10,%edx # set up ds,es to kernel space mov %dx,%ds mov %dx,%es movl $0x17,%edx # fs points to local data space mov %dx,%fs call sys_fork pushl %eax movl current,%eax cmpl $0,state(%eax) // 看pcb中的state是否等于0 jne reschedule // 如果不是那就要调度 cmpl $0,counter(%eax) # counter je reschedule ret_from_sys_call: // 中断出口 popl %eax // 返回值 popl %ebx ... %fs ... iret // 重要 switch_to: // 使用的是tss(task struct segement) // 类比"快照" 详见<源码> // 内嵌汇编格式 // 函数目标: 将当前任务current切换到n #define switch_to(n) {\ struct {long a,b;} __tmp; \ __asm__( // 首先检查n是不是当前进程, 如果是什么都不做退出拉 "cmpl %%ecx,current\n\t" \ // 如果是什么都不做退出拉 "je 1f\n\t" \ // %edx -> %1(*&__tmp.b) // 新任务的16位选择符存入__tmp.b "movw %%dx,%1\n\t" \ "xchgl %%ecx,current\n\t" \ "ljmp *%0\n\t" \ // 因为ljmp要64位, 因此ljmp a // 1. 把当前cpu所有寄存器放在当前TR寄存器指向的段中(拍照) // 2. 把新的tss中内容加载到寄存器中(扣) "cmpl %%ecx,last_task_used_math\n\t" \ "jne 1f\n\t" \ "clts\n" \ "1:" \ ::"m" (*&__tmp.a),"m" (*&__tmp.b), \ "d" (_TSS(n)),"c" ((long) task[n])); \ // _TSS(n) -> %edx } sys_fork: call find_empty_process testl %eax,%eax js 1f push %gs pushl %esi pushl %edi pushl %ebp pushl %eax call copy_process addl $20,%esp 1: ret !!!!!!!! // copy_process的参数从何而来? 1. 执行int0x80 自动入栈用户态下的ss, esp, eflg, cs, eip 2. _sys_call手动入栈的各个寄存器 3. 调用 call _sys_call_table 入栈的返回地址. (long none) 4. sys_fork 入栈的各个寄存器 !!!!!!! copy_process做了什么??? 1. 申请内存空间 2. 创建TCB 3. 创建内核栈和用户栈 4. 填写两个栈 5. 关联栈和TCB int copy_process(int nr,long ebp,long edi,long esi,long gs,long none, long ebx,long ecx,long edx, long fs,long es,long ds, long eip,long cs,long eflags,long esp,long ss) { struct task_struct *p; int i; struct file *f; // 禁止使用malloc // 获得一页内存 p = (struct task_struct *) get_free_page(); if (!p) return -EAGAIN; task[nr] = p; *p = *current; /* NOTE! this doesn't copy the supervisor stack */ p->state = TASK_UNINTERRUPTIBLE; p->pid = last_pid; p->father = current->pid; p->counter = p->priority; // p->counter = 1; p->signal = 0; p->alarm = 0; p->leader = 0; /* process leadership doesn't inherit */ p->utime = p->stime = 0; p->cutime = p->cstime = 0; p->start_time = jiffies; /// 开始"拍照" p->tss.back_link = 0; // esp0是内核栈. esp是用户栈 // 内核栈就是PAGE_SIZE 加上刚刚申请的这一页的初始地址. 那就是紧跟这一页之后(顶端) +-----------------------+ <-------- 指针esp0 | | | | <-------- 一页内存 |-----------------------| | task_struct | +-----------------------+ <-------- 指针p p->tss.esp0 = PAGE_SIZE + (long) p; // 10是什么: 内核数据段 p->tss.ss0 = 0x10; // 父进程执行int0x80下一句话 p->tss.eip = eip; p->tss.eflags = eflags; // 子进程fork会返回0 p->tss.eax = 0; p->tss.ecx = ecx; p->tss.edx = edx; p->tss.ebx = ebx; // 这两句是设置用户栈 // 直接用参数? --> 就是直接使用父进程的用户栈!??(INT 0x80自动传入) p->tss.ss = ss & 0xffff; p->tss.esp = esp; p->tss.ebp = ebp; p->tss.esi = esi; p->tss.edi = edi; p->tss.es = es & 0xffff; p->tss.cs = cs & 0xffff; p->tss.ds = ds & 0xffff; p->tss.fs = fs & 0xffff; p->tss.gs = gs & 0xffff; p->tss.ldt = _LDT(nr); p->tss.trace_bitmap = 0x80000000; if (last_task_used_math == current) __asm__("clts ; fnsave %0"::"m" (p->tss.i387)); if (copy_mem(nr,p)) { task[nr] = NULL; free_page((long) p); return -EAGAIN; } for (i=0; i<NR_OPEN;i++) if ((f=p->filp[i])) f->f_count++; if (current->pwd) current->pwd->i_count++; if (current->root) current->root->i_count++; if (current->executable) current->executable->i_count++; set_tss_desc(gdt+(nr<<1)+FIRST_TSS_ENTRY,&(p->tss)); set_ldt_desc(gdt+(nr<<1)+FIRST_LDT_ENTRY,&(p->ldt)); p->state = TASK_RUNNING; /* do this last, just in case */ return last_pid; } // 一旦子进程被调度, 会怎么样? - 把tss中的内容扣到cpu, 包括eip是父进程的eip, 就是0x80之后一句话, - 因为eax被制成0, 因此会返回0回到调用fork之处 ``` ## 在此再次梳理系统调用全过程, 用fork()举例. 1. INT 0x80这个中断是怎么来的? - main.c 中有sched_init() 中有调用set_system_gate(0x80, &system_call) ``` // 组装'idt' // dpl = 3 // 因此system_call 能访问内核 #define _set_gate(gate_addr,type,dpl,addr) \ __asm__ ("movw %%dx,%%ax\n\t" \ "movw %0,%%dx\n\t" \ "movl %%eax,%1\n\t" \ "movl %%edx,%2" \ : \ : "i" ((short) (0x8000+(dpl<<13)+(type<<8))), \ "o" (*((char *) (gate_addr))), \ "o" (*(4+(char *) (gate_addr))), \ "d" ((char *) (addr)),"a" (0x00080000)) ``` 2. fork() 会通过宏汇编把系统调用号放到eax中, 然后int0x80, 之后从内核出来的时候, 从eax去结果 - 因此int 0x80会跳到system_call执行, 且之间会压栈用户态的诸多信息(ss, esp, eflag, cs, eip); - 之后调用sys_call, 且系统调用函数号被放在eax中, 那么sys_call 会push 几个寄存器, 然后call系统调用函数地址数组偏移eax中的值 - 那么此时此刻依然进入真正的系统调用 3. 在sys_fork的时候, 也会压栈几个东西, 然后调用copy_process 4 ..... <file_sep>1. sys_waitpid 中的 **p怎么理解? ``` struct task_struct ** p; // ??? .... for(p = &LAST_TASK ; p > &FIRST_TASK ; --p) { .... ``` 2. 什么是信号位图? schedlue() 和 sys_waitpid中两句话怎么理解? 3. wait是当有一个子进程结束就直接结束吗? 4. 执行./hallo为什么有两个进程create? 5. switch_to的ecx是什么? <file_sep>## 内核级线程 - 用户级线程的切换是内核级线程切换的一个部分 ## 为什么要有核心级线程, 有什么用? - 多核要想充分发挥作用, 就要用到核心级线程 - 多处理器和多核的区别: 多处理器用的是多套映射(MMU), 多核只用到一套映射 - 并行!!!, 之前的用户级线程是并发. 操作系统看不到用户级线程, 也就无法分配硬件 ## 和用户级相比, 核心级线程有什么不同? - 本质区别: 从多个栈 -> 多套栈, 因为在用户态和核心态都要进行函数调用。 - 在核心级线程, 一个TCB关联一套栈, 而且是放在内核里边 ## 用户栈和内核栈之间的关联 - 在用户态执行的时候, 一旦int触发, 操作系统会用硬件方式找到本线程对应的内核栈 - 用户态的ss,sp,cs,ip入栈, 相当于保存用户态状态 - iret的时候会返回用户态, 出栈各种寄存器值, 恢复用户态(回弹完成指令的跳转) e.g ``` 100: A() { B(); 104 } 200 B() { read(); 204 } 300 read() { int 0x80; 304 } system_call: call sys_read; 1000 2000: sys_read() { } - 用户栈 高 104 204 低 - 内核栈 ss:sp eflags 304 cs 1000 ``` ## 如何进行switch_to? - 首先switch_to在核心态中执行. - 线程S的TCB通过switch_to切换到线程T的TCB, 线程T的TCB关联着线程T的核心栈 - 线程T的核心栈关联着线程T的用户栈 ## 内核级线程切换switch_to的五段论 1. 中断入口 - 要把内核栈关联上用户栈, 为了切换做准备 - 然后进行中断处理 2. 中断处理, 引发切换 3. 找到TCB 4. 根据TCB完成内核栈的切换. 5. 中断出口: - iret返回, - 弹出栈中的各个用户态的现场 ## 如何实现ThreadCreate - 就是要做成那个样子(能切换的样子) ## 用户级线程和核心级线程的对比: - 见网课<file_sep>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "buff.h" struct buf* shmbuf; int poll() { int shmid; int res; if (!shmbuf) { if((shmid = shmget(KEY, sizeof(struct buf), FLAG)) == -1) { printf("shmget error!\n"); return -1; } if(!(shmbuf = shmat(shmid, 0, 0))) { printf("shmget error!\n"); return -1; } } res = shmbuf->buffer[shmbuf->tail]; shmbuf->tail = (shmbuf->tail + 1) % BUFFER_SIZE; return res; } void offer(int val) { int shmid; if (!shmbuf) { if((shmid = shmget(KEY, sizeof(struct buf), FLAG)) == -1) { printf("shmget error!\n"); return; } if(!(shmbuf = shmat(shmid, 0, 0))) { printf("shmget error!\n"); return; } } shmbuf->buffer[shmbuf->head] = val; shmbuf->head = (shmbuf->head + 1) % BUFFER_SIZE; }<file_sep>## 操作系统的那棵树 ### 怎么做出操作系统的复杂系统??? - 略 ### 关于时钟中断 - 在sched_init() 中创建时钟中断的 "gate" ``` void sched_init(void) { int i; struct desc_struct * p; if (sizeof(struct sigaction) != 16) panic("Struct sigaction MUST be 16 bytes"); set_tss_desc(gdt+FIRST_TSS_ENTRY,&(init_task.task.tss)); set_ldt_desc(gdt+FIRST_LDT_ENTRY,&(init_task.task.ldt)); p = gdt+2+FIRST_TSS_ENTRY; for(i=1;i<NR_TASKS;i++) { task[i] = NULL; p->a=p->b=0; p++; p->a=p->b=0; p++; } /* Clear NT, so that we won't have troubles with that later on */ __asm__("pushfl ; andl $0xffffbfff,(%esp) ; popfl"); ltr(0); lldt(0); outb_p(0x36,0x43); /* binary, mode 3, LSB/MSB, ch 0 */ outb_p(LATCH & 0xff , 0x40); /* LSB */ outb(LATCH >> 8 , 0x40); /* MSB */ ///////////////////////////////////////////// // 设置时钟中断处理程序句柄(时钟中断门), 修改中断控制器屏蔽码(???), // 允许时钟中断, set_intr_gate(0x20,&timer_interrupt); ///////////////////////////////////////////// outb(inb_p(0x21)&~0x01,0x21); set_system_gate(0x80,&system_call); } ``` ```s # jiffies每10ms增加1 # 跟sys_call一样, 保存各个用户寄存器的值 # 待会直接调用ret_from_sys_call弹出这些东西即可 .align 2 timer_interrupt: push %ds # save ds,es and put kernel data space push %es # into them. %fs is used by _system_call push %fs pushl %edx # we save %eax,%ecx,%edx as gcc doesn't pushl %ecx # save those across function calls. %ebx pushl %ebx # is saved as we use that in ret_sys_call pushl %eax movl $0x10,%eax mov %ax,%ds mov %ax,%es movl $0x17,%eax mov %ax,%fs incl jiffies # 自增jiffies movb $0x20,%al # EOI to interrupt controller #1 outb %al,$0x20 movl CS(%esp),%eax # 拿出cs给eax andl $3,%eax # %eax is CPL (当前特权级) (0 or 3, 0=supervisor) pushl %eax # do_timer 参数cpl, push 一波 call do_timer # 'do_timer(long CPL)' does everything from addl $4,%esp # task switching to accounting ... jmp ret_from_sys_call ``` - DPL: 目标特权级, 内核为0, 用户为3 - CPL(当前特权级) <= DPL 才能执行. ``` // cpl是当前特权级. void do_timer(long cpl) { extern int beepcount; extern void sysbeepstop(void); if (beepcount) if (!--beepcount) sysbeepstop(); // 当前特权级是什么, 响应增加什么的时间 if (cpl) current->utime++; else current->stime++; // 如果有定时器 if (next_timer) { next_timer->jiffies--; while (next_timer && next_timer->jiffies <= 0) { void (*fn)(void); fn = next_timer->fn; next_timer->fn = NULL; next_timer = next_timer->next; (fn)(); } } // 键盘中断? if (current_DOR & 0xf0) do_floppy_timer(); // 如果当前进程时间片没有用完, 则-1return if ((--current->counter)>0) return; // 用完了(-1), 置为0 current->counter=0; // 如果是在用户态下面, 不可执行调度. if (!cpl) return; // 在内核态执行调度 schedule(); } ```<file_sep>## 什么是操作系统? - 是计算机! - 是给裸机(计算机硬件)穿上的衣服. - 在计算机硬件之上和应用之间的一层软件, 方便我们使用硬件 ### 管理哪些硬件? - cpu - 内存 - 终端 - 磁盘 - 文件 ### 怎么学操作系统? - 接口(应用软件和操作系统之间, 怎么用接口. ) - 原理(书中的概念) - **明白真正原理**! **~编写~改操作系统**. <file_sep>## 内存换入 ### 为什么要换入换出? - 为了实现虚拟内存就应该有换入换出 - 虚拟内存有4G内存, 实际内存只有16M - linux0.11每个进程划分了64M的空间, 因此程序逻辑地址范围是0x00000000 - 0x40000000 ### 请求的时候才映射, 换入.(请求调页) - 缺页会导致缺页中断 (MMU发出) - 磁盘读页之后建立映射, MMU指令重新执行 ### 一个实际的请求调页 1. 设置中断处理函数 ``` void trap_init(void) { int i; //... set_trap_gate(14,&page_fault); // ... } ``` ``` page_fault: xchgl %eax,(%esp) pushl %ecx pushl %edx push %ds push %es push %fs movl $0x10,%edx mov %dx,%ds mov %dx,%es mov %dx,%fs // 页错误的线性地址 movl %cr2,%edx pushl %edx pushl %eax testl $1,%eax jne 1f call do_no_page jmp 2f 1: call do_wp_page 2: addl $8,%esp pop %fs pop %es pop %ds popl %edx popl %ecx popl %eax iret ``` ``` // 从磁盘上读页面 // 建立映射 void do_no_page(unsigned long error_code,unsigned long address) { int nr[4]; unsigned long tmp; unsigned long page; int block,i; // 页面地址 address &= 0xfffff000; tmp = address - current->start_code; if (!current->executable || tmp >= current->end_data) { get_empty_page(address); return; } if (share_page(tmp)) return; // 得到物理空闲页 if (!(page = get_free_page())) oom(); /* remember that 1 block is used for header */ block = 1 + tmp/BLOCK_SIZE; for (i=0 ; i<4 ; block++,i++) nr[i] = bmap(current->executable,block); // 从磁盘上读一个页, 读到刚刚申请的空闲内存 bread_page(page,current->executable->i_dev,nr); i = tmp + 4096 - current->end_data; tmp = page + 4096; while (i-- > 0) { tmp--; *(char *)tmp = 0; } // 把物理页放在虚拟地址, 建立映射 if (put_page(page,address)) return; free_page(page); oom(); } ``` ``` unsigned long put_page(unsigned long page,unsigned long address) { unsigned long tmp, *page_table; /* NOTE !!! This uses the fact that _pg_dir=0 */ if (page < LOW_MEM || page >= HIGH_MEMORY) printk("Trying to put page %p at %p\n",page,address); if (mem_map[(p age-LOW_MEM)>>12] != 1) printk("mem_map disagrees with %p at %p\n",page,address); page_table = (unsigned long *) ((address>>20) & 0xffc); if ((*page_table)&1) page_table = (unsigned long *) (0xfffff000 & *page_table); else { if (!(tmp=get_free_page())) return 0; *page_table = tmp|7; page_table = (unsigned long *) tmp; } page_table[(address>>12) & 0x3ff] = page | 7; /* no need for invalidate */ return page; } ```<file_sep>## 目录解析代码实现 ```c int sys_open(const char * filename,int flag,int mode) { struct m_inode * inode; struct file * f; int i,fd; mode &= 0777 & ~current->umask; for(fd=0 ; fd<NR_OPEN ; fd++) if (!current->filp[fd]) break; if (fd>=NR_OPEN) return -EINVAL; current->close_on_exec &= ~(1<<fd); f=0+file_table; for (i=0 ; i<NR_FILE ; i++,f++) if (!f->f_count) break; if (i>=NR_FILE) return -EINVAL; (current->filp[fd]=f)->f_count++; // 通过文件名找到inode if ((i=open_namei(filename,flag,mode,&inode))<0) { current->filp[fd]=NULL; f->f_count=0; return i; } /* ttys are somewhat special (ttyxx major==4, tty major==5) */ if (S_ISCHR(inode->i_mode)) { if (MAJOR(inode->i_zone[0])==4) { if (current->leader && current->tty<0) { current->tty = MINOR(inode->i_zone[0]); tty_table[current->tty].pgrp = current->pgrp; } } else if (MAJOR(inode->i_zone[0])==5) if (current->tty<0) { iput(inode); current->filp[fd]=NULL; f->f_count=0; return -EPERM; } } /* Likewise with block-devices: check for floppy_change */ if (S_ISBLK(inode->i_mode)) check_disk_change(inode->i_zone[0]); f->f_mode = inode->i_mode; f->f_flags = flag; f->f_count = 1; f->f_inode = inode; f->f_pos = 0; return (fd); } ``` ``` int open_namei(const char * pathname, int flag, int mode, struct m_inode ** res_inode) { const char * basename; int inr,dev,namelen; struct m_inode * dir, *inode; struct buffer_head * bh; struct dir_entry * de; if ((flag & O_TRUNC) && !(flag & O_ACCMODE)) flag |= O_WRONLY; mode &= 0777 & ~current->umask; mode |= I_REGULAR; if (!(dir = dir_namei(pathname,&namelen,&basename))) return -ENOENT; if (!namelen) { /* special case: '/usr/' etc */ if (!(flag & (O_ACCMODE|O_CREAT|O_TRUNC))) { *res_inode=dir; return 0; } iput(dir); return -EISDIR; } bh = find_entry(&dir,basename,namelen,&de); if (!bh) { if (!(flag & O_CREAT)) { iput(dir); return -ENOENT; } if (!permission(dir,MAY_WRITE)) { iput(dir); return -EACCES; } // inode = new_inode(dir->i_dev); if (!inode) { iput(dir); return -ENOSPC; } inode->i_uid = current->euid; inode->i_mode = mode; inode->i_dirt = 1; bh = add_entry(dir,basename,namelen,&de); if (!bh) { inode->i_nlinks--; iput(inode); iput(dir); return -ENOSPC; } de->inode = inode->i_num; bh->b_dirt = 1; brelse(bh); iput(dir); *res_inode = inode; return 0; } inr = de->inode; dev = dir->i_dev; brelse(bh); iput(dir); if (flag & O_EXCL) return -EEXIST; if (!(inode=iget(dev,inr))) return -EACCES; if ((S_ISDIR(inode->i_mode) && (flag & O_ACCMODE)) || !permission(inode,ACC_MODE(flag))) { iput(inode); return -EPERM; } inode->i_atime = CURRENT_TIME; if (flag & O_TRUNC) truncate(inode); *res_inode = inode; return 0; } ``` 真正完成路径解析 ``` static struct m_inode * get_dir(const char * pathname) { char c; const char * thisname; // 当前迭代的inode struct m_inode * inode; struct buffer_head * bh; int namelen,inr,idev; struct dir_entry * de; if (!current->root || !current->root->i_count) panic("No root inode"); if (!current->pwd || !current->pwd->i_count) panic("No cwd inode"); // 如果是'/'打头的要从根目录开始 if ((c=get_fs_byte(pathname))=='/') { inode = current->root; pathname++; // 否则从当前目录开始 } else if (c) inode = current->pwd; else return NULL; /* empty name is bad */ inode->i_count++; while (1) { thisname = pathname; if (!S_ISDIR(inode->i_mode) || !permission(inode,MAY_EXEC)) { iput(inode); return NULL; } for(namelen=0;(c=get_fs_byte(pathname++))&&(c!='/');namelen++) /* nothing */ ; if (!c) return inode; // 根据根目录inode找到数据内容(目录项) if (!(bh = find_entry(&inode,thisname,namelen,&de))) { iput(inode); return NULL; } inr = de->inode; idev = inode->i_dev; brelse(bh); iput(inode); if (!(inode = iget(idev,inr))) return NULL; } } ```<file_sep>## 系统调用的实现 - 插座背后的故事 ### whoami? ``` // 用户程序 main() { whoami(); } // 系统调用 whoami() { printf(100, 8); } 100: jt ``` - 为啥用户程序不能直接 printf(100, 8); ? (直接访问内核内存? ) - 禁止随意jump!~ - why不能这样? - 首先是安全性问题(用户名密码存在内存中) - 怎么让它不这样? - 区分用户态和核心态 -> 是一种处理器的**硬件**设计 - 内核(用户)态, 内核(用户)段 - CS:IP是当前指令, CS最低两位来表示内核态和用户态: 0是内核态, 3是用户态(数字越大越低) - 内核态可以访问任何目标数据, 用户态不能方位内核数据 - 对于指令的跳转也实现了隔离 - CPL(CS (当前特权级)), DPL(目标特权级) => CPL <= DPL 当前特权级大于目标特权级才能执行 - 整理: 1. 在系统初始化的时候(head.s 执行的时候, 会针对内核态的数据建立GDT表项, 对应的DPL = 0) 2. 初始化好以后, 进入用户态执行, 启动shell, 让cs的cpl置为3, 启动用户程序的时候, 用户程序的对应CPL = 3. - 那我应该哪样? - 硬件提供了主动进入内核的方法 -> 那就是中断指令int(唯一) - int指令将使得cs中的cpl改成0, "进入内核" - 这是用户程序发起的调用内核代码的唯一方法 - 系统调用的核心 1. 用户程序中包含一段包含int指令的代码(库函数) 2. 操作系统写中断处理, 获取想调程序的编号 3. 操作系统根据编号执行响应的代码 - 详见源码3.0 - 大火都是从int 0x80 进入系统调用 - 宏观 -> **将一个int系统调用号置给eax**(&system_call的时候取并执行), 然后调用int 0x80 ==> 到内核了 - int 0x80 的中断处理 1. 查idt表 -> 在idt表中查出中断处理函数, 跳到那儿去执行 - 为什么是0x80? - set_system_gate(0x80, &system_call); -> 已经规定好0x80就是做中断处理 - 调用int 0x80 会把dpl变成3(目标特权级) 2. 查表用段选择符和段偏移设置成新的pc, cs=8, ip=&system_call ==> 内核代码段, 就是内核中的system call函数 - cs = 8 的时候 cpu 的 cpl = 0!!! (cs最后两位 -> 00) - system_call ``` // .... call _sys_call_table(,%eax,4) ==> _sys_call_table(系统调用函数表) + 4 * %eax 就是响应系统调用处理函数的入口 ==> why 4? - 每个系统调用函数占4字节 // .... ```s - _sys_call_table - 是一个全局的函数数组 - 在sys.h中ss - printf过程 1. printf系统调用(用户态) 2. printf展开, 其中有int 0x80.(用户态) 3. 从idt表找到80对应表项(system_call函数地址, 在初始化时已然设置好(CS = 8, IP = &system_call)) 3. system_call中断处理(核心态) 4. call _sys_call_table(,%eax,4) 跳到系统调用函数 <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdbool.h> struct running_task { int state; // 进程状态: 运行1等待0 int create; // 开始时间片 int end; // 结束时间片 int running_time; // 运行总时间 int waiting_time; // 等待总时间 int w; // 上次等待的时间 int r; // 上次运行的时间 }; void dealWithProcess(int pid, char state, int time_peaces, struct running_task * tasks); int main(int argc, char const *argv[]) { // 只计算12/13/14/15 // 平均周转时间: 进程结束时间片 - 进程开始时间片 // 平均等待时间: 进程等待时间 // 吞吐率: 完成多少道作业/总时间 FILE *log = fopen("process.log", "r"); struct running_task *tasks = (struct running_task *)malloc(4 * sizeof(struct running_task)); // init for (int i = 0; i < 4; i++) { tasks[i].state = 0; tasks[i].create = 0; tasks[i].end = 0; tasks[i].running_time = 0; tasks[i].waiting_time = 0; tasks[i].w = 0; tasks[i].r = 0; } char *bf = (char *)malloc(sizeof(char) * 1024); char *buf; while (buf = fgets(bf, 1024, log)) { int pid = 0; char state = 0; int time_peaces = 0; int i = 0; while (buf[i] != '\n') { if (buf[i] >= 'A' && buf[i] <= 'Z') { state = buf[i]; } else if (buf[i] == '\t') { /* do nothing */ } else { if (state == 0) { pid = pid * 10 + buf[i] - '0'; } else { time_peaces = time_peaces * 10 + buf[i] - '0'; } } i++; } dealWithProcess(pid, state, time_peaces, tasks); } for (int i = 0; i < 4; i++) { printf("pid = %d, create = %d, end = %d, waiting_time = %d, running_time = %d\n", 12 + i, tasks[i].create, tasks[i].end, tasks[i].waiting_time, tasks[i].running_time); } return 0; } void dealWithProcess(int pid, char state, int time_peaces, struct running_task *tasks ) { if (pid < 12 || pid > 15) return; switch (state) { case 'N': // 新建 tasks[pid - 12].w = time_peaces; tasks[pid - 12].create = time_peaces; break; case 'J': // 就绪 tasks[pid - 12].w = time_peaces; tasks[pid - 12].waiting_time += time_peaces - tasks[pid - 12].w; break; case 'R': // 运行 tasks[pid - 12].r = time_peaces; tasks[pid - 12].waiting_time += time_peaces - tasks[pid - 12].w; case 'W': // 阻塞 tasks[pid - 12].w = time_peaces; tasks[pid - 12].running_time += time_peaces - tasks[pid - 12].r; break; case 'E': // 退出 tasks[pid - 12].running_time += time_peaces - tasks[pid - 12].r; tasks[pid - 12].end = time_peaces; break; } } /* PS C:\Users\12164\Documents\HBuilderProjects\OS\experiment\exp3> .\log.exe pid = 12, create = 16035, end = 16648, waiting_time = 2, running_time = 3 pid = 13, create = 16038, end = 16647, waiting_time = 16, running_time = 1 pid = 14, create = 16038, end = 16550, waiting_time = 197, running_time = 0 pid = 15, create = 16054, end = 16646, waiting_time = 295, running_time = 96 tips: 还没计算sleep的时间 */<file_sep> #define __LIBRARY__ #include "sem.h" _syscall2(sem_t, opensem, char*, name, int, value); _syscall1(int, unlinksem, char*, name); _syscall1(int, waitsem, sem_t, s); _syscall1(int, postsem, sem_t, s); sem_t *sem_open(char* name, int value) { char sem_name[20] = { 0 }; int i = 0; sem_t* s = (sem_t*)malloc(sizeof(sem_t)); while (name[i]) { sem_name[i] = name[i]; i++; } sem_name[i] = '\0'; *s = opensem(sem_name, value); return s; } int sem_wait(sem_t* sem) { return waitsem(*sem); } int sem_post(sem_t* sem) { return postsem(*sem); } int sem_unlink(char* name) { return unlinksem(name); } <file_sep>## 生磁盘到文件 - 核心主题 -- 如何从文件得到盘块号/从盘块号抽象出文件? - 文件的本质 -- 字符流!!!(字符序列) - 磁盘上的文件是什么样子? - 一堆盘块接在一起 - 我们要建立字符流到盘块的映射! - 1个盘块有多大 -- 1K(两个扇区) ### 从文件怎么得到盘块号? 1. 首先用FCB(文件控制块)记录文件的信息(文件名/起始块/块数) 2. 读写某一个字符的时候一顿换算, 能找出当前读写的是第几块 3. 放到电梯队列中等待磁盘中断操作 ### 利用索引来存储文件! - 先把inode读进来, 有了文件对应信息 - // ... <file_sep>## 目录与文件系统 - 怎么完成文件名到i节点的映射? - 怎么实现目录? - 路径名 -> inode ### 树状目录的完整实现 1. 首先将磁盘分为数据盘块和inode数组 2. 查询目录的时候比如 /usr/data/test.c 3. 会从根目录开始查, 目录的数据结构只记录inode数组的下标 对应 文件名, 首先匹配usr, 那么我们就知道了usr的下标, 拿到usr的inode, 从usr的inode我们可以拿到usr的数据块, 又可以递归的往下查, 最终得到想要拿到的文件的inode 4. 在i节点之前还有引导块超级块, i节点位图, 磁盘块位图, 这些位图负责磁盘的管理, 而超级块负责存储磁盘大小位图大小等信息.<file_sep>fork() exec() 1.进程 线程 协程的区别 2.32位和64位操作系统的区别(不知道) 3.上下文???(没听说过) 4.缓存置换算法 操作系统 僵尸进程 ------------------------------------------ ## 进程通信的几种方式 1. 共享存储区: - 进程A想和进程B通信, 首先进程A无法访问进程B的地址空间, 因为这样不安全. - 操作系统会为这两个进程分配共享存储区 - A可以把数据写入该区域, B可以从该区域读数据, 对该区域的读写是互斥的(PV操作)。 - 共享存储区有两种类型一种是基于数据结构的共享存储区, 另一种是基于应用的共享存储区, 后者较为高级 2. 管道通信 - 进程A想对进程B通信, 就好像在A, B之间开设一条半双工的管道。(就是一个页表的大小 4kb) - 对于这条管道的读写也是互斥的. 而且管道之间的通信在任意时刻只能是单向的. - 如果要实现双向通信, 那么要开两条管道. - 以字符流的形式写入管道, 当管道满的时候write()的系统调用会被阻塞, 当管道空的时候, read() 的系统调用会被阻塞. - 对于这条管道有两点特性, 写要写满, 读要读完 - 读取进程最多只能有一个, 不然读不全数据 3. 信箱通信 - 进程A想对进程B通信, 就把信息放在B的消息队列中. - 消息还会添加首部, 因此这种机制有点像计网中的信息传递. - 对于消息的发送的读取是原语操作。 如果不是原语操作就有可能A发一半的时候切换进程B, B就会开始读取, 而且读到不完整信息. - 另外还有一种机制是A直接把信息放在操作系统管理的信箱中, 之后在适合的时候在放到B的消息队列中. ## 说说核心态和用户态 - CPU处于用户态只能执行非特权指令, CPU处于核心态, 能执行特权指令和非特权指令. - 在内核态运行的程序叫做内核程序, 在用户态运行的程序叫应用程序, - 用户态转为内核态, 需要中断, 内核态转为用户态只需修改寄存器中的程序状态字即可(0 为核心态, 3 为用户态) - 内核态运行时钟管理, 原语操作, 进程管理等等. - 不同操作系统的内核态大小有所不同, 分为微内核和大内核. ## 线程和进程的区别是什么, 线程的实现方式? - 定义方面: 线程是程序运行的最小单位, 进程是资源分配的最小单位 - 资源方面: 线程一般不会用到系统资源, 因为都是用进程的资源 - 切换开销方面: 进程之间的切换开销比较大, 需要转到内核态, 线程之间的切换开销比较小. - 运行方面: 进程A的结束不会影响到进程B, 反过来一个进程里面的多个线程, 当一个线程异常终止可能会导致进程异常终止 - 实现方式: 内核级线程/用户级线程. ## 说说用户级线程和内核级线程? 多线程模型, 优点? - 用户级线程就是只能用户看到的线程, 操作系统看不到, 内核级线程就是操作系统看到的线程 - 操作系统只会对内核级线程分配内核. - 多线程模型 1. 多对一: 多个用户级线程对应一个内核级线程. 在操作系统看来这就是一个进程 优点是: 进程切换块, 只需要在应用层面就可以切换. 缺点是: 因为它们只用到一个核, 所以当一个线程阻塞的时候, 其他的线程也会阻塞. 并发度不是很高. 2. 一对一: 一个用户级线程对应一个内核级线程. 优点是: 并发度很高, 可以同时在多个核并行执行, 即使一个线程阻塞了, 其他线程还能执行. 缺点是: 因为是内核级线程, 切换线程要调用内核代码, 开销较大. 3. 多对多: n个用户级线程对应m个内核级线程. - 进程切换块, 只需要在应用层面就可以切换. 并发度很高, 可以同时在多个核并行执行, 即使一个线程阻塞了, 其他线程还能执行. ## 说说三层调度。 1. 高级调度: 就是进程创建 -> 进入内存 -> 进程销毁的过程: 一般都是从外存加载到内存中, 并且创建进程PCB, 关系到内存的分配和回收 2. 中级调度: 当内存紧张的时候, 会将一部分进程从内存移到外存中, 外存指的是文件系统中的..区该区域IO较快, 然而 进程的PCB会被放在内存中, 一般会放在就绪挂起队列或者阻塞挂起队列之后. 当内存有空间的时候再将外村中的进程放入内存中 3. 初级调度: 就是就绪和运行态的转换. ## 讲讲进程调度方式? 什么时候不能进程调度? - 抢占式和非抢占式. 1. 响应中断过程中. 2. 执行原语期间 3. 在内核临界区时 ## 说说几种调度算法 1. 先来先服务:维护一个队列, 加入内存的进程先来先执行 - 优点: 公平 - 缺点: 执行时间较短的进程要等很久. 2. 短时间优先: 维护一个队列, 按进程的服务时间排序, 如果是抢占式的, 进程加入的时候, 如果当前进程剩余时间>加入进程的时间, 那么会抢占当前进程 - 优点: 执行时间短的进程友好, 不用等待很久 - 缺点: 如果一直加入执行时间短的进程, 那么执行时间长的进程得不到执行, 会导致饥饿, 3. 高响应比优先:和短时间优先差不多, 只是判定标准变成响应比, 响应比就是(服务时间 + 等待时间) / 服务时间. 因此等待的时间越长响应比越高、 - 优点:不会导致饥饿, 等待时间短的进程也可以优先得到运行. - 缺点: 耗费系统性能比较高. 4. 时间片轮转: 跟先来先服务差不多道理, 只不过达到相应时间片如果没运行完, 会被加下来的进程抢占. - 优点: 公平, 用户等待的时间比较短. - 缺点: 会花大量cpu资源用于进程调度. 5. 线程优先级: 为每个进程添加进程优先级属性. 操作系统按照进程的优先级来先后运行, 也份抢式和非抢占式 - 优点: 区分任务的紧急性. - 缺点: 还是会导致饥饿 6. 多级反馈队列: 维护多个队列, 这些队列从上到下优先级降低, 时间片变长 1. 进程进入的时候先进入第一级队列. 如果时间片用完的话还没执行完, 放入下一级队列 2. 如果执行一半被优先级更高的进程抢占, 那么放到本级队列末尾 3. 只有k级没有进程才会从k + 1级开始执行 ## 进程互斥的实现方法(软件/硬件)? - 软件: 1. 单标志法: ``` int now = 1; // 当前执行进程 // 进程1 p1 { while (now == 2) {} // do something... now = 2; } // 进程2 p2 { while (now == 1) {} // do something... now = 1; } ``` - 缺点: 1. 会循环等待. 2. 不满足空闲则进原则. 2. 双标志 (1) 双标志先判断 ``` // 假设现在有两个进程. boolean[] visit = new boolean[2]; // 表示进程想进入临界区的意愿 visit[0] = false; visit[1] = false; // 进程0 p1 { while (visit[1]) {} visit[0] = true; // do something.... visit[0] = false; } p2 { while (visit[0]) {} visit[1] = true; // do something.... visit[1] = false; } ``` - 缺点: 会同时进入临界区 (2) 双标志后判断: ``` // 假设现在有两个进程. boolean[] visit = new boolean[2]; // 表示进程想进入临界区的意愿 visit[0] = false; visit[1] = false; // 进程0 p1 { visit[0] = true; // 先表名自己的意愿 while (visit[1]) {} // do something.... visit[0] = false; } p2 { visit[1] = true; while (visit[0]) {} // do something.... visit[1] = false; } ``` - 缺点: 会导致死锁. 3. Peterson算法 ``` // 假设现在有两个进程. bool visit[2]; // 表示进程想进入临界区的意愿 visit[0] = false; visit[1] = false; int last = 0; // 进程0 p1 { visit[0] = true; // 先表明自己想进入临界区的意愿 last = 1; // 将机会让给别人. while (visit[1] && last == 1) {} // do something.... visit[0] = false; } p2 { visit[1] = true; last = 0; while (visit[0] && last == 0) {} // do something.... visit[1] = false; } ``` - 缺点: 会导致cpu空转 - 硬件 1. 开关中断实现 ``` 关中断; // do something... 开中断; ``` 2. test and set lock ``` // 硬件实现的逻辑 bool TSL(bool lock) { bool tmp = lock; lock = true; return tmp; } bool lock = false; // 进程 p { while (TSL(lock)) {} // do something... lock = false; } ``` 3. swap ``` swap 意在原子操作交换两个值 (XCHG) bool lock; // 进程 p { bool tmp = true; while (swap(lock, tmp)) {} // dosomething... lock = false; } ``` ## 原语具体怎么实现的? - 通过关中断和开中断实现 - 或者通过软件? ## 信号量怎么实现的? 有什么类型? ## 说说两种类型的PV操作 1. 整数类型 ``` void wait(int mutex) { mutex--; while (mutex < 0) {} } void signal(int mutex) { mutex++; } int mutex = 1; // 表示资源数为1 // 进程1 p1 { wait(mutex); // do something signal(mutex); } ``` 2. 结构类型 ``` struct { int val; // 资源数量 struct process *queue; // 等待队列 } semaphore void wait(semaphore mutex) { mutex -> val--; while (mutex -> val < 0) { // 阻塞原语 block(mutex -> queue); } } void signal(semaphore mutex) { mutex++; while (mutex <= 0) { // 唤醒原语 // wakeup(mutex -> queue); wakeupall(mutex -> queue); } } // p1 { wait(mutex); // do something signal(mutex); } ``` ## PV操作是怎么实现互斥, 同步, 前驱的? 1. 互斥 ``` semaphore mutex; mutex.val = 1; // 进程1 p1 { wait(mutex); // do something signal(mutex); } // 进程2 p2 { wait(mutex); // do something signal(mutex); } ``` 2. 同步 ``` semaphore mutex; mutex.val = 0; // 规定语句4必须在语句2 之后执行 p1 { 语句1; 语句2; signal(mutex); 语句3; } p1 { wait(mutex); 语句4; 语句5; 语句6; } ``` 3. 前驱: 和同步差不多, 把PV操作理解为请求资源和释放资源即可. ## 说说生产者和消费者问题(多消费者生产者呢? ) - 生产者生产产品, 消费者消费产品. ``` semaphore product = 0; semaphore free = n; // 缓冲区可以放n个产品 semaphore mutex = 1; prodecer { while (true) { // 生产产品 // ... wait(free); // 放入缓冲区 wait(mutex); // ... signal(mutex); signal(prodect); } } customer { while (true) { wait(prodect); // 从缓冲区拿出产品 wait(mutex); // ... signal(mutex); signal(free); // 使用产品 // ... } } ``` ## 说说吸烟者问题 // ... ## 说说读者写着问题 1. 允许多个读者进行读操作 2. 只允许一个写者进行写操作 3. 任意写着在完成写之前不允许其他读者/写着 4. 写者想进行写要等到所有读者,写者退出. ``` semaphore rw = 1; // 读写锁 semaphore mutex = 1; // 保证对count的互斥访问 semaphore fair = 1; // 保证读者写者的公平 ==> 对wait(rw)的访问不会抢占 int count = 0; // 读者数量 writer { wait(fair); wait(rw); signal(fair); // 写文件 // .... signal(rw); } reader { wait(fair); wait(mutex); // 没有读者 if (count == 0) { // 请求读写锁 wait(rw); } count++; signal(mutex); signal(fair); // 读 // ... wait(mutex); // 释放读写锁 count--; if (count == 1) { // 请求读写锁 signal(rw); } signal(mutex); } ``` ## 说说管程 - 管程是把临界区抽象化的一种对象或者数据结构. - 访问管程内的数据只能通过调用管程的函数来进行. ## 死锁产生的条件? - 互斥 - 不可剥夺 - 请求和保持 - 循环等待条件 - (用哲学家进餐问题举例) ## 说说死锁和死循环、饥饿的区别 // ... ## 怎么避免死锁? - 破坏四个条件之一即可避免死锁 1. 破坏互斥条件: 比如对一些外部资源的使用是互斥的, 比如打印机。 我们可以利用有关技术(SPOOling) 将打印机的访问变成不是互斥的, 用一个进程来分配和调剂打印机的访问(比如设置队列), 其他进程看来好像同时拥有打印机(逻辑上共享) 2. 破坏不可剥夺性:进程请求不到想要的资源应该释放其他资源. 或者利用进程的优先级 这种方法造成严重资源浪费 3. 破坏请求和保持条件: 静态分配方法, 进程运行前分配所有资源, 会造成资源浪费. 4. 破坏循环等待条件: 给资源编号, 并且按照序号申请资源. - 通过安全序列避免死锁. - 安全序列指的是系统资源分配顺序 - 当一个进程想申请资源的时候, 检查一下如果分给这个进程相应资源, 能否找到一个安全序列 - 如果能的话, 那么便给进程分配资源, 如果不能, 则让线程阻塞. ## 说说银行家算法? ## 说说死锁检测算法? ------------------------------------------------------------ ## 什么是内存? 有什么作用? - 内存是区别于磁盘的一种存储单位 - 它的存取速度很快 - 因为CPU必须要取指执行, 这里的指就是内存中的地址. ## 装入的几种方式? 链接的三种方式? - 绝对装入, 静态重定位(装入到内存固定位置), 运行时装入(重定位寄存器决定) - 链接: 1. 静态链接: 编译期间把各个模块连接成一个大的模块, 之后就不在拆开. 2. 装入时动态链接: 装入的时候才动态的链接 3. 运行时动态链接: 在需要某个模块的时候才把该模块放到内存中. ## 操作系统怎么管理内存? 1. 内存的分配和回收 - 分配: 1. 连续分配 1. 单一分区分配 2. 固定分区分配 3. 动态分区分配 1. 首次适应 2. 最佳适应 3. 最坏适应 4. 邻近适应 2. 非连续分配 1. 基本分页 2. 基本分段 3. 段也式 - 快表 - 两级页表 - 回收: - 只要回收完了有空闲分区连在一起, 就要把他们合并 2. 内存空间的扩展 1. 覆盖技术 2. 交换技术 3. 虚拟内存技术 - 请求分页 - 页面置换 - OPT - FIFO - LRU - NRU - 请求调页(缺页中断) 3. 地址转换 - 逻辑地址转化为物理地址. 4. 存储保护 1. 上下界寄存器 2. 重定位寄存器 ## 怎么实现内存的扩充? 1. 覆盖技术 - 把内存分为覆盖区和常驻区 ``` main() -> a, b a -> c b -> d 常驻区 main() 覆盖区0 a, b 覆盖区1 c, d ``` 2. 交换技术 - 就是实现内存和外存的转换 - 当内存空间不足的时候, 操作系统会把优先级较低, 或者阻塞的进程放到外存中, 外存就是磁盘的对换区 - 而且进程的PCB会存留在内存中, 会被放到阻塞队列或者就绪队列之中 - 当内存有空间的时候, 这些进程会被换入。 3. 虚拟内存技术 // ... ## 怎么实现内存的分配? ⭐ - 连续分配: 1. 单一分配: 在开始有计算机还没有多道程序的时候, 比如DOS系统, 每次只为一道程序分配内存, 因此可以让程序员自由分配 也没有所谓的内部碎片 外部碎片. 2. 固定分区分配: 有两种, 一种是真的每个分区都一样大小, 另外是逐级递增分区, 但它们都是一样, 进程只能占有一个分区, 因此会产生内部碎片, 不会产生外部碎片 3. 动态分区分配: 进程加入内存的时候才动态的选择要分给他哪个分区, 会产生外部碎片. 要维护空闲分区表/空闲分区链 - 非连续分配: - // ... ## 什么是内部/外部碎片? - 外部碎片指的是: 进行内存分配的时候有一些小的内存空间无法进行分配, 这些就是外部碎片 - 内部碎片指的是: 进行内存分配的时候, 一个进程不得不沾满一个分区, 即使这个进程的内存不用这么大, 那么剩下来的这些就是内部碎片. ## 动态分区的分配算法是什么? (4种) - 首次适应算法 - 维护一个空闲分区表, 按照内存从高到低的顺序进行分配 - 优点: 不用排序, 效率比较高, 对大内存进程友好 - 缺点: 会产生一些外部碎片 - 最佳适应算法 - 维护一个空闲分区表, 每次分区都要按照空闲分区的大小进行排序. 优先选择分区最小的进行分配 - 优点: 对大内存的进程友好. - 缺点: 需要找出最小空闲内存, 耗费性能, 也会造成外部碎片 - 最差适应算法、 - 维护一个空闲分区表, 每次分区都要按照空闲分区的大小进行排序. 优先选择分区最大的进行分配 - 内存分配均匀, 产生较少的外部碎片 - 大内存进程进入的时候, 可能分配不到内存, 要采用紧凑技术. 耗费时间, 还要进行排序. - 邻近适应算法. - 维护一个空闲分区表, 每次分配都找当前分配到的下一个分区, 环形绕表走. - 内存分配均匀, 产生较少的外部碎片 - 大内存进程进入的时候, 可能分配不到内存, 要采用紧凑技术. 耗费时间 ## 基本分页存储管理怎么实现逻辑地址到物理地址的转换?从计算和硬件说. (## 讲一讲页表) - 首先说说分页机制: 把内存分为一个个相同大小的页面. 进入内存的进程也分为一个个大小相同的页面 - 因为我们是非连续存储方式, 这些页面会放在内存的不同区域. 因此我们需要通过页表这一数据结构来找到相应内存地址 - 页表由一个个页表项组成, 页表项的元素有页号和内存块号. - 通常进程PCB中会存放页表起始地址, 页表长度 - 当我们的cPU加载该进程的运行环境, 页表起始地址和页表长度将会被加载到页表寄存器中, ``` 举个例子: 当前逻辑地址为85, 页面大小为10 我们的 页偏移量就是85 % 10 = 5, 页号就是85 / 10 = 8; ``` - 由于寄存器是二进制存放比特位的, 因此我们直接截取位数即可. - 比如说低10位是偏移量, 那么高22位就是页号 - 我们拿到页号, 先和页表长度做对比, 如果>=页表长度, 要产生越界中断. - 否则我们通过页表地址, 找到相应页表的位置, 再通过内存偏移相应位数, - 找到内存块号 - 因此内存起始地址 = 内存块号 * 页面大小 - 物理地址 = 内存起始地址 + 页面偏移量, 这个页面偏移量可以通过去低位得出. ## 如果有快表那又会是怎么样 - 快表是一种高速缓冲的存储器. 但是它存储能力是有限的 - 如果想要找的页号在快表中, 就不用区内存找页表了, 速度也会快得多. - 如果在快表中没有的话, 我们在查询页表的时候也要同时更新快表. 以保证最近访问的内存都在快表中. ## 什么是两级页表 ``` 假设一个页面4KB. 我们有4G内存, 而且是32位操作系统 那我们的页偏移量最大 = 4KB = 4 * 2^10 = 2 ^ 12 B 因此偏移地址占12位 那么页面号占20位 那么就有最多 2 ^ 20个页表项 假设一个页表项4B 4KB / 4B = 2 ^ 10 个页表项. ``` - 如果只是单级页表, 这个页表将会很庞大, 不符合我们非连续 分配地址的行为 - 我们把页表分为两级, 一级是页目录表, 二级才是页表 - 那么每一个小页表的大小都是4KB, 那么就可以依次放到内存块之中 - 那么我们的逻辑地址将会被分割为三部分, 分别是一级页号, 二级页号和偏移量. - 页目录表存放一级页号和其对应的页表的内存块号 - 我们首先通过一级页号找到其内存块号 - 页表地址 = 内存块号 * 页面大小 - 之后正常继续执行即可 - 不过我们搞了二级页表以后, 以前本来是两次访存, 现在要三次访存, 空间换时间. ## 说说基本分段管理 - 内存中分为不固定长的段, 程序员可以根据代码层次分段, 各段被加载到不同的内存地址中 - 我们寻找段的地址就要通过段表, 段表和页表一样//...(段号, 段长度, 段起始地址) - // ... ## 分段和分页有啥区别? - 分页是操作系统帮我们做好的, 对用户是不可见的, 分段需要程序员自己来分... - 分页查找物理地址, 只需给出逻辑地址 - 分段查找物理地址, 要给出段号, 段偏移量 ## 什么是段页式管理方式? // ... ``` PC --> 段号 | 页号 | 页偏移量 段表 --> 段号 | 页表长度 | 页表内存块号 页表 --> 页号 | 内存块号 ``` // ... ## 什么是虚拟内存管理方式? - 程序加入内存中, 不一定要把程序中所有的页一次性放入内存 - 因此在页表中会多了几项 --> (是否在内存中 | 访问标志 | 修改标志 ... ) - 加载进程运行环境, 查询页表, 发现页号对应的内存块不在内存中 - 那么线程会产生缺页中断, 阻塞等待IO. - 如果当前内存很满, 要发生页面置换, 就是选出一些页面换出内存 --> 页面置换算法. ## 具体说下请求分页式管理方式? 页表和基本分页存储管理有什么区别? // ... ## 说说页面置换算法? - OPT: 哪个会最后用到 - FIFO: 先进先出 - LRU: 哪个最久没用到 - NRU clock算法 ------------------------------------------------------------- ## 讲一讲系统调用? - 首先说说用户态和内核态的区别: 1. 用CS寄存器的低2位判断是用户态还是内核态, 3为用户态, 0为内核态 2. 内核态执行原语操作, 时钟管理, 进程调度等... 3. 用户态就是应用程序, 不能随意访问内核态的东西 4. 所以会通过系统调用来进行操作内核. - 系统调用 - 系统调用就是操作系统对上级提供的接口, 用来操作内核 - 一般采用int 0x80中断进入系统调用. - 为什么是0x80 - set_system_gate(0x80, &system_call) (system_call 是call eax里面存放的地址..) - 初始化时故意设下的"陷阱" - 一般系统调用函数展开里面有 - 把系统调用号放在eax --> int 0x80(syscall宏) - int 0x80 -> dpl设为3, eax取出系统调用号, call table中的函数地址. - 函数地址正是内核态的函数地址, 而且这个地址刚好cs后面两位为0, 就是核心态 - CPL(CS (当前特权级)), DPL(目标特权级) - int 0x80 --> dpl = 3 - call table[...] --> cpl = 0 数据密集型应用系统设计<file_sep>## 10. 用户级线程 - 为什么讲进程切换要线程? - 是否可以资源不动而切换指令序列? - 进程 = 资源 + 指令序列 - 线程: 保留了并发的优点, 避免了进程切换的代价(轻巧的指令序列. ) - 进程的切 = 指令的切 + 映射表的切. ``` void GetData(); void Show(); void WebExplorer() { char URL[] = "...." char buffer[1000]; pthread_create(..., GetData, URL, buffer); pthread_create(..., Show, buffer); } void Yield(); // 用户级线程交替切换 ``` #### 操作系统怎么切换多个进程( switch_to() ? ) - 每个线程要有一个栈 - - 函数调用是在内部发生的. ret时不能跳到其他线程 - 栈也要"切 "<file_sep>## 本次实验的基本内容是: 1. 用 Bochs 调试工具跟踪 Linux 0.11 的地址翻译(地址映射)过程,了解 IA-32 和 Linux 0.11 的内存管理机制; 2. 在 Ubuntu 上编写多进程的生产者—消费者程序,用共享内存做缓冲区; 3. 在信号量实验的基础上,为 Linux 0.11 增加共享内存功能,并将生产者—消费者程序移植到 Linux 0.11。 ## 对于地址映射实验部分,列出你认为最重要的那几步(不超过 4 步),并给出你获得的实验数据。 ## test.c 退出后,如果马上再运行一次,并再进行地址跟踪,你发现有哪些异同?为什么? ## share mem #### key_t key = ftok("/home/jt/project/c/os", 1); - 由项目路径 + id产生键<file_sep>## 操作系统的历史. #### 批处理系统. #### 多进程结构 OS 360! - 多道程序 - 作业之间交替切换和调度. #### 分时系统. MIT - 定期切换作业. #### 从MIT 到 UNIX #### 从UNIX到LINUX<file_sep>## 多进程图象。 #### 到底什么是多进程图像? - 启动了的程序就是进程, 所以是多个进程推进 - main的fork()创建了第一个进程 ``` if (!fork()) { init(); } ``` #### 操作系统怎么支持多进程图象 - PCB 放在不同队列中 - 推进各个进程状态转换 - "进程的切换" `schedule() { pNew = getNext(ReadyQueue); switch_to(pCur, pNew) }` - getNext: 进程的调度 -- 很多算法. - fifo.... - switch_to: 具体的切换: 根据PCB中的东西恢复现场 - 多进程如何影响? - 内存管理的内容. 实现地址的访问的分离 - 就是逻辑地址怎么转化为物理地址. - 多进程如何合作? - 核心在于进程同步 ### fork() #### fork() 功能 - fork()用于创建子进程 - 参见系统调用一章: 会执行内核态中的system_call.s中的以下片段代码 ``` .align 2 sys_fork: # 调用函数之后返回值存在eax中(是进程号pid) call find_empty_process # testl %eax,%eax来检查%eax是正数负数还是0; # %eax = %eax & %eax; testl %eax,%eax # 结果为负则转移。 js 1f # 进程当前的"样子"放入栈中(函数参数) push %gs pushl %esi pushl %edi pushl %ebp pushl %eax # copy_process: 复制代码段和数据段和环境 call copy_process addl $20,%esp 1: ret ``` ``` // 调用sys_fork第一个调用的函数 int find_empty_process(void) { int i; repeat: if ((++last_pid)<0) last_pid=1; for(i=0 ; i<NR_TASKS ; i++) if (task[i] && task[i]->pid == last_pid) goto repeat; for(i=1 ; i<NR_TASKS ; i++) if (!task[i]) return i; return -EAGAIN; } ``` ``` /* * Ok, this is the main fork-routine. It copies the system process * information (task[nr]) and sets up the necessary registers. It * also copies the data segment in it's entirety. */ // 用于创建并复制进程的代码段和数据段及环境 // 再进程复制的过程中, 主要工作设计进程数据结构中的信息复制(PCB) // 系统首先为新建的进程在主内存区申请一页内存来存放其任务数据结构信息 // 并且复制当前进程任务数据结构中的所有内容作为新进程任务数据结构模板. int copy_process(int nr,long ebp,long edi,long esi,long gs,long none, long ebx,long ecx,long edx, long fs,long es,long ds, long eip,long cs,long eflags,long esp,long ss) { struct task_struct *p; int i; struct file *f; // 申请一页内存 p = (struct task_struct *) get_free_page(); // 如果当前内存不足, 返回负值 if (!p) return -EAGAIN; // 进程数组中的第n个pcb为p? // 任务数组[nr] 项 // nr为任务号, 由find_empty_process返回 task[nr] = p; // 把当前进程任务结构内容复制到刚申请到的内存页面p开始处 /*--------------------------------------------------------*/ *p = *current; /* NOTE! this doesn't copy the supervisor stack */ /*--------------------------------------------------------*/ // 随后对复制来的进程结构内容做一些修改, 作为新进程的任务结构 // p: 新的进程 // 将新的进程的状态设置为不可中断等待状态, 防止复制一半的时候 // 发生内核调度. p->state = TASK_UNINTERRUPTIBLE; // 设置新进程的pid号和父进程的pid号 p->pid = last_pid; p->father = current->pid; // 初始进程的时间片值等于其priority值 p->counter = p->priority; // 信号位图 p->signal = 0; // 报警定时值 p->alarm = 0; // 领导标志 p->leader = 0; /* process leadership doesn't inherit */ // 进程及其子进程在内核和用户态的时间统计值 p->utime = p->stime = 0; p->cutime = p->cstime = 0; // 开始运行的系统时间 p->start_time = jiffies; // 修改进程tss数据 // 宏观上理解就是运行时状态, 把各个寄存器都存了. p->tss.back_link = 0; /** * 由于系统给任务p分配了一页新的内存 * PAGE_SIZE + (long) p;让esp0正好指向该页顶端. * ss0:esp0作为程序内核态中运行的栈 */ p->tss.esp0 = PAGE_SIZE + (long) p; p->tss.ss0 = 0x10; p->tss.eip = eip; p->tss.eflags = eflags; p->tss.eax = 0; p->tss.ecx = ecx; p->tss.edx = edx; p->tss.ebx = ebx; p->tss.esp = esp; p->tss.ebp = ebp; p->tss.esi = esi; p->tss.edi = edi; p->tss.es = es & 0xffff; p->tss.cs = cs & 0xffff; p->tss.ss = ss & 0xffff; p->tss.ds = ds & 0xffff; p->tss.fs = fs & 0xffff; p->tss.gs = gs & 0xffff; p->tss.ldt = _LDT(nr); p->tss.trace_bitmap = 0x80000000; /* 协处理器相关 */ if (last_task_used_math == current) __asm__("clts ; fnsave %0"::"m" (p->tss.i387)); /** * 复制进程页表: * 在线性地址空间中设置新任务代码段和数据段描述符中的基址 * 和限长 */ // 如果出错(返回值不是0) if (copy_mem(nr,p)) { // 复位任务数组中响应项 task[nr] = NULL; // 释放为该新任务分配的用于任务结构的内存页 free_page((long) p); // 返回错误 return -EAGAIN; } // 如果父进程中有文件是打开的, 则对应的文件打开次数 + 1 for (i=0; i<NR_OPEN;i++) if ((f=p->filp[i])) f->f_count++; // 因为这里父进程和子进程共享打开的文件, 因此如果他们不是0 // 都要增加 1 if (current->pwd) current->pwd->i_count++; if (current->root) current->root->i_count++; if (current->executable) current->executable->i_count++; // 设置gdt表表项 set_tss_desc(gdt+(nr<<1)+FIRST_TSS_ENTRY,&(p->tss)); set_ldt_desc(gdt+(nr<<1)+FIRST_LDT_ENTRY,&(p->ldt)); // 就绪态 p->state = TASK_RUNNING; /* do this last, just in case */ return last_pid; } ``` ``` /** * 复制内存页表 * @nr: 新进程pid号 * @*p: 新进程进程结构指针. * 该函数为新任务在线性地址空间中设置代码段和数据段基址, 限长, * 复制页表 * ----------------------------------------------* * 由于linux使用写实复制(copy on write) * 这里仅为新进程设置自己的页目录表项和页表项 * 没有为新进程分配物理内存页面, 此时新进程和父进程共享内存页面 * -------------------------------------------------* * 返回值: 成功返回0 */ int copy_mem(int nr,struct task_struct * p) { // 代码段和数据段基址, 限长 unsigned long old_data_base,new_data_base,data_limit; unsigned long old_code_base,new_code_base,code_limit; // 0x0f是数据段选择符 // 0x17是代码段选择符. // 详见include/linux/sched.h code_limit=get_limit(0x0f); data_limit=get_limit(0x17); old_code_base = get_base(current->ldt[1]); old_data_base = get_base(current->ldt[2]); if (old_data_base != old_code_base) panic("We don't support separate I&D"); if (data_limit < code_limit) panic("Bad data_limit"); // 设置创建中的进程在线性地址空间中基地址 = 64 MB * 任务号 new_data_base = new_code_base = nr * 0x4000000; // 那么该值就是新进程局部描述符表中段描述符中的基地址 p->start_code = new_code_base; set_base(p->ldt[1],new_code_base); set_base(p->ldt[2],new_data_base); // 设置新进程的页目录表项和页表项 if (copy_page_tables(old_data_base,new_data_base,data_limit)) { printk("free_page_tables: from copy_mem\n"); free_page_tables(new_data_base,data_limit); return -ENOMEM; } return 0; } ``` - main.c中关于文件描述符部分 ``` if (!fork()) { /* we count on this going ok */ init(); /* 这就是"进程1" */ } for(;;) pause(); /* 这就是"进程0" */ ``` - 为什么fork()子进程会返回0 ### wait.c - 当我们调用wait.c的时候实际上会调用以下代码 ``` 会跳到系统调用函数里面执行 pid_t wait(int * wait_stat) { return waitpid(-1,wait_stat,0); } ``` - 实则上调用exit.c中的int sys_waitpid(pid_t pid,unsigned long * stat_addr, int options) ``` // 调用该函数会挂起当前进程, 直到pid指定的子进程退出(终止) // 或者收到要求终止该进程的信号. // pid_t pid: 子进程id // unsigned long * stat_addr: 保存状态信息位置的指针 // int options: waitpid选项 int sys_waitpid(pid_t pid,unsigned long * stat_addr, int options) { // flag标志用于后面表示所选出的子进程处于就绪态或者睡眠态 int flag, code; // ??? // p可以理解为任务数组task[]的下标? struct task_struct ** p; verify_area(stat_addr,4); repeat: flag=0; // sched.h // #define FIRST_TASK task[0] // #define LAST_TASK task[NR_TASKS-1] // 从任务数组末端开始扫描所有任务 for(p = &LAST_TASK ; p > &FIRST_TASK ; --p) { // 如果task数组对应项为空, 或者就是当前进程, 那么直接continue if (!*p || *p == current) continue; // 如果扫到的进程的父进程不是该进程, 也要跳过 if ((*p)->father != current->pid) continue; // 如果等待的子进程号pid>0, 但与被扫描子进程p的pid不相等 // 说明它是当前进程的另外子进程, 也不符合要求 if (pid>0) { if ((*p)->pid != pid) continue; // 如果pid = 0, 说明正在等待的进程组号等于当前进程组号的 // 任何子进程, 如果进程组号不等则跳过. } else if (!pid) { if ((*p)->pgrp != current->pgrp) continue; // 绝对值 } else if (pid != -1) { if ((*p)->pgrp != -pid) continue; } // 能到这里说明pid = -1, // 表明进程在等待其任何子进程 // 接下来根据子进程状态来处理 switch ((*p)->state) { case TASK_STOPPED: // 子进程处于停止状态, // 如果没有WUNTRACED标志位, 没必要马上返回 // if (!(options & WUNTRACED)) continue; put_fs_long(0x7f,stat_addr); return (*p)->pid; case TASK_ZOMBIE: // 子进程处于僵死状态. // 先把它的用户态和内核态时间累计到父进程中 current->cutime += (*p)->utime; current->cstime += (*p)->stime; // 取出pid和退出码 flag = (*p)->pid; code = (*p)->exit_code; // 释放进程p release(*p); // 置状态信息和退出码值 put_fs_long(code,stat_addr); return flag; default: // 找到过一个符合要求的子进程, 但是他是运行态或者睡眠态 flag=1; continue; } } if (flag) { // WNOHANG: 表示若没有子进程处于退出或者终止状态就立刻返回 if (options & WNOHANG) return 0; // 否则把当前进程置为可中断等待状态并重新执行调度 // !!!! current->state=TASK_INTERRUPTIBLE; schedule(); if (!(current->signal &= ~(1<<(SIGCHLD-1)))) goto repeat; else return -EINTR; // 中断的系统调用 } return -ECHILD; } ``` ``` void schedule(void) { int i,next,c; struct task_struct ** p; /* check alarm, wake up any interruptible tasks that have got a signal */ // 从后往前扫描task数组. for(p = &LAST_TASK ; p > &FIRST_TASK ; --p) if (*p) { // p存在且设置过任务定时值alarm, 并且已经过期 // alarm < jiffies // 要在信号位图中置SIGALRM信号. 并且把这个任务的定时值清0 if ((*p)->alarm && (*p)->alarm < jiffies) { (*p)->signal |= (1<<(SIGALRM-1)); (*p)->alarm = 0; } // 如果信号位图中除了被阻塞的信号还有其他信号, 并且任务处于可中断 // 状态 // 说明p此时可以被调度. // ???/ if (((*p)->signal & ~(_BLOCKABLE & (*p)->blocked)) && (*p)->state==TASK_INTERRUPTIBLE) (*p)->state=TASK_RUNNING; } /* this is the scheduler proper: */ // 找到counter最大的进程. while (1) { c = -1; // 进程数组中的下一个的下标 next = 0; i = NR_TASKS; p = &task[NR_TASKS]; while (--i) { if (!*--p) continue; if ((*p)->state == TASK_RUNNING && (*p)->counter > c) c = (*p)->counter, next = i; } if (c) break; // 如果走到这里说明系统中没有TASK_RUNNING的进程 // 对每个存在的进程实行counter = counter / 2 + priority for(p = &LAST_TASK ; p > &FIRST_TASK ; --p) if (*p) (*p)->counter = ((*p)->counter >> 1) + (*p)->priority; } switch_to(next); } ``` ### 进程的N, J, R, W, E 1. 新建(N) -- fork - 在copy_process() return 之前添加 2. 进入就绪态(J) -- schedule - 在void schedule(void)中一开始遍历任务数组的时候, 若找到符合条件的p则将其变为可执行状态 3. 进入运行态(R) - switch_to(next) - schedule() 找到的 next 进程是接下来要运行的进程 - (注意,一定要分析清楚 next 是什么)。 - 如果 next 恰好是当前正处于运行态的进程, - swith_to(next) 也会被调用。这种情况下相当于当前进程的状态没变。 4. 进入阻塞态(W): - 在sys_waitpid中, 最后if(flag) (找到子进程, 但是子进程还在sleep/running), 父进程只好current->state=TASK_INTERRUPTIBLE; - 顺便打印. . 5. 退出(E); - wait()之中父进程会检查子进程是否已经是僵死状态, 是则回收释放 ### 进程的各个状态 1. TASK_RUNNING 运行状态 - 表示进程正在被CPU执行(运行), 或者已经拥有资源, 随时可以执行(就绪运行) - 运行还分为两种 1. 执行内核代码: 内核运行态 2. 执行用户代码: 用户运行态 - 当系统资源可用的时候, 进程就会被唤醒变成task_running状态 ``` // 位于sched.c中 if (((*p)->signal & ~(_BLOCKABLE & (*p)->blocked)) && (*p)->state==TASK_INTERRUPTIBLE) { (*p)->state=TASK_RUNNING; } ``` 2. TASK_INTERRUPTIBLE 可中断睡眠状态 - 当系统产生中断/等待资源释放, 都可以转换到就绪状态 3. TASK_UNINTERRUPTIBLE 不可中断睡眠状态 - 与可中断睡眠状态类似, 但是只能用wake_up() 来唤醒 4. TASK_STOPPED - 直接视为进程终止 5. TASK_ZOMBIE 僵死状态 - 进程停止运行, 但是父进程还没有调度到wait()询问其状态时候 - 当父进程调用wait的时候发现有子进程是zombie, 就会回收释放. - 什么是僵尸进程/孤儿进程 - 僵尸进程: 父进程没有调用wait等待子进程, 子进程的结构得不到释放 - 孤儿进程: 父进程比子进程先结束. - 它们都会被1号进程回收.. ### 修改时间片: 1. 进程counter是怎么初始化的? - 进程的counter就是时间片: 具体意思是"还能运行多少个滴答?" - 在一个进程创建的时候counter值 == 优先级 ``` // COPY_PROCESS内 ... p-> counter = p->priority; ... ``` 1. 当进程时间片用完的时候被初始化成什么值? - 当进程的时间片用完意味着不会被调度, - 当所有进程的时间片用完的时候 - 会导致找不到next, 因此又会执行上面那句话 - 又变成优先级了. ### 关于p->signal的理解(信号位图) - 共个32个bit, 因此有32个信号. 每个系统调用处理的过程最后, 会使用该位图进行预处理 - 信号 = 位偏移值 + 1 # sched.c的理解 - 包含的函数: - sleep_on(), wake_up(), schedule(); - 简单的getpid(), 时钟中断处理过程调用的do_timer() ### 对于**p的理解: 看书中282页的图 <file_sep>## 信号量的代码实现 ```c Prodecer(item) { P(empty); ... V(full) } main() { // 打开名字为empty的信号量 sd = sem_open("empty"); } typedef struct { char name[20]; int value; task_struct *queue; } semtable[20];1 sys_semo_open(char* name) { // 找到一个信号量 // 没有则创建 } ```<file_sep>## 段页结合的实际内存管理 ### 程序员希望用段, 物理内存希望用页.... ### 段页结合的轮廓 程序 -> 虚拟内存 -> 物理内存 这里画不了图哈哈 - 用户: cs:ip - 首先要找虚拟地址: 根据段表拿到段基址, 然后根据偏移量得到虚拟地址 - 然后找到物理地址: 通过分页机制, 首先查询页目录表然后查询页表找到物理地址 ### 段页结合的具体实现? 1. 故事的开始? - 肯定先让程序放入内存, 才能使用内存 - fork的内存分配~ 2. 整个过程分为几步 1. 割一块 2. 假装放在虚拟内存 3. 在物理内存中找一段 4. 建立页表, 真正载入物理内存 5. 真的使用内存 3. fork ``` int copy_process(int nr,long ebp,long edi,long esi,long gs,long none, long ebx,long ecx,long edx, long fs,long es,long ds, long eip,long cs,long eflags,long esp,long ss) { struct task_struct *p; int i; struct file *f; p = (struct task_struct *) get_free_page(); // ... if (copy_mem(nr,p)) { task[nr] = NULL; free_page((long) p); return -EAGAIN; } // ... return last_pid; } ``` ``` int copy_mem(int nr,struct task_struct * p) { unsigned long old_data_base,new_data_base,data_limit; unsigned long old_code_base,new_code_base,code_limit; code_limit=get_limit(0x0f); data_limit=get_limit(0x17); old_code_base = get_base(current->ldt[1]); old_data_base = get_base(current->ldt[2]); if (old_data_base != old_code_base) panic("We don't support separate I&D"); if (data_limit < code_limit) panic("Bad data_limit"); // 1. // 64M * nr // 赋给段表中的基址, 这就是虚拟地址!!!完成了对虚拟地址的分割 // 每个进程64M地址空间, 互补重叠 new_data_base = new_code_base = nr * 0x4000000; p->start_code = new_code_base; // 2. 完成了段表的建立 set_base(p->ldt[1],new_code_base); set_base(p->ldt[2],new_data_base); // 3. 分配内存, 建立页表! if (copy_page_tables(old_data_base,new_data_base,data_limit)) { printk("free_page_tables: from copy_mem\n"); free_page_tables(new_data_base,data_limit); return -ENOMEM; } return 0; } ``` ``` // from: 父进程的虚拟地址 // to: 子进程的虚拟地址 int copy_page_tables(unsigned long from,unsigned long to,long size) { unsigned long * from_page_table; unsigned long * to_page_table; unsigned long this_page; unsigned long * from_dir, * to_dir; unsigned long nr; if ((from&0x3fffff) || (to&0x3fffff)) panic("copy_page_tables called with wrong alignment"); // >> 22, and * = >> 20 // 找到页目录表中的响应项起始地址 from_dir = (unsigned long *) ((from>>20) & 0xffc); /* _pg_dir = 0 */ // 子进程的页目录项起始地址 to_dir = (unsigned long *) ((to>>20) & 0xffc); size = ((unsigned) (size+0x3fffff)) >> 22; for( ; size-->0 ; from_dir++,to_dir++) { if (1 & *to_dir) panic("copy_page_tables: already exist"); if (!(1 & *from_dir)) continue; from_page_table = (unsigned long *) (0xfffff000 & *from_dir); // 为子进程的新的页表分配物理内存 if (!(to_page_table = (unsigned long *) get_free_page())) return -1; /* Out of memory, see freeing */ // 子进程页目录项存子进程页表的地址 *to_dir = ((unsigned long) to_page_table) | 7; nr = (from==0)?0xA0:1024; for ( ; nr-- > 0 ; from_page_table++,to_page_table++) { this_page = *from_page_table; if (!(1 & this_page)) continue; this_page &= ~2; *to_page_table = this_page; if (this_page > LOW_MEM) { *from_page_table = this_page; this_page -= LOW_MEM; this_page >>= 12; mem_map[this_page]++; } } } invalidate(); return 0; } ``` ``` unsigned long get_free_page(void) { register unsigned long __res asm("ax"); __asm__("std ; repne ; scasb\n\t" "jne 1f\n\t" "movb $1,1(%%edi)\n\t" "sall $12,%%ecx\n\t" "addl %2,%%ecx\n\t" "movl %%ecx,%%edx\n\t" "movl $1024,%%ecx\n\t" "leal 4092(%%edx),%%edi\n\t" "rep ; stosl\n\t" "movl %%edx,%%eax\n" "1:" :"=a" (__res) :"0" (0),"i" (LOW_MEM),"c" (PAGING_PAGES), "D" (mem_map+PAGING_PAGES-1) ); return __res; } ``` - MMU - 负责逻辑地址 -> 线性地址 -> 物理地址 - 写时复制: <file_sep>## 生磁盘的使用 - 怎么让磁盘用起来 - 扇区大小512字节 - 磁盘的工作: 寻道 -- 旋转 -- 传输 - 柱面 -> 磁头 -> 扇区 -> 缓存位置 - 最后无非就是out指令 ### 第一层抽象 -- 通过一个block号算出sec, head, cyl(CHS) - 怎样给block编址? - 磁盘访问时间 = 写入控制器时间 + 寻道时间(花的时间最多) + 旋转时间 + 传输时间 - 尽量少寻道, 相邻盘块号尽量放在物理磁盘的相邻之处 - 每次读写的大小如果增大, 读写的速度会上升。 - 用空间换时间!!! 故意把读写的单位变大, 操作系统"认定"成一个盘块, 解释为连续扇区, 操作系统会根据你给的盘块号算出chs, 再通过out发给磁盘控制器操作磁盘 - b = c * (heads * sectors) * h * sectors + s - heads: 磁头数目 - sectors: 扇区数 ### 第二层抽象 -- 多进程通过队列使用磁盘 - 多个进程通过队列有序访问磁盘 - 什么时候从队列取出来呢? - 肯定是磁盘中断的时候 - 磁盘干完一件事就会中断一次 - 磁盘调度算法: 让寻道时间越少越好 - fcfs - sstf: 短寻道优先, 经过**顺便**处理 - scan: 磁盘调度(电题算法·)<file_sep>## 一個實際的調度函數 -- schedlue() -- 详见《源码》 -- counter = counter / 2 + proriety ### counter作用 1. (充当时间片) counter保证响应时间的界, 体现了"照顾"响应 2. IO时间越长, counter就会越大, 照顾了IO约束性 3. 后台进程一直按照counter轮转, 近似了SJF调度. 4. 每个进程只维护了counter变量, 简单又高效!<file_sep>## 进程通信的几种方式 1. 共享内存地址通信: 假如进程a要和进程b通信, 进程a不能直接访问进程b的地址空间, 因为每个进程的地址空间都是独立的 因此, 进程a会把通信内容放到共享内存块, 在共享内存存取数据是互斥的, 因此进程b要等a释放对共享内存块的锁才能访问, 这样就完成了进程间通信 这种共享内存有两种: 基于数据结构的共享内存/基于存储区的共享内存 2. 管道通信: 我的理解就是假如有进程a和进程b想要通信, 进程a好像给进程b开了一条半双工的管道一样, 其实这条管道就是一页, 4KB 对于这样一条管道也是互斥的而且满足写完才能读, 读完才能写 3. 类似计网的报文, 消息队列通信, 发送原语接收原语 ,进程a想要和进程b通信, 会把消息放在b的消息队列中, 或者放在信箱中 ## 说说核心态和用户态 - CPU处于用户态, 只能执行非特权指令, CPU处于和心态, 能执行非特权指令和特权指令 - 这两种状态是程序状态字寄存器里面的某一位, 0为用户态1为核心态 - 根据这两种状态分为内核程序和应用程序 - 操作系统的时钟管理, 原语操作,中断处理, 进程调度都是核心程序完成的, 至于设备管理哪些要看你是什么操作系统 - 如果是微内核那就是用户态执行, 微内核结构清晰但速度慢, 大内核要写大量核心程序代码, 但是速度快 ## 线程和进程的区别是什么, 线程的实现方式? - 线程是程序运行的最小单位, 进程是系统资源分配的最小单位, 线程几乎不拥有系统资源, 多个线程可以共享同个资源, 多个进程无法共享资源, 只能通信 - 切换开销: 线程的切换开销比较小, 可以在用户程序中自行实现. 进程的切换开销比较大, 要调用中断跳到内核态来进行进程切换, 而且要保存上下文, 重新载入新的进程的上下文, 从PCB进程控制块来载入. - 内核级线程/用户及线程 ## 说说用户级线程和内核级线程? 多线程模型, 优点? - 用户级线程顾名思义, 就是用户能看到的线程。 - 内核级线程和用户及线程相反, 是操作系统能看到的线程。因为操作系统只能看到内核级线程, 所有操作系统的时间片只会分给内核级线程 - 举个例子, 如果一个进程有多个用户级线程, 那其实操作系统不知道, 只知道这是一个进程罢了 - 一对多, 一对一, 多对多 - 一对多: 多个用户及线程对应一个内核级线程 - 优点: 线程的切换只在同一个进程中, 开销小, 而且保持在用户态. - 缺点: 整个进程只能占有CPU的一个核, 因此当有一个用户及线程阻塞的时候, 其他也会阻塞. 并发度不高 - 一对一: 一个用户及线程对应一个内核级线程 - 优点: 可以使用CPU的多个核, 即使一个线程被阻塞了, 其他线程也不会阻塞, 并发度高 - 缺点: 切换线程要在内核态中执行, 所以开销大 - 多对多: m映射n ## 说说三层调度。 - 高级调度(作业调度): 进程从无到有的过程, 无 --> 创建 --> 就绪。 一般都是从外存加载放到内存中, 并设置响应PCB - 中级调度(内存调度): 如果内存不足, 会把一部分程序设为挂起态, 放到外存中的挂起队列, PCB仍然保留内存中, 因为该进程还属于调度管理范围 - 初级调度(进程调度): 理解为进程调度: 就绪 --> 运行 ## 讲讲进程调度方式? 什么时候不能进程调度? - 进程的调度方式分为抢占式和非抢占式 - 不能: 1. 处理中断的过程中 2. 操作系统内核临界区 3. 原子操作的过程中 ## 说说几种调度算法 从简单到复杂说起 - 优点 - 缺点 - 是否引起饥饿 1. 先来先服务FCFS: 维护一个队列, 进程按照加入时间放到队尾 - 优点: 比较公平 - 缺点: 花费时间比较小的线程要等待很久 - 是否引起饥饿: 否 2. 短时间优先SJF: 1. 非抢占式: 每次都取出所有当前线程中的花费时间最小的来执行 2. 抢占式:每次都取出所有当前线程中的花费时间最小的来执行, 当有一个新的进程加入时, 会先检查当前运行进程的剩余时间, 如果剩余时间大于加入进程的运行时间, 那么会抢占当前进程 - 优点:用户等待时间总体比较短, 对花费时间比较短的进程友好 - 缺点: 用户虚假报时, 对长时间作业的进程不友好 - 是否引起饥饿: 会, 如果一直有短时间进程加入, 那么长时间的进程得不到运行 3. 高相应比有限算法HRRF 相应比就是 [用户等待时间 + 服务时间 / 服务时间] - 优点:用户等待时间总体比较短, 不管进程服务时间长短都可以充分得到运行. - 缺点: - 是否引起饥饿: 不会. 因为等待时间越久相应比越高 4. 时间片轮转 - 类比一下刚刚说的先来先服务, 只不过加了一个时间片, 进程在时间片内如果没有执行完, 将会被抢夺运行权 放到队尾, - 优点:用户等待时间总体比较短, 不管进程服务时间长短都可以充分得到运行. - 缺点: 高频路切换进程, 开销比较大. 不能区分紧急任务 - 是否引起饥饿: 不会. 等待时间一致 5. 线程优先级 - 类比高响应比, 把对比的方式改为优先级。 也分为抢占式和非抢占式 - 优点:区分紧急任务 - 缺点: 用户虚假报时, 对低优先级的进程不友好 - 是否引起饥饿: 会 6. 多级反馈队列 - 将进程等待区域分为多级队列, 按优先级从高到低, 时间片从小到大排列(指数) 1. 进程加入时从最高优先级加入 2. 一个进程执行完时间片若还没结束将被放至下一级队列队尾 3. 当有比当前优先级更高的进程加入的时候, 会抢占当前进程, 当前进程会被放到本层队尾 4. 只有k层没进程, k+1层才会得到执行 ## 进程互斥的实现方法(软件/硬件)? 1. 单标志法 ``` int a = 0; // 标志 // 进程1 P1 { while (a == 0); // dosomething ... a = 1; } // 进程2 P2 { while (a == 1); // dosomething ... a = 0; } ``` 2. 双标志法 (1) 先判断 ``` int[] flag = new int[2]; flag[0] = false; // 进程进入临界区意愿 flag[1] = false; // 进程1 P1 { while (flag[1]); flag[0] = true; // dosomething ... flag[0] = false; } // 进程2 P2 { while (flag[0]); flag[1] = true; // dosomething ... flag[1] = false; } ``` (2) 后判断 ``` int[] flag = new int[2]; flag[0] = false; // 进程进入临界区意愿 flag[1] = false; // 进程1 P1 { flag[0] = true; while (flag[1]); // dosomething ... flag[0] = false; } // 进程2 P2 { flag[1] = true; while (flag[0]); // dosomething ... flag[1] = false; } ``` 3. Peterson算法 ``` int[] flag = new int[2]; flag[0] = false; // 进程进入临界区意愿 flag[1] = false; int turn = 0; // 进程谦让位 // 进程1 P1 { flag[0] = true; turn = 1; while (flag[1] && turn == 1); // dosomething ... flag[0] = false; } // 进程2 P2 { flag[1] = true; turn = 0; while (flag[0] && turn == 0); // dosomething ... flag[1] = false; } - 硬件 1. 中断实现互斥 关中断; // do something 开中断; 2. turn and set lock bool lock; bool turnAndSetLock(bool lock) { bool old = lock; lock = true; return lock; } while (turnAndSetLock(lock)); // do some thing lock = false; 3. swap (XCHG) lock = false; // 进程 P { bool tmp = true; while (tmp) { swap(lock, tmp); } // do some thing lock = false; } ``` ## 原语具体怎么实现的? - 首先原语是在内核态中完成的 - 通过关中断和开中断实现 - 有创建进程/阻塞唤醒/销毁进程原语 ## 信号量怎么实现的? 有什么类型? ## 说说两种类型的PV操作 1. 整形信号量 ``` int mutex = 1; // 系统资源数目 void wait(int mutex) { while (mutex == 0) ; mutex--; } void signal(int mutex) { mutex ++; } // P1 { wait(mutex); // 访问临界资源 signal(mutex); } P2 { wait(mutex); // 访问临界资源 signal(mutex); } ``` 2. 结构型信号量 ``` struct { int val; // 资源数目 struct process queue; // 等待队列 } semaphorn semaphorn mutex; // 系统资源数目 mutex.val = 1; void wait(int mutex) { mutex.val--; if (mutex.val < 0) { // 阻塞原语 block(mutex.queue); } } void signal(int mutex) { mutex.val++; if (mutex.val <= 0) { // 唤醒原语 wakeup(mutex.queue); } } // P1 { wait(mutex); // 访问临界资源 signal(mutex); } P2 { wait(mutex); // 访问临界资源 signal(mutex); } ``` ## PV操作是怎么实现互斥, 同步, 前驱的? ## 说说生产者和消费者问题(多消费者生产者呢? ) ## 说说吸烟者问题 ## 说说读者写着问题 ## 说说管程 ## 死锁产生的条件? ## 说说死锁和死循环、饥饿的区别 ## 怎么避免死锁? ## 说说银行家算法? ## 说说死锁检测算法? 数据密集型应用系统设计<file_sep>- 此次实验的基本内容是:在 Linux 0.11 上添加两个系统调用,并编写两个简单的应用程序测试它们。 1. 修改unistd.h ``` // ... #define __NR_iam 72 #define __NR_whoami 73 // ... ``` 2. 修改sys.h ``` // ... extern int sys_iam(); extern int sys_whoami(); // ... // 在数组添加上面两个内容 fn_ptr sys_call_table[] = {sys_setup, sys_exit, sys_fork, sys_read, sys_write, sys_open, sys_close, sys_waitpid, sys_creat, sys_link, sys_unlink, sys_execve, sys_chdir, sys_time, sys_mknod, sys_chmod, sys_chown, sys_break, sys_stat, sys_lseek, sys_getpid, sys_mount, sys_umount, sys_setuid, sys_getuid, sys_stime, sys_ptrace, sys_alarm, sys_fstat, sys_pause, sys_utime, sys_stty, sys_gtty, sys_access, sys_nice, sys_ftime, sys_sync, sys_kill, sys_rename, sys_mkdir, sys_rmdir, sys_dup, sys_pipe, sys_times, sys_prof, sys_brk, sys_setgid, sys_getgid, sys_signal, sys_geteuid, sys_getegid, sys_acct, sys_phys, sys_lock, sys_ioctl, sys_fcntl, sys_mpx, sys_setpgid, sys_ulimit, sys_uname, sys_umask, sys_chroot, sys_ustat, sys_dup2, sys_getppid, sys_getpgrp, sys_setsid, sys_sigaction, sys_sgetmask, sys_ssetmask, sys_setreuid, sys_setregid, sys_iam, sys_whoami}; ``` 3. 修改system_call.s ``` // ... nr_system_calls = 74 // ... ``` 4. 书写who.c + iam.c + whoami.c; 5. 修改makefile<file_sep>## 内存的分区和分页 - 将代码段和数据段放到内存中 - 取指执行, 把逻辑地址转换为物理地址 - ldtr是存放ldt表起始地址的寄存器, 也会存放在进程的ocb之中, 当进程被调度到的时候, 会把这个进程的ldtr加载到当前寄存器, 那么cpu就能去到进程对应的ldt表根据选择子选出合适的地址 1. 分段 2. 找出空闲分区 3. 将映射表做好 ### 如何在内存中找出空闲区域? 1. 固定分区 2. 可变分区 - 维护空闲分区表和已分配分区表 - 选取什么分区给段请求? 1. 最佳适配 2. 最差适配 3. 首先适配 ### 为什么要有分页, 分段不是已经足够了吗? - 分区的效率不高, 很多内存碎片 - 内存够但却放不进去!!!! - 可以使用内存紧缩进行内存移动, 不过耗费时间... - 利用mem_map[] 将内存分页! - 以页为单位分配内存 - 不用进行内存紧缩! 内存浪费很少 - 物理内存需要分页 - 用户需要分段 ### 页已经载入内存, 怎么让程序跑起来? - 维护"页表" - 页表地址寄存器 -- cr3 - 根据逻辑地址算出是那一页, 算出偏移量 - 然后去页表中通过 页号拿出页框号 - 通过页框号我们就可以拿出物理地址起始地址, 然后再加上偏移量, 就真正得出物理地址 - MMU: 内存管理单元<file_sep>## 死锁的处理. - 银行家 ? - 如果是以下这种顺序? P { P(mutex); P(empty); // ... V(mutex); V(full); } C { P(mutex); P(full); // ... V(mutex); V(empty); } - 会阻塞!!! - 相互依赖... - 形成了循环等待圈(环路等待) - 互相等待对方造成死锁 ### 死锁的成因 1. 资源互斥使用, 一旦占有别人无法使用 2. 资源不可抢占, 只能自愿放弃 3. 进程占有其他资源, 又不释放, 再去申请其他资源 4. 循环等待 ### 死锁的处理方法 1. 死锁预防; 破坏死锁的必要条件条件. - 一次申请所有资源 1. 一次申请所有资源, 需要预知未来编程困难 2. 分配资源很长时间才使用, 利用率低 - 资源按顺序申请 1. 仍然造成资源浪费 2. 死锁避免; 检测每个资源的请求, 如果造成超标, 就拒绝 - 判断此次请求是否引起死锁, 判断所有进程存在一个可完成的执行序列p1, ... pn, 则称系统是安全的 - 执行的代价很大... - 假装分配, 算一下有没有安全序列. - 如果没有安全序列, 此次申请被拒绝, 说明可能造成死锁 3. 死锁检测 + 恢复; 检测到死锁出现让进程回滚, 让出资源 - 发现问题再处理 - 找到死锁进程组(谁也执行不下去) - 挑一个进程再回滚 - 怎么回滚? 回滚到有安全序列 - 选择谁回滚? - 怎么实现回滚? 难以实现 4. 死锁忽略; 就好像没出现死锁一样<file_sep>#include <linux/kernel.h> #include <asm/segment.h> /* linux-0.11/include/asm */ #include <unistd.h> #include <signal.h> #include <linux/sched.h> #include <asm/system.h> #define MAX_NAMELEN 20 struct semaphore * sems[SEM_SIZE] = { NULL }; void show_sem() { int i; for (i = 0; i < SEM_SIZE; i++) { if (sems[i]) { printk("%s:%d ", sems[i]->name, sems[i]->value); } } printk("\n"); } // return the array idx of semaphore sem_t sys_opensem(char* name, int value) { char sem_name[MAX_NAMELEN] = { 0 }; int namelen = 0, i = 0; while (get_fs_byte(name + namelen) != '\0') { namelen++; } if (namelen > MAX_NAMELEN) return -1; while (i < namelen) { char ch = get_fs_byte(name + i); sem_name[i++] = ch; } sem_name[i] = '\0'; printk("sys_opensem(%s, %d)!\n",sem_name, value); // find an empty slot and create; i = 0; int tmp; int same; // check if there is same name? while (i < SEM_SIZE) { if (!sems[i]) { i++; continue; } tmp = 0; char *name = sems[i]->name; while (name[tmp]) tmp++; if (tmp != namelen) { i++; continue; } same = 1; tmp = 0; while (tmp < namelen) { if (name[tmp] != sem_name[tmp]) { same = 0; break; } tmp++; } if (same) { // printk("exist the sem [%s], will just return.\n", sem_name); return i; } i++; } // now should create a sem; i = 0; while (i < SEM_SIZE) { if (!sems[i]) { // printk("create a sem [%s] :)\n", sem_name); struct semaphore *s; s = (struct semaphore *) malloc(sizeof(struct semaphore)); char* n = (char*) malloc(sizeof(char) * namelen); int j = 0; while (sem_name[j]) { n[j] = sem_name[j]; j++; } s->name = n; s->value = value; s->p = (struct task_struct*) malloc(sizeof(struct task_struct)); sems[i] = s; return i; } i++; } return NULL; } int sys_waitsem(sem_t s) { // show_sem(); cli(); // printk("sys_waitsem(%d)!\n", s); if (!sems[s]) return -1; sems[s]->value--; // printk("decrease sem [%s]'s value, and it is [%d]\n", // sems[s]->name, sems[s]->value); if (sems[s]->value < 0) { sleep_on(&(sems[s]->p)); } sti(); return 0; } int sys_postsem(sem_t s) { cli(); // printk("sys_postsem(%d)!\n",s); if (!sems[s]) return -1; sems[s]->value++; // printk("increase sem [%s]'s value, and it is [%d]\n", // sems[s]->name, sems[s]->value); if (sems[s]->value <= 0) { wake_up(&(sems[s]->p)); } sti(); return 0; } int sys_unlinksem(char* name) { char sem_name[MAX_NAMELEN] = { 0 }; int namelen = 0, i = 0; while (get_fs_byte(name + namelen) != '\0') { namelen++; } if (namelen > MAX_NAMELEN) return -1; while (i < namelen) { char ch = get_fs_byte(name + i); sem_name[i++] = ch; } sem_name[i] = '\0'; printk("sys_unlinksem(%s)!\n", sem_name); i = 0; int tmp; int same; while (i < SEM_SIZE) { if (!sems[i]) { i++; continue; } tmp = 0; char *name = sems[i]->name; while (name[tmp]) tmp++; if (tmp != namelen) { i++; continue; } same = 1; tmp = 0; while (tmp < namelen) { if (name[tmp] != sem_name[tmp]) { same = 0; break; } tmp++; } if (same) { printk("exist the sem [%s], now delete it.\n", sem_name); sems[i] = NULL; return 0; } i++; } printk("not find the same [%s] :(\n", sem_name); return -1; }<file_sep>#include <asm/memory.h> #include <linux/mm.h> #include <linux/kernel.h> #include <linux/sched.h> #include <asm/segment.h> #define LOW_MEM 0x100000 #define PAGING_MEMORY (15*1024*1024) #define PAGING_PAGES (PAGING_MEMORY>>12) extern unsigned char mem_map [ PAGING_PAGES ] ; struct shm_struct * shms[SHARED_SIZE] = { NULL, }; int sys_shmget(int key, int size) { int i; struct shm_struct* tmp; // printk("sys_shmget(%d)\n", key); if (size <= 0 || size > PAGE_SIZE) return -1; // find the same key for (i = 0; i < SHARED_SIZE; ++i) { if (shms[i] && shms[i]->key == key) { // printk("find the same key [%d] and will return.\n", key); return i; } } // find the empty slot for (i = 0; i < SHARED_SIZE; ++i) { if (!shms[i]); break; } // no empty slot if (i == SHARED_SIZE) { printk("the is no empty slot!\n"); return -1; } // make the struct tmp = (struct shm_struct*) malloc(sizeof(struct shm_struct)); // init tmp tmp->key = key; tmp->addr = 0; if (!(tmp->addr = get_free_page())) { printk("can't not get a free page!\n"); free(tmp); return -1; } shms[i] = tmp; return i; } // make the addr to the buf void * sys_shmat(int shmid) { unsigned long addr; unsigned long tmp, *page_table; // printk("sys_shmat(%d)\n", shmid); if (!shms[shmid]) { printk("shms[%d] is NULL:( !!\n", shmid); return NULL; } // printk("start code: 0x%lx\n", current->start_code); addr = current->brk; current->brk += PAGE_SIZE; put_page(shms[shmid]->addr, addr + current->start_code); mem_map[(shms[shmid]->addr-LOW_MEM)>>12]++; // printk("physical addr is 0x%x\n", shms[shmid]->addr); // printk("linear addr is 0x%x\n", addr + current->start_code); // printk("logic addr is 0x%x\n", addr); return (void *) addr; }<file_sep>## 文件使用磁盤的實現 - 写磁盘为例 ```c int sys_write(unsigned int fd,char * buf,int count) { struct file * file; struct m_inode * inode; if (fd>=NR_OPEN || count <0 || !(file=current->filp[fd])) return -EINVAL; if (!count) return 0; inode=file->f_inode; if (inode->i_pipe) return (file->f_mode&2)?write_pipe(inode,buf,count):-EIO; if (S_ISCHR(inode->i_mode)) return rw_char(WRITE,inode->i_zone[0],buf,count,&file->f_pos); if (S_ISBLK(inode->i_mode)) return block_write(inode->i_zone[0],&file->f_pos,buf,count); // 会进入这里~~~~ if (S_ISREG(inode->i_mode)) // inode: 文件索引 // file: 进程文件描述表 // buf: 要写的缓存 // count: 要写的长度 return file_write(inode,file,buf,count); printk("(Write)inode->i_mode=%06o\n\r",inode->i_mode); return -EINVAL; } ``` ``` int file_write(struct m_inode * inode, struct file * filp, char * buf, int count) { off_t pos; int block,c; struct buffer_head * bh; char * p; int i=0; /* * ok, append may not work when many processes are writing at the same time * but so what. That way leads to madness anyway. */ // 增长写 if (filp->f_flags & O_APPEND) pos = inode->i_size; else pos = filp->f_pos; while (i<count) { // block 表示在磁盘中的第几块 if (!(block = create_block(inode,pos/BLOCK_SIZE))) break; if (!(bh=bread(inode->i_dev,block))) break; // 在块中的偏移 c = pos % BLOCK_SIZE; p = c + bh->b_data; bh->b_dirt = 1; c = BLOCK_SIZE-c; if (c > count-i) c = count-i; pos += c; if (pos > inode->i_size) { inode->i_size = pos; inode->i_dirt = 1; } i += c; while (c-->0) *(p++) = get_fs_byte(buf++); brelse(bh); } inode->i_mtime = CURRENT_TIME; if (!(filp->f_flags & O_APPEND)) { filp->f_pos = pos; inode->i_ctime = CURRENT_TIME; } return (i?i:-1); } ``` ### 如何根据filp, inode, buf, count进行磁盘读写 1. 在sys_write中判断是对磁盘的读写, 进入file_write 2. 在file_write中通过filp得到pos, 就是偏移量, 通过pos可以算出在本文件的第几个盘块 pos / BLOCK_SIZE.通过create_block得到逻辑盘块, 就是缓存 3. 既然得到逻辑盘块, 那么直接往逻辑盘块中写就行了<file_sep> #include<unistd.h> #include<linux/kernel.h> #include<fcntl.h> sem_t *sem_open(char* name, int value); int sem_wait(sem_t* sem); int sem_post(sem_t* sem) ; int sem_unlink(char* name);<file_sep>## 实验要求 1. 用信号量解决生产者—消费者问题 - 在 Ubuntu 上编写应用程序“pc.c”,解决经典的生产者—消费者问题,完成下面的功能: 1. 建立一个生产者进程,N 个消费者进程(N>1); 2. 用文件建立一个共享缓冲区; 3. 生产者进程依次向缓冲区写入整数 0,1,2,...,M,M>=500; 4. 消费者进程从缓冲区读数,每次读一个,并将读出的数字从缓冲区删除,然后将本进程 ID 和 + 数字输出到标准输出; 5. 缓冲区同时最多只能保存 10 个数。 - 实现信号量 - 实现一套山寨版的完全符合 POSIX 规范的信号量 ``` sem_t *sem_open(const char *name, unsigned int value); int sem_wait(sem_t *sem); int sem_post(sem_t *sem); int sem_unlink(const char *name); ``` 1. sem_open() 的功能是创建一个信号量,或打开一个已经存在的信号量。 - sem_t 是信号量类型,根据实现的需要自定义。 - name 是信号量的名字。不同的进程可以通过提供同样的 name 而共享同一个信号量。如果该信号量不存在,就创建新的名为 name 的信号量;如果存在,就打开已经存在的名为 name 的信号量。 - value 是信号量的初值,仅当新建信号量时,此参数才有效,其余情况下它被忽略。当成功时,返回值是该信号量的唯一标识(比如,在内核的地址、ID 等),由另两个系统调用使用。如失败,返回值是 NULL。 - sem_wait() 就是信号量的 P 原子操作。如果继续运行的条件不满足,则令调用进程等待在信号量 sem 上。返回 0 表示成功,返回 -1 表示失败。 - sem_post() 就是信号量的 V 原子操作。如果有等待 sem 的进程,它会唤醒其中的一个。返回 0 表示成功,返回 -1 表示失败。 - sem_unlink() 的功能是删除名为 name 的信号量。返回 0 表示成功,返回 -1 表示失败。 在 kernel 目录下新建 sem.c 文件实现如上功能。然后将 pc.c 从 Ubuntu 移植到 0.11 下,测试自己实现的信号量。 ## 踩坑记录 1. sem_open()的用法, 和sem_init()的初始化 2. pc.c文件我本来写了个队列, 但是发现进程之间不能共享堆空间!!!准备改写共享内存/文件 3. open的信号量如果没有destory,是跟内核共存的....., 因此如果程序写的不好, 忘记destory了, 会导致奇怪的结果4 4. 传进去read的buf要先申请内存~~~ 5. 在栈区的char*不能直接分配给内存中的struct ## POXI信号量 - https://blog.csdn.net/anonymalias/article/details/9219945 ## 多进程共享文件 - off_t lseek(int fd, off_t offset, int whence) 1. whence = SEEK_SET, 则将该文件的偏移量设置为据文件开始处offset个字节 2. whence = SEEK_CUR, 则将该文件的偏移量设置为当前值加offset. 3. whence = SEEK_END, 则将该文件的偏移量设置为文件长度加offset. - <file_sep>## 我们的任务是什么? <file_sep>- 实验网址 https://www.shiyanlou.com/courses/115 - 操作系统实验配置环境脚本 https://github.com/DeathKing/hit-oslab - 课程网址 https://www.bilibili.com/video/av51437944 - linux命令大全 https://www.runoob.com/linux/linux-command-manual.html - linux 教程 https://linuxtools-rst.readthedocs.io/zh_CN/latest/base/index.html - 删除目录: - rmdir(空) - rm -rf (r是递归选项, f是强制删除不提示) - 关闭防火墙: - sudo service ufw stop - sudo ufw disable - gdb基础命令 https://linux265.com/course/linux-command-gdb.html<file_sep># 進程同步和信號量 - 多進程的合作是合理有序! ### 爲什麽要有信號量? - 因爲要使得多個進程按照一定順序向前推進 - 進程間要合作!!! - 有時候不合作後果很嚴重!!!(司機和售票員) - 每個進程都有自己的一套執行方案, 但不是隨便執行的 - 但是要通過信號來促進各個進程之間的合作 . #### 生產者-- 消費者問題 - 要有一個量 - 信號量是判斷需要發信息的變量.有多少個進程在等待 ### 如何通過信號量使得多進程推進合理有序? ```c struct semaphore { int val; PCB* queue; } P(semaphore s); // 消費資源 V(semaphore s); // 產生資源 P(semaphore s) { --s.value; if (s.value < 0) { sleep(s.queue); } } V(semaphore s) { ++s.value; if (s.value <= 0) { wake_up(s.queue); } } ``` ### 信號量經典問題 - https://blog.csdn.net/fjtooo/article/details/102997932<file_sep>## 内存换出 - 一直get_free_page()也不行 ## 运用什么算法找一页进行淘汰 -- 评测标准: 缺页次数 - FIFO - 有可能刚换出又换入 - 极为慢 - MIN - 将最远使用的淘汰 - 这个要预测未来 - 怎么可能实现.? - LRU: 选最近最长一段时间没有使用的页面淘汰 -- 过去历史预测未来(局部性!) ## LRU的准确实现 -- 时间戳 - 为每个页维护一个时间戳, 表明什么时候使用过, 要换出的时候就看看哪一页是时间戳最小的, 说明最久没用过, 就把哪一页给换出 ## LRU准确实现 -- 维护一个页面栈 - 每执行一条指令都要往下沉, 代价也很大 ## LRU近似实现 - 将时间计数变为是和否 - 为每个页加一个引用位(ref bit) - 最近访问过就是1, - 淘汰算法: 是1清零, 是0就淘汰! - 可以放在页表中, 让MMU代劳 - 别名clock算法 - 现实情况是缺页很少发生, 导致全是1 - 当有缺页, 指针会转一圈, 然后拿出一个 - 这样就退化成FIFO了!!! ## CLOCK算法的改进 -- - CLOCK记录了太长的历史信息, 因此要定时清除R位 - 再来一个扫描指针 - 真的是clock!!! - 快指针负责清除R位, 放在时钟中断 - 慢指针来选择淘汰页, 放在缺页中断 ## 颠簸/抖动 - 指的是随着进程个数的增加. CPU的利用率增加 - 但是进程太多CPU利用率急剧下降 - 就是因为每个进程分配的实际物理页少, 频繁换入换出 - 就是磁盘和内存之间不停进行页面换入换出 ## 工作集? ## 给一个进程要分配多少页框? - 最好是动态调整 - 也要限制进程的数量<file_sep>#include <sys/stat.h> #define BUFFER_SIZE 4 #define FREE "/free_c" #define MUTEX "/mutex_c" #define PRODUCT "/product_c" #define FILE_MODE S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP #define KEY 1234 #define FLAG 0666 struct buf { int head; int tail; int buffer[BUFFER_SIZE]; }; int poll(); void offer(int val);<file_sep># exp4 ## 回答下面三个题: - 问题1 : 针对下面的代码片段: ``` movl tss,%ecx addl $4096,%ebx movl %ebx,ESP0(%ecx) copy ``` - 回答问题: 1. 为什么要加 4096; - ebx存储的是next进程的地址, 因为为进程申请了一页内存, 增加4096刚好指向栈顶 - (栈的增长是由高地址向低地址增长的) 2. 为什么没有设置 tss 中的 ss0 - tss.ss0是内核数据段,现在只用一个tss,因此不需要设置了。 - 问题 2 : 针对代码片段: ``` *(--krnstack) = ebp; *(--krnstack) = ecx; *(--krnstack) = ebx; *(--krnstack) = 0; ``` - 回答问题: 1. 子进程第一次执行时,eax=?为什么要等于这个数?哪里的工作让 eax 等于这样一个数? - eax = 0, 让子进程返回0区分父进程和子进程 2. 这段代码中的 ebx 和 ecx 来自哪里,是什么含义,为什么要通过这些代码将其写到子进程的内核栈中? - 是swtch_to参数, 因为要造出能切的样子. 而且子进程是父进程的副本, 因此直接把父进程的ebx, ecx置给它 3. 这段代码中的 ebp 来自哪里,是什么含义,为什么要做这样的设置?可以不设置吗?为什么? - 父进程, 用户栈基址. 不能不设置, 栈的切换包括esp的切换和ebp的切换. - 问题 3 - 为什么要在切换完 LDT 之后要重新设置 fs=0x17?而且为什么重设操作要出现在切换完 LDT 之后,出现在 LDT 之前又会怎么样? - 我们通过fs来访问用户态内存, 如果不设置/在之前设置, 访问的还是之前的用户态内存 ### link - [寄存器逻辑结构图](https://www.zhihu.com/question/291255701/answer/474405270) - [lldt指令](http://blog.sina.com.cn/s/blog_5a75aaa501013ktq.html) ### 实验目标 - 本次实践项目就是将 Linux 0.11 中采用的 TSS 切换部分去掉,取而代之的是基于堆栈的切换程序。具体的说,就是将 Linux 0.11 中的 switch_to 实现去掉,写成一段基于堆栈切换的代码。 本次实验包括如下内容: 1. 编写汇编程序 switch_to: 2. 完成主体框架; - 在主体框架下依次完成 PCB 切换、内核栈切换、LDT 切换等; - 修改 fork(),由于是基于内核栈的切换,所以进程需要创建出能完成内核栈切换的样子。 - 修改 PCB,即 task_struct 结构,增加相应的内容域,同时处理由于修改了 task_struct 所造成的影响。 - 用修改后的 Linux 0.11 仍然可以启动、可以正常使用。 (选做)分析实验 3 的日志体会修改前后系统运行的差别。 ### TSS 切换 - 所谓的 TSS 切换就将 CPU 中几乎所有的寄存器都复制到 TR 指向的那个 TSS 结构体中保存起来,同时找到一个目标 TSS,即要切换到的下一个进程对应的 TSS,将其中存放的寄存器映像“扣在” CPU 上,就完成了执行现场的切换. ### switch_to要做的事 ``` pushl %ebp movl %esp, %ebp # 栈基址 pushl %ecx # push当前参数 pushl %ebx pushl %eax movl 8(%ebp), %ebx # 把下一个进程地址放在ebx中 cmpl %ebx, current # 如果当前进程和next相同, 则什么也不做. je 1f ``` 1. 切换PCB ``` mov %ebx, %eax xchgl %eax, current ``` 2. TSS中内核栈指针的重写 - tss: 0号进程的tss地址. - %ebx: next进程的地址 - ESP0: tss结构中esp0的偏移量 ``` movl tss, %ecx # 将0号进程的tss地址放到ecx中 addl $4096, %ebx # 下一个进程的地址向上增长4K(一页), 刚好就是栈顶 movl %ebx, ESP0(%ecx) # 把栈顶地址放在tss结构中 ``` 3. 切换内核栈 - 现在的esp是当前栈顶, 我们要拿到下一个esp, 对当前esp进行修改, 栈就切过去了! - 切换esp之后我们要拿到当前栈基址ebp - 我们之前已经push ebp ---- 在自己的栈中放好自己的ebp, 然后切换. - 因此我们待会pop出来的ebp, 就是当前栈基址!!! ``` mov %ebx, %esp ``` 4. 切换LDT ``` mov 12(%ebp), %eax lldt %ax movl $0x17, %ecx mov %cx, %fs ``` 5. 切换pc指针. - 执行switch中的ret会跳到schedule() 的 "}", 然后再返回会跳到中断处理中(ret_from_sys_call); - 因此会有iret, pop各种当前内核栈中存的当前用户态的寄存器, 然后再跳到用户态 ### fork.c要做的事 - 把进程变成"能切"的样子 1. 要"抄袭"父进程的用户态: INT 0x80: ss, esp, eflag, cs, eip 2. 思考一下父进程怎么到达copy_process() 的? - sys_call - sys_fork ### sched.h 和 sched.c,<file_sep>## 信号量的临界区保护. - 靠临界区保护信号量 - 靠信号量来让进程走走停停 ### 为什么要保护信号量/引出临界区 - 不光要读信号量, 也要写信号量!(共同修改变量) - 进程的调度是随机的 - 有一些可能性的调度会使得共享数据发生错误 - 竞争条件!!! - 直观想法: 在写共享变量empty之前阻止其他进程访问empty! (给empty上锁) - 就是: 一段代码一次只能允许一个进程进入. (原子操作!) - 临界区: 一次只允许一个进程进入 的 该进程的那一段代码(成对出现. ) ### 怎么保护信号量/实现临界区 - 基本原则: 1. 互斥! 2. 有空让进 3. 有限等待 - 三种方法! - 软件方法 1. 轮换法 ``` P1 { while (turn != 0); // 临界区 turn = 1; // 剩余区 } P2 { while (turn != 1); // 临界区 turn = 0; // 剩余区 } ``` 1. 标记法 ``` // !!会死锁 P1 { flag[0] = true; while (flag[1]); // 临界区 flag[0] = false; // 剩余区 } P2 { flag[1] = true; while (flag[0]); // 临界区 flag[1] = false; // 剩余区 } ``` 1. 非对称标记(Peterson) ``` P1 { flag[0] = true; turn = 1; while (flag[1] && turn == 1); // 临界区 flag[0] = false; } P2 { flag[1] = true; turn = 0; while (flag[0] && turn == 0); // 临界区 flag[1] = false; } ``` - 互斥进入: 假设两个人都在临界区, 那么flag[0] == flag[1] == true, turn == 0 == 1, 因此不可能 - 有空让进: P0不在临界区, 那么flag[0] == false || turn == 1;那么P1能进入 - 有限等待: 一个进程不可能循环跑(类似值日) 1. 多进程怎么办? -- 面包店算法 - 仍然是标记和轮转结合 - 每个进程获得一个序号, 序号最小的进入 - 怎么标记? 离开时候序号为0, 不为0的序号就是标记 - 硬件方法: 中断 - 多cpu不好使 ``` cli(); // 临界区 sti(); ``` -- 中断的本质: intr寄存器 - cpu每执行一条指令都会看有没有中断...? 在寄存器里面 - 关中断, 就是cpu不看! - 多cpu: 每个cpu都有这么个玩意, - tsl - test and set lock! bool TestAndSet(bool x) { bool rv = x; x = true; return rv; } - 另外还有xchg... .<file_sep>#include <stdio.h> #include <fcntl.h> #include "buff.h" #include "sem.h" void offer(int val); int main(int argc, char *argv[]) { int id; int procucts; int i; sem_t *empty; sem_t *product; sem_t *mutex; char* s; if (argc != 3) { printf("error params! please input like this: ./cus [id] [products]\n"); return -1; } printf("argv[1] = %s, argv[2] = %s\n", argv[1], argv[2]); for (i = 0, id = 0, s = argv[1]; s[i]; ++i) { id *= 10; id += s[i] - '0'; } for (i = 0, procucts = 0, s = argv[2]; s[i]; ++i) { procucts *= 10; procucts += s[i] - '0'; } printf("producer[%d] start to make [%d] products!\n", id, procucts); if (!(product = sem_open(PRODUCT, 0))) { printf("error to open sem product\n"); return -1; } if (!(empty = sem_open(FREE, BUFFER_SIZE))) { printf("error to open sem empty\n"); return -1; } if (!(mutex = sem_open(MUTEX, 1))) { printf("error to open sem mutex\n"); return -1; } for (i = 0; i < procucts; i++) { sem_wait(empty); sem_wait(mutex); offer(i); printf("producer [%d] make a product [%d]!\n", id, i); sem_post(mutex); sem_post(product); } return 0; } <file_sep>## 关闭标准输出, 然后输出到文件中 ```c #include<fcntl.h> #include<unistd.h> #include<stdio.h> int main() { close(STDOUT_FILENO); int fd = open("stdout.txt", O_CREAT | O_RDWR); printf("%d\n", fd); printf("Hello world!\n"); } ``` ## lseek 1. 对于管道/套接字... lseek返回-1, 表示不是random access file! 2. 注意文件偏移量可以大于当前文件长度, 这会在文件中形成一个空洞, 全部用'\0'代替, 但这是允许的. 下次write的时候会增加文件长度. 中间的空洞不用分配磁盘块 - 使用od命令可以查看文件内容!(字符形式) ## read - 创建的buf的size最好比read的size大1. ## 用O_APPEND标志可以防止文件错乱~且不用原子操作<file_sep># CPU调度策略 - 选出一个进程next来执行. ### FIFO - 先来先服务. ### Priority - 任务短适当优先 - 可以随时降低/提高优先级 ### 算法要让什么更好 - 周转时间(任务进入到任务结束) - 操作尽快响应(操作到响应) - 吞吐量(完成的任务量) ### 怎样合理? - 折衷和综合. - 响应时间小 -> 切换次数多 -> 系统内耗大 -> 吞吐量小 - IO约束性/CPU约束性 - IO约束性优先级更高!稍微执行一段, 就IO了, 能与其他CPU约束性进程更好并行执行 - 简单! ## 各种CPU调度算法 ### First come, First Served(FCFS) - 先来先服务. ### 短作业优先(SJF) ### 时间片轮转调度(RR) ### 设置优先级 - 前台任务用RR, 后台任务用SJF, 前台和后台之间采用优先级(饥饿) - 因此要让后台任务优先级有动态的提升<file_sep># So what is LDT/GDT? ### GDT - GDT是全局描述符表. - 一个CPU对应一个GDT表, GDT表可以放在内存的任何地方, 但是CPU必须要知道它在哪里 - **GDTR**就是用来存放GDT表的入口地址. - GDTR中存放的是GDT在内存中的基地址和其表长界限。 - 由GDTR访问GDT表是通过段选择子(Selector)来进行的. - 段选择子是一个16位的寄存器 ### LDT - LDT是局部描述符表. - 每个进程都有一张LDT表 - GDT为一级描述符表, LDT为二级描述符表 - LDT和GDT从本质上是相同的, LDT嵌套在GDT表之中. LDTR记录局部描述符表的起始位置 - LDT表中存放的是什么? 与GDTR不同,LDTR的内容是一个段选择子 - LDTR可以随时改变.(lldt指令) ### summary - linux0.11中, 程序逻辑地址到物理地址的转换使用了CPU的全局段描述符表GDT和局部段描述符表LDT, 由GDT映射的地址空间称其为全局地址空间, 由LDT映射的地址空间成为局部地址空间, 而这两者构成了虚拟地址空间. ### 关于jmpi 0, 8 首先会执行这两句指令 ``` mov ax, 1H mov cr0, ax ``` cr0当最后一位是1表示保护模式 因此现在是保护模式, 在执行jmpi 0, 8 因此现在cs是8, 是一个段选择子 在此之前会初始化gdt表 ``` gdt: .word 0, 0, 0, 0 .word 0x07FF, 0x0000, 0x9A00, 0x00C0 .word 0x07FF, 0x0000, 0x9200, 0x00C0 ``` 可以看出一个GDT表项是4个word组成. 一个word是16B, 因此是64B 根据GDT表项获得当前地址位0x0000<file_sep>## 操作系统的启动 - 把操作系统从磁盘上载入到内存中, 才能取指执行 - 接下来就是setup.s ``` setup.s -> 将计算机的"样子"让操作系统记住, 要开始接管硬件! -> 初始化 start: .... int 0x10 -> 取光标位置 ... int 0x15 mov [2], ax -> 设置扩展内存大小: 操作系统要管理内存, 要知道内存大小 cli -> 不允许中断 mov ax, #0x0000 cld -> 改变copy方向 do_move: mov es, ax add ax, #0x1000 cmp ax, #0x9000 jz end_move mov ds, ax sub di, di sub si, si mov cx, #0x8000 rep -> ds:si -> es:di => 9000:0 -> 0000:0 copy movsw jmp do_move .... // 从十六位机切换到32位(保护模式) mov ax, #0x0001 mov cr0, ax --> cr0 : 最后一位0: 16, 1: 保护模式 .... gdt: ... -> 初始化gdt表 .... jmpi 0, 8 --> cs放的是查表索引 --> 保护模式: 物理地址 = cs查表 + ip(gdt表) --> 结果是0地址 1. 读硬件参数 2. 设置为保护模式 3. 跳到0地址处(system) ``` - MakeFile - head.s ``` ... call setup_idt call setup_gdt -> 初始化idt/gdt表 .... je lb -> 开启20号地址线 .... -> 通过压栈来调到main.c after_page_tables: pushl $0 pushl $0 pushl $0 pushl $L6 -> 返回地址 pushl $_main jmp set_paging ```<file_sep>## 操作系统的接口 - 接口(interface) - 用户怎么使用计算机? 1. 命令行 2. 图形按钮 3. 应用程序 - answer: system call -> 系统调用 - 有什么具体的操作系统接口: -> printf -> open -> fork -> .... - POSIX -> IEEE 指定的标准簇 使得代码可以在不同操作系统上跑 - 什么是操作系统接口? - 就是叫做系统调用的函数 - 是非常具体的东西!<file_sep>## IO和显示器 - 计算机怎么让外设工作? - CPU给相应的控制器的寄存器写东西/发指令 - 卡控制器进行处理, 具体操控设备 - 完事之后向CPU发出中断 - out xxx, al ```c int fd = open("dev/xxx/"); // ... write(...) // ... close(); ``` ``` printf("..", ...) { // .. write(1, buf, ...) // .. } ``` write 之中会进行分支: 判断往哪里写? ``` // 不管是什么fd, 都是从内存中的buf写一段长度count! int sys_write(unsigned int fd,char * buf,int count) { struct file * file; struct m_inode * inode; // 从fd对应到一个文件 if (fd>=NR_OPEN || count <0 || !(file=current->filp[fd])) return -EINVAL; if (!count) return 0; // 取出文件信息 inode=file->f_inode; if (inode->i_pipe) return (file->f_mode&2)?write_pipe(inode,buf,count):-EIO; if (S_ISCHR(inode->i_mode)) return rw_char(WRITE,inode->i_zone[0],buf,count,&file->f_pos); if (S_ISBLK(inode->i_mode)) return block_write(inode->i_zone[0],&file->f_pos,buf,count); if (S_ISREG(inode->i_mode)) return file_write(inode,file,buf,count); printk("(Write)inode->i_mode=%06o\n\r",inode->i_mode); return -EINVAL; } ``` 在fork.c中有这么一段 ```c // 拷贝父进程 *p = *current; // ... for (i=0; i<NR_OPEN;i++) if ((f=p->filp[i])) f->f_count++; // ... ``` 可以看出在复制进程的时候会复制文件描述符表, 并且他们指向相同的文件表项<file_sep>#define __LIBRARY__ #include <unistd.h> #include <linux/kernel.h> _syscall2(int, getshm, int, key, int, size) _syscall1(void *, atshm, int, shmid) int shmget(key_t key, size_t size, int flag) { int i; if ((i = getshm(key, size)) == -1) { printf("system call error!\n"); return -1; } return i; } void *shmat(int shmid, void *addr, int flag) { void* ptr; /* ptr = (void *) malloc(sizeof(void)); */ if (!(ptr = atshm(shmid))) { printf("system call error!\n"); return NULL; } /* printf("the ptr to shm is %p\n", ptr);*/ return ptr; } <file_sep>## 揭开的钢琴的盖子 ### 从启动开始说起! #### 神秘的黑色背后发生了啥? - 取指执行! - 打开电源计算机的第一条指令是什么? (PC = ?) 1. 开机时cpu处于实模式 2. 开机时CS = 0xFFFF, IP = 0x0000 3. 物理地址 = CS << 4 + IP = 0xFFFF0; 寻址0xFFFF0(ROM BIOS映射区) 4. 检查RAM, 键盘, 显示器, 软硬键盘 5. 将磁盘0磁道0扇区读入0x7c00处 - 一个扇区: 512字节 - 把磁盘中的。。。读出来放到内存0x7c00处 - 磁盘0磁道0扇区是什么呢? 引导扇区! - 做了什么事? - 引导扇区代码bootsect.s(汇编) - **为什么不用c?** - c要经过编译, 编译之后可能无法对内存进行控制 - 汇编操作的是硬件, 能起完整控制的作用 ``` --> BOOTSEG = 0x07c0 --> INITSEG = 0x9000 --> SETUPSEG = 0x9020 start: mov ax, #BOOTSEG mov ds, ax --> ds = 07c0 mov ax, #INITSEG mov es, ax --> es = 9000 mov cx, #256 sub si, si sub di, di --> 清零 --> tips: ds:si(7c00), es:di(90000) rep movw --> 重复移动字 --> rep: 重复执行该语句直至寄存器cx为0 --> movw: 将DS:SI的内容送至ES:DI,note! 是复制过去,原来的代码还在 --> 移动256次(512字节): 把bootstep的内存中的代码从7c00挪到90000 --> 要**腾出空间** jmpi go, INITSEG -> 会把go赋给ip, INITSEG赋给cs. --> 跳到,INITSEG(0x9000):go处执行 --> bootstep已经放在内存90000的地方, 而bootstep之后就是go --> 意思是跳到90000之后的bootstep之后(其实是顺序执行, 但必须写. ) go: ..... load_setup: ..... ..... ..... int 0x13 --> 什么是13: 读磁盘中断 --> ah = 0x02 - 读磁盘, al = 扇区数量 --> cl = 柱面号, cl = 开始扇区 --> dh = 磁头号, dl = 驱动器号 --> es:bx = 内存地址 第二扇区开始读, 读STUPLEN个扇区, 柱面号为0, 开始扇区为2 --> 磁头号为0, 驱动器号为0. --> 内存地址是: 90200(读512字节) j load_setup 重读 Ok_load_setup: ...... int 0x10 --> 显示字符中断 - 网上查阅! ``` 6. 设置cs = 0x07c0, ip = 0x0000 - bios从现在要调到0x7c00处 #### 关于"通用图灵机" - 把程序放到内存中, 用指针指向它 - [自动]取指执行 ### 为什么要把system模块放在起始位置? - 这样处理物理地址可以直接拿到 ### 为什么要等到setup.s才移动system模块? - setup需要利用ROM BIOS的中断调用获取机器的参数. - ROM BIOS初始化会在内存起始地址放一个中断向量表, - 因此拿取完信息方才能进行初始化 <file_sep>## CPU管理的直观想法. #### 怎么管理cpu? - 多道程序交替执行. (并发) #### 首先学会使用CPU! - CPU 的工作原理 -- 取指执行 - PC 设置一个初始值 --> 让其取指 #### 怎么做到的? - 修改寄存器PC就行了吗? - 还要保存运行环境, 各种寄存器的值... (PCB: 程序执行到哪了, 执行的瞬间的**样子**是什么? ) - 这也是静态的程序和运行中的程序的区别. #### 引入进程的概念! - 刻画运行中的程序. - 进程有开始有结束, 程序没有 - 进程会走走停停, 程序不会 - 进程需要记录各个寄存器, 程序不用.
5807fe92966340dbd09d818ffc06a8c36f5f50c7
[ "Markdown", "C" ]
52
C
Nagisa12321/os
a54be8e18b313c19d6fd0a0ae42dcebc9efcec92
d8b269b6331f49f861ef8fcb3767f15f4e7e5ae3
refs/heads/master
<repo_name>a1bertwang/SmartLock<file_sep>/SmartLock/PBPrivateFuncation.h // // PBPrivateFuncation.h // SmartLock // // Created by A1bert on 2017/3/9. // Copyright © 2017年 PlumBlossom. All rights reserved. // #ifndef PBPrivateFuncation_h #define PBPrivateFuncation_h #ifdef DEBUG //A better version of NSLog #define PBLog(format, ...) do { \ fprintf(stderr, "------------------------------------------------------------------------------------\n"); \ (NSLog)((format), ##__VA_ARGS__); \ fprintf(stderr, "\n<%s : %d> %s\n", \ [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], \ __LINE__, __func__); \ fprintf(stderr, "------------------------------------------------------------------------------------\n"); \ } while (0) #else //A better version of NSLog #define PBLog(format, ...) do {} while (0) #endif #endif /* PBPrivateFuncation_h */
3e15699f5860edb15631d460dc9156496da5b8b8
[ "C" ]
1
C
a1bertwang/SmartLock
c6b673a0795fa74d93f50ccbca45eb25157fe1ed
eb974a55a9b0104a91d83ff6e40dc68a01630956
refs/heads/master
<file_sep>using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Security.Claims; namespace AuthenticationBasics.Controllers { [ApiController] [Route("api/[controller]")] public class HomeController : ControllerBase { [HttpGet] public IActionResult GetHome() { return Ok(new { response = "Data anyone can see" }); } [Authorize] [HttpGet("secret")] public IActionResult GetSecretInfo() { return Ok(new { response = "Private data" }); } [HttpGet("authenticate")] public IActionResult Authenticate() { var userClaim = new List<Claim>() { new Claim(ClaimTypes.Name, "lfallon"), new Claim(ClaimTypes.Email, "<EMAIL>") }; var licenseClaim = new List<Claim>() { new Claim(ClaimTypes.Name, "lance fallon"), new Claim("LicenseNumber", "340874074502702075047") }; var userIdentity = new ClaimsIdentity(userClaim, "userIdentity"); var licenseIdentity = new ClaimsIdentity(licenseClaim, "licenseIdentity"); var userPrincipal = new ClaimsPrincipal(new[] { userIdentity, licenseIdentity }); HttpContext.SignInAsync(userPrincipal); //Response.Cookies.Append("Auth.Cookie", "Password"); return Ok(); } } }
2d8754f8788826f2688784534f7f4da45be1213b
[ "C#" ]
1
C#
lfallo1/AuthBasics
977e11b30310b8f2b803ea590658640b2e53d1da
2287fb14f48d7bcfbe1ec576d3cd5f638dcc76f6
refs/heads/master
<repo_name>RodriBrc/GitHubPrueba<file_sep>/src/entidades/github.java package entidades; public class github { private String name; private String adress; private Integer dni; private Integer age; private Integer bornAge; private String atrib2; private String bla; private String pepe; private Integer sisters; private String lol; public github() { } public github(String name, String adress, Integer dni, Integer age) { this.name = name; this.adress = adress; this.dni = dni; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAdress() { return adress; } public void setAdress(String adress) { this.adress = adress; } public Integer getDni() { return dni; } public void setDni(Integer dni) { this.dni = dni; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "github{" + "name=" + name + ", adress=" + adress + ", dni=" + dni + ", age=" + age + '}'; } }
666caf89a224611109d2f7d737b5143e8f864cb1
[ "Java" ]
1
Java
RodriBrc/GitHubPrueba
e109deb7a3127e6ddb9a3e7201476436f630363e
148c54aa863e1dd1fa2bedbbf9eaa13c8167ba1d
refs/heads/master
<file_sep>## @file enemy.py # Source file for enemy object # # Project: Gallaga Clone # Author: <NAME> # Created: 10/17/19 from actor import Actor import random import constants as const ## @class Enemy # @brief Implements Actor base class as Enemy object class Enemy(Actor): ## Constructor # @param image, surface object with Enemy image def __init__(self, image): Actor.__init__(self, image) self.direction = random.randrange(-1, 2) * const.ENEMY_SPEED if self.direction > 0: self.rect.left = const.SCREENRECT.left else: self.rect.right = const.SCREENRECT.right # For now we are not letting enemies reload ## Function to update the enemy def update(self): self.rect[0] = self.rect[0] + self.direction if not const.SCREENRECT.contains(self.rect): self.direction = - self.direction self.rect.top = self.rect.bottom + 10 self.rect = self.rect.clamp(const.SCREENRECT) ## Checks for collisions # @param actor, check collisions with this actor # @returns bool, True if collision is detected; false, otherwise def collision_check(self, actor): return self.rect.colliderect(actor.rect) <file_sep>var searchData= [ ['shot_2epy',['shot.py',['../shot_8py.html',1,'']]] ]; <file_sep># Project Sources ## Images * Space Background - [cnn.com](https://cdn.cnn.com/cnnnext/dam/assets/150103074330-hubble-space-background-2-full-169.jpg) * Player Spaceship - [opengameart.org](https://opengameart.org/content/rocket) * Enemy Spaceship - [opengameart.org](https://opengameart.org/content/spaceship-2d) * Missile - [kenney.nl](https://kenney.nl/assets/space-shooter-extension) <file_sep>var searchData= [ ['run',['run',['../classgame_1_1_game.html#a5ac60e090ecb22edd8fe33073b45866e',1,'game::Game']]] ]; <file_sep>var searchData= [ ['shot',['Shot',['../classshot_1_1_shot.html',1,'shot']]], ['shot_2epy',['shot.py',['../shot_8py.html',1,'']]] ]; <file_sep>## @file game.py # Source file for game class # # Project: Gallaga Clone # Author: <NAME> # Created: 10/14/19 import pygame import os.path import sys import random from player import Player from enemy import Enemy from shot import Shot from pygame.locals import * import constants as const ## @class Game # @brief Runs the game session and manages all actors class Game: ## Constructor # @post: Game components have been initialized def __init__(self): # Initialize pygame pygame.init() # Initialize member variables self.screen = pygame.display.set_mode(const.SCREENRECT.size, 0) self.clock = pygame.time.Clock() self.quit = False # Setup Game Window icon = pygame.image.load('assets/images/player_ship.png') icon = pygame.transform.scale(icon, (60, 80)) pygame.display.set_icon(icon) pygame.display.set_caption('Gallaga Clone') pygame.mouse.set_visible(0) ## Loads and scales object/game image # @author: Kristi # @pre: image exists # @param: filename, name of image to be loaded # @param: width, desired width of image # @param: height, desired height of image # @returns: Surface object def load_image(self, filename, file_width, file_height): # Load image filename = os.path.join('assets/images', filename) img = pygame.image.load(filename) # Scale image img = pygame.transform.scale(img, (file_width, file_height)) # Make transparent img.set_colorkey(img.get_at((0,0)), RLEACCEL) return img.convert() ## Runs the game session # @pre: Game components have been initialized # @post: Game has been exited properly def run(self): # Load Images background_img = pygame.image.load('assets/images/space.jpg') player_img = self.load_image('player_ship.png', 45, 65) enemy_img = self.load_image('enemy_spaceship.png', 26, 26) shot_img = self.load_image('missile1.png', 10, 24) # Load Background background = pygame.Surface(const.SCREENRECT.size) for x in range(0, const.SCREENRECT.width, background_img.get_width()): background.blit(background_img, (x, 0)) self.screen.blit(background, (0, 0)) pygame.display.flip() # Initialize Starting Actors player = Player(player_img) enemies = [Enemy(enemy_img)] shots = [] actors = [] # Game loop while player.alive and not self.quit: self.clock.tick(const.FPS) # Call event queue pygame.event.pump() # Process input key_presses = pygame.key.get_pressed() right = key_presses[pygame.K_RIGHT] left = key_presses[pygame.K_LEFT] shoot = key_presses[pygame.K_SPACE] exit = key_presses[pygame.K_q] # Check for quit conditions if pygame.event.peek(QUIT) or exit: self.quit = True break # Update actors for actor in [player] + enemies + shots: render = actor.erase(self.screen, background) actors.append(render) actor.update() # Remove out-of-frame shots for shot in shots: if shot.rect.top <= 0: shots.remove(shot) # Move the player x_dir = right - left player.move(x_dir) # Create new shots if not player.reloading and shoot and len(shots) < const.MAX_SHOTS: shots.append(Shot(shot_img, player)) player.reloading = shoot # Create new alien if not int(random.random() * const.ENEMY_ODDS): enemies.append(Enemy(enemy_img)) # Check for collisions for enemy in enemies: if enemy.collision_check(player): player.alive = False for shot in shots: if shot.collision_check(enemy): enemies.remove(enemy) # Draw actors for actor in [player] + enemies + shots: render = actor.draw(self.screen) actors.append(render) # Update actors pygame.display.update(actors) actors = [] # Exit game and system pygame.display.quit() pygame.quit() sys.exit() <file_sep>var searchData= [ ['enemy',['Enemy',['../classenemy_1_1_enemy.html',1,'enemy']]], ['enemy_2epy',['enemy.py',['../enemy_8py.html',1,'']]], ['erase',['erase',['../classactor_1_1_actor.html#a6a623e54b2ca7f1791ea89372afbe480',1,'actor::Actor']]] ]; <file_sep>## @file player.py # Source file for player object # # Project: Gallaga Clone # Author: <NAME> # Created: 10/17/19 from actor import Actor import constants as const ## @class Player # @brief Implements Actor base class as Player object class Player(Actor): ## Constructor # @param image, surface object with Player image def __init__(self, image): Actor.__init__(self, image) self.alive = True self.reloading = False self.rect.centerx = const.SCREENRECT.centerx self.rect.bottom = const.SCREENRECT.bottom ## Moves player in a specific direction # @pre: Player object exists # @param: direction, coordinates that represent desired move # @post: Player location has been updated def move(self, direction): self.rect = self.rect.move(direction * const.PLAYER_SPEED, 0).clamp(const.SCREENRECT) <file_sep># Gibbonga (EECS448: Project 3) Gallaga arcade game clone using Python and Pygame. ## Getting Started Python can be downloaded [here](https://www.python.org/downloads/). Make sure to add Pygame as well, using the command ``` python3 -m pip install -U pygame --user ``` To play the game, run main with Python through terminal. ``` python3 ./main.py ``` ## Built With * [Python](https://www.python.org/) - Version 3.7.1 * [Pygame](https://www.pygame.org/news) - Game language library * [Doxygen](http://www.doxygen.nl/) - Documentation generation ## Authors * **<NAME>** - [amalkhatib90](https://github.com/amalkhatib90/) * **<NAME>** - [k19c90](https://github.com/k19c90) * **<NAME>** - [kdaigh](https://github.com/kdaigh) * **<NAME>** - [elefert400](https://github.com/elefert400) * **<NAME>** - [clareMeyer](https://github.com/clareMeyer) See also the list of [contributors](https://github.com/kdaigh/gibbonga/graphs/contributors) who participated in this project. ## Documentation [Doxygen](http://www.doxygen.nl/) was used to provide [documentation](https://github.com/kdaigh/gibbonga/tree/master/docs/html) for this project. ## Versioning This is an prototype version that will be further developed in a separate repository. ## Acknowledgments Please read [SOURCES.md](https://github.com/kdaigh/gibbonga/tree/master/docs/SOURCES.md) for a works cited. <file_sep>var searchData= [ ['collision_5fcheck',['collision_check',['../classenemy_1_1_enemy.html#a339fff6f51710e42818b4b4e8379c97b',1,'enemy.Enemy.collision_check()'],['../classshot_1_1_shot.html#a94b1204146f71947ab2a9a292ebba043',1,'shot.Shot.collision_check()']]], ['constants_2epy',['constants.py',['../constants_8py.html',1,'']]] ]; <file_sep>## @file actor.py # Source file for actor base class # # Project: Gallaga Clone # Author: <NAME> # Created: 10/17/19 import pygame from pygame.locals import * ## @class Actor # @brief Abstract base class for game actors class Actor: ## Constructor # @param image, surface object with Actor image def __init__(self, image): self.image = image self.rect = image.get_rect() ## Abstract method; Updates actor in frame def update(self): pass ## Draws the actor into the screen # @param screen, screen which actor will be drawn onto # @returns render, new render of actor def draw(self, screen): render = screen.blit(self.image, self.rect) return render; ## Removes the actor from the screen # @param screen, screen which actor will be erased from # @param background, background that will be drawn over actor # @returns render, new render of actor def erase(self, screen, background): render = screen.blit(background, self.rect, self.rect) return render; <file_sep>var searchData= [ ['update',['update',['../classactor_1_1_actor.html#aef45dfd5490083692799b66ab8f0a329',1,'actor.Actor.update()'],['../classenemy_1_1_enemy.html#a65aaeda8241be972b0c3c6a233a0f302',1,'enemy.Enemy.update()']]] ]; <file_sep>## @file shot.py # Source file for shot object # # Project: Gallaga Clone # Author: <NAME> # Created: 10/17/19 import pygame from actor import Actor ## @class Shot # @brief Implements Actor base class as Shot object class Shot(Actor): ## Constructor # @param image, surface object with Shot image # @param player, Player object that fired the shot def __init__(self, image, player): Actor.__init__(self, image) self.rect.centerx = player.rect.centerx self.rect.top = player.rect.top - 5 # Updates the shot object def update(self): self.rect.top = self.rect.top - 10 ## Checks for collisions # @param actor, check collisions with this actor # @returns bool, True if collision is detected; false, otherwise def collision_check(self, actor): return self.rect.colliderect(actor.rect)<file_sep>## @file constants.py # File containing game constants # # Project: Gallaga Clone # Author: <NAME> # Created: 10/18/19 from pygame.locals import * # Frames Per Second FPS = 40 # Window Size SCREENRECT = Rect(0, 0, 640, 480) # Player Speed PLAYER_SPEED = 12 # Enemy ENEMY_SPEED = 4 ENEMY_ODDS = 24 ENEMY_SIZE = (26, 26) # Shots MAX_SHOTS = 5 SHOT_SPEED = 10 <file_sep>## @file main.py # Main file for project # # Project: Gallaga Clone # Author: <NAME> # Created: 10/17/19 from game import Game new_game = Game() new_game.run() <file_sep>var searchData= [ ['draw',['draw',['../classactor_1_1_actor.html#ab2a549fa31de3c311263294b0a76738f',1,'actor::Actor']]] ]; <file_sep>var searchData= [ ['shot',['Shot',['../classshot_1_1_shot.html',1,'shot']]] ]; <file_sep>var searchData= [ ['actor',['Actor',['../classactor_1_1_actor.html',1,'actor']]], ['actor_2epy',['actor.py',['../actor_8py.html',1,'']]] ]; <file_sep>var searchData= [ ['move',['move',['../classplayer_1_1_player.html#afd279e43eb9d940e4132aca7837f09d2',1,'player::Player']]] ];
d23d1711aec12c3595d887d9682d3a4e9c75f397
[ "JavaScript", "Python", "Markdown" ]
19
Python
kdaigh/gibbonga-prototype
725e3af5ef0ad43e0ef997fa307939979ad51f92
66cfad761bb17522371c4f72b31236e9b66078f1
refs/heads/master
<file_sep># FRCNewTabCA Custom new tab page for Chrome (other browsers coming soon) which displays information about a random FIRST Robotics Competition team along with a picture of their most recent robot. CANADIAN version. ![Screenshot](screenshots/1.png) ![Screenshot](screenshots/2.png) ![Screenshot](screenshots/3.png) ## Installation The packaged extension can be downloaded [here](https://chrome.google.com/webstore/detail/dennopgbicbgjgpiodhmedbjnkdjkokh/). To install from source: 1. Clone or download files. 2. Open Chrome Extensions page and activate Developer Mode. 3. Load Unpacked Extension, and locate the extension folder. 4. Select the folder and click open. 5. If you like, click options to go to the configuration page. This extension should work out of box. Settings can be configured in the Options link visible in the extensions menu. -------------------------------------------------------------------------------- This project is protected under the MIT license. More information in `LICENSE`. <file_sep>// If something's wrong with the options (generally, if they aren't set yet), // clear all options and reset to defaults. // TODO: This is duplicated in newtab.js. Combine these somehow. if (localStorage.length != 5) { localStorage.clear(); localStorage.clockMode = false; localStorage.teams = undefined; localStorage.name = true; localStorage.location = true; localStorage.optionsButton = true; } // Alias all the data inputs so we don't have to keep getting them by ID later on var o = { clock: document.getElementById('clock'), teams: document.getElementById('teams'), name: document.getElementById('name'), location: document.getElementById('location'), optionsButton: document.getElementById('options-button') }; // Get option values from localStorage and set all the inputs to those values. o.clock.checked = JSON.parse(localStorage.clockMode); // TEMPORARY: If the 'teams' data has brackets around it, remove the brackets. if (localStorage.teams[0] === '[' || localStorage.teams[localStorage.teams.length - 1] === ']') { localStorage.teams = localStorage.teams.substring(1, localStorage.teams.length - 1); } // If the custom team list is valid, put it into the textbox. // If the list doesn't exist or isn't valid, the textbox will be left empty. if (localStorage.teams !== undefined && localStorage.teams !== 'undefined' && localStorage.teams !== '') { o.teams.value = localStorage.teams; } o.name.checked = JSON.parse(localStorage.name); o.location.checked = JSON.parse(localStorage.location); o.optionsButton.checked = JSON.parse(localStorage.optionsButton); console.log('Loaded options!'); // Function to update localStorage with new values from inputs. function updateOptions() { localStorage.clockMode = o.clock.checked; localStorage.teams = o.teams.value; localStorage.name = o.name.checked; localStorage.location = o.location.checked; localStorage.optionsButton = o.optionsButton.checked; console.log('Options updated!'); } // Update localStorage, using the above function, when options are changed. // TODO: Should call the function directly. Very strange that this doesn't work. oninput = function() { updateOptions(); }; onchange = function() { updateOptions(); };
4a4e68338c27d6287db1e3bcd3c4ea31db91d4a8
[ "Markdown", "JavaScript" ]
2
Markdown
newjanson/FRCNewTabCA
df81d16541750d93486f6f8188f6e03045f1c4f1
15a6bcca06fc624066c0e3f63a88a294e0f69dd9
refs/heads/master
<file_sep>import { Getter, Setter, Atom, WritableAtom, NonPromise, NonFunction, SetStateAction, } from './types' // writable derived atom export function atom<Value, Update>( read: (get: Getter) => NonPromise<Value>, write: (get: Getter, set: Setter, update: Update) => void | Promise<void> ): WritableAtom<Value, Update> // write-only derived atom export function atom<Value, Update>( read: NonFunction<NonPromise<Value>>, write: (get: Getter, set: Setter, update: Update) => void | Promise<void> ): WritableAtom<Value, Update> // async-read writable derived atom export function atom<Value, Update>( read: (get: Getter) => Promise<Value>, write: (get: Getter, set: Setter, update: Update) => void | Promise<void> ): WritableAtom<Value | Promise<Value>, Update> // read-only derived atom export function atom<Value>( read: (get: Getter) => NonPromise<Value> ): Atom<Value> // async-read read-only derived atom export function atom<Value>( read: (get: Getter) => Promise<Value> ): Atom<Value | Promise<Value>> // primitive atom export function atom<Value>( initialValue: NonFunction<NonPromise<Value>> ): WritableAtom<Value, SetStateAction<Value>> export function atom<Value, Update>( read: Value | ((get: Getter) => Value | Promise<Value>), write?: (get: Getter, set: Setter, update: Update) => void | Promise<void> ) { const instance = {} as WritableAtom<Value | Promise<Value>, Update> if (typeof read === 'function') { instance.read = read as (get: Getter) => Value | Promise<Value> const value = (read as (get: Getter) => Value | Promise<Value>)( (a) => a.initialValue ) if (value instanceof Promise) { value.then((v) => { instance.initialValue = v }) } instance.initialValue = value } else { instance.initialValue = read instance.read = (get: Getter) => get(instance) instance.write = (get: Getter, set: Setter, update: Update) => { set( instance, typeof update === 'function' ? update(get(instance)) : update ) } } if (write) { instance.write = write } return instance } <file_sep>import { useCallback, useDebugValue } from 'react' import { useContext, useContextSelector } from 'use-context-selector' import { StateContext, ActionsContext, AtomState } from './Provider' import { Atom, WritableAtom, AnyWritableAtom, NonPromise } from './types' import { useIsoLayoutEffect } from './utils' const isWritable = <Value, Update>( atom: Atom<Value> | WritableAtom<Value, Update> ): atom is WritableAtom<Value, Update> => !!(atom as WritableAtom<Value, Update>).write export function useAtom<Value, Update>( atom: WritableAtom<Value, Update> ): [NonPromise<Value>, (update: Update) => void] export function useAtom<Value>(atom: Atom<Value>): [NonPromise<Value>, never] export function useAtom<Value, Update>( atom: Atom<Value> | WritableAtom<Value, Update> ) { const actions = useContext(ActionsContext) const promiseOrValue = useContextSelector( StateContext, useCallback( (state) => { const atomState = state.get(atom) as AtomState<Value> | undefined if (atomState) { return atomState.promise || atomState.value } if (atom.initialValue instanceof Promise) { atom.initialValue.then(() => { actions.init(null, atom) }) } return atom.initialValue }, [atom] ) ) const setAtom = useCallback( (update: Update) => { if (isWritable(atom)) { actions.write(atom as AnyWritableAtom, update) } else { throw new Error('not writable atom') } }, [atom, actions] ) useIsoLayoutEffect(() => { const id = Symbol() actions.init(id, atom) return () => { actions.dispose(id) } }, [actions, atom]) if (promiseOrValue instanceof Promise) { throw promiseOrValue } useDebugValue(promiseOrValue) return [promiseOrValue, setAtom] } <file_sep>export { Provider } from './Provider' export { atom } from './atom' export { useAtom } from './useAtom' export type { Atom, WritableAtom } from './types' <file_sep><p align="center"> <a id="cover" href="#cover"><img src="img/cover.svg" alt="Jotai Primitive and flexible state management for React. No extra re-renders, state resides within React, you get full benefits from suspense, and concurrent mode. It's scalable from a simple React.useState replacement up to a large application with complex requirements. npm i jotai" /></a> </p> [![Build Size](https://img.shields.io/bundlephobia/min/jotai?label=bundle%20size&style=flat&colorA=000000&colorB=000000)](https://bundlephobia.com/result?p=jotai) [![Build Status](https://img.shields.io/travis/react-spring/jotai/master?style=flat&colorA=000000&colorB=000000)](https://travis-ci.org/react-spring/jotai) [![Version](https://img.shields.io/npm/v/jotai?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/jotai) [![Downloads](https://img.shields.io/npm/dt/jotai.svg?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/jotai) Jotai is pronounced "joe-tie" and means "state" in Japanese. You can try a live demo [here](https://codesandbox.io/s/jotai-demo-47wvh). #### How does Jotai differ from Recoil? * Minimalistic API * No string keys * TypeScript oriented <a id="firstcreateaprimitiveatom" href="#firstcreateaprimitiveatom"><img src="img/doc.01.svg" alt="First create a primitive atom" /></a> An atom represents a piece of state. All you need is to specify an initial value, which can be primitive values like strings and numbers, objects and arrays. You can create as many primitive atoms as you want. ```jsx import { atom } from 'jotai' const countAtom = atom(0) const countryAtom = atom("Japan") const citiesAtom = atom(["Tokyo", "Kyoto", "Osaka"]) const mangaAtom = atom({ "Dragon Ball": 1984, "One Piece": 1997, "Naruto": 1999 }) ``` <a id="wrapyourcomponenttree" href="#wrapyourcomponenttree"><img src="img/doc.02.svg" alt="Wrap your component tree with Jotai's Provider" /></a> You can only use atoms under this component tree. ```jsx import { Provider } from 'jotai' const Root = () => ( <Provider> <App /> </Provider> ) ``` <a id="usetheatom" href="#usetheatom"><img src="img/doc.03.svg" alt="Use the atom in your components" /></a> It can be used just like `React.useState`: ```jsx import { useAtom } from 'jotai' function Counter() { const [count, setCount] = useAtom(countAtom) return ( <h1> {count} <button onClick={() => setCount(c => c + 1)}>one up</button> ``` <a id="derivedatomswithcomputedvalues" href="#derivedatomswithcomputedvalues"><img src="img/doc.04.svg" alt="Create derived atoms with computed values" /></a> A new read-only atom can be created from existing atoms by passing a read function as the first argument. `get` allows you to fetch the contextual value of any atom. ```jsx const doubledCountAtom = atom(get => get(countAtom) * 2) function DoubleCounter() { const [doubledCount] = useAtom(doubledCountAtom) return <h2>{doubledCount}</h2> ``` <a id="recipes" href="#recipes"><img src="img/rec.00.svg" alt="Recipes" /></a> <a id="multipleatoms" href="#multipleatoms"><img src="img/rec.01.svg" alt="Creating an atom from multiple atoms" /></a> You can combine multiple atoms to create a derived atom. ```jsx const count1 = atom(1) const count2 = atom(2) const count3 = atom(3) const sum = atom(get => get(count1) + get(count2) + get(count3)) ``` Or if you like fp patterns ... ```jsx const atoms = [count1, count1, count3, ...otherAtoms] const sum = atom(get => atoms.map(get).reduce((acc, count) => acc + count)) ``` <a id="derivedasyncatoms" href="#derivedasyncatoms"><img src="img/rec.02.svg" alt="Derived async atoms (needs suspense)" /></a> You can make the read function an async function, too. ```jsx const urlAtom = atom("https://json.host.com") const fetchUrlAtom = atom( async get => { const response = await fetch(get(urlAtom)) return await response.json() } ) function Status() { // Re-renders the component after urlAtom changed and the async function above concludes const [json] = useAtom(fetchUrlAtom) ``` <a id="writabledrivedatom" href="#writabledrivedatom"><img src="img/rec.03.svg" alt="You can create a writable derived atom" /></a> Specify a write function at the second argument. `get` will return the current value of an atom, `set` will update an atoms value. ```jsx const decrementCountAtom = atom( get => get(countAtom), (get, set, _arg) => set(countAtom, get(countAtom) - 1), ) function Counter() { const [count, decrement] = useAtom(decrementCountAtom) return ( <h1> {count} <button onClick={decrement}>Decrease</button> ``` <a id="writeonlyatoms" href="#writeonlyatoms"><img src="img/rec.04.svg" alt="Write only atoms" /></a> Just do not define a read function. ```jsx const multiplyCountAtom = atom(null, (get, set, by) => set(countAtom, get(countAtom) * by)) function Controls() { const [, multiply] = useAtom(multiplyCountAtom) return <button onClick={() => multiply(3)}>triple</button> ``` <a id="asyncactions" href="#asyncactions"><img src="img/rec.05.svg" alt="Async actions (needs suspense)" /></a> Just make the write function an async function and call `set` when you're ready. ```jsx const fetchCountAtom = atom( get => get(countAtom), async (_get, set, url) => { const response = await fetch(url) set(countAtom, (await response.json()).count) } ) function Controls() { const [count, compute] = useAtom(fetchCountAtom) return <button onClick={() => compute("http://count.host.com")}>compute</button> ``` <file_sep>export type NonPromise<T> = T extends Promise<unknown> ? never : T export type NonFunction<T> = T extends Function ? never : T export type SetStateAction<Value> = | NonFunction<Value> | ((prev: Value) => NonFunction<Value>) export type Getter = <Value>(atom: Atom<Value>) => Value export type Setter = <Value, Update>( atom: WritableAtom<Value, Update>, update: Update ) => void export type Atom<Value> = { initialValue: Value read: (get: Getter) => Value | Promise<Value> } export type WritableAtom<Value, Update> = Atom<Value> & { write: (get: Getter, set: Setter, update: Update) => void | Promise<void> } export type AnyAtom = Atom<unknown> export type AnyWritableAtom = WritableAtom<unknown, unknown> <file_sep># Explore Examples ```bash git clone https://github.com/react-spring/jotai # install project dependencies & build the library cd jotai && yarn # move to the examples folder & install dependencies cd examples && yarn # start the dev server yarn start ``` After playing with the examples you can explore the src code. Each example URL maps to a folder name in the `examples/src/demos` folder. <file_sep>import { useLayoutEffect, useEffect } from 'react' const isClient = typeof window !== 'undefined' && !/ServerSideRendering/.test(window.navigator && window.navigator.userAgent) export const useIsoLayoutEffect = isClient ? useLayoutEffect : useEffect export const appendMap = <K, V>(dst: Map<K, V>, src: Map<K, V>) => { src.forEach((v, k) => { dst.set(k, v) }) return dst } export const concatMap = <K, V>(src1: Map<K, V>, src2: Map<K, V>) => { const dst = new Map<K, V>() src1.forEach((v, k) => { dst.set(k, v) }) src2.forEach((v, k) => { dst.set(k, v) }) return dst } <file_sep>import React, { Dispatch, SetStateAction, createElement, useMemo, useState, useRef, } from 'react' import { createContext } from 'use-context-selector' import { AnyAtom, AnyWritableAtom, Getter, Setter } from './types' import { appendMap, concatMap } from './utils' const warningObject = new Proxy( {}, { get() { throw new Error('Please use <Provider>') }, apply() { throw new Error('Please use <Provider>') }, } ) export type Actions = { init: (id: symbol | null, atom: AnyAtom) => void dispose: (id: symbol) => void write: (atom: AnyWritableAtom, update: unknown) => void } // dependents for get operation type DependentsMap = WeakMap<AnyAtom, Set<AnyAtom | symbol>> // symbol is id from INIT_ATOM const addDependent = ( dependentsMap: DependentsMap, atom: AnyAtom, dependent: AnyAtom | symbol ) => { let dependents = dependentsMap.get(atom) if (!dependents) { dependents = new Set<AnyAtom | symbol>() dependentsMap.set(atom, dependents) } dependents.add(dependent) } const deleteDependent = ( dependentsMap: DependentsMap, atom: AnyAtom, dependent: AnyAtom | symbol ) => { const dependents = dependentsMap.get(atom) if (dependents && dependents.has(dependent)) { dependents.delete(dependent) return dependents.size === 0 // empty } return false // not found } const listDependents = (dependentsMap: DependentsMap, atom: AnyAtom) => { const dependents = dependentsMap.get(atom) return dependents || new Set<AnyAtom | symbol>() } export type AtomState<Value = unknown> = { promise: Promise<void> | null value: Value } type State = Map<AnyAtom, AtomState> type PartialState = State type WriteCache = WeakMap<State, Map<symbol, PartialState>> // symbol is writeId const initialState: State = new Map() const getAtomState = (state: State, atom: AnyAtom) => { const atomState = state.get(atom) if (!atomState) { throw new Error('atom is not initialized') } return atomState } const getAtomStateValue = (state: State, atom: AnyAtom) => { const atomState = state.get(atom) return atomState ? atomState.value : atom.initialValue } const initAtom = ( id: symbol | null, initializingAtom: AnyAtom, setState: Dispatch<SetStateAction<State>>, dependentsMap: DependentsMap ) => { const createAtomState = ( prevState: State, atom: AnyAtom, dependent: AnyAtom | symbol | null ) => { if (dependent) { addDependent(dependentsMap, atom, dependent) } const partialState: State = new Map() let atomState = prevState.get(atom) if (atomState) { return partialState // already initialized } let isSync = true const nextValue = atom.read(((a: AnyAtom) => { if (a !== atom) { if (isSync) { const nextPartialState = createAtomState(prevState, a, atom) appendMap(partialState, nextPartialState) } else { setState((prev) => { const nextPartialState = createAtomState(prev, a, atom) return appendMap(new Map(prev), nextPartialState) }) } } return getAtomStateValue(prevState, a) }) as Getter) if (nextValue instanceof Promise) { const promise = nextValue.then((value) => { setState((prev) => new Map(prev).set(atom, { promise: null, value })) }) atomState = { promise, value: atom.initialValue } } else { atomState = { promise: null, value: nextValue } } partialState.set(atom, atomState) isSync = false return partialState } setState((prev) => { const nextPartialState = createAtomState(prev, initializingAtom, id) return appendMap(new Map(prev), nextPartialState) }) } const disposeAtom = ( id: symbol, setState: Dispatch<SetStateAction<State>>, dependentsMap: DependentsMap ) => { const deleteAtomState = (prevState: State, dependent: AnyAtom | symbol) => { let nextState = new Map(prevState) const deleted: AnyAtom[] = [] nextState.forEach((_atomState, atom) => { const isEmpty = deleteDependent(dependentsMap, atom, dependent) if (isEmpty) { nextState.delete(atom) deleted.push(atom) dependentsMap.delete(atom) } }) nextState = deleted.reduce((p, c) => deleteAtomState(p, c), nextState) return nextState } setState((prev) => deleteAtomState(prev, id)) } const writeAtomValue = ( updatingAtom: AnyWritableAtom, update: unknown, setState: Dispatch<SetStateAction<State>>, dependentsMap: DependentsMap, writeCache: WriteCache ) => { const updateDependentsState = (prevState: State, atom: AnyAtom) => { const partialState: State = new Map() listDependents(dependentsMap, atom).forEach((dependent) => { if (typeof dependent === 'symbol') return const v = dependent.read(((a: AnyAtom) => { if (a !== dependent) { addDependent(dependentsMap, a, dependent) } return getAtomStateValue(prevState, a) }) as Getter) if (v instanceof Promise) { const promise = v.then((vv) => { const nextAtomState: AtomState = { promise: null, value: vv } setState((prev) => { const nextState = new Map(prev).set(dependent, nextAtomState) const nextPartialState = updateDependentsState(nextState, dependent) return appendMap(nextState, nextPartialState) }) }) partialState.set(dependent, { ...getAtomState(prevState, dependent), promise, }) } else { partialState.set(dependent, { promise: null, value: v, }) appendMap(partialState, updateDependentsState(prevState, dependent)) } }) return partialState } const updateAtomState = ( writeId: symbol, prevState: State, atom: AnyWritableAtom, value: unknown ) => { if (!writeCache.has(prevState)) { writeCache.set(prevState, new Map()) } const cache = writeCache.get(prevState) as Map<symbol, PartialState> const hit = cache.get(writeId) if (hit) return hit const partialState: State = new Map() let isSync = true const promise = atom.write( ((a: AnyAtom) => getAtomStateValue(concatMap(prevState, partialState), a)) as Getter, ((a: AnyWritableAtom, v: unknown) => { if (a === atom) { const nextAtomState: AtomState = { promise: null, value: v } if (isSync) { partialState.set(a, nextAtomState) appendMap( partialState, updateDependentsState(concatMap(prevState, partialState), a) ) } else { setState((prev) => { const nextState = new Map(prev).set(a, nextAtomState) const nextPartialState = updateDependentsState(nextState, a) return appendMap(nextState, nextPartialState) }) } } else { const newWriteId = Symbol() if (isSync) { const nextPartialState = updateAtomState( newWriteId, prevState, a, v ) appendMap(partialState, nextPartialState) } else { setState((prev) => { const nextPartialState = updateAtomState(newWriteId, prev, a, v) return appendMap(new Map(prev), nextPartialState) }) } } }) as Setter, value ) if (promise instanceof Promise) { const nextAtomState: AtomState = { ...getAtomState(prevState, atom), promise: promise.then(() => { setState((prev) => new Map(prev).set(atom, { ...getAtomState(prev, atom), promise: null, }) ) }), } partialState.set(atom, nextAtomState) } isSync = false cache.set(writeId, partialState) return partialState } const newWriteId = Symbol() setState((prevState) => { const updatingAtomState = prevState.get(updatingAtom) if (updatingAtomState && updatingAtomState.promise) { // schedule update after promise is resolved const promise = updatingAtomState.promise.then(() => { const updateState = updateAtomState( newWriteId, prevState, updatingAtom, update ) setState((prev) => appendMap(new Map(prev), updateState)) }) return new Map(prevState).set(updatingAtom, { ...updatingAtomState, promise, }) } else { const updateState = updateAtomState( newWriteId, prevState, updatingAtom, update ) return appendMap(new Map(prevState), updateState) } }) } export const ActionsContext = createContext(warningObject as Actions) export const StateContext = createContext(warningObject as State) export const Provider: React.FC = ({ children }) => { const [state, setState] = useState(initialState) const dependentsMapRef = useRef<DependentsMap>() if (!dependentsMapRef.current) { dependentsMapRef.current = new WeakMap() } const writeCacheRef = useRef<WriteCache>() if (!writeCacheRef.current) { writeCacheRef.current = new WeakMap() } const actions = useMemo( () => ({ init: (id: symbol | null, atom: AnyAtom) => initAtom(id, atom, setState, dependentsMapRef.current as DependentsMap), dispose: (id: symbol) => disposeAtom(id, setState, dependentsMapRef.current as DependentsMap), write: (atom: AnyWritableAtom, update: unknown) => writeAtomValue( atom, update, setState, dependentsMapRef.current as DependentsMap, writeCacheRef.current as WriteCache ), }), [] ) return createElement( ActionsContext.Provider, { value: actions }, createElement(StateContext.Provider, { value: state }, children) ) }
aac83354bb5e58aca6474fee4cd46b8d7e6bcb46
[ "Markdown", "TypeScript" ]
8
TypeScript
leonardoelias/jotai
245cbfa330283a86186832690271ef050e00e785
f9eed647deeed5419a12b4ca9213341159f0fdfa
refs/heads/master
<repo_name>DigitalMachinist/astar-testing<file_sep>/AStarTesting/Testbed/AStarTestbed.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using AStarTesting.Navmesh; using AStarTesting.Heuristics; using AStarTesting.NaiveAStar; using AStarTesting.OptimizedAStar; namespace AStarTesting.Testbed { public enum AgentType { Naive, // Jeff's first implementation of A*, ignoring any optimizations Optimized // Jeff's second A* implementation, taking advantage of optimizations } public class AStarTestbed { /////////////////////////////////////////////////////////////////////////////////////////// #region Member Variables Dictionary<string, IAStarHeuristic> heuristicsMap; bool keypressAdvance; int randomSeed; GridType gridType; int columns, rows; int agents, iterations; AgentType agentType; float minSimplexAmplitude, maxSimplexAmplitude; float minSimplexScale, maxSimplexScale; float minSimplexXOffset, maxSimplexXOffset; float minSimplexYOffset, maxSimplexYOffset; float minCoeffCostFromStart, maxCoeffCostFromStart; float minCoeffCostToGoal, maxCoeffCostToGoal; #endregion public AStarTestbed() { /////////////////////////////////////////////////////////////////////////////////////// #region Setup heuristics map heuristicsMap = new Dictionary<string, IAStarHeuristic>(); heuristicsMap.Add( "Dijkstra", new DijkstraAStarHeuristic() ); heuristicsMap.Add( "Manhattan", new ManhattanAStarHeuristic() ); heuristicsMap.Add( "StraightLine", new StraightLineAStarHeuristic() ); #endregion /////////////////////////////////////////////////////////////////////////////////////// #region Read configuration file XDocument xdoc = XDocument.Load( "config.xml" ); // Read in the grid type string gridTypeString = xdoc.Descendants( "gridType" ).First().Value; switch ( gridTypeString ) { case "SquareGrid": gridType = GridType.SquareGrid; break; case "SquareDiagonal": gridType = GridType.SquareDiagonal; break; case "HexGrid": gridType = GridType.HexGrid; break; default: throw new ArgumentOutOfRangeException(); } // Read in the agent type string agentTypeString = xdoc.Descendants( "agentType" ).First().Value; switch ( agentTypeString ) { case "Naive": agentType = AgentType.Naive; break; case "Optimized": agentType = AgentType.Optimized; break; default: throw new ArgumentOutOfRangeException(); } keypressAdvance = bool.Parse( xdoc.Descendants( "keypressAdvance" ).First().Value ); randomSeed = int.Parse( xdoc.Descendants( "randomSeed" ).First().Value ); columns = int.Parse( xdoc.Descendants( "columns" ).First().Value ); rows = int.Parse( xdoc.Descendants( "rows" ).First().Value ); agents = int.Parse( xdoc.Descendants( "agents" ).First().Value ); iterations = int.Parse( xdoc.Descendants( "iterations" ).First().Value ); minSimplexAmplitude = float.Parse( xdoc.Descendants( "minSimplexAmplitude" ).First().Value ); maxSimplexAmplitude = float.Parse( xdoc.Descendants( "maxSimplexAmplitude" ).First().Value ); minSimplexScale = float.Parse( xdoc.Descendants( "minSimplexScale" ).First().Value ); maxSimplexScale = float.Parse( xdoc.Descendants( "maxSimplexScale" ).First().Value ); minSimplexXOffset = float.Parse( xdoc.Descendants( "minSimplexXOffset" ).First().Value ); maxSimplexXOffset = float.Parse( xdoc.Descendants( "maxSimplexXOffset" ).First().Value ); minSimplexYOffset = float.Parse( xdoc.Descendants( "minSimplexYOffset" ).First().Value ); maxSimplexYOffset = float.Parse( xdoc.Descendants( "maxSimplexYOffset" ).First().Value ); minCoeffCostFromStart = float.Parse( xdoc.Descendants( "minCoeffCostFromStart" ).First().Value ); maxCoeffCostFromStart = float.Parse( xdoc.Descendants( "maxCoeffCostFromStart" ).First().Value ); minCoeffCostToGoal = float.Parse( xdoc.Descendants( "minCoeffCostToGoal" ).First().Value ); maxCoeffCostToGoal = float.Parse( xdoc.Descendants( "maxCoeffCostToGoal" ).First().Value ); Console.WriteLine(); if ( keypressAdvance ) Console.WriteLine( "Keypress advance is ENABLED!" ); else Console.WriteLine( "Keypress advance is disabled." ); Console.WriteLine(); Console.WriteLine( "*** Configuration ***" ); Console.WriteLine( "randomSeed:\t\t" + randomSeed ); Console.WriteLine( "gridType:\t\t" + gridType.ToString() ); Console.WriteLine( "columns:\t\t" + columns ); Console.WriteLine( "rows:\t\t\t" + rows ); Console.WriteLine( "agents:\t\t\t" + agents ); Console.WriteLine( "iterations:\t\t" + iterations ); Console.WriteLine( "agentType:\t\t" + agentType.ToString() ); Console.WriteLine( "minSimplexAmplitude:\t" + minSimplexAmplitude ); Console.WriteLine( "maxSimplexAmplitude:\t" + maxSimplexAmplitude ); Console.WriteLine( "minSimplexScale:\t" + minSimplexScale ); Console.WriteLine( "maxSimplexScale:\t" + maxSimplexScale ); Console.WriteLine( "minSimplexXOffset:\t" + minSimplexXOffset ); Console.WriteLine( "maxSimplexXOffset:\t" + maxSimplexXOffset ); Console.WriteLine( "minSimplexYOffset:\t" + minSimplexYOffset ); Console.WriteLine( "maxSimplexYOffset:\t" + maxSimplexYOffset ); Console.WriteLine( "minCoeffCostFromStart:\t" + minCoeffCostFromStart ); Console.WriteLine( "maxCoeffCostFromStart:\t" + maxCoeffCostFromStart ); Console.WriteLine( "minCoeffCostToGoal:\t" + minCoeffCostToGoal ); Console.WriteLine( "maxCoeffCostToGoal:\t" + maxCoeffCostToGoal ); // Build list of heuristics to use List<IAStarHeuristic> heuristics = new List<IAStarHeuristic>(); foreach ( XElement heuristicTag in xdoc.Descendants( "heuristics" ) ) { IAStarHeuristic heuristic = null; if ( heuristicsMap.TryGetValue( heuristicTag.Value, out heuristic ) ) heuristics.Add( heuristic ); } Console.WriteLine(); Console.WriteLine( "*** Heuristics ***" ); foreach ( IAStarHeuristic heuristic in heuristics ) { Console.WriteLine( heuristic.GetType().Name ); } #endregion /////////////////////////////////////////////////////////////////////////////////////// #region Prepare output file string datetime = DateTime.Now.ToString( "yyyy-MM-dd_HH-mm-ss" ); string filename = "results_" + datetime + ".csv"; string output = String.Join( ",", "Keypress Advance", "Random Seed", "Grid Type", "Navmesh Columns", "Navmesh Rows", "Agent Type", "Start Node", "Goal Node", "Noise Amplitude", "Noise Scale", "Noise Offset", "Heuristic", "Coeff From Start", "Coeff To Goal", "Total (ms)", "Setup (ms)", "Body (ms)", "Find Min (ms)", "Backtrace (ms)", "Closed Set (ms)", "Open Set (ms)", "Nodes (ms)", "Total (ticks)", "Setup (ticks)", "Body (ticks)", "Find Min (ticks)", "Backtrace (ticks)", "Closed Set (ticks)", "Open Set (ticks)", "Nodes (ticks)", "Nodes Considered", "Max Closed Set", "Max Open Set", "Path Length", "Path Nodes" ); File.WriteAllText( filename, output, UTF8Encoding.UTF8 ); Console.WriteLine(); Console.WriteLine( "*** Output File ***" ); Console.WriteLine( "Filename:\t" + filename ); Console.WriteLine( "Encoding:\t" + UTF8Encoding.UTF8.ToString() ); #endregion /////////////////////////////////////////////////////////////////////////////////////// #region Set up the test // Set up the benckmarking tools AStarTestResult result = new AStarTestResult(); Random random = new Random( randomSeed ); Stopwatch stopwatch = new Stopwatch(); // Create and size the navmesh -- It will not be resized after this IAStarNavmesh navmesh = new IAStarNavmesh( gridType, columns, rows ); Console.WriteLine(); Console.WriteLine( "*** Navmesh Nodes (10x10 Sample) ***" ); for ( int x = 0; x < 10 && x < navmesh.Columns; x++ ) for ( int y = 0; y < 10 && y < navmesh.Rows; y++ ) Console.WriteLine( navmesh.Navmesh[ x, y ].ToString() ); Console.WriteLine(); Console.WriteLine( "*** Agents ***" ); // Create a list of agents and randomize their configurations for ( int i = 0; i < agents; i++ ) { IAStarHeuristic heuristic = heuristics[ random.Next( 0, heuristics.Count ) ]; float coeffCostFromStart = (float)( minCoeffCostFromStart + random.NextDouble() * ( maxCoeffCostFromStart - minCoeffCostFromStart ) ); float coeffCostToGoal = (float)( minCoeffCostToGoal + random.NextDouble() * ( maxCoeffCostToGoal - minCoeffCostToGoal ) ); IAStarAgent agent = null; switch ( agentType ) { case AgentType.Naive: agent = new NaiveAStarAgent( heuristic, coeffCostFromStart, coeffCostToGoal, keypressAdvance ); break; case AgentType.Optimized: agent = new OptimizedAStarAgent( heuristic, coeffCostFromStart, coeffCostToGoal, keypressAdvance ); break; } int xStart = random.Next( 0, navmesh.Columns ); int yStart = random.Next( 0, navmesh.Rows ); agent.StartNode = navmesh.Navmesh[ xStart, yStart ]; int xGoal = random.Next( 0, navmesh.Columns ); int yGoal = random.Next( 0, navmesh.Rows ); agent.GoalNode = navmesh.Navmesh[ xGoal, yGoal ]; navmesh.AddAgent( agent ); Console.WriteLine( agent ); } #endregion // Wait for a keypress to begin testing Console.WriteLine(); Console.WriteLine( "Press any key to begin benchmarks..." ); Console.ReadKey(); /////////////////////////////////////////////////////////////////////////////////////// #region Run the benchmarks for ( int i = 0; i < iterations; i++ ) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine( "Iteration " + ( i + 1 ) + " started!" ); // Randomize terrain costs float simplexAmplitude = (float)( minSimplexAmplitude + random.NextDouble() * ( maxSimplexAmplitude - minSimplexAmplitude ) ); float simplexScale = (float)( minSimplexScale + random.NextDouble() * ( maxSimplexScale - minSimplexScale ) ); float simplexXOffset = (float)( minSimplexXOffset + random.NextDouble() * ( maxSimplexXOffset - minSimplexXOffset ) ); float simplexYOffset = (float)( minSimplexYOffset + random.NextDouble() * ( maxSimplexYOffset - minSimplexYOffset ) ); navmesh.GenerateResistanceNoise( simplexAmplitude, simplexScale, simplexXOffset, simplexYOffset ); #if ( DEBUG ) // Don't need to see raw move costs unless this is a debug build Console.WriteLine(); Console.WriteLine( "*** Navmesh Move Costs ***" ); for ( int x = 0; x < navmesh.Columns; x++ ) { string navmeshRow = navmesh.Navmesh[ x, 0 ].MoveCost.ToString( "F2" ); for ( int y = 1; y < navmesh.Rows; y++ ) { navmeshRow += "\t" + navmesh.Navmesh[ x, y ].MoveCost.ToString( "F2" ); } Console.WriteLine( navmeshRow ); } #endif Console.WriteLine(); for ( int j = 0; j < agents; j++ ) { IAStarAgent peekAgent = navmesh.Agents.Peek(); Console.WriteLine(); Console.WriteLine( peekAgent ); // Solve the A* path for this agent on the navmesh IAStarAgent solvedAgent = navmesh.SolveNext(); IAStarBenchmark benchmark = solvedAgent as IAStarBenchmark; // Store the test parameters result.KeypressAdvance = keypressAdvance; result.RandomSeed = randomSeed; result.NavmeshGridType = navmesh.GridType.ToString(); result.NavmeshColumns = navmesh.Columns; result.NavmeshRows = navmesh.Rows; result.AgentType = solvedAgent.GetType().Name; result.XStart = solvedAgent.StartNode.Column; result.YStart = solvedAgent.StartNode.Row; result.XGoal = solvedAgent.GoalNode.Column; result.YGoal = solvedAgent.GoalNode.Row; result.SimplexAmplitude = simplexAmplitude; result.SimplexScale = simplexScale; result.SimplexXOffset = simplexXOffset; result.SimplexYOffset = simplexYOffset; result.Heuristic = solvedAgent.Heuristic.GetType().Name; result.CoeffCostFromStart = solvedAgent.CoeffCostFromStart; result.CoeffCostToGoal = solvedAgent.CoeffCostToGoal; // Store the test results result.MaxClosedSetCount = benchmark.MaxClosedSetCount; result.MaxOpenSetCount = benchmark.MaxOpenSetCount; result.NodesConsideredCount = benchmark.NodesConsideredCount; result.PathLength = benchmark.PathLength; result.PathString = benchmark.PathString; result.MSBacktrace = benchmark.SWBacktrace.ElapsedMilliseconds; result.TicksBacktrace = benchmark.SWBacktrace.ElapsedTicks; result.MSBody = benchmark.SWBody.ElapsedMilliseconds; result.TicksBody = benchmark.SWBody.ElapsedTicks; result.MSClosedSet = benchmark.SWClosedSet.ElapsedMilliseconds; result.TicksClosedSet = benchmark.SWClosedSet.ElapsedTicks; result.MSFindMin = benchmark.SWFindMin.ElapsedMilliseconds; result.TicksFindMin = benchmark.SWFindMin.ElapsedTicks; result.MSNodes = benchmark.SWNodes.ElapsedMilliseconds; result.TicksNodes = benchmark.SWNodes.ElapsedTicks; result.MSOpenSet = benchmark.SWOpenSet.ElapsedMilliseconds; result.TicksOpenSet = benchmark.SWOpenSet.ElapsedTicks; result.MSSetup = benchmark.SWSetup.ElapsedMilliseconds; result.TicksSetup = benchmark.SWSetup.ElapsedTicks; result.MSTotal = benchmark.SWTotal.ElapsedMilliseconds; result.TicksTotal = benchmark.SWTotal.ElapsedTicks; // Write results to the output file File.AppendAllText( filename, "\n" + result, UTF8Encoding.UTF8 ); Console.WriteLine( "Result " + ( j + 1 ) + " stored." ); } Console.WriteLine(); Console.WriteLine( "Iteration complete!" ); } #endregion // Wait for a keypress to close Console.WriteLine(); Console.WriteLine( "Press any key to exit..." ); Console.ReadKey(); } } } <file_sep>/AStarTesting/Heuristics/StraightLineAStarHeuristic.cs using System; using System.Collections.Generic; using AStarTesting.Navmesh; namespace AStarTesting.Heuristics { public class StraightLineAStarHeuristic : IAStarHeuristic { /////////////////////////////////////////////////////////////////////////////////////////// #region Interface Methods public float GetEstimatedCost( AStarNode currentNode, AStarNode goalNode ) { float diffColumns = Math.Abs( goalNode.Column - currentNode.Column ); float diffRows = Math.Abs( goalNode.Row - currentNode.Row ); return (float)Math.Sqrt( diffColumns * diffColumns + diffRows * diffRows ); } #endregion } } <file_sep>/AStarTesting/Navmesh/IAStarAgent.cs using System; using AStarTesting.Heuristics; namespace AStarTesting.Navmesh { public interface IAStarAgent { float CoeffCostFromStart { get; set; } float CoeffCostToGoal { get; set; } AStarNode GoalNode { get; set; } IAStarHeuristic Heuristic { get; set; } AStarNode StartNode { get; set; } /// <summary> /// Solves for the path from the start node to the goal node. /// </summary> void Solve(); } } <file_sep>/AStarTesting/Testbed/IAStarBenchmark.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AStarTesting.Testbed { public interface IAStarBenchmark { /// <summary> /// The maximum size that the closed set reached during the last Solve() operation. /// </summary> long MaxClosedSetCount { get; set; } /// <summary> /// The maximum size that the open set reached during the last Solve() operation. /// </summary> long MaxOpenSetCount { get; set; } /// <summary> /// The total number of nodes considered by the last Solve() operation. /// </summary> long NodesConsideredCount { get; set; } /// <summary> /// The length of the path from the start node to the goal node computer by the last Solve() operation. /// </summary> long PathLength { get; set; } /// <summary> /// The string-formatted path chosen by the agent from the StartNode to the GoalNode. /// </summary> string PathString { get; } /// <summary> /// The stopwatch to measure the time cost of performing the backtrace to produce the linear path from start node to goal node. /// </summary> Stopwatch SWBacktrace { get; set; } /// <summary> /// The stopwatch to measure the primary loop performed by the Solve() operation to find a path. /// </summary> Stopwatch SWBody { get; set; } /// <summary> /// The stopwatch to measure the time cost of all operations using the closed set. /// </summary> Stopwatch SWClosedSet { get; set; } /// <summary> /// The stopwatch to measure the time cost of any operation done to determine the lowest-cost node in the open set. /// </summary> Stopwatch SWFindMin { get; set; } /// <summary> /// The stopwatch to measure the time cost of changing node values. /// </summary> Stopwatch SWNodes { get; set; } /// <summary> /// The stopwatch to measure the time cost of all operations using the open set. /// </summary> Stopwatch SWOpenSet { get; set; } /// <summary> /// The stopwatch to measure the time for the entire Solve() operation from start to finish. /// </summary> Stopwatch SWTotal { get; set; } /// <summary> /// The stopwatch to measure the time cost of any operations before the bosy of the Solve() operation. /// </summary> Stopwatch SWSetup { get; set; } } } <file_sep>/AStarTesting/OptimizedAStar/OptimizedAStarAgent.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using AStarTesting.Navmesh; using AStarTesting.Heuristics; using AStarTesting.Testbed; using GPWiki; namespace AStarTesting.OptimizedAStar { public class OptimizedAStarAgent : IAStarAgent, IAStarBenchmark { /////////////////////////////////////////////////////////////////////////////////////////// #region Properties /// <summary> /// /// </summary> List<AStarNode> mClosedSet; public List<AStarNode> ClosedSet { get { return mClosedSet; } private set { mClosedSet = value; } } /// <summary> /// /// </summary> float mCoeffCostFromStart; public float CoeffCostFromStart { get { return mCoeffCostFromStart; } set { mCoeffCostFromStart = value; } } /// <summary> /// /// </summary> float mCoeffCostToGoal; public float CoeffCostToGoal { get { return mCoeffCostToGoal; } set { mCoeffCostToGoal = value; } } /// <summary> /// /// </summary> AStarNode mGoalNode; public AStarNode GoalNode { get { return mGoalNode; } set { mGoalNode = value; } } /// <summary> /// /// </summary> IAStarHeuristic mHeuristic; public IAStarHeuristic Heuristic { get { return mHeuristic; } set { mHeuristic = value; } } /// <summary> /// /// </summary> bool mKeypressAdvance; public bool KeypressAdvance { get { return mKeypressAdvance; } set { mKeypressAdvance = value; } } /// <summary> /// /// </summary> long mMaxClosedSetCount; public long MaxClosedSetCount { get { return mMaxClosedSetCount; } set { mMaxClosedSetCount = value; } } /// <summary> /// /// </summary> long mMaxOpenSetCount; public long MaxOpenSetCount { get { return mMaxOpenSetCount; } set { mMaxOpenSetCount = value; } } /// <summary> /// /// </summary> long mNodesConsideredCount; public long NodesConsideredCount { get { return mNodesConsideredCount; } set { mNodesConsideredCount = value; } } /// <summary> /// /// </summary> GPWiki.BinaryHeap<AStarNode> mOpenSet; public GPWiki.BinaryHeap<AStarNode> OpenSet { get { return mOpenSet; } private set { mOpenSet = value; } } /// <summary> /// /// </summary> List<AStarNode> mPath; public List<AStarNode> Path { get { return mPath; } private set { mPath = value; } } /// <summary> /// /// </summary> long mPathLength; public long PathLength { get { return mPathLength; } set { mPathLength = value; } } /// <summary> /// /// </summary> public string PathString { get { StringBuilder pathStr = new StringBuilder(); foreach ( AStarNode node in Path ) pathStr.Append( "[ " + node.Column + " : " + node.Row + " ], " ); return pathStr.ToString(); } } /// <summary> /// /// </summary> AStarNode mStartNode; public AStarNode StartNode { get { return mStartNode; } set { mStartNode = value; } } /// <summary> /// /// </summary> Stopwatch mSWBacktrace; public Stopwatch SWBacktrace { get { return mSWBacktrace; } set { mSWBacktrace = value; } } /// <summary> /// /// </summary> Stopwatch mSWBody; public Stopwatch SWBody { get { return mSWBody; } set { mSWBody = value; } } /// <summary> /// /// </summary> Stopwatch mSWClosedSet; public Stopwatch SWClosedSet { get { return mSWClosedSet; } set { mSWClosedSet = value; } } /// <summary> /// /// </summary> Stopwatch mSWFindMin; public Stopwatch SWFindMin { get { return mSWFindMin; } set { mSWFindMin = value; } } /// <summary> /// /// </summary> Stopwatch mSWNodes; public Stopwatch SWNodes { get { return mSWNodes; } set { mSWNodes = value; } } /// <summary> /// /// </summary> Stopwatch mSWOpenSet; public Stopwatch SWOpenSet { get { return mSWOpenSet; } set { mSWOpenSet = value; } } /// <summary> /// /// </summary> Stopwatch mSWSetup; public Stopwatch SWSetup { get { return mSWSetup; } set { mSWSetup = value; } } /// <summary> /// /// </summary> Stopwatch mSWTotal; public Stopwatch SWTotal { get { return mSWTotal; } set { mSWTotal = value; } } #endregion /////////////////////////////////////////////////////////////////////////////////////////// #region Methods /// <summary> /// Returns the traversal cost of moving from the start node to the specified node. /// </summary> /// <param name="node">The node to compute the traversal cost to from the start node.</param> /// <param name="parent">(Default null) The node to use as the parent. If null, this node is used.</param> /// <returns>An integer traversal cost from the start node to the specified node, or 0 if parent == null.</returns> public float GetCostFromStart( AStarNode node, AStarNode parent = null ) { if ( parent == null ) parent = node.Parent; if ( parent == null ) return 0f; return parent.CostFromStart + CoeffCostFromStart * node.MoveCost; } /// <summary> /// Returns the estimated traversal cost of moving from the specified node to the goal node. /// </summary> /// <param name="node">The node to compute the heuristic estimate traversal cost from to the goal node.</param> /// <returns>An integer heuristic estimate traversal cost from the specified node to the goal node.</returns> public float GetCostToGoal( AStarNode node ) { if ( Heuristic == null ) return 0f; return CoeffCostToGoal * Heuristic.GetEstimatedCost( node, mGoalNode ); } /// <summary> /// Zeroes all benchmark counters and stopwatches. /// </summary> void ResetBenchmark() { MaxClosedSetCount = 0; MaxOpenSetCount = 0; NodesConsideredCount = 0; PathLength = 0; SWBacktrace.Reset(); SWBody.Reset(); SWClosedSet.Reset(); SWFindMin.Reset(); SWNodes.Reset(); SWOpenSet.Reset(); SWSetup.Reset(); SWTotal.Reset(); } /// <summary> /// Solves for the first identified A* path from the StartNode to the GoalNode. /// </summary> public void Solve() { // Zero the benchmark variables ResetBenchmark(); SWTotal.Start(); SWSetup.Start(); //SWClosedSet.Start(); //// Clear the closed set //ClosedSet.Clear(); //SWClosedSet.Stop(); //SWOpenSet.Start(); //// Clear the open set //OpenSet.Clear(); //SWOpenSet.Stop(); // Clear the path Path.Clear(); SWNodes.Start(); // Set the current node being considered AStarNode currentNode = StartNode; currentNode.Parent = null; currentNode.CostFromStart = 0; currentNode.CostToGoal = 0; currentNode.CostTotal = 0; SWNodes.Stop(); SWClosedSet.Start(); // Closed list of nodes to not be reconsidered ClosedSet.Add( currentNode ); currentNode.BelongsToClosedSet = true; SWClosedSet.Stop(); // Open list of nodes to consider and the node's parent (for backtracing) foreach ( AStarNode node in currentNode.Neighbors ) { if ( node.Traversable ) { SWNodes.Start(); // Calculate its cost and set its parent to the current node node.Parent = currentNode; node.CostFromStart = GetCostFromStart( node ); node.CostToGoal = GetCostToGoal( node ); node.CostTotal = node.CostFromStart + node.CostToGoal; SWNodes.Stop(); SWOpenSet.Start(); // Add the node to the open set OpenSet.Add( node ); node.BelongsToOpenSet = true; SWOpenSet.Stop(); if ( KeypressAdvance ) { AStarNode minNode = OpenSet.Peek(); Console.WriteLine( "This node: " + node.CostTotal + ", Minimum: " + minNode.CostTotal ); } } NodesConsideredCount++; } SWSetup.Stop(); SWBody.Start(); if ( KeypressAdvance ) { Console.WriteLine(); Console.WriteLine( "Press any key to advance to the next iteration..." ); } // Continue looping until the goal is reached while ( currentNode != GoalNode && OpenSet.Count > 0 ) { if ( KeypressAdvance ) { Console.ReadKey(); Console.WriteLine( currentNode ); } SWOpenSet.Start(); SWFindMin.Start(); // Find the lowest cost node in the open list currentNode = OpenSet.Remove(); currentNode.BelongsToOpenSet = false; //currentNode = OpenSet.Aggregate( // ( curmin, x ) => // ( ( curmin == null || ( x.CostTotal < curmin.CostTotal ) ) ? x : curmin ) //); SWOpenSet.Stop(); SWFindMin.Stop(); //SWOpenSet.Start(); // //// Remove this node on the open set //OpenSet.Remove( currentNode ); // //SWOpenSet.Stop(); SWClosedSet.Start(); // Then add it to the closed set ClosedSet.Add( currentNode ); currentNode.BelongsToClosedSet = true; SWClosedSet.Stop(); foreach ( AStarNode node in currentNode.Neighbors ) { //SWClosedSet.Start(); // //// Check if the current node belongs to the closed set //bool isInClosedSet = ClosedSet.Contains( node ); // //SWClosedSet.Stop(); // If this node is traversable and is NOT in the closed set if ( node.Traversable && !node.BelongsToClosedSet ) //if ( node.Traversable && !isInClosedSet ) { //SWOpenSet.Start(); // //// Check if the current node is in the open set //bool isInOpenSet = OpenSet.Contains( node ); // //SWOpenSet.Stop(); SWNodes.Start(); // Compute the CoeffCostFromStart of moving to this node assuming the // current node were its parent float costFromThisNode = GetCostFromStart( node, currentNode ); SWNodes.Stop(); // If this node is NOT in the open set if ( !node.BelongsToOpenSet ) { SWNodes.Start(); // Calculate its cost and set its parent to the current node node.Parent = currentNode; node.CostFromStart = costFromThisNode; node.CostToGoal = GetCostToGoal( node ); node.CostTotal = node.CostFromStart + node.CostToGoal; SWNodes.Stop(); SWOpenSet.Start(); // Add the node to the open set OpenSet.Add( node ); node.BelongsToOpenSet = true; SWOpenSet.Stop(); NodesConsideredCount++; if ( KeypressAdvance ) { AStarNode minNode = OpenSet.Peek(); Console.WriteLine( "This node: " + node.CostTotal + ", Minimum: " + minNode.CostTotal ); } } else { // If this node would have been reached more easily by this route if ( node.CostFromStart > costFromThisNode ) { SWNodes.Start(); // Reset the parent to the current node and recalculate the node cost node.Parent = currentNode; node.CostFromStart = costFromThisNode; // Don't need to update cost to goal -- that remains the same node.CostTotal = node.CostFromStart + node.CostToGoal; SWNodes.Stop(); if ( KeypressAdvance ) { AStarNode minNode = OpenSet.Peek(); Console.WriteLine( "This node: " + node.CostTotal + ", Minimum: " + minNode.CostTotal ); } } } } } MaxClosedSetCount = Math.Max( MaxClosedSetCount, ClosedSet.Count ); MaxOpenSetCount = Math.Max( MaxOpenSetCount, OpenSet.Count ); } SWBody.Stop(); SWBacktrace.Start(); for ( ; currentNode != null; currentNode = currentNode.Parent ) { Path.Add( currentNode ); } Path.Reverse(); SWBacktrace.Stop(); SWSetup.Start(); SWClosedSet.Start(); // Clear the state of the closed set nodes and clear the list foreach ( AStarNode node in ClosedSet ) node.BelongsToClosedSet = false; ClosedSet.Clear(); SWClosedSet.Stop(); SWOpenSet.Start(); // Clear the state of the open set nodes and clear the heap foreach ( AStarNode node in OpenSet ) node.BelongsToOpenSet = false; OpenSet.Clear(); SWOpenSet.Stop(); SWSetup.Stop(); SWTotal.Stop(); PathLength = mPath.Count; } AStarNode PopOpenSetMinimumNode() { AStarNode result = OpenSet.Remove(); result.BelongsToOpenSet = false; return result; } public override string ToString() { return "Agent >> Type: " + GetType().Name + ", Heuristic: " + Heuristic.GetType().Name + ", Start: [ " + StartNode.Column + " : " + StartNode.Row + " ], Goal: [ " + GoalNode.Column + " : " + GoalNode.Row + " ]"; } #endregion /////////////////////////////////////////////////////////////////////////////////////////// #region ctor public OptimizedAStarAgent( IAStarHeuristic heuristic, float coeffCostFromStart = 1f, float coeffCostToGoal = 1f, bool keypressAdvance = false ) { SWBacktrace = new Stopwatch(); SWBody = new Stopwatch(); SWClosedSet = new Stopwatch(); SWFindMin = new Stopwatch(); SWNodes = new Stopwatch(); SWOpenSet = new Stopwatch(); SWSetup = new Stopwatch(); SWTotal = new Stopwatch(); KeypressAdvance = keypressAdvance; Heuristic = heuristic; CoeffCostFromStart = coeffCostFromStart; CoeffCostToGoal = coeffCostToGoal; ClosedSet = new List<AStarNode>(); OpenSet = new GPWiki.BinaryHeap<AStarNode>(); Path = new List<AStarNode>();; } #endregion } } <file_sep>/README.md astar-testing ============= This project was created as a means of benchmarking different A* pathfinding implementations against one-another. Its primary purpose is to identify the factors resulting in the greatest increase in computational complexity, and so that different strategies to alleviate these factors can be compared.<file_sep>/AStarTesting/Navmesh/IAStarNavmesh.cs using System; using System.Collections.Generic; using SimplexNoise; namespace AStarTesting.Navmesh { public enum GridType { SquareGrid, // A regular square grid where only directly adjacent squares are linked SquareDiagonal, // A regular square grid where squares are linked to adjacent and diagonal squares HexGrid // A regular hexagonal grid } public class IAStarNavmesh { /////////////////////////////////////////////////////////////////////////////////////////// #region Properties /// <summary> /// /// </summary> Queue<IAStarAgent> mAgents; public Queue<IAStarAgent> Agents { get { return mAgents; } private set { mAgents = value; } } /// <summary> /// /// </summary> int mColumns; public int Columns { get { return mColumns; } private set { mColumns = value; } } /// <summary> /// /// </summary> GridType mGridType; public GridType GridType { get { return mGridType; } private set { mGridType = value; } } /// <summary> /// /// </summary> AStarNode[,] mNavmesh; public AStarNode[,] Navmesh { get { return mNavmesh; } private set { mNavmesh = value; } } /// <summary> /// /// </summary> int mRows; public int Rows { get { return mRows; } private set { mRows = value; } } #endregion /////////////////////////////////////////////////////////////////////////////////////////// #region Methods /// <summary> /// Adds the specified agent to the agents queue if it isn't already in there. /// </summary> /// <param name="agentToAdd">The agent to add to the queue.</param> /// <returns>True if the specified agent was added. False if the specified user is in the queue already.</returns> public bool AddAgent( IAStarAgent agentToAdd ) { if ( Agents.Contains( agentToAdd ) ) return false; Agents.Enqueue( agentToAdd ); return true; } /// <summary> /// /// </summary> public void GenerateResistanceNoise( float amplitude, float scale, float xOffset, float yOffset ) { // Build the mesh nodes for ( int i = 0; i < Columns; i++ ) { for ( int j = 0; j < Rows; j++ ) { float xPerlin = xOffset + scale * i; float yPerlin = yOffset + scale * j; float perlinSample = 0.5f * amplitude * ( Noise.Generate( xPerlin, yPerlin ) + 1f ); Navmesh[ i, j ].MoveCost = perlinSample; } } } /// <summary> /// Perform any startup operation necessary to prepare the nacmesh for traversal by agents. /// </summary> public void Init() { // Build the mesh nodes for ( int i = 0; i < Columns; i++ ) for ( int j = 0; j < Rows; j++ ) Navmesh[ i, j ] = new AStarNode( i, j, true, 1f ); // Link the navmesh for the selected grid type switch ( GridType ) { case GridType.SquareGrid: LinkAdjacentSquareGrid(); break; case GridType.SquareDiagonal: LinkDiagonalSquareGrid(); break; case GridType.HexGrid: LinkHexGrid(); break; } } protected void LinkAdjacentSquareGrid() { // Link the mesh nodes into a square grid without diagonal links for ( int i = 0; i < Columns; i++ ) { for ( int j = 0; j < Rows; j++ ) { if ( i < Columns - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i + 1, j ] ); Navmesh[ i + 1, j ].AddNeighbor( Navmesh[ i, j ] ); } if ( j < Rows - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i, j + 1 ] ); Navmesh[ i, j + 1 ].AddNeighbor( Navmesh[ i, j ] ); } } } } protected void LinkDiagonalSquareGrid() { // Link the mesh nodes into a square grid WITH diagonal links for ( int i = 0; i < Columns; i++ ) { for ( int j = 0; j < Rows; j++ ) { if ( i < Columns - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i + 1, j ] ); Navmesh[ i + 1, j ].AddNeighbor( Navmesh[ i, j ] ); } if ( j < Rows - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i, j + 1 ] ); Navmesh[ i, j + 1 ].AddNeighbor( Navmesh[ i, j ] ); } if ( i < Columns - 1 && j < Rows - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i + 1, j + 1 ] ); Navmesh[ i + 1, j + 1 ].AddNeighbor( Navmesh[ i, j ] ); } } } } protected void LinkHexGrid() { // Link the mesh nodes into a hex grid for ( int i = 0; i < Columns; i++ ) { for ( int j = 0; j < Rows; j++ ) { if ( j % 2 == 0 ) { // Hex 0 if ( i < Columns - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i + 1, j ] ); Navmesh[ i + 1, j ].AddNeighbor( Navmesh[ i, j ] ); } // Hex 1 if ( j < Rows - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i, j + 1 ] ); Navmesh[ i, j + 1 ].AddNeighbor( Navmesh[ i, j ] ); } // Hex 2 if ( i > 0 && j < Rows - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i - 1, j + 1 ] ); Navmesh[ i - 1, j + 1 ].AddNeighbor( Navmesh[ i, j ] ); } } else { // Hex 0 if ( i < Columns - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i + 1, j ] ); Navmesh[ i + 1, j ].AddNeighbor( Navmesh[ i, j ] ); } // Hex 1 if ( i < Columns - 1 && j < Rows - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i + 1, j + 1 ] ); Navmesh[ i + 1, j + 1 ].AddNeighbor( Navmesh[ i, j ] ); } // Hex 2 if ( j < Rows - 1 ) { Navmesh[ i, j ].AddNeighbor( Navmesh[ i, j + 1 ] ); Navmesh[ i, j + 1 ].AddNeighbor( Navmesh[ i, j ] ); } } } } } /// <summary> /// Removes the specified agent from the agent queue. /// </summary> /// <param name="agentToRemove">The agent to remove from the queue.</param> /// <returns>True if the specified agent was removed. False if the specified user wan't found in the queue.</returns> public bool RemoveAgent( IAStarAgent agentToRemove ) { if ( !Agents.Contains( agentToRemove ) ) return false; IAStarAgent firstAgent = Agents.Dequeue(); for ( IAStarAgent nextAgent = Agents.Dequeue(); nextAgent != firstAgent; nextAgent = Agents.Dequeue() ) { if ( agentToRemove != nextAgent ) Agents.Enqueue( nextAgent ); } return true; } /// <summary> /// Solve the A* path for the next agent in the queue. /// </summary> /// <returns>The agent that a path was solved for.</returns> public IAStarAgent SolveNext() { IAStarAgent nextAgent = Agents.Dequeue(); nextAgent.Solve(); Agents.Enqueue( nextAgent ); return nextAgent; } #endregion /////////////////////////////////////////////////////////////////////////////////////////// #region ctor public IAStarNavmesh( GridType gridType, int columns, int rows ) { GridType = gridType; Columns = columns; Rows = rows; Agents = new Queue<IAStarAgent>(); Navmesh = new AStarNode[ mColumns, mRows ]; Init(); } #endregion } } <file_sep>/AStarTesting/Heuristics/IAStarHeuristic.cs using System; using System.Collections.Generic; using AStarTesting.Navmesh; namespace AStarTesting.Heuristics { public interface IAStarHeuristic { /////////////////////////////////////////////////////////////////////////////////////////// #region Method Declarations /// <summary> /// Returns the estimated heuristic cost to reach the goal node from the current node (define the nodes in your implementation). /// </summary> /// <returns>An integer representing the heuristic estimate traversal cost.</returns> float GetEstimatedCost( AStarNode currentNode, AStarNode goalNode ); #endregion } } <file_sep>/AStarTesting/Navmesh/AStarNode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AStarTesting.Navmesh { public class AStarNode : IComparable<AStarNode> { /////////////////////////////////////////////////////////////////////////////////////////// #region Properties /// <summary> /// /// </summary> IAStarAgent mAgent; public IAStarAgent Agent { get { return mAgent; } set { mAgent = value; } } /// <summary> /// /// </summary> bool mBelongsToClosedSet; public bool BelongsToClosedSet { get { return mBelongsToClosedSet; } set { mBelongsToClosedSet = value; } } /// <summary> /// /// </summary> bool mBelongsToOpenSet; public bool BelongsToOpenSet { get { return mBelongsToOpenSet; } set { mBelongsToOpenSet = value; } } /// <summary> /// /// </summary> int mColumn; public int Column { get { return mColumn; } set { mColumn = value; } } /// <summary> /// /// </summary> float mCostTotal; public float CostTotal { get { return mCostTotal; } set { mCostTotal = value; } } /// <summary> /// /// </summary> float mCostFromStart; public float CostFromStart { get { return mCostFromStart; } set { mCostFromStart = value; } } /// <summary> /// /// </summary> float mCostToGoal; public float CostToGoal { get { return mCostToGoal; } set { mCostToGoal = value; } } /// <summary> /// /// </summary> float mMoveCost; public float MoveCost { get { return mMoveCost; } set { mMoveCost = value; } } /// <summary> /// /// </summary> List<AStarNode> mNeighbors; public List<AStarNode> Neighbors { get { return mNeighbors; } private set { mNeighbors = value; } } /// <summary> /// /// </summary> AStarNode mParent; public AStarNode Parent { get { return mParent; } set { mParent = value; } } /// <summary> /// /// </summary> int mRow; public int Row { get { return mRow; } set { mRow = value; } } /// <summary> /// /// </summary> bool mTraversable; public bool Traversable { get { return mTraversable; } set { mTraversable = value; } } #endregion /////////////////////////////////////////////////////////////////////////////////////////// #region Methods public void AddNeighbor( AStarNode node ) { Neighbors.Add( node ); } public void RemoveNeighbor( AStarNode node ) { Neighbors.Remove( node ); } public override string ToString() { StringBuilder result = new StringBuilder( "Node >> Column: " + Column + ", Row: " + Row + ", Traversable: " + Traversable + ", Neighbors: " ); foreach ( AStarNode neighbor in Neighbors ) result.Append( "[ " + neighbor.Column + " : " + neighbor.Row + " ], " ); return result.ToString(); } public int CompareTo( AStarNode other ) { if ( other == null ) return 1; return CostTotal.CompareTo( other.CostTotal ); } #endregion /////////////////////////////////////////////////////////////////////////////////////////// #region ctor public AStarNode( int column, int row, bool traversable = true, float moveCost = 1 ) { Column = column; Row = row; Traversable = traversable; MoveCost = moveCost; Neighbors = new List<AStarNode>(); } #endregion } } <file_sep>/AStarTesting/Program.cs using System; using AStarTesting.Testbed; namespace AStarTesting { public class Program { static void Main( string[] args ) { new AStarTestbed(); } } } <file_sep>/AStarTesting/Heuristics/ManhattanAStarHeuristic.cs using System; using System.Collections.Generic; using AStarTesting.Navmesh; namespace AStarTesting.Heuristics { public class ManhattanAStarHeuristic : IAStarHeuristic { /////////////////////////////////////////////////////////////////////////////////////////// #region Interface Methods public float GetEstimatedCost( AStarNode currentNode, AStarNode goalNode ) { return Math.Abs( goalNode.Column - currentNode.Column ) + Math.Abs( goalNode.Row - currentNode.Row ); } #endregion } } <file_sep>/AStarTesting/Testbed/AStarTestResult.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AStarTesting.Testbed { public struct AStarTestResult { // Test parameters public bool KeypressAdvance; public int RandomSeed; public string NavmeshGridType; public int NavmeshColumns; public int NavmeshRows; public string AgentType; public int XStart; public int YStart; public int XGoal; public int YGoal; public float SimplexAmplitude; public float SimplexScale; public float SimplexXOffset; public float SimplexYOffset; public string Heuristic; public float CoeffCostFromStart; public float CoeffCostToGoal; // Result data public long MaxClosedSetCount; public long MaxOpenSetCount; public long NodesConsideredCount; public long PathLength; public string PathString; public long MSBacktrace; public long TicksBacktrace; public long MSBody; public long TicksBody; public long MSClosedSet; public long TicksClosedSet; public long MSFindMin; public long TicksFindMin; public long MSNodes; public long TicksNodes; public long MSOpenSet; public long TicksOpenSet; public long MSSetup; public long TicksSetup; public long MSTotal; public long TicksTotal; public override string ToString() { return String.Join( ",", KeypressAdvance, RandomSeed, NavmeshGridType, NavmeshColumns, NavmeshRows, AgentType, "[ " + XStart + " : " + YStart + " ]", "[ " + XGoal + " : " + YGoal + " ]", SimplexAmplitude, SimplexScale, "[ " + SimplexXOffset + " : " + SimplexYOffset + " ]", Heuristic, CoeffCostFromStart, CoeffCostToGoal, MSTotal, MSSetup, MSBody, MSFindMin, MSBacktrace, MSClosedSet, MSOpenSet, MSNodes, TicksTotal, TicksSetup, TicksBody, TicksFindMin, TicksBacktrace, TicksClosedSet, TicksOpenSet, TicksNodes, NodesConsideredCount, MaxClosedSetCount, MaxOpenSetCount, PathLength, PathString ); } } } <file_sep>/AStarTesting/Heuristics/DijkstraAStarHeuristic.cs using System; using System.Collections.Generic; using AStarTesting.Navmesh; namespace AStarTesting.Heuristics { public class DijkstraAStarHeuristic : IAStarHeuristic { /////////////////////////////////////////////////////////////////////////////////////////// #region Interface Methods public float GetEstimatedCost( AStarNode currentNode, AStarNode goalNode ) { return 0; } #endregion } }
6cb2725179f1f50ae182d5b1969051dafb4a8273
[ "Markdown", "C#" ]
13
C#
DigitalMachinist/astar-testing
ff1165401a10ad0061230eb0b412a85fb89006fc
01fed32caa68314220cb7215b1b7606a77f3111b
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { NavigationContainer } from '@react-navigation/native'; import DrawerNavigator from './drawernavigator'; import { connect } from "react-redux"; import {setHomeData} from '../functions/redux/actions/homeAction'; class AppNavigator extends Component { constructor(props) { super(props); this.routeNameRef = React.createRef(); this.navigationRef = React.createRef(); } componentDidMount(){ this.props.dispatch(setHomeData()); } componentDidUpdate(){ console.log(this.props) } navigationReady = () => { this.routeNameRef.current = this.navigationRef.current.getCurrentRoute().name; console.log("Main Route ==>", this.routeNameRef.current) } navigationStateChange = () => { const previousRouteName = this.routeNameRef.current; const currentRouteName = this.navigationRef.current.getCurrentRoute().name if (previousRouteName !== currentRouteName) { console.log("New Route ===>", currentRouteName); } // Save the current route name for later comparision this.routeNameRef.current = currentRouteName; } render() { console.log("XXX===>",this.props) return ( <NavigationContainer ref={this.navigationRef} onReady={this.navigationReady} onStateChange={this.navigationStateChange} > <DrawerNavigator /> </NavigationContainer> ) } } function mapStateToProps(state) { return { homeState: state.home } } export default connect(mapStateToProps)(AppNavigator); <file_sep>import React, { Component } from 'react' import { Text, StyleSheet, View, Button } from 'react-native' import { connect } from "react-redux"; class HomeScreen extends Component { constructor(props){ super(props) } render() { const { navigation,homeState } = this.props console.log("===>", homeState) return ( <View> <Text> HomeScreen </Text> <Button title="test navigation" onPress={() => { navigation.navigate('FAQ') }} /> </View> ) } } const styles = StyleSheet.create({}) function mapStateToProps(state) { return { homeState: state.homeState, } } export default connect(mapStateToProps)(HomeScreen);<file_sep>import {setHomeData} from './homeReducer'; import {combineReducers} from 'redux'; import initialState from '../states'; const appReducer = combineReducers({ homeState:setHomeData }); const rootReducer = (state, action) => { // if (action.type === types.RESET_ROOT_STATE) { // const keptStates = { // states to preserve // }; // state = { // ...initialState, // ...keptStates // } // } return appReducer(state, action) }; export default rootReducer;<file_sep>import * as types from '../actionTypes'; export function setHomeData(data){ return function(dispatch){ dispatch({ type:types.SET_HOMEPAGE_DATA, homeState:{ Title:"asdasd" } }) } }<file_sep>import Contact from '../../screens/generic/contact'; import FAQ from '../../screens/generic/faq'; import TermsAndCondition from '../../screens/generic/termsandcondition'; import HomeScreen from '../../screens/private/homescreen'; import Profile from '../../screens/private/profile'; export default ({ Contact: { name: "Contact", screen: Contact, options: {} }, FAQ: { name: "FAQ", screen: FAQ, options: {} }, TermsAndCondition: { name: "TermsAndCondition", screen: TermsAndCondition, options: {} }, HomeScreen: { name: "HomeScreen", screen: HomeScreen, options: {} }, Profile: { name: "Profile", screen: Profile, options: {} } })<file_sep>export const SET_HOMEPAGE_DATA = "SET_HOMEPAGE_DATA";<file_sep>import React from 'react' import { View, Text, ImageBackground } from 'react-native'; import {Container,Content} from 'native-base'; import { DrawerContentScrollView, DrawerItemList, DrawerItem, } from '@react-navigation/drawer'; const Sidebar = (props) => { return ( <DrawerContentScrollView {...props}> {/* <DrawerItemList {...props} /> */} <DrawerItem label="Help" onPress={() => alert('Link to help')} /> </DrawerContentScrollView> ) } export default Sidebar; <file_sep>import { createStore, applyMiddleware, compose, } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from '../reducers'; import initialState from '../states'; const logger = store => next => action => { console.group(action.type) console.info('dispatching', action) let result = next(action) console.log('next state', store.getState()) console.groupEnd() return result; } const round = number => Math.round(number * 100) / 100 const monitorReducersEnhancer = createStore => ( reducer, enhancer ) => { const monitoredReducer = (state, action) => { const start = performance.now() const newState = reducer(state, action) const end = performance.now() const diff = round(end - start) console.log('reducer process time:', diff) return newState } return createStore(monitoredReducer, enhancer) } const configureStore = (preloadedState) => { const middlewares = [thunk,logger]; const middlewareObject = applyMiddleware(...middlewares); const enhancers = [middlewareObject, monitorReducersEnhancer]; const composedEnhancers = compose(...enhancers) const store = createStore( rootReducer, composedEnhancers ); return store; } const store = configureStore(); export { store };<file_sep>import * as types from '../actionTypes'; import initialState from '../states'; export function setHomeData(state = initialState.homeState, action) { switch (action.type) { case types.SET_HOMEPAGE_DATA: return { ...state, ...action.homeState }; break; default: return state; break; } }<file_sep>var jsonServer = require('json-server') var server = jsonServer.create() var router = jsonServer.router(require('./mock_database')()) var middlewares = jsonServer.defaults() router.render = (req,res) =>{ const path = req.url; const method = req.method.toLowerCase(); const db_data = require('./mock_database/database'+ path + '/index.' + method + '.json'); res.status(200).jsonp(db_data); } server.use(middlewares) server.use(router) server.listen(3000, function () { console.log('JSON Server is running') })<file_sep>import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import ScreenList from './screenlist'; import HomeScreen from '../../screens/private/homescreen'; const MainStackNavigator = () => { const MainNavigator = createStackNavigator(); return ( <MainNavigator.Navigator initialRouteName="HomeScreen"> { Object.entries({ ...ScreenList }).map(([key,component])=>{ // console.log(key,component) return <MainNavigator.Screen key={key} name={key} component={component.screen} options={component.options}/> }) } {/* <MainNavigator.Screen name="HOme" component={HomeScreen} /> */} </MainNavigator.Navigator> ) } export default MainStackNavigator;<file_sep>import React, { Component } from 'react' import { Text, View } from 'react-native' import AppNavigator from './navigators'; import { Root } from "native-base"; import { Provider } from "react-redux"; import { store } from './functions/redux/stores'; import 'react-native-gesture-handler'; class App extends Component { render() { return ( <Root> <Provider store={store}> <AppNavigator /> </Provider> </Root> ) } } export default App;<file_sep># Routing * This project uses reactnavigation v5 for routing. * Two Navigator is being used. 1. Stack Navigator - src/navigators/stacknavigator 2. Drawer Navigator - src/navigators/drawernavigator ## Routing screenflow * All screens are imported inside screenlist.js file. - src/navigators/stacknavigator/screenlist.js * All screens are nested under stack navigator. * And this stack navigator is nested inside the drawer navigator. - src/navigators/drawernavigator/index.js ```javascript <Stack.Navigator initialRouteName="Home"> {Object.entries({ ...screenlist, }).map(([name, component]) => ( return <Stack.Screen key={name} name={name} component={component.screen} options={component.options}/> ))} </Stack.Navigator> ``` * Finally we wrap the drawer navigator inside our Navigation cotainer and render in App.js. - src/navigators/index.js - src/App.js > Reason: - In previous versions of react navigation all configuration was static, so React Navigation could statically find the list of all the navigators and their screens by recursing into nested configurations. - As little nesting of navigators as possible to keep your code simpler. - Drawer navigator nested inside the initial screen of stack navigator with the initial screen's stack header hidden - The drawer can only be opened from the first screen of the stack. - We dont need send extra parameters to goback to previous page in our navigation. - If we press the back button when inside a screen in a nested stack navigator, it'll go back to the previous screen inside the nested stack even if there's another navigator as the parent. - Which means suppose we have screens A and B listed in our drawer navigator. And screens C, D and E in our stack navigator. And if or App we move from screen C to Screen A and then go to our Screen D . From Screen D if we try to go back using goBack() method it will not go to ScreenA it will go to Screen C . - We can achieve it through sending extra parameters. - For more information [https://reactnavigation.org/docs/nesting-navigators/] - Drawer is rendered under custom drawer content. - Swipe enable has been disabled ### Task List For Routing - [X] Create basic routing. - [ ] Remove header from stack navigation. - [ ] Create customized Header. - [ ] Finish Sidebar design.
6ef6292674c0b43bf054c75247f777c36b61954a
[ "JavaScript", "Markdown" ]
13
JavaScript
soum21/react_native_practice_app
57a1a0e676f03925b5530348255af5962674d534
d3349b36e87ca2de7fe902716ea07b84f5b44990
refs/heads/master
<file_sep>## Lachen App Web API coming soon... <file_sep>process.env.NODE_ENV = process.env.NODE_ENV || 'development'; var mongoose = require('./config/mongoose'); var express = require('./config/express'); var passport = require('./config/passport'); const settings = require('./config/settings.json'); var db = mongoose(); var app = express(); var passport = passport(); app.listen(8250); module.exports = app; console.log('Server running at http://localhost:8250'); <file_sep>module.exports = function(app) { var post = require('../controllers/post.controller'); app.route('/post') .post(post.list); app.route('/createpost') .post(post.create); app.route('/post/:id') // .get(post.read) // .put(post.update) .delete(post.delete); };<file_sep>var mongoose = require('mongoose'); var Post = mongoose.model('Post'); var User = mongoose.model('User'); var Schema = mongoose.Schema; var CommentSchema = new Schema({ comment: { type: String, required: true }, deleted: { type: String, required: true }, postId: { type: Schema.ObjectId, ref: 'Post' }, commenterId: { type: Schema.ObjectId, ref: 'User' } }); var Comment = mongoose.model('Comment', CommentSchema); var post = new Post(); post.save(); var user = new User(); user.save(); var comment = new Comment(); comment.postId = post; comment.commenterId = user; comment.save();<file_sep>module.exports = function(app) { var user = require('../controllers/user.controller'); app.post('/login', user.login); app.post('/logout', user.logout); app.route('/user') .post(user.create) .get(user.list); app.route('/user/:username') .get(user.read) .put(user.update) .delete(user.delete); app.param('username', user.userByUsername); };<file_sep>var mongoose = require('mongoose'); var User = mongoose.model('User'); var Schema = mongoose.Schema; var PostSchema = new Schema({ header: { type: String, required: true }, title: { type: String, required: true }, postDate: { type: Date, default: Date.now }, deleted: { type: String, required: true }, author: { type: Schema.ObjectId, ref: 'User' } }); var Post = mongoose.model('Post', PostSchema); var user = new User(); user.save(); var post = new Post(); post.author = user; post.save();<file_sep>module.exports = { debug: true, mongoUri: 'mongodb://localhost/api', sessionSecret: 'dev_secret_key' };<file_sep>'use strict' const error = module.exports = {} // Error Code Success error.code_00000 = '00000' error.desc_00000 = 'Success.' // error.desc_00000_login = 'Login success.' // error.desc_00000_logout = 'Logout success.' // error.desc_00000_logout = 'ออกจากระบบสำเร็จ' // Error Code Internal error.code_00001 = '00001' error.desc_00001 = 'Invalid Username or Password' error.code_00002 = '00002' error.desc_00002 = 'Invalid token.' error.code_00003 = '00003' error.desc_00003 = 'Internal exception error.' error.code_00004 = '00004' error.desc_00004 = 'Unknow URL.' error.code_00005 = '00005' error.desc_00005 = 'Incomplete parameter.' error.code_00006 = '00006' error.desc_00006 = 'Token expire.' error.code_00007 = '00007' error.desc_00007 = 'File not found.' error.code_00008 = '00008' error.desc_00008 = 'Upload file error.' error.code_00009 = '00009' error.desc_00009 = 'No Permission to Access.' // Error Code DB error.code_01001 = '01001' error.desc_01001 = 'Unsuccess data update.' error.code_01002 = '01002' error.desc_01002 = 'Query error.' error.code_01003 = '01003' error.desc_01003 = 'Data not found.' error.code_01004 = '01004' error.desc_01004 = 'Data already exist.' error.code_01005 = '01005' error.desc_01005 = 'Contract update unsuccess' error.code_01006 = '01006' error.desc_01006 = 'Location update unsuccess' error.code_01007 = '01007' error.desc_01007 = 'Area update unsuccess' error.code_01008 = '01008' error.desc_01008 = 'Contract and Location update unsuccess' error.code_01009 = '01009' error.desc_01009 = 'Contract and Area update unsuccess' error.code_01010 = '01010' error.desc_01010 = 'Contract, Lodation and Area update unsuccess' error.code_01011 = '01011' error.desc_01011 = 'Location and Area update unsuccess' error.code_01012 = '01012' error.desc_01012 = 'Area delete unsuccess' error.code_01013 = '01013' error.desc_01013 = 'Contract udpate and Area delete unsuccess' error.code_01014 = '01014' error.desc_01014 = 'Contract, Lodation update and Area delete unsuccess' error.code_01015 = '01015' error.desc_01015 = 'Location update and Area delete unsuccess' error.code_01016 = '01016' error.desc_01016 = 'Area insert unsuccess' error.code_01017 = '01017' error.desc_01017 = 'Contract udpate and Area insert unsuccess' error.code_01018 = '01018' error.desc_01018 = 'Contract, Lodation update and Area insert unsuccess' error.code_01019 = '01019' error.desc_01019 = 'Location update and Area insert unsuccess' error.code_01020 = '01020' error.desc_01020 = 'Agent insert unsuccess' error.code_01021 = '01021' error.desc_01021 = 'Location insert unsuccess' // Error Code Archiving error.code_02001 = '02001' error.desc_02001 = 'Archiving error.' error.code_02002 = '02002' error.desc_02002 = 'Archiving authen error.' error.code_02003 = '02003' error.desc_02003 = 'Archiving download error.' // Error Code OM error.code_03001 = '03001' error.desc_03001 = 'OM error.' error.code_03002 = '03002' error.desc_03002 = 'OM data not found.' error.code_03003 = '03003' error.desc_03003 = 'OM soapCreateClient error.' error.code_03004 = '03004' error.desc_03004 = 'OM client call error.' error.code_03005 = '03005' error.desc_03005 = 'OM parseString result error.' error.code_03006 = '03006' error.desc_03006 = 'OM query unsuccess.' error.code_03007 = '03007' error.desc_03007 = 'OM manager not found.' error.code_03008 = '03008' error.desc_03008 = 'Create soap client error.' error.code_03009 = '03009' error.desc_03009 = 'Authenticate ldap error.' error.code_03010 = '03010' error.desc_03010 = 'Authenticate ldap invalid username/password.' // Error Code Email error.code_04000 = '04000' error.desc_04000 = 'Email Sent.' error.code_04001 = '04001' error.desc_04001 = 'Send Email Unsuccess.' // Error Code SAP error.code_05001 = '05001' error.desc_05001 = 'ไม่สามารถส่งเบิกอุปกรณ์ที่ SAP ได้ กรุณาติดต่อ Admin'<file_sep>var User = require('mongoose').model('User'); var Post = require('mongoose').model('Post'); var PostDetail = require('mongoose').model('PostDetail'); const error = require('../../config/error'); exports.create = function (req, res, next) { var post = new Post(req.body.post); post.save(function (err) { if (err) { return next(err); } else { var postDetail = new PostDetail({ "sequence": req.body.postdetail.sequence, "content": req.body.postdetail.content, "angularjs": req.body.postdetail.angularjs, "html5": req.body.postdetail.html5, "css": req.body.postdetail.css, "postId": post._id }); postDetail.save(function (err) { if (err) { return next(err); } else { res.json({ errorCode: error.code_00000, errorDesc: error.desc_00000 }); } }); } }); }; exports.list = function (req, res, next) { var innerjoin = { path: 'postId', model: 'Post', populate: { path: 'author', model: 'User' } } var total = 0; PostDetail.find({}, function(err, postdetails) { if (err) { return next(err); } else { total = postdetails.length; } }); PostDetail.find({},{},{ skip: (req.body.currentPage-1) * req.body.pageSize, limit: req.body.pageSize}).populate(innerjoin).exec(function (err, postdetails) { if (err) { return next(err); } else { var postdetail = {}; var index = 0; postdetails.forEach(function (element) { postdetail[index] = { "id": element.postId._id, "header": element.postId.header, "title": element.postId.title, "content": element.content, "sequence": element.sequence, "username": element.postId.author.username, "postDate": element.postId.postDate, "angularjs": element.angularjs, "html5": element.html5, "css": element.css }; index++; }, this); postdetail.length = total; res.json(postdetail); } }); }; exports.delete = function (req, res, next) { PostDetail.findOneAndRemove({ postId: req.params.id }, function (err) { if (err) { return next(err); } else { Post.findByIdAndRemove(req.params.id, function (err) { if (err) { return next(err); } else { res.json({ errorCode: error.code_00000, errorDesc: error.desc_00000 }); } }); } }); }; <file_sep>var mongoose = require('mongoose'); var Post = mongoose.model('Post'); var Schema = mongoose.Schema; var PostDetailSchema = new Schema({ sequence: { type: String, required: true }, content: { type: String, required: true }, angularjs: { type: Boolean, default: false }, html5: { type: Boolean, default: false }, css: { type: Boolean, default: false }, postId: { type: Schema.ObjectId, ref: 'Post' } }); var PostDetail = mongoose.model('PostDetail', PostDetailSchema); var post = new Post(); post.save(); var postDetail = new PostDetail(); postDetail.postId = post; postDetail.save();
5cb313b0b71d8d1ae4e7c274d435e909854520ed
[ "Markdown", "JavaScript" ]
10
Markdown
lachendev/api
1561742deaaceaac7abae9157ee5b8edb9cfe419
38abb19564925a5e7323d5cfc8ca75d9faeb5dfb
refs/heads/master
<repo_name>Air-TR/springcloud-s<file_sep>/eureka-feign/src/main/java/com/tr/springcloud/eurekafeign/controller/HiController.java package com.tr.springcloud.eurekafeign.controller; import com.tr.springcloud.eurekafeign.service.HiService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author TR * @date 2021/1/19 下午5:19 */ @RestController public class HiController { @Resource HiService hiService; @GetMapping("/hi/{name}") public String hi(@PathVariable String name) { return hiService.hi(name); } } <file_sep>/eureka-client-cp1/src/main/java/com/tr/springcloud/eurekaclient/EurekaClientCp1Application.java package com.tr.springcloud.eurekaclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author TR * @date 2021/1/19 下午3:06 */ @SpringBootApplication @EnableEurekaClient public class EurekaClientCp1Application { public static void main(String[] args) { SpringApplication.run(EurekaClientCp1Application.class, args); } } <file_sep>/config-client/src/main/java/com/tr/springcloud/configclient/controller/ConfigClientController.java package com.tr.springcloud.configclient.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @RefreshScope 注解必须放在Controller层上,否则请求 http://localhost:8770/actuator/bus-refresh 正确后也读不到最新配置。 * post 请求 http://localhost:8770/actuator/bus-refresh 正确响应后返回 204 code。 * * @author TR * @date 2021/1/21 上午11:24 */ @RestController @RefreshScope public class ConfigClientController { @Value("${version}") private String version; @Value("${name}") private String name; @GetMapping("/version") public String getVersionFromConfigServer() { return version; } @GetMapping("/name") public String getNameFromConfigServer() { return name; } } <file_sep>/eureka-client-cp2/src/main/java/com/tr/springcloud/eurekaclient/controller/HiController.java package com.tr.springcloud.eurekaclient.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * @author TR * @date 2021/1/19 下午3:10 */ @RestController public class HiController { @Value("${spring.application.name}") private String server; @Value("${server.port}") private String port; @GetMapping("/hi/{name}") public String hi(@PathVariable String name) { return "Hi " + name + ", response from " + server + ", port: " + port; } } <file_sep>/eureka-feign/src/main/java/com/tr/springcloud/eurekafeign/config/FeignConfig.java package com.tr.springcloud.eurekafeign.config; import feign.Retryer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static java.util.concurrent.TimeUnit.SECONDS; /** * @author TR * @date 2021/1/19 下午4:52 */ @Configuration public class FeignConfig { /** * 在该类中注入Retryer的Bean,覆盖掉默认的Retryer的Bean,从而达到自定义配置的目的。 * 例如Feign 默认的配置在请求失败后,重试次数为0,即不重试( Retry er.NEVER_RETRY )。 * 更改为FeignClient 请求失败后:重试间隔为100毫秒,最大重试时间为1秒,重试次数5次。 * @return */ @Bean public Retryer feignRetryer() { return new Retryer.Default(100, SECONDS.toMillis(1), 5); } }
76b6ee5dd1651b776dbfeef7e7d63a8f2209babc
[ "Java" ]
5
Java
Air-TR/springcloud-s
8b32ad1bac0fbf092b590c760f5a63f8c948e465
fbc6483ca87d953ed36c8abb20f6dfe6102b20c2
refs/heads/master
<file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Contact:</h2> <img src="images/tab-divider.png"> <p>If you need us to suggest a company to you, please complete the questionnaire found <a href="http://debtcompanyresearch.com">here.</a></p> <p>We answer every email we get so if you have questions, email us at <EMAIL>.</p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><!DOCTYPE html> <html> <head> <title>Debt Company Research</title> <link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic' rel='stylesheet' type='text/css'> <link href="http://debtcompanyresearch.com/thankyou/normalize.css" rel="stylesheet" type="text/css" /> <link href="http://debtcompanyresearch.com/thankyou/style.css" rel="stylesheet" type="text/css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="http://fast.fonts.net/jsapi/6dbe4694-2b80-4458-8fce-b314a507def2.js"></script> <script src="http://debtcompanyresearch.com/function.js"></script> <script src="http://debtcompanyresearch.com/thankyou/functions.js"></script> <script src="http://debtcompanyresearch.com/js/spritely.js" type="text/javascript"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-44289017-1', 'debtcompanyresearch.com'); ga('send', 'pageview'); var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-44289017-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> (function() { window._pa = window._pa || {}; // _pa.orderId = "<EMAIL>"; // OPTIONAL: attach user email or order ID to conversions // _pa.revenue = "19.99"; // OPTIONAL: attach dynamic purchase values to conversions var pa = document.createElement('script'); pa.type = 'text/javascript'; pa.async = true; pa.src = ('https:' == document.location.protocol ? 'https:' : 'http:') + "//tag.perfectaudience.com/serve/524c51761c34d41143000097.js"; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pa, s); })(); </script> </head> <body> <div class="header"> <div class="clouds"> </div> <div class="container"> <div class="logo"> <a href="http://debtcompanyresearch.com"><img alt="debt relief logo" src="http://www.debtcompanyresearch.com/thankyou/images/logo.png"></a> </div> <div class="success-banner"> </div> <div class="scott-face"> </div> <div class="scott-message"> <p>Hello,</p> <p>We have helped over 69,000 people find honest, reliable, and ethical debt solution companies you can trust.</p> <p>We personally meet with every company as part of our extensive research so you can relax and get out of debt safely.</p> <p>Based on the information you provided, here is the company we suggest you speak with for straightforward, no pressure debt relief options and advice so you can become debt free as fast as possible. We have passed along your information so they can contact you with a quote.</p> <p>Thank You!</p> <p>Scott</p> </div> <?php if (trim($_GET["chosen"]) == "delray") { ?> <div class="content-panel delray"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Delray Credit Counseling</h1> <p>www.DelrayCC.com</p> <p>877.209.2225</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT DELRAY:</p> <p>&raquo; <span>In Business Since:</span> 2003</p> <p>&raquo; <span>BBB Rating:</span> A</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> Association of Credit Counseling Professionals, Fincert.org Certified, BSI Certified</p> </div> <div class="full-report-text"> <p>Get the full report on Delray and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <a href="pdf/Delray_Report.pdf"><div class="download-report"> </div><a href="pdf/Cambridge_Report.pdf"> </div> </div> <?php } if (trim($_GET["chosen"]) == "cambridge") { ?> <div class="content-panel cambridge"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Cambridge Credit Counseling</h1> <p>www.Cambridge-Credit.org</p> <p>800.857.2808</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT CAMBRIDGE:</p> <p>&raquo; <span>In Business Since:</span> 1996</p> <p>&raquo; <span>BBB Rating:</span> A+</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> AICCCA Member, ACC Pros Member, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on Cambridge and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <a href="pdf/Cambridge_Report.pdf"><div class="download-report"> </div></a> </div> </div> <?php } if (trim($_GET["chosen"]) == "national") { ?> <div class="content-panel national"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>National Debt Relief</h1> <p>www.NationalDebtRelief.com</p> <p>888.703.4948</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT NATIONAL:</p> <p>&raquo; <span>In Business Since:</span> 2005</p> <p>&raquo; <span>BBB Rating:</span> A</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> AFCC Member, IAPDA Certified, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on National and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <a href="pdf/National_Report.pdf"><div class="download-report"> </div></a> </div> </div> <?php } if (trim($_GET["chosen"]) == "pacific") { ?> <div class="content-panel pacific"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Pacific Debt Relief</h1> <p>www.PacificDebt.com</p> <p>877.722.3328</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT PACIFIC:</p> <p>&raquo; <span>In Business Since:</span> 2002</p> <p>&raquo; <span>BBB Rating:</span> A+</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> BSI Certified, AFCC Member, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on Pacific and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <a href="pdf/Pacific_Report.pdf"><div class="download-report"> </div></a> </div> </div> <?php } if (trim($_GET["chosen"]) == "superior") { ?> <div class="content-panel superior"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Superior Debt Relief</h1> <p>www.SuperiorDebtRelief.com</p> <p>888.366.3414</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT SUPERIOR:</p> <p>&raquo; <span>In Business Since:</span> 1998</p> <p>&raquo; <span>BBB Rating:</span> A+</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> BSI Certified, IAPDA Certified, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on Superior and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <a href="pdf/Superior_Report.pdf"><div class="download-report"> </div></a> </div> </div> <?php } ?> <div class="footer-content"> <div class="footer-privacy"> <p>Privacy</p> </div> <p>|</p> <div class="footer-terms"> <p>Terms</p> </div> </div> </div> </div> <div class="close-popout"> <div class="close-popout-x"> <p>X</p> </div> </div> <div class="privacy-popout"> <div class="tabbed-content"> <div class="tab-text"> <h2>Privacy:</h2> <p> This Privacy Policy covers what we do with any personal information you may submit, as well as any other information that we may gather when you access our website. </p> <p> Please note that our policies and procedures apply only to this website owned by us and not to websites maintained by other companies or to any website to which we may link or businesses with which we may share information. </p> <p> Personal information is any information that you provide to us that identifies you, personally, or that can be associated with you. Examples of personal information that will be collected on our site include your name, your address, your e-mail address, your phone number. </p> <p> We collect and use personal information in order to respond to your requests for services offered through our website and those of our business partners. We also collect personal and other information in order to make you aware of products and/or services that are likely to be of interest to you. </p> <p> We collect and maintain the information you provide to us whenever you visit our website(s), such as: </p> <ul type="disc"> <li> Any information you provide to us when you request a quote, more information, or a service. This includes your contact information, your name, and additional information such as the amount of your current unsecured debt. </li> <li> Information, such as your e-mail address, that you provide to us when you register to receive communications from us or when you communicate with us, or otherwise correspond with us. </li> </ul> <p> We also collect other, non-personal information, which is broadly defined as any information that is not and cannot be directly associated with you. An example of this type of non-personal information would be your state of residence. We use the personal information you supply to us, or that you authorize us to obtain, to provide to you the service(s) or product(s) that you request. We may also use your personal and other information to enhance your experience on our website(s) by displaying content based on your preferences and/or to send information to you about additional products or services in which you may be interested. </p> <p> If you submit a request for information or a quote, we will share the personal and other information you supply (such as your name, email, zip code, debt amounts etc.) with those product and service providers that have agreed to participate in our network. Generally, these are debt relief solution providers who are prohibited from using the information we provide to them for any other purpose, including using your information for other, unrelated marketing purposes. </p> <p> By submitting your request you are consenting to being contacted by us or by our business partners through any means, based on the information you provide to us, even if you have opted into the National Do Not Call List administered by the Federal Trade Commission, any state Do Not Call List or the Do Not Call List of any specific institution. If, after you are contacted by that product or service provider, you do not wish to be contacted by that person again you must make a specific request to the service provider. </p> <p> We may be required to share your information with law enforcement or government agencies in response to subpoenas, court orders or other forms of legal process. We may elect to share information when, in our reasonable judgment, such sharing is necessary or appropriate for the investigation or prevention of illegal activities, including actual or suspected fraud, real or potential threats to the physical safety of any person or otherwise as required by law. </p> <p> In addition, if we are merged with, or acquired by, another company the successor company will have access to all of the information collected and maintained by us. In such a circumstance, the successor company would continue to be bound by the terms and conditions of this Privacy Policy. You will be notified via email and/or a prominent notice on our Web site of any change in ownership or uses of your personal information, as well as any choices you may have regarding your personal information. </p> <p> We collect certain types of non-personal information and technical data from each visitor to our website(s). For example, when you click on a banner advertisement or text link that is associated with one of our websites, the banner or text placement, along with the time of your visit, your Internet Protocol address and other path-related information, is sent to us. Similarly, the page requests you make when you visit our website(s) are stored and used by us. We use this information, none of which is or can be personally associated with you, for statistical and analytic purposes, to help us understand which page views are most appealing to our customers and to help us improve the likelihood that we will be able to offer you only products or services in which you have a genuine interest. </p> <p> "Cookies" are small files that are placed automatically on your computer system when you visit a website. Cookies enable a website to recognize you as a return visitor and, by keeping track of your website activity, help us identify which pages to serve to you while reducing the time it takes for those pages to load. Cookies enable us to personalize and enrich your experience and are not tied in any way to your personal information. If you do not wish to accept cookies or if you wish to remove cookies that remain in your browser following the close of your browser session, you may adjust the settings on your web browser to prevent cookies from being placed on your hard drive. </p> <p> The security of your personal information is a very high priority for us and we take a number of steps to safeguard it. </p> <p> We use commercially reasonable physical and technical security measures to protect all personal information in our possession. We cannot, however, guarantee or warrant the absolute security of any system or that any information we hold will not be accessed, disclosed, altered or destroyed. </p> <p> We may retain your information indefinitely although it would only be used within the specifications of this privacy policy. We will retain and use your information as necessary to comply with our legal obligations, resolve disputes, and enforce our agreements. Under certain circumstances, Federal and/or state law may require us to retain your personal information for different periods of time. Accordingly, we may not be able to delete or otherwise remove your personal information from our systems. </p> <p> Yes, you may contact us to do so at anytime to remove or edit your information. </p> <p> You can always elect not to provide personal information to us. If you wish to request that we no longer use your information to provide you services contact us at <EMAIL>. If you decide, at a later point in time, that you no longer want us to share your personal information with our business partners you may notify us either by sending us an e-mail: <EMAIL> </p> <p> We have a strict "anti-spam" policy. You will not receive e-mails from us unless you submit your e-mail address to us. We do not permit any third-party e-mail service to send unsolicited e-mails &#8212; "spam" &#8212; to any person who has not previously given their permission to receive such communications to that third party e-mail service. If you wish to stop receiving future e-mails from a third-party e-mail service, we recommend you follow the opt-out instructions included in the e-mail. An "unsubscribe" link should appear within or at the top or bottom of any e-mail you receive. </p> <p> If you submit a testimonial to us, we will ask for your permission to post your testimonial prior to any public use. We will post your name as given to us in your testimonial. We may post a photo of you or use a stock photo. Please be aware that any personally identifiable information you submit as a testimonial to be posted can be read, collected, or used by the general public, and could be used to send you unsolicited messages. We are not responsible for the personally identifiable information you choose to include in any testimonial you choose to submit. If at any time you decide to remove your testimonial, please contact us via e-mail or postal mail. </p> <p> We do not knowingly collect, use or share personal information about visitors under 18 years of age. If you are under 18 years of age, you can use the products and/or services offered on our website(s) only in conjunction with your parents or guardians. </p> </div> </div> </div> <div class="terms-popout"> <div class="tabbed-content"> <div class="tab-text"> <h2>Terms:</h2> <p> The Agreement describes the terms and conditions applicable to your use of the Debt Company Research (DCR) Website. These terms may be updated by DCR from time to time without notice to you. </p> <p> You must read and agree with all of the terms and conditions contained in these terms and the DCR Website privacy policy before you use the Service. If you do not agree to be bound by the terms and conditions of this Agreement, you may not use or access the Service. </p> <p> 1. <strong>What We Do.</strong> The DCR Website is a matching service that helps you find companies and counselors to assist you with financial needs. You understand and agree that if you submit a request for a service offered through the Website, DCR will share your personal information (such as your full name, state of residence, telephone number, email, and debt amount) with Providers in our provider network (referred to individually as &quot;Provider&quot; and collectively as &quot;Providers&quot;) to process and fulfill your request about their services. </p> <p> We carefully screen our providers and offer the opportunity to be on our site only to those we believe are trustworthy and reputable. Please understand the providers shown on this site are paying clients of ours. We have a marketing relationship with them and we may be compensated for providing your information as a lead or on a per client obtained basis. You acknowledge that DCR is not a party to any agreement that you may make with the Provider, and that the Provider is solely responsible for its services to you. You further acknowledge that DCR is not acting as your agent or broker and is not recommending any particular product or Provider to you. We offer our opinion and our research. The opinions about companies profiled on the DCR website are ours and we make no warranties, representations, or guarantees regarding the products or services provided by the 3rd party companies on the site. The opinions are opinions only and any user should do their own research prior to engaging the services of the companies profiled on DCR. Any compensation DCR may receive is paid by the individual Provider for services rendered by DCR to that particular Provider on a per lead, per sale or per phone contact basis. DCR does not charge you a fee to use the DCR Website. You understand that DCR does not endorse, warrant, or guarantee the products or services of any the Providers. We have done research on the companies mentioned on the site and have based our opinions on that research. You agree that DCR shall not be liable for any damages or costs of any type which arise out of or in connection with your use of the Provider&#39;s service. </p> <p> By submitting your contact request, you are consenting to be contacted by the Provider either by telephone, email or mail based on the information you have provided to us, even if you have opted into the National Do Not Call List administered by the Federal Trade Commission, any state equivalent Do Not Call List, or the Do Not Call List of an internal company. You understand that the Provider may maintain the information you submitted to DCR whether you elect to use their services or not. In the event you no longer want to receive communications from a Provider, you agree to notify the Provider directly. You also give DCR permission to send you periodic updates on behalf of the Provider which may be of interest to you. </p> <p> 2. <strong>Uses of the DCR Website and Service.</strong> You certify to DCR that: (i) you are at least eighteen (18) years of age; (ii) you assume full responsibility for the use of the Service by any minors; (iii) you agree that all information you have submitted to DCR, online or otherwise, is accurate and complete, and that you have not knowingly submitted false information on or through the DCR Website or Service; and, (iv) your use of the Service is subject to all applicable federal, state, and local laws and regulations. </p> <p> 3. <strong>Prohibited.</strong> You must not (i) submit, transmit or facilitate the distribution of information or content that is harmful, abusive, racially or ethnically offensive, vulgar, sexually explicit, defamatory, infringing, invasive of personal privacy or publicity rights, or in a reasonable person&#39;s view, objectionable; (ii) submit, transmit, promote or distribute information or content that is illegal; (iii) attempt to interfere with, compromise the system integrity or security or decipher any transmissions to or from the servers running the Service; (iv) take any action that imposes, or may impose at our sole discretion an unreasonable or disproportionately large load on our infrastructure; (v) upload invalid data, viruses, worms, or other software agents through the Service; (vi) use any robot, spider, scraper or other automated access the Service for any purpose without our express written permission; (vii) impersonate another person or otherwise misrepresent your affiliation with a person or entity, conduct fraud, hide or attempt to hide your identity; (viii) submit, upload, post, email, transmit or otherwise make available any information or content that you do not have a right to make available under any law or under contractual or fiduciary relationships; (ix) interfere with the proper working of the Service; or, (x) bypass the measures we may use to prevent or restrict access to the Service. </p> <p> 4. <strong>Privacy.</strong> DCR respects your privacy. Personal information submitted in connection with the Service is subject to our Privacy Policy. </p> <p> 5. <strong>Copyright and Trademark Notice Info.</strong> All contents of the DCR Website are: Copyright &copy; 2013 &#8212; DCR and/or its Providers and third party vendors. All rights reserved. All trademarks and service marks and other DCR logos, Provider logos, and product service names are trademarks of DCR (&quot;DCR Marks&quot;) and the Providers. Without DCR prior permission, you agree not to display or use in any manner, the DCR Marks. All other logos or brand names shown on the Service are trademarks of their respective owners and/or licensors. </p> <p> 6. <strong>Proprietary Rights.</strong> You acknowledge and agree that the Service and any necessary software used in connection with the Service (&quot;Software&quot;) contain proprietary and confidential information that is protected by applicable intellectual property and other laws. You further agree that all materials and/or content, including, but not limited to, articles, artwork, screen shots, graphics, logos, text, drawings and other files on the DCR Website or as part of the Service are copyrights, trademarks, service marks, patents or other proprietary rights of DCR or their respective intellectual property owners. Except as expressly authorized by DCR, you agree not to modify, copy, reproduce, sell, distribute or create derivative works based on or contained within the Service or the Software, in whole or in part. </p> <p> DCR grants you a personal, non-transferable and non-exclusive right and license to use the code of its Software on a single computer; provided that you do not copy, modify, create a derivative work of, reserve engineer, decompile, reverse assemble or otherwise attempt to discover any source code, sell, assign, sublicense, grant a security interest in or otherwise transfer any right in the Software. You agree not to modify the Software in any manner or form, or to use modified versions of the Software, including, without limitation, for the purpose of obtaining unauthorized access to the Service by any means other than through the interface that is provided by DCR for use in accessing the Service. </p> <p> 7. <strong>Site </strong><strong>Links.</strong> DCR, through the Service or otherwise, may provide links to other websites. Because DCR has no control over such websites, you acknowledge and agree that DCR is not responsible for the availability of such external websites, and does not endorse and is not responsible or liable for any content, advertising, products or other materials on or available from such websites. You further acknowledge and agree that DCR shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, products, goods or services available on or through any such website. </p> <p> 8. <strong>Indemnification.</strong> You agree to indemnify and hold DCR, its subsidiaries, affiliates, agents, shareholders, officers, contractors, vendors and employees harmless from any claim or demand, including reasonable attorneys&#39; fees, made by any third party due to or arising out of your use of the Service, the violation of the Agreement by you, or the infringement by you, or any other user of the Service using your computer, of any intellectual property or other right of any person or entity. DCR reserves the right, at its own expense, to assume the exclusive defense and control of any matter otherwise subject to indemnification by you. </p> <p> 9. <strong>No Warranty.</strong> DCR PROVIDES THE SERVICE &quot;AS IS,&quot; &quot;WITH ALL FAULTS&quot; AND &quot;AS AVAILABLE,&quot; AND THE ENTIRE RISK AS TO SATISFACTORY QUALITY, PERFORMANCE, ACCURANCY, AND EFFORT IS WITH YOU. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, DCR MAKES NO REPRESENTATIONS, WARRANTIES OR CONDITIONS, EXPRESS OR IMPLIED. DCR DISCLAIMS ANY AND ALL WARRANTIES OR CONDITIONS, EXPRESS, STATUTORY AND IMPLIED, INCLUDING WITHOUT LIMITATION: (i) WARRANTIES OR CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, ACCURACY, TITLE, QUIET ENJOYMENT, NO ENCUMBRANCES, NO LIENS AND NON-INFRINGEMENT; (ii) WARRANTIES OR CONDITIONS ARISING THROUGH COURSE OF DEALING OR USAGE OF TRADE; AND, (iii) WARRANTIES OR CONDITIONS THAT ACCESS TO OR USE OF THE SERVICE WILL BE UNINTERRUPTED OR ERROR-FREE. THERE ARE NO WARRANTIES THAT EXTEND BEYOND THE FACE OF THIS AGREEMENT. </p> <p> 10. <strong>Limitation of Liability</strong>. IN NO EVENT WILL DCR BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION ANY INDIRECT, CONSEQUENTIAL, SPECIAL, INCIDENTAL, OR PUNITIVE DAMAGES ARISING OUT OF, BASED ON, OR RESULTING FROM THIS AGREEMENT OR YOUR USE OF THE SERVICE, EVEN IF DCR HAS BEEN ADVISED OF THE POSSIBLITY OF SUCH DAMAGES. THESE LIMITATIONS AND EXCLUSIONS APPLY WITHOUT REGARD TO WHETHER THE DAMAGES ARISE FROM (1) BREACH OF CONTRACT, (2) BREACH OF WARRANTY, (3) STRICT LIABILITY, (4) TORT, (5) NEGLIGENCE, OR (6) ANY OTHER CAUSE OF ACTION, TO THE EXTENT SUCH EXCLUSION AND LIMITATIONS ARE NOT PROHIBITED BY APPLICABLE LAW. IF YOU ARE DISSATISFIED WITH THE SERVICE, YOU DO NOT AGREE WITH ANY PART OF THIS AGREEMENT, OR HAVE ANY OTHER DISPUTE OR CLAIM WITH OR AGAINST DCR WITH RESPECT THIS AGREEMENT OR THE SERVICE, THEN YOUR SOLE AND EXCLUSIVE REMEDY IS TO DISCONTINUE USING THE SERVICE. </p> <p> 11. <strong>Release.</strong> YOU HEREBY AGREE TO RELEASE, REMISE AND FOREVER DISCHARGE DCR AND ITS AFFILLIATES, PARTNERS, SERVICE PROVIDERS, VENDORS, AND CONTRCTORS AND EACH OF THEIR RESPECTIVE AGENTS, DIRECTORS, OFFICERS, EMPLOYEES, AND ALL OTHER RELATED PERSONS OR ENTITIES FROM ANY AND ALL MANNER OF RIGHTS, CLAIMS, COMPLAINTS, DEMANDS, CAUSES OF ACTION, PROCEEDINGS, LIABLITIES, OBLIGATIONS, LEGAL FEES, COSTS, AND DISBURSEMENTS OF ANY NATURE WHATSOEVER, WHETHER KNOWN OR UNKNOWN, WHICH NOW OR HEREAFTER ARISE FROM, RELATE TO, OR ARE CONNECTED WITH YOUR USE OF THE SERVICE. </p> <p> 12. <strong>Notice.</strong> DCR may provide you with notices, including those regarding changes to the Agreement by posting on this Service. </p> <p> 13. <strong>Termination.</strong> You agree that DCR may, under certain circumstances and without prior notice, immediately terminate your access to the Service. Cause for such termination shall include, but not be limited to: (i) breaches or violations of the Agreement or other incorporated agreements or the Privacy Policy; (ii) requests by law enforcement or other government agencies; (iii) discontinuance or material modification to the Service (or any part thereof); and (iv) unexpected technical or security issues or problems. You agree that all terminations for cause shall be made in DCR&#39;s sole discretion and that DCR shall not be liable to you or any third party for any termination or access to the Service. </p> <p> 14. <strong>Dealings with Third Parties.</strong> Your correspondence or business dealings with any third parties as a result of your visit and participation in the Service or any other terms, conditions, warranties, representations associated with such dealings, are solely between you and such third party. You agree that DCR shall not be responsible or liable for any loss or damage of any sort incurred as the result of any such dealings or as the result of the presence of such third party on the Service. </p> <p> 15. <strong>Disputes.</strong> This Agreement will be interpreted in accordance with the laws of the State of California, without regard to the conflicts of laws principles thereof. The parties agree that any and all disputes, claims or controversies arising out of or relating to the Agreement, its interpretation, performance, or breach, that are not resolved by informal negotiation within 30 days (or any mutually agreed extension of time), shall be submitted to final and binding arbitration before a single arbitrator of the American Arbitration Association (&quot;AAA&quot;) in San Diego, California, or its successor. Either party may commence the arbitration process called for herein by submitting a written demand for arbitration with the AAA, and providing a copy to the other party. The arbitration will be conducted in accordance with the provisions of the AAA&#39;s Commercial Dispute Resolutions Procedures in effect at the time of submission of the demand for arbitration. The costs of arbitration plus reasonable attorneys&#39; fees (including fees for the value of services provided by in house counsel) shall be awarded to the prevailing party in such arbitration. Judgment on the award rendered by the arbitrator may be entered in the Superior Court of California, County of San Diego. Notwithstanding the foregoing, the following shall not be subject to arbitration and may be adjudicated only in the Superior Court of California, County of San Diego: (i) any dispute, controversy, or claim relating to or contesting the validity of DCR&#39;s proprietary rights, including without limitation, trademarks, service marks, copyrights, or trade secrets; or, (ii) an action by a party for temporary, preliminary, or permanent injunctive relief, whether prohibitive or mandatory, or provisional relief such as writs of attachments or possession. </p> <p> THE PARTIES AGREE THAT THIS AGREEMENT HAS BEEN ENTERED INTO AT DCR&#39;S PLACE OF BUSINESS IN THE COUNTY OF SAN DIEGO, STATE OF CALIFORNIA, AND ANY ARBITRATION, LEGAL ACTION OR PROCEEDING ARISING OUT OF OR RELATING TO THIS AGREEMENT MUST BE COMMENCED AND TAKE PLACE IN THE COUNTY OF SAN DIEGO, STATE OF CALIFORNIA. </p> <p> 16. <strong>Modification to Service.</strong> DCR reserves the right at any time and from time to time to modify or discontinue, temporarily or permanently, the Service (or any part thereof) with or without notice. You agree that DCR shall not be liable to you or to any third party for any modification, suspension or discontinuance of the Service. </p> <p> 17. <strong>Waiver and Severability of Terms.</strong> The failure of DCR to exercise or enforce any right or provision of the Agreement shall not constitute a waiver of such right or provision. If any provision of the Agreement is found by a court of competent jurisdiction to be invalid, the parties nevertheless agree that the court should endeavor to give effect to the parties&#39; intentions as reflected in the provision, and the other provisions of the Agreement remain in full force and effect. </p> <p> 18. <strong>Disclosure of Your Information.</strong> You acknowledge, consent and agree that DCR may access, preserve, and disclose the information we collect about you if required to do so by law or in good faith belief that such access preservation or disclosure is reasonably necessary to: (i) comply with legal process; (ii) enforce the Agreement; (iii) respond to claims that any information or content violated the rights of the third parties; (iv) respond to your requests for customer service; or (v) protect the rights, property, or personal safety of DCR, its users and the public. </p> <p> 19. <strong>Entire Agreement.</strong> The Agreement constitutes the entire agreement between you and DCR and governs your use of the Service, superseding any prior agreements between you and DCR. You also may be subject to additional terms and conditions that may apply when you use or purchase certain when you use certain other DCR services, affiliate services, third party content or third party software. </p> <p> 20. <strong>Survival.</strong> The following paragraphs shall survive termination or your refusal to continue to use the Service: 4, 5, 6, 8, 9, 10, 11, and 15. </p> <p> 21. <strong>Statute of Limitations.</strong> YOU AGREE THAT REGARDLESS OF ANY STATUTE OR LAW TO THE CONTRARY, ANY CLAIM OR CAUSE OF ACTION ARISING OUT OF RELATED TO USE OF THE SERVICE OR THE AGREEMENT MUST BE FILED WITHIN ONE (1) YEAR AFTER SUCH CLAIM OR CAUSE OF ACTION AROSE OR BE FOREVER BARRED. </p> </div> </div> </div> </body> </html><file_sep>$(document).ready(function(){ $('.footer-privacy').click(function(){ $('.close-popout').css('display','block'); $('.privacy-popout').css('display','block'); $('html,body').animate({scrollTop: $('body').offset().top},'slow'); }); $('.footer-terms').click(function(){ $('.close-popout').css('display','block'); $('.terms-popout').css('display','block'); $('html,body').animate({scrollTop: $('body').offset().top},'slow'); }); $('.close-popout').click(function(){ $('.close-popout').css('display','none'); $('.privacy-popout').css('display','none'); $('.terms-popout').css('display','none'); }); });<file_sep><!DOCTYPE html> <html lang="en"> <head> <title>Debt Company Research</title> <link href='http://fonts.googleapis.com/css?family=Lato:700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,400italic,700,700italic,200' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="normalize.css"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="glow"> 1 </div> <div id="debt-container"> <div class="rounded-arrow"> </div> <div class="phase-images"> <div class="phase1-bg phasebg"> </div> <div class="phase1"> </div> <div class="phase2"> </div> <div class="phase3"> </div> <div class="phase4"> </div> <div class="phase5"> </div> <div class="phase6"> </div> </div> <div class="debt-container-left"> <div class="top-headline"> <p>YES there's light at the <span>end</span> of your <span>debt</span> tunnel</p> </div> <div class="free-report"> <div class="free-report-left"> <p><span>Free</span> Report</p> </div> <div class="free-report-right"> <p>Safe, Honest &amp; Reliable Debt Relief Companies</p> <h6>"We do the research so you can relax"</h6> </div> </div> <div class="checkmarks-area"> <div class="checkmarks-single"> <p>Over 69,500 people help since 2006</p> </div> <div class="checkmarks-single"> <p>All firms "A" BBB rated</p> </div> <div class="checkmarks-single"> <p>All firms fully FTC laws compliant</p> </div> </div> <div class="blurbs"> <div class="blurbs-single lower"> <div class="blurbs-single-icon-1"> <img src="images/lowerpayments.png" alt="Lower Payments" /> </div> <p><span>Lower</span><br />your<br />payments</p> </div> <div class="blurbs-single debt"> <div class="blurbs-single-icon-2"> <img src="images/debtfree.png" alt="Debt Free" /> </div> <p><span>Debt free</span><br />in 18 - 36<br />months</p> </div> <div class="blurbs-single save"> <div class="blurbs-single-icon-3"> <img src="images/savetime.png" alt="Save Time" /> </div> <p><span>Save time,</span><br />money,<br />+ stress</p> </div> </div> <div class="footer-area"> </div> <div class="final-stage-ticket"> </div> </div> <div class="form-area"> <div class="form-header"> <h2><span>Free</span>Report</h2> <p>&amp; savings consultation</p> </div> <div class="form-feature"> <div class="form-feature-image"> <img src="images/tunnel_book.png" alt="Debt Tunnel Book" /> </div> <div class="form-feature-text"> <h4>The <span>Best</span> Firms</h4> <p>to get you</p> <p><span>out of debt</span></p> </div> </div> <div class="form-fillout"> <form class="contactForm" action="mailformprocess.php" method="POST" onsubmit> <p>Your Debt</p> <select name="debt" class="debt required"> <option value="nil">Please select a value</option> <option value="5000">$5,000</option> <option value="7000">$7,000</option> <option value="10000">$10,000</option> <option value="15000">$15,000</option> <option value="20000">$20,000</option> <option value="30000">$30,000</option> <option value="50000">$50,000</option> <option value="70000">$70,000+</option> </select> <p>Zip Code</p> <input name="zip" type="text" placeholder="ie: 94304" class="zip required" maxlength="5" required disabled> <p>First Name</p> <input name="fname" type="text" placeholder="ie: Bob" class="fname required" required disabled> <p>Last Name</p> <input name="lname" type="text" placeholder="ie: Williams" class="lname required" required disabled> <p>Email</p> <input name="email" type="text" placeholder="ie: <EMAIL>" class="email required" required disabled> <p>Phone</p> <input name="phonefirst" type="text" placeholder="ie: 387" class="areacode phone required" maxlength="3" required disabled> <input name="phonesecond" type="text" placeholder="ie: 987" class="prefix phone required" maxlength="3" required disabled> <input name="phonethird" type="text" placeholder="ie: 3929" class="suffix phonelong required" maxlength="4" required disabled> <input name="sid" type="hidden" value="<?php echo $_GET['sid'] ?>"> <input name="pid" type="hidden" value="<?php echo $_GET['pid'] ?>"> <input class="submit-form-ajax" type="image" src="images/form-submit.png" disabled> </form> </div> </div> <div class="form-area-final"> <div class="form-header-final"> <h2><span>Thank</span>you</h2> </div> <div class="form-final-text"> <p>Your <span>Free Report</span> will be emailed shortly.</p> <p>An "<em>A</em>" rated debt relief company we've carefully pre-screened will contact you to provide your savings quote.</p> <img src="images/final-text-squig.png" alt="final squiggle" /> </div> </div> </div> <div class="bottom-section"> <div class="tabbed-content"> <div class="tab-navigation"> <div class="tab one tab-hover"> Top Rated <br /><span>Firms</span> </div> <div class="tab two"> Free <br /><span>Matching </div> <div class="tab three"> Over 69,500 <br /><span>Helped</span> </div> <div class="tab four"> Debt Free <br /><span>Safely!</span> </div> </div> <div class="tab-text"> <div class="tab-one"> <img class="tab-image" src="images/ben-body.png"> <div class="tab-content-wrap"> <h3>Frustrated? Confused?</h3> <p>So many companies say they can help you get out of debt but let's face it, it's unlikely you've heard of any of them before.</p> <h3>Who can you trust?</h3> <p>Our team has been involved in the debt relief business for years. We've witnessed first-hand people's frustrations signing up with companies that are here today and gone tomorrow. A waste of time & money, not to mention added frustration when trying to get out of debt.</p> <h4>You need honest help, not more problems!</h4> <p>We saw a need to help people like you. As insiders, we know which companies are honest, trustworthy, and have stood the test of time.</p> <p>We actually know the people behind the companies we suggest. We've met them and they are all "A" rated with the BBB for extra measure.</p> <p>With the thousands of people we've helped, we're pretty confident in our research and we know it can help you too.</p> </div> </div> <div class="tab-two"> <img class="tab-image" src="images/bob-body.png"> <div class="tab-content-wrap"> <img src="images/tab-divider.png" alt="Tab Divider" /> <p>When you complete the simple form above we determine if you are a candidate for one of our companies. Certain companies only operate in certain states and with particular debt amounts which is why we ask the questions.</p> <p>Once a match is made, we provide you with information about the company. You can contact them or they will contact you to provide a free consultation.</p> <p>The purpose of the consultation is to learn more about the details of your financial situation so they can be sure you could benefit from their program. If not, they will likely provide you with advice about your options and may even have another suggestion for you.</p> <p>Every financial situation is unique, the goal is to find you the right solution for you!</p> </div> </div> <div class="tab-three"> <img class="tab-image" src="images/nicole-body.png"> <div class="tab-content-wrap"> <img src="images/tab-divider.png" alt="Tab Divider" /> <p>We are a team of hardworking people with husbands, wives, and kids, probably just like you - but most importantly, we're insiders - we have debt relief industry experience since 2006!</p> <p>Over the years ten's of thousands of people have benefitted from our research and suggestions. We help people all day, every day and we love the feedback we get from people relieved to have found our service.</p> <p>There's no better feeling than opening emails from people relieved to finally see light at the end of a tunnel. They are ecstatic to finally feel as though they are in trustworthy hands that will lead them out of debt.</p> <p>Every financial situation is unique, the goal is to find you the right solution for you!</p> </div> </div> <div class="tab-four"> <img class="tab-image" src="images/marco-body.png"> <div class="tab-content-wrap"> <img src="images/tab-divider.png" alt="Tab Divider" /> <p>The debt relief industry for many years was lightly regulated which resulted in hundreds of debt relief companies that were more concerned about their fees than getting their clients out of debt. It was the Wild West!</p> <p>Many of those companies have been regulated out of business but where there's money to be made there will always be new fly by night companies that pop up.</p> <p>Our goal is to steer you out of harm's way.</p> <p>You want to consider companies that have been in business for at least 5-7 years, provide honest advice, comply with all the government rules and regulations, don't engage in high pressure sales pitches, and offer excellent customer service after you've become a client.</p> <p>In short, you want to get out of debt safely in the shortest time possible - we know the companies that can get you there.</p> </div> </div> </div> </div> <div class="sidebar"> <div class="sidebar-module"> <div class="sidebar-header"> <h4>&#183; Finding Help Tips &#183;</h4> </div> <ul> <li><img src="images/list-arrows.png">Use a firm in business at least<br/>&nbsp;&nbsp;&nbsp; 5-7 years</li> <li><img src="images/list-arrows.png">Look them up on BBB website</li> <li><img src="images/list-arrows.png">Google the Owners Name<br/>&nbsp;&nbsp;&nbsp; (From BBB Website)</li> <li><img src="images/list-arrows.png">It's best if they don't<br/>&nbsp;&nbsp;&nbsp;&nbsp;outsource any services</li> <li><img src="images/list-arrows.png">Understand many reviews sites<br/>&nbsp;&nbsp;&nbsp; are faked</li> </ul> </div> <div class="sidebar-module"> <div class="sidebar-header"> <h4>&#183; Why Us? &#183;</h4> </div> <ul> <li><img src="images/list-arrows.png">Our Reviews are real</li> <li><img src="images/list-arrows.png">We have been doing this since<br/>&nbsp;&nbsp;&nbsp; 2006</li> <li><img src="images/list-arrows.png">We always answer your emails</li> <li><img src="images/list-arrows.png">We have helped over 69,500<br/>&nbsp;&nbsp;&nbsp; people</li> <li><img src="images/list-arrows.png">Our Criteria is Strict</li> <li><img src="images/list-arrows.png">We guarentee our service</li> </ul> </div> <div class="sidebar-module"> <div class="sidebar-header"> <h4>&#183; About Our Process &#183;</h4> </div> <p>We are very selective about the companies we suggest. Yes, we do REAL research and we even personally meet most of the companies in person before they make the cut. We approach the carefully selected firms and develop marketing relationships with them.</p> <p>Yes, they do pay us referral fees (our families need to eat too :) and we have no problem admitting that because we sleep great at night knowing we are suggesting only the best most honest companies to you.</p> </div> </div> </div> </div> <div class="footer-section"> <div class="footer-privacy">Privacy</div> <p> | </p> <div class="footer-terms">Terms</div> <p>By using this site and/or providing your personal information and clicking the submit button, you are stating that you have read all terms and conditions and privacy statement contained on this website and that you agree to be bound by those terms of use. You are also agreeing and consenting to be matched with third parties in our network and you consent for those in our network to contact you through live, automated, recorded, mobile device, text message, or email, notwithstanding the registration of your telephone number on any Do Not Call Registry. Those companies in our network will provide you with information on their financial assistance services which you are expressing interest in.</p> <a href="http://www.debtcompanyresearch.com/optout/">Unsubscribe</a> <h6>7975 Raytheon Rd <br />San Diego, CA 92111</h6> </div> <div class="final-step-thankyou-panels"> <div class="success-banner"> </div> <div class="scott-face"> </div> <div class="scott-message"> <p>Hello,</p> <p>We have helped over 69,000 people find honest, reliable, and ethical debt solution companies you can trust.</p> <p>We personally meet with every company as part of our extensive research so you can relax and get out of debt safely.</p> <p>Based on the information you provided, here is the company we suggest you speak with for straightforward, no pressure debt relief options and advice so you can become debt free as fast as possible. We have passed along your information so they can contact you with a quote.</p> <p>Thank You!</p> <p>Scott</p> </div> <div class="content-panel delray"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Delray Credit Counseling</h1> <p>www.DelrayCC.com</p> <p>877.209.2225</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT DELRAY:</p> <p>&raquo; <span>In Business Since:</span> 2003</p> <p>&raquo; <span>BBB Rating:</span> A</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> Association of Credit Counseling Professionals, Fincert.org Certified, BSI Certified</p> </div> <div class="full-report-text"> <p>Get the full report on Delray and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <div class="download-report"> </div> </div> </div> <div class="content-panel cambridge"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Cambridge Credit Counseling</h1> <p>www.Cambridge-Credit.org</p> <p>800.857.2808</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT CAMBRIDGE:</p> <p>&raquo; <span>In Business Since:</span> 1996</p> <p>&raquo; <span>BBB Rating:</span> A+</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> AICCCA Member, ACC Pros Member, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on Cambridge and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <div class="download-report"> </div> </div> </div> <div class="content-panel national"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>National Debt Relief</h1> <p>www.NationalDebtRelief.com</p> <p>888.703.4948</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT NATIONAL:</p> <p>&raquo; <span>In Business Since:</span> 2005</p> <p>&raquo; <span>BBB Rating:</span> A</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> AFCC Member, IAPDA Certified, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on National and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <div class="download-report"> </div> </div> </div> <div class="content-panel pacific"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Pacific Debt Relief</h1> <p>www.PacificDebt.com</p> <p>877.722.3328</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT PACIFIC:</p> <p>&raquo; <span>In Business Since:</span> 2002</p> <p>&raquo; <span>BBB Rating:</span> A+</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> BSI Certified, AFCC Member, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on Pacific and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <div class="download-report"> </div> </div> </div> <div class="content-panel superior"> <div class="left-arrow-space"> </div> <div class="right-content"> <p>For You We Suggest</p> <h1>Superior Debt Relief</h1> <p>www.SuperiorDebtRelief.com</p> <p>888.366.3414</p> </div> <div class="right-content-two"> <p>FAST FACTS ABOUT SUPERIOR:</p> <p>&raquo; <span>In Business Since:</span> 1998</p> <p>&raquo; <span>BBB Rating:</span> A+</p> <p>&raquo; <span>Non-Profit:</span> Yes</p> <p>&raquo; <span>Follow all FTC laws:</span> Yes</p> <p>&raquo; <span>Certifications:</span> BSI Certified, IAPDA Certified, BBB Accredited</p> </div> <div class="full-report-text"> <p>Get the full report on Superior and more helpful educational information on best solutions:</p> </div> <div class="content-bottom"> <div class="content-bottom-left"> <h3>You'll Discover:</h3> <p><span>1</span>) More About This Firm</p> <p><span>2</span>) 3 Ways to Debt Freedom</p> <p><span>3</span>) 6 Critical Debt Relief Tips</p> </div> <div class="debt-help-book"> </div> <div class="download-report"> </div> </div> </div> </div> </div> <div class="loading-screen"> <div class="loading-text"> <p>Processing.</p> </div> </div> <div class="close-popout"> <div class="close-popout-x"> <p>X</p> </div> </div> <div class="privacy-popout"> <div class="tabbed-content"> <div class="tab-text"> <h2>Privacy:</h2> <img src="images/tab-divider.png"> <p> This Privacy Policy covers what we do with any personal information you may submit, as well as any other information that we may gather when you access our website. </p> <p> Please note that our policies and procedures apply only to this website owned by us and not to websites maintained by other companies or to any website to which we may link or businesses with which we may share information. </p> <p> Personal information is any information that you provide to us that identifies you, personally, or that can be associated with you. Examples of personal information that will be collected on our site include your name, your address, your e-mail address, your phone number. </p> <p> We collect and use personal information in order to respond to your requests for services offered through our website and those of our business partners. We also collect personal and other information in order to make you aware of products and/or services that are likely to be of interest to you. </p> <p> We collect and maintain the information you provide to us whenever you visit our website(s), such as: </p> <ul type="disc"> <li> Any information you provide to us when you request a quote, more information, or a service. This includes your contact information, your name, and additional information such as the amount of your current unsecured debt. </li> <li> Information, such as your e-mail address, that you provide to us when you register to receive communications from us or when you communicate with us, or otherwise correspond with us. </li> </ul> <p> We also collect other, non-personal information, which is broadly defined as any information that is not and cannot be directly associated with you. An example of this type of non-personal information would be your state of residence. We use the personal information you supply to us, or that you authorize us to obtain, to provide to you the service(s) or product(s) that you request. We may also use your personal and other information to enhance your experience on our website(s) by displaying content based on your preferences and/or to send information to you about additional products or services in which you may be interested. </p> <p> If you submit a request for information or a quote, we will share the personal and other information you supply (such as your name, email, zip code, debt amounts etc.) with those product and service providers that have agreed to participate in our network. Generally, these are debt relief solution providers who are prohibited from using the information we provide to them for any other purpose, including using your information for other, unrelated marketing purposes. </p> <p> By submitting your request you are consenting to being contacted by us or by our business partners through any means, based on the information you provide to us, even if you have opted into the National Do Not Call List administered by the Federal Trade Commission, any state Do Not Call List or the Do Not Call List of any specific institution. If, after you are contacted by that product or service provider, you do not wish to be contacted by that person again you must make a specific request to the service provider. </p> <p> We may be required to share your information with law enforcement or government agencies in response to subpoenas, court orders or other forms of legal process. We may elect to share information when, in our reasonable judgment, such sharing is necessary or appropriate for the investigation or prevention of illegal activities, including actual or suspected fraud, real or potential threats to the physical safety of any person or otherwise as required by law. </p> <p> In addition, if we are merged with, or acquired by, another company the successor company will have access to all of the information collected and maintained by us. In such a circumstance, the successor company would continue to be bound by the terms and conditions of this Privacy Policy. You will be notified via email and/or a prominent notice on our Web site of any change in ownership or uses of your personal information, as well as any choices you may have regarding your personal information. </p> <p> We collect certain types of non-personal information and technical data from each visitor to our website(s). For example, when you click on a banner advertisement or text link that is associated with one of our websites, the banner or text placement, along with the time of your visit, your Internet Protocol address and other path-related information, is sent to us. Similarly, the page requests you make when you visit our website(s) are stored and used by us. We use this information, none of which is or can be personally associated with you, for statistical and analytic purposes, to help us understand which page views are most appealing to our customers and to help us improve the likelihood that we will be able to offer you only products or services in which you have a genuine interest. </p> <p> "Cookies" are small files that are placed automatically on your computer system when you visit a website. Cookies enable a website to recognize you as a return visitor and, by keeping track of your website activity, help us identify which pages to serve to you while reducing the time it takes for those pages to load. Cookies enable us to personalize and enrich your experience and are not tied in any way to your personal information. If you do not wish to accept cookies or if you wish to remove cookies that remain in your browser following the close of your browser session, you may adjust the settings on your web browser to prevent cookies from being placed on your hard drive. </p> <p> The security of your personal information is a very high priority for us and we take a number of steps to safeguard it. </p> <p> We use commercially reasonable physical and technical security measures to protect all personal information in our possession. We cannot, however, guarantee or warrant the absolute security of any system or that any information we hold will not be accessed, disclosed, altered or destroyed. </p> <p> We may retain your information indefinitely although it would only be used within the specifications of this privacy policy. We will retain and use your information as necessary to comply with our legal obligations, resolve disputes, and enforce our agreements. Under certain circumstances, Federal and/or state law may require us to retain your personal information for different periods of time. Accordingly, we may not be able to delete or otherwise remove your personal information from our systems. </p> <p> Yes, you may contact us to do so at anytime to remove or edit your information. </p> <p> You can always elect not to provide personal information to us. If you wish to request that we no longer use your information to provide you services contact us at <EMAIL>. If you decide, at a later point in time, that you no longer want us to share your personal information with our business partners you may notify us either by sending us an e-mail: <EMAIL> </p> <p> We have a strict "anti-spam" policy. You will not receive e-mails from us unless you submit your e-mail address to us. We do not permit any third-party e-mail service to send unsolicited e-mails &#8212; "spam" &#8212; to any person who has not previously given their permission to receive such communications to that third party e-mail service. If you wish to stop receiving future e-mails from a third-party e-mail service, we recommend you follow the opt-out instructions included in the e-mail. An "unsubscribe" link should appear within or at the top or bottom of any e-mail you receive. </p> <p> If you submit a testimonial to us, we will ask for your permission to post your testimonial prior to any public use. We will post your name as given to us in your testimonial. We may post a photo of you or use a stock photo. Please be aware that any personally identifiable information you submit as a testimonial to be posted can be read, collected, or used by the general public, and could be used to send you unsolicited messages. We are not responsible for the personally identifiable information you choose to include in any testimonial you choose to submit. If at any time you decide to remove your testimonial, please contact us via e-mail or postal mail. </p> <p> We do not knowingly collect, use or share personal information about visitors under 18 years of age. If you are under 18 years of age, you can use the products and/or services offered on our website(s) only in conjunction with your parents or guardians. </p> </div> </div> </div> <div class="terms-popout"> <div class="tabbed-content"> <div class="tab-text"> <h2>Terms:</h2> <img src="images/tab-divider.png"> <p> The Agreement describes the terms and conditions applicable to your use of the Debt Company Research (DCR) Website. These terms may be updated by DCR from time to time without notice to you. </p> <p> You must read and agree with all of the terms and conditions contained in these terms and the DCR Website privacy policy before you use the Service. If you do not agree to be bound by the terms and conditions of this Agreement, you may not use or access the Service. </p> <p> 1. <strong>What We Do.</strong> The DCR Website is a matching service that helps you find companies and counselors to assist you with financial needs. You understand and agree that if you submit a request for a service offered through the Website, DCR will share your personal information (such as your full name, state of residence, telephone number, email, and debt amount) with Providers in our provider network (referred to individually as &quot;Provider&quot; and collectively as &quot;Providers&quot;) to process and fulfill your request about their services. </p> <p> We carefully screen our providers and offer the opportunity to be on our site only to those we believe are trustworthy and reputable. Please understand the providers shown on this site are paying clients of ours. We have a marketing relationship with them and we may be compensated for providing your information as a lead or on a per client obtained basis. You acknowledge that DCR is not a party to any agreement that you may make with the Provider, and that the Provider is solely responsible for its services to you. You further acknowledge that DCR is not acting as your agent or broker and is not recommending any particular product or Provider to you. We offer our opinion and our research. The opinions about companies profiled on the DCR website are ours and we make no warranties, representations, or guarantees regarding the products or services provided by the 3rd party companies on the site. The opinions are opinions only and any user should do their own research prior to engaging the services of the companies profiled on DCR. Any compensation DCR may receive is paid by the individual Provider for services rendered by DCR to that particular Provider on a per lead, per sale or per phone contact basis. DCR does not charge you a fee to use the DCR Website. You understand that DCR does not endorse, warrant, or guarantee the products or services of any the Providers. We have done research on the companies mentioned on the site and have based our opinions on that research. You agree that DCR shall not be liable for any damages or costs of any type which arise out of or in connection with your use of the Provider&#39;s service. </p> <p> By submitting your contact request, you are consenting to be contacted by the Provider either by telephone, email or mail based on the information you have provided to us, even if you have opted into the National Do Not Call List administered by the Federal Trade Commission, any state equivalent Do Not Call List, or the Do Not Call List of an internal company. You understand that the Provider may maintain the information you submitted to DCR whether you elect to use their services or not. In the event you no longer want to receive communications from a Provider, you agree to notify the Provider directly. You also give DCR permission to send you periodic updates on behalf of the Provider which may be of interest to you. </p> <p> 2. <strong>Uses of the DCR Website and Service.</strong> You certify to DCR that: (i) you are at least eighteen (18) years of age; (ii) you assume full responsibility for the use of the Service by any minors; (iii) you agree that all information you have submitted to DCR, online or otherwise, is accurate and complete, and that you have not knowingly submitted false information on or through the DCR Website or Service; and, (iv) your use of the Service is subject to all applicable federal, state, and local laws and regulations. </p> <p> 3. <strong>Prohibited.</strong> You must not (i) submit, transmit or facilitate the distribution of information or content that is harmful, abusive, racially or ethnically offensive, vulgar, sexually explicit, defamatory, infringing, invasive of personal privacy or publicity rights, or in a reasonable person&#39;s view, objectionable; (ii) submit, transmit, promote or distribute information or content that is illegal; (iii) attempt to interfere with, compromise the system integrity or security or decipher any transmissions to or from the servers running the Service; (iv) take any action that imposes, or may impose at our sole discretion an unreasonable or disproportionately large load on our infrastructure; (v) upload invalid data, viruses, worms, or other software agents through the Service; (vi) use any robot, spider, scraper or other automated access the Service for any purpose without our express written permission; (vii) impersonate another person or otherwise misrepresent your affiliation with a person or entity, conduct fraud, hide or attempt to hide your identity; (viii) submit, upload, post, email, transmit or otherwise make available any information or content that you do not have a right to make available under any law or under contractual or fiduciary relationships; (ix) interfere with the proper working of the Service; or, (x) bypass the measures we may use to prevent or restrict access to the Service. </p> <p> 4. <strong>Privacy.</strong> DCR respects your privacy. Personal information submitted in connection with the Service is subject to our Privacy Policy. </p> <p> 5. <strong>Copyright and Trademark Notice Info.</strong> All contents of the DCR Website are: Copyright &copy; 2013 &#8212; DCR and/or its Providers and third party vendors. All rights reserved. All trademarks and service marks and other DCR logos, Provider logos, and product service names are trademarks of DCR (&quot;DCR Marks&quot;) and the Providers. Without DCR prior permission, you agree not to display or use in any manner, the DCR Marks. All other logos or brand names shown on the Service are trademarks of their respective owners and/or licensors. </p> <p> 6. <strong>Proprietary Rights.</strong> You acknowledge and agree that the Service and any necessary software used in connection with the Service (&quot;Software&quot;) contain proprietary and confidential information that is protected by applicable intellectual property and other laws. You further agree that all materials and/or content, including, but not limited to, articles, artwork, screen shots, graphics, logos, text, drawings and other files on the DCR Website or as part of the Service are copyrights, trademarks, service marks, patents or other proprietary rights of DCR or their respective intellectual property owners. Except as expressly authorized by DCR, you agree not to modify, copy, reproduce, sell, distribute or create derivative works based on or contained within the Service or the Software, in whole or in part. </p> <p> DCR grants you a personal, non-transferable and non-exclusive right and license to use the code of its Software on a single computer; provided that you do not copy, modify, create a derivative work of, reserve engineer, decompile, reverse assemble or otherwise attempt to discover any source code, sell, assign, sublicense, grant a security interest in or otherwise transfer any right in the Software. You agree not to modify the Software in any manner or form, or to use modified versions of the Software, including, without limitation, for the purpose of obtaining unauthorized access to the Service by any means other than through the interface that is provided by DCR for use in accessing the Service. </p> <p> 7. <strong>Site </strong><strong>Links.</strong> DCR, through the Service or otherwise, may provide links to other websites. Because DCR has no control over such websites, you acknowledge and agree that DCR is not responsible for the availability of such external websites, and does not endorse and is not responsible or liable for any content, advertising, products or other materials on or available from such websites. You further acknowledge and agree that DCR shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, products, goods or services available on or through any such website. </p> <p> 8. <strong>Indemnification.</strong> You agree to indemnify and hold DCR, its subsidiaries, affiliates, agents, shareholders, officers, contractors, vendors and employees harmless from any claim or demand, including reasonable attorneys&#39; fees, made by any third party due to or arising out of your use of the Service, the violation of the Agreement by you, or the infringement by you, or any other user of the Service using your computer, of any intellectual property or other right of any person or entity. DCR reserves the right, at its own expense, to assume the exclusive defense and control of any matter otherwise subject to indemnification by you. </p> <p> 9. <strong>No Warranty.</strong> DCR PROVIDES THE SERVICE &quot;AS IS,&quot; &quot;WITH ALL FAULTS&quot; AND &quot;AS AVAILABLE,&quot; AND THE ENTIRE RISK AS TO SATISFACTORY QUALITY, PERFORMANCE, ACCURANCY, AND EFFORT IS WITH YOU. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, DCR MAKES NO REPRESENTATIONS, WARRANTIES OR CONDITIONS, EXPRESS OR IMPLIED. DCR DISCLAIMS ANY AND ALL WARRANTIES OR CONDITIONS, EXPRESS, STATUTORY AND IMPLIED, INCLUDING WITHOUT LIMITATION: (i) WARRANTIES OR CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, ACCURACY, TITLE, QUIET ENJOYMENT, NO ENCUMBRANCES, NO LIENS AND NON-INFRINGEMENT; (ii) WARRANTIES OR CONDITIONS ARISING THROUGH COURSE OF DEALING OR USAGE OF TRADE; AND, (iii) WARRANTIES OR CONDITIONS THAT ACCESS TO OR USE OF THE SERVICE WILL BE UNINTERRUPTED OR ERROR-FREE. THERE ARE NO WARRANTIES THAT EXTEND BEYOND THE FACE OF THIS AGREEMENT. </p> <p> 10. <strong>Limitation of Liability</strong>. IN NO EVENT WILL DCR BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION ANY INDIRECT, CONSEQUENTIAL, SPECIAL, INCIDENTAL, OR PUNITIVE DAMAGES ARISING OUT OF, BASED ON, OR RESULTING FROM THIS AGREEMENT OR YOUR USE OF THE SERVICE, EVEN IF DCR HAS BEEN ADVISED OF THE POSSIBLITY OF SUCH DAMAGES. THESE LIMITATIONS AND EXCLUSIONS APPLY WITHOUT REGARD TO WHETHER THE DAMAGES ARISE FROM (1) BREACH OF CONTRACT, (2) BREACH OF WARRANTY, (3) STRICT LIABILITY, (4) TORT, (5) NEGLIGENCE, OR (6) ANY OTHER CAUSE OF ACTION, TO THE EXTENT SUCH EXCLUSION AND LIMITATIONS ARE NOT PROHIBITED BY APPLICABLE LAW. IF YOU ARE DISSATISFIED WITH THE SERVICE, YOU DO NOT AGREE WITH ANY PART OF THIS AGREEMENT, OR HAVE ANY OTHER DISPUTE OR CLAIM WITH OR AGAINST DCR WITH RESPECT THIS AGREEMENT OR THE SERVICE, THEN YOUR SOLE AND EXCLUSIVE REMEDY IS TO DISCONTINUE USING THE SERVICE. </p> <p> 11. <strong>Release.</strong> YOU HEREBY AGREE TO RELEASE, REMISE AND FOREVER DISCHARGE DCR AND ITS AFFILLIATES, PARTNERS, SERVICE PROVIDERS, VENDORS, AND CONTRCTORS AND EACH OF THEIR RESPECTIVE AGENTS, DIRECTORS, OFFICERS, EMPLOYEES, AND ALL OTHER RELATED PERSONS OR ENTITIES FROM ANY AND ALL MANNER OF RIGHTS, CLAIMS, COMPLAINTS, DEMANDS, CAUSES OF ACTION, PROCEEDINGS, LIABLITIES, OBLIGATIONS, LEGAL FEES, COSTS, AND DISBURSEMENTS OF ANY NATURE WHATSOEVER, WHETHER KNOWN OR UNKNOWN, WHICH NOW OR HEREAFTER ARISE FROM, RELATE TO, OR ARE CONNECTED WITH YOUR USE OF THE SERVICE. </p> <p> 12. <strong>Notice.</strong> DCR may provide you with notices, including those regarding changes to the Agreement by posting on this Service. </p> <p> 13. <strong>Termination.</strong> You agree that DCR may, under certain circumstances and without prior notice, immediately terminate your access to the Service. Cause for such termination shall include, but not be limited to: (i) breaches or violations of the Agreement or other incorporated agreements or the Privacy Policy; (ii) requests by law enforcement or other government agencies; (iii) discontinuance or material modification to the Service (or any part thereof); and (iv) unexpected technical or security issues or problems. You agree that all terminations for cause shall be made in DCR&#39;s sole discretion and that DCR shall not be liable to you or any third party for any termination or access to the Service. </p> <p> 14. <strong>Dealings with Third Parties.</strong> Your correspondence or business dealings with any third parties as a result of your visit and participation in the Service or any other terms, conditions, warranties, representations associated with such dealings, are solely between you and such third party. You agree that DCR shall not be responsible or liable for any loss or damage of any sort incurred as the result of any such dealings or as the result of the presence of such third party on the Service. </p> <p> 15. <strong>Disputes.</strong> This Agreement will be interpreted in accordance with the laws of the State of California, without regard to the conflicts of laws principles thereof. The parties agree that any and all disputes, claims or controversies arising out of or relating to the Agreement, its interpretation, performance, or breach, that are not resolved by informal negotiation within 30 days (or any mutually agreed extension of time), shall be submitted to final and binding arbitration before a single arbitrator of the American Arbitration Association (&quot;AAA&quot;) in San Diego, California, or its successor. Either party may commence the arbitration process called for herein by submitting a written demand for arbitration with the AAA, and providing a copy to the other party. The arbitration will be conducted in accordance with the provisions of the AAA&#39;s Commercial Dispute Resolutions Procedures in effect at the time of submission of the demand for arbitration. The costs of arbitration plus reasonable attorneys&#39; fees (including fees for the value of services provided by in house counsel) shall be awarded to the prevailing party in such arbitration. Judgment on the award rendered by the arbitrator may be entered in the Superior Court of California, County of San Diego. Notwithstanding the foregoing, the following shall not be subject to arbitration and may be adjudicated only in the Superior Court of California, County of San Diego: (i) any dispute, controversy, or claim relating to or contesting the validity of DCR&#39;s proprietary rights, including without limitation, trademarks, service marks, copyrights, or trade secrets; or, (ii) an action by a party for temporary, preliminary, or permanent injunctive relief, whether prohibitive or mandatory, or provisional relief such as writs of attachments or possession. </p> <p> THE PARTIES AGREE THAT THIS AGREEMENT HAS BEEN ENTERED INTO AT DCR&#39;S PLACE OF BUSINESS IN THE COUNTY OF SAN DIEGO, STATE OF CALIFORNIA, AND ANY ARBITRATION, LEGAL ACTION OR PROCEEDING ARISING OUT OF OR RELATING TO THIS AGREEMENT MUST BE COMMENCED AND TAKE PLACE IN THE COUNTY OF SAN DIEGO, STATE OF CALIFORNIA. </p> <p> 16. <strong>Modification to Service.</strong> DCR reserves the right at any time and from time to time to modify or discontinue, temporarily or permanently, the Service (or any part thereof) with or without notice. You agree that DCR shall not be liable to you or to any third party for any modification, suspension or discontinuance of the Service. </p> <p> 17. <strong>Waiver and Severability of Terms.</strong> The failure of DCR to exercise or enforce any right or provision of the Agreement shall not constitute a waiver of such right or provision. If any provision of the Agreement is found by a court of competent jurisdiction to be invalid, the parties nevertheless agree that the court should endeavor to give effect to the parties&#39; intentions as reflected in the provision, and the other provisions of the Agreement remain in full force and effect. </p> <p> 18. <strong>Disclosure of Your Information.</strong> You acknowledge, consent and agree that DCR may access, preserve, and disclose the information we collect about you if required to do so by law or in good faith belief that such access preservation or disclosure is reasonably necessary to: (i) comply with legal process; (ii) enforce the Agreement; (iii) respond to claims that any information or content violated the rights of the third parties; (iv) respond to your requests for customer service; or (v) protect the rights, property, or personal safety of DCR, its users and the public. </p> <p> 19. <strong>Entire Agreement.</strong> The Agreement constitutes the entire agreement between you and DCR and governs your use of the Service, superseding any prior agreements between you and DCR. You also may be subject to additional terms and conditions that may apply when you use or purchase certain when you use certain other DCR services, affiliate services, third party content or third party software. </p> <p> 20. <strong>Survival.</strong> The following paragraphs shall survive termination or your refusal to continue to use the Service: 4, 5, 6, 8, 9, 10, 11, and 15. </p> <p> 21. <strong>Statute of Limitations.</strong> YOU AGREE THAT REGARDLESS OF ANY STATUTE OR LAW TO THE CONTRARY, ANY CLAIM OR CAUSE OF ACTION ARISING OUT OF RELATED TO USE OF THE SERVICE OR THE AGREEMENT MUST BE FILED WITHIN ONE (1) YEAR AFTER SUCH CLAIM OR CAUSE OF ACTION AROSE OR BE FOREVER BARRED. </p> </div> </div> </div> <script src="jquery-1.10.2.min.js"></script> <script src="function.js"></script> </body> </html><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Consolidation Loan:</h2> <img src="images/tab-divider.png"> <h4>Who will give me a loan?</h4> <p>It is hard to qualify for a consolidation loan. Most banks and loan companies will not risk giving money to someone who already has lots of debt they are looking to consolidate. It's too risky. Typically the only way around this is if you own something of value you can put up as collateral. If you default on the loan, they will own that collateral.</p> <h4>What is collateral?</h4> <p>The most common form of collateral is a home you own without a high mortgage balance. In that case you can refinance your mortgage and pull money out which you can then use to pay off any high interest credit card balances.</p> <h4>Since I can't get a loan, what should I do?</h4> <p>If your debt is not manageable given your income level and you see very little way you will ever be able to pay down that debt over time on your own, you may want to request a free consultation with a debt settlement or credit counseling company. The more you learn about your options, the easier and safer the entire process will be.</p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Credit Counseling:</h2> <img src="images/tab-divider.png"> <h4>What is credit counseling?</h4> <p>A credit counseling program helps you pay back the full amount that you owe but makes it much easier by consolidating your payments, reducing your interest rates, and reducing or eliminating fees that creditors often pile onto late payments.</p> <h4>What does non-profit credit counseling mean?</h4> <p>Most credit counseling companies are designated as non-profit by the US government (the IRS specifically). Non-profit does not mean their services are totally free but it does mean they are heavily regulated and there are strict limits on what they can charge for their services. However, they do often provide lots of great information and free initial counseling sessions to help you determine the best way for you to get out of debt.</p> <h4>Why not just do debt settlement?</h4> <p>For many people debt settlement is the best option as it can do more to lessen your debt burden and lower your payments however, unlike debt settlement, credit counseling agencies are more creditor friendly. As a result, you typically do not have as much damage to your credit score and you end up paying back everything you owe which is important to some people who feel that's their moral obligation.</p> <h4>Who qualifies?</h4> <p>It really depends on your specific situation and will require you speak with a counselor to determine if you qualify. However, generally people with at least $5,000 in credit card debt can qualify and certain companies only are able to assist people in certain states. To find a company that can help people in your state, you can get a free consultation here.</p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <img src="images/free-report-button.png" class="report-button" alt="Free Report Button" /> <div class="form-area"> <form class="contactForm" action="mailformprocess.php" method="POST" onsubmit=""> <p>Your Debt</p> <select name="debt" class="debt required"> <option value="nil">Please select a value</option> <option value="5000">$5,000</option> <option value="7000">$7,000</option> <option value="10000">$10,000</option> <option value="15000">$15,000</option> <option value="20000">$20,000</option> <option value="30000">$30,000</option> <option value="50000">$50,000</option> <option value="70000">$70,000+</option> </select> <p>Zip Code</p> <input name="zip" type="text" placeholder="ie: 94304" class="zip required" maxlength="5" required> <p>First Name</p> <input name="fname" type="text" placeholder="ie: Bob" class="fname required" required> <p>Last Name</p> <input name="lname" type="text" placeholder="ie: Williams" class="lname required" required> <p>Email</p> <input name="email" type="text" placeholder="ie: <EMAIL>" class="email required" required> <p>Phone</p> <input name="phonefirst" type="text" placeholder="ie: 387" class="areacode phone required" maxlength="3" required> <input name="phonesecond" type="text" placeholder="ie: 987" class="prefix phone required" maxlength="3" required> <input name="phonethird" type="text" placeholder="ie: 3929" class="suffix phonelong required" maxlength="4" required> <input name="sid" type="hidden" value="<?php echo $_GET['sid'] ?>"> <input name="pid" type="hidden" value="<?php echo $_GET['pid'] ?>"> <input class="submit-form-ajax" type="image" src="images/form-button.png"> </form> </div> <div class="discovery-area"> <div class="discovery-text"> <h3>You'll Discover:</h3> <p><span>1</span>) Safe Companies To Use</p> <p><span>2</span>) 3 Ways To Debt Freedom</p> <p><span>3</span>) 8 Critical Questions to Ask</p> </div> <div class="discovery-photo"> <img src="images/debt_book.png" alt="Debt Relief Book" /> </div> </div> <div class="tabbed-content"> <div class="tab-navigation"> <div class="tab one tab-hover"> Top Rated <br /><span>Firms</span> </div> <div class="tab two"> Free <br /><span>Matching</span> </div> <div class="tab three"> Over 69,500 <br /><span>Helped</span> </div> <div class="tab four"> Debt Free <br /><span>Safely!</span> </div> </div> <div class="tab-text"> <div class="tab-one"> <img class="tab-image" src="images/ben-body.png"> <div class="tab-content-wrap"> <h3>Frustrated? Confused?</h3> <p>So many companies say they can help you get out of debt but let's face it, it's unlikely you've heard of any of them before.</p> <h3>Who can you trust?</h3> <p>Our team has been involved in the debt relief business for years. We've witnessed first-hand people's frustrations signing up with companies that are here today and gone tomorrow. A waste of time & money, not to mention added frustration when trying to get out of debt.</p> <h4>You need honest help, not more problems!</h4> <p>We saw a need to help people like you. As insiders, we know which companies are honest, trustworthy, and have stood the test of time.</p> <p>We actually know the people behind the companies we suggest. We've met them and they are all "A" rated with the BBB for extra measure.</p> <p>With the thousands of people we've helped, we're pretty confident in our research and we know it can help you too.</p> </div> </div> <div class="tab-two"> <img class="tab-image" src="images/bob-body.png"> <div class="tab-content-wrap"> <p>When you complete the simple form above we determine if you are a candidate for one of our companies. Certain companies only operate in certain states and with particular debt amounts which is why we ask the questions.</p> <p>Once a match is made, we provide you with information about the company. You can contact them or they will contact you to provide a free consultation.</p> <p>The purpose of the consultation is to learn more about the details of your financial situation so they can be sure you could benefit from their program. If not, they will likely provide you with advice about your options and may even have another suggestion for you.</p> <p>Every financial situation is unique, the goal is to find you the right solution for you!</p> </div> </div> <div class="tab-three"> <img class="tab-image" src="images/nicole-body.png"> <div class="tab-content-wrap"> <p>We are a team of hardworking people with husbands, wives, and kids, probably just like you - but most importantly, we're insiders - we have debt relief industry experience since 2006!</p> <p>Over the years ten's of thousands of people have benefitted from our research and suggestions. We help people all day, every day and we love the feedback we get from people relieved to have found our service.</p> <p>There's no better feeling than opening emails from people relieved to finally see light at the end of a tunnel. They are ecstatic to finally feel as though they are in trustworthy hands that will lead them out of debt.</p> <p>Every financial situation is unique, the goal is to find you the right solution for you!</p> </div> </div> <div class="tab-four"> <img class="tab-image" src="images/marco-body.png"> <div class="tab-content-wrap"> <p>The debt relief industry for many years was lightly regulated which resulted in hundreds of debt relief companies that were more concerned about their fees than getting their clients out of debt. It was the Wild West!</p> <p>Many of those companies have been regulated out of business but where there's money to be made there will always be new fly by night companies that pop up.</p> <p>Our goal is to steer you out of harm's way.</p> <p>You want to consider companies that have been in business for at least 5-7 years, provide honest advice, comply with all the government rules and regulations, don't engage in high pressure sales pitches, and offer excellent customer service after you've become a client.</p> <p>In short, you want to get out of debt safely in the shortest time possible - we know the companies that can get you there.</p> </div> </div> </div> <img src="images/content-bottom.png"> </div> <div class="mainpagesidebar"> <?php include 'homepage-sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>How We Research:</h2> <img src="images/tab-divider.png"> <p>Our mission is to suggest reliable, honest, straightforward talking companies to people who seek trustworthy advice and suggestions on how to get out of debt. We use a combination of industry experience and contacts, online research, industry tradegroups, and face to face meetings to determine which companies we suggest.</p> <p>We believe that all the extra legwork is critical for knowing which companies are about helping people and not just their bottom line.</p> <p>And once a company makes the cut, we maintain constant communication with them. Customer service is critical to any debt relief process and we want to ensure that they take care of people once they are in the program. After all most programs last many months and years so you deserve to have clear communication with the company you are working with.</p> <p>When problems come up, we often can help resolve them if it is a communication issue between you and the company we suggested to you.</p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Website FAQ:</h2> <img src="images/tab-divider.png"> <h4>Who are you?</h4> <p>We are a small group of people in business to help people like you find honest and reputable debt relief companies. You can read more about us here.We are a small group of people in business to help people like you find honest and reputable debt relief companies. You can read more about us here.</p> <h4>Do you offer debt counseling?</h4> <p>No, we do not. We leave that up to the companies we've thoroughly researched and suggest to you when you request help from us. They will offer you a free counseling session and help you determine the best way for you to get out of debt.</p> <h4>Do you work for the companies you suggest?</h4> <p>No. We are not employees of the companies we suggest. The companies we research and find reputable are ones develop marketing relationships with. We find you great companies for you that you can trust and they pay us for finding you for their services. It's making a match and it's a win for everybody.</p> <h4>Why must I answer questions to get a company suggestion?</h4> <p>It's because each company can limitations on who they can help. Primarily these limitations center around the state you live in and the amount of debt you have. Also, it's how the companies we suggest get in touch with you for your free consultation and how they track which people we suggested to them.</p> <h4>What if I have questions?</h4> <p>We are here and answer every email we get. If you have questions about our service, let us know. If you have questions about the company we suggested to you, we can help you with that too. Any questions regarding the specifics of your program or situation would be addressed directly with the company you are working with. Our email is questions<EMAIL></p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Privacy:</h2> <img src="images/tab-divider.png"> <p> This Privacy Policy covers what we do with any personal information you may submit, as well as any other information that we may gather when you access our website. </p> <p> Please note that our policies and procedures apply only to this website owned by us and not to websites maintained by other companies or to any website to which we may link or businesses with which we may share information. </p> <p> Personal information is any information that you provide to us that identifies you, personally, or that can be associated with you. Examples of personal information that will be collected on our site include your name, your address, your e-mail address, your phone number. </p> <p> We collect and use personal information in order to respond to your requests for services offered through our website and those of our business partners. We also collect personal and other information in order to make you aware of products and/or services that are likely to be of interest to you. </p> <p> We collect and maintain the information you provide to us whenever you visit our website(s), such as: </p> <ul type="disc"> <li> Any information you provide to us when you request a quote, more information, or a service. This includes your contact information, your name, and additional information such as the amount of your current unsecured debt. </li> <li> Information, such as your e-mail address, that you provide to us when you register to receive communications from us or when you communicate with us, or otherwise correspond with us. </li> </ul> <p> We also collect other, non-personal information, which is broadly defined as any information that is not and cannot be directly associated with you. An example of this type of non-personal information would be your state of residence. We use the personal information you supply to us, or that you authorize us to obtain, to provide to you the service(s) or product(s) that you request. We may also use your personal and other information to enhance your experience on our website(s) by displaying content based on your preferences and/or to send information to you about additional products or services in which you may be interested. </p> <p> If you submit a request for information or a quote, we will share the personal and other information you supply (such as your name, email, zip code, debt amounts etc.) with those product and service providers that have agreed to participate in our network. Generally, these are debt relief solution providers who are prohibited from using the information we provide to them for any other purpose, including using your information for other, unrelated marketing purposes. </p> <p> By submitting your request you are consenting to being contacted by us or by our business partners through any means, based on the information you provide to us, even if you have opted into the National Do Not Call List administered by the Federal Trade Commission, any state Do Not Call List or the Do Not Call List of any specific institution. If, after you are contacted by that product or service provider, you do not wish to be contacted by that person again you must make a specific request to the service provider. </p> <p> We may be required to share your information with law enforcement or government agencies in response to subpoenas, court orders or other forms of legal process. We may elect to share information when, in our reasonable judgment, such sharing is necessary or appropriate for the investigation or prevention of illegal activities, including actual or suspected fraud, real or potential threats to the physical safety of any person or otherwise as required by law. </p> <p> In addition, if we are merged with, or acquired by, another company the successor company will have access to all of the information collected and maintained by us. In such a circumstance, the successor company would continue to be bound by the terms and conditions of this Privacy Policy. You will be notified via email and/or a prominent notice on our Web site of any change in ownership or uses of your personal information, as well as any choices you may have regarding your personal information. </p> <p> We collect certain types of non-personal information and technical data from each visitor to our website(s). For example, when you click on a banner advertisement or text link that is associated with one of our websites, the banner or text placement, along with the time of your visit, your Internet Protocol address and other path-related information, is sent to us. Similarly, the page requests you make when you visit our website(s) are stored and used by us. We use this information, none of which is or can be personally associated with you, for statistical and analytic purposes, to help us understand which page views are most appealing to our customers and to help us improve the likelihood that we will be able to offer you only products or services in which you have a genuine interest. </p> <p> "Cookies" are small files that are placed automatically on your computer system when you visit a website. Cookies enable a website to recognize you as a return visitor and, by keeping track of your website activity, help us identify which pages to serve to you while reducing the time it takes for those pages to load. Cookies enable us to personalize and enrich your experience and are not tied in any way to your personal information. If you do not wish to accept cookies or if you wish to remove cookies that remain in your browser following the close of your browser session, you may adjust the settings on your web browser to prevent cookies from being placed on your hard drive. </p> <p> The security of your personal information is a very high priority for us and we take a number of steps to safeguard it. </p> <p> We use commercially reasonable physical and technical security measures to protect all personal information in our possession. We cannot, however, guarantee or warrant the absolute security of any system or that any information we hold will not be accessed, disclosed, altered or destroyed. </p> <p> We may retain your information indefinitely although it would only be used within the specifications of this privacy policy. We will retain and use your information as necessary to comply with our legal obligations, resolve disputes, and enforce our agreements. Under certain circumstances, Federal and/or state law may require us to retain your personal information for different periods of time. Accordingly, we may not be able to delete or otherwise remove your personal information from our systems. </p> <p> Yes, you may contact us to do so at anytime to remove or edit your information. </p> <p> You can always elect not to provide personal information to us. If you wish to request that we no longer use your information to provide you services contact us at <EMAIL>. If you decide, at a later point in time, that you no longer want us to share your personal information with our business partners you may notify us either by sending us an e-mail: <EMAIL> </p> <p> We have a strict "anti-spam" policy. You will not receive e-mails from us unless you submit your e-mail address to us. We do not permit any third-party e-mail service to send unsolicited e-mails – "spam" – to any person who has not previously given their permission to receive such communications to that third party e-mail service. If you wish to stop receiving future e-mails from a third-party e-mail service, we recommend you follow the opt-out instructions included in the e-mail. An "unsubscribe" link should appear within or at the top or bottom of any e-mail you receive. </p> <p> If you submit a testimonial to us, we will ask for your permission to post your testimonial prior to any public use. We will post your name as given to us in your testimonial. We may post a photo of you or use a stock photo. Please be aware that any personally identifiable information you submit as a testimonial to be posted can be read, collected, or used by the general public, and could be used to send you unsolicited messages. We are not responsible for the personally identifiable information you choose to include in any testimonial you choose to submit. If at any time you decide to remove your testimonial, please contact us via e-mail or postal mail. </p> <p> We do not knowingly collect, use or share personal information about visitors under 18 years of age. If you are under 18 years of age, you can use the products and/or services offered on our website(s) only in conjunction with your parents or guardians. </p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Terms:</h2> <img src="images/tab-divider.png"> <p> The Agreement describes the terms and conditions applicable to your use of the Debt Company Research (DCR) Website. These terms may be updated by DCR from time to time without notice to you. </p> <p> You must read and agree with all of the terms and conditions contained in these terms and the DCR Website privacy policy before you use the Service. If you do not agree to be bound by the terms and conditions of this Agreement, you may not use or access the Service. </p> <p> 1. <strong>What We Do.</strong> The DCR Website is a matching service that helps you find companies and counselors to assist you with financial needs. You understand and agree that if you submit a request for a service offered through the Website, DCR will share your personal information (such as your full name, state of residence, telephone number, email, and debt amount) with Providers in our provider network (referred to individually as “Provider” and collectively as “Providers”) to process and fulfill your request about their services. </p> <p> We carefully screen our providers and offer the opportunity to be on our site only to those we believe are trustworthy and reputable. Please understand the providers shown on this site are paying clients of ours. We have a marketing relationship with them and we may be compensated for providing your information as a lead or on a per client obtained basis. You acknowledge that DCR is not a party to any agreement that you may make with the Provider, and that the Provider is solely responsible for its services to you. You further acknowledge that DCR is not acting as your agent or broker and is not recommending any particular product or Provider to you. We offer our opinion and our research. The opinions about companies profiled on the DCR website are ours and we make no warranties, representations, or guarantees regarding the products or services provided by the 3rd party companies on the site. The opinions are opinions only and any user should do their own research prior to engaging the services of the companies profiled on DCR. Any compensation DCR may receive is paid by the individual Provider for services rendered by DCR to that particular Provider on a per lead, per sale or per phone contact basis. DCR does not charge you a fee to use the DCR Website. You understand that DCR does not endorse, warrant, or guarantee the products or services of any the Providers. We have done research on the companies mentioned on the site and have based our opinions on that research. You agree that DCR shall not be liable for any damages or costs of any type which arise out of or in connection with your use of the Provider’s service. </p> <p> By submitting your contact request, you are consenting to be contacted by the Provider either by telephone, email or mail based on the information you have provided to us, even if you have opted into the National Do Not Call List administered by the Federal Trade Commission, any state equivalent Do Not Call List, or the Do Not Call List of an internal company. You understand that the Provider may maintain the information you submitted to DCR whether you elect to use their services or not. In the event you no longer want to receive communications from a Provider, you agree to notify the Provider directly. You also give DCR permission to send you periodic updates on behalf of the Provider which may be of interest to you. </p> <p> 2. <strong>Uses of the DCR Website and Service.</strong> You certify to DCR that: (i) you are at least eighteen (18) years of age; (ii) you assume full responsibility for the use of the Service by any minors; (iii) you agree that all information you have submitted to DCR, online or otherwise, is accurate and complete, and that you have not knowingly submitted false information on or through the DCR Website or Service; and, (iv) your use of the Service is subject to all applicable federal, state, and local laws and regulations. </p> <p> 3. <strong>Prohibited.</strong> You must not (i) submit, transmit or facilitate the distribution of information or content that is harmful, abusive, racially or ethnically offensive, vulgar, sexually explicit, defamatory, infringing, invasive of personal privacy or publicity rights, or in a reasonable person’s view, objectionable; (ii) submit, transmit, promote or distribute information or content that is illegal; (iii) attempt to interfere with, compromise the system integrity or security or decipher any transmissions to or from the servers running the Service; (iv) take any action that imposes, or may impose at our sole discretion an unreasonable or disproportionately large load on our infrastructure; (v) upload invalid data, viruses, worms, or other software agents through the Service; (vi) use any robot, spider, scraper or other automated access the Service for any purpose without our express written permission; (vii) impersonate another person or otherwise misrepresent your affiliation with a person or entity, conduct fraud, hide or attempt to hide your identity; (viii) submit, upload, post, email, transmit or otherwise make available any information or content that you do not have a right to make available under any law or under contractual or fiduciary relationships; (ix) interfere with the proper working of the Service; or, (x) bypass the measures we may use to prevent or restrict access to the Service. </p> <p> 4. <strong>Privacy.</strong> DCR respects your privacy. Personal information submitted in connection with the Service is subject to our Privacy Policy. </p> <p> 5. <strong>Copyright and Trademark Notice Info.</strong> All contents of the DCR Website are: Copyright © 2013 – DCR and/or its Providers and third party vendors. All rights reserved. All trademarks and service marks and other DCR logos, Provider logos, and product service names are trademarks of DCR (“DCR Marks”) and the Providers. Without DCR prior permission, you agree not to display or use in any manner, the DCR Marks. All other logos or brand names shown on the Service are trademarks of their respective owners and/or licensors. </p> <p> 6. <strong>Proprietary Rights.</strong> You acknowledge and agree that the Service and any necessary software used in connection with the Service (“Software”) contain proprietary and confidential information that is protected by applicable intellectual property and other laws. You further agree that all materials and/or content, including, but not limited to, articles, artwork, screen shots, graphics, logos, text, drawings and other files on the DCR Website or as part of the Service are copyrights, trademarks, service marks, patents or other proprietary rights of DCR or their respective intellectual property owners. Except as expressly authorized by DCR, you agree not to modify, copy, reproduce, sell, distribute or create derivative works based on or contained within the Service or the Software, in whole or in part. </p> <p> DCR grants you a personal, non-transferable and non-exclusive right and license to use the code of its Software on a single computer; provided that you do not copy, modify, create a derivative work of, reserve engineer, decompile, reverse assemble or otherwise attempt to discover any source code, sell, assign, sublicense, grant a security interest in or otherwise transfer any right in the Software. You agree not to modify the Software in any manner or form, or to use modified versions of the Software, including, without limitation, for the purpose of obtaining unauthorized access to the Service by any means other than through the interface that is provided by DCR for use in accessing the Service. </p> <p> 7. <strong>Site </strong><strong>Links.</strong> DCR, through the Service or otherwise, may provide links to other websites. Because DCR has no control over such websites, you acknowledge and agree that DCR is not responsible for the availability of such external websites, and does not endorse and is not responsible or liable for any content, advertising, products or other materials on or available from such websites. You further acknowledge and agree that DCR shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, products, goods or services available on or through any such website. </p> <p> 8. <strong>Indemnification.</strong> You agree to indemnify and hold DCR, its subsidiaries, affiliates, agents, shareholders, officers, contractors, vendors and employees harmless from any claim or demand, including reasonable attorneys’ fees, made by any third party due to or arising out of your use of the Service, the violation of the Agreement by you, or the infringement by you, or any other user of the Service using your computer, of any intellectual property or other right of any person or entity. DCR reserves the right, at its own expense, to assume the exclusive defense and control of any matter otherwise subject to indemnification by you. </p> <p> 9. <strong>No Warranty.</strong> DCR PROVIDES THE SERVICE “AS IS,” “WITH ALL FAULTS” AND “AS AVAILABLE,” AND THE ENTIRE RISK AS TO SATISFACTORY QUALITY, PERFORMANCE, ACCURANCY, AND EFFORT IS WITH YOU. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, DCR MAKES NO REPRESENTATIONS, WARRANTIES OR CONDITIONS, EXPRESS OR IMPLIED. DCR DISCLAIMS ANY AND ALL WARRANTIES OR CONDITIONS, EXPRESS, STATUTORY AND IMPLIED, INCLUDING WITHOUT LIMITATION: (i) WARRANTIES OR CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, ACCURACY, TITLE, QUIET ENJOYMENT, NO ENCUMBRANCES, NO LIENS AND NON-INFRINGEMENT; (ii) WARRANTIES OR CONDITIONS ARISING THROUGH COURSE OF DEALING OR USAGE OF TRADE; AND, (iii) WARRANTIES OR CONDITIONS THAT ACCESS TO OR USE OF THE SERVICE WILL BE UNINTERRUPTED OR ERROR-FREE. THERE ARE NO WARRANTIES THAT EXTEND BEYOND THE FACE OF THIS AGREEMENT. </p> <p> 10. <strong>Limitation of Liability</strong>. IN NO EVENT WILL DCR BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION ANY INDIRECT, CONSEQUENTIAL, SPECIAL, INCIDENTAL, OR PUNITIVE DAMAGES ARISING OUT OF, BASED ON, OR RESULTING FROM THIS AGREEMENT OR YOUR USE OF THE SERVICE, EVEN IF DCR HAS BEEN ADVISED OF THE POSSIBLITY OF SUCH DAMAGES. THESE LIMITATIONS AND EXCLUSIONS APPLY WITHOUT REGARD TO WHETHER THE DAMAGES ARISE FROM (1) BREACH OF CONTRACT, (2) BREACH OF WARRANTY, (3) STRICT LIABILITY, (4) TORT, (5) NEGLIGENCE, OR (6) ANY OTHER CAUSE OF ACTION, TO THE EXTENT SUCH EXCLUSION AND LIMITATIONS ARE NOT PROHIBITED BY APPLICABLE LAW. IF YOU ARE DISSATISFIED WITH THE SERVICE, YOU DO NOT AGREE WITH ANY PART OF THIS AGREEMENT, OR HAVE ANY OTHER DISPUTE OR CLAIM WITH OR AGAINST DCR WITH RESPECT THIS AGREEMENT OR THE SERVICE, THEN YOUR SOLE AND EXCLUSIVE REMEDY IS TO DISCONTINUE USING THE SERVICE. </p> <p> 11. <strong>Release.</strong> YOU HEREBY AGREE TO RELEASE, REMISE AND FOREVER DISCHARGE DCR AND ITS AFFILLIATES, PARTNERS, SERVICE PROVIDERS, VENDORS, AND CONTRCTORS AND EACH OF THEIR RESPECTIVE AGENTS, DIRECTORS, OFFICERS, EMPLOYEES, AND ALL OTHER RELATED PERSONS OR ENTITIES FROM ANY AND ALL MANNER OF RIGHTS, CLAIMS, COMPLAINTS, DEMANDS, CAUSES OF ACTION, PROCEEDINGS, LIABLITIES, OBLIGATIONS, LEGAL FEES, COSTS, AND DISBURSEMENTS OF ANY NATURE WHATSOEVER, WHETHER KNOWN OR UNKNOWN, WHICH NOW OR HEREAFTER ARISE FROM, RELATE TO, OR ARE CONNECTED WITH YOUR USE OF THE SERVICE. </p> <p> 12. <strong>Notice.</strong> DCR may provide you with notices, including those regarding changes to the Agreement by posting on this Service. </p> <p> 13. <strong>Termination.</strong> You agree that DCR may, under certain circumstances and without prior notice, immediately terminate your access to the Service. Cause for such termination shall include, but not be limited to: (i) breaches or violations of the Agreement or other incorporated agreements or the Privacy Policy; (ii) requests by law enforcement or other government agencies; (iii) discontinuance or material modification to the Service (or any part thereof); and (iv) unexpected technical or security issues or problems. You agree that all terminations for cause shall be made in DCR’s sole discretion and that DCR shall not be liable to you or any third party for any termination or access to the Service. </p> <p> 14. <strong>Dealings with Third Parties.</strong> Your correspondence or business dealings with any third parties as a result of your visit and participation in the Service or any other terms, conditions, warranties, representations associated with such dealings, are solely between you and such third party. You agree that DCR shall not be responsible or liable for any loss or damage of any sort incurred as the result of any such dealings or as the result of the presence of such third party on the Service. </p> <p> 15. <strong>Disputes.</strong> This Agreement will be interpreted in accordance with the laws of the State of California, without regard to the conflicts of laws principles thereof. The parties agree that any and all disputes, claims or controversies arising out of or relating to the Agreement, its interpretation, performance, or breach, that are not resolved by informal negotiation within 30 days (or any mutually agreed extension of time), shall be submitted to final and binding arbitration before a single arbitrator of the American Arbitration Association (“AAA”) in San Diego, California, or its successor. Either party may commence the arbitration process called for herein by submitting a written demand for arbitration with the AAA, and providing a copy to the other party. The arbitration will be conducted in accordance with the provisions of the AAA’s Commercial Dispute Resolutions Procedures in effect at the time of submission of the demand for arbitration. The costs of arbitration plus reasonable attorneys’ fees (including fees for the value of services provided by in house counsel) shall be awarded to the prevailing party in such arbitration. Judgment on the award rendered by the arbitrator may be entered in the Superior Court of California, County of San Diego. Notwithstanding the foregoing, the following shall not be subject to arbitration and may be adjudicated only in the Superior Court of California, County of San Diego: (i) any dispute, controversy, or claim relating to or contesting the validity of DCR’s proprietary rights, including without limitation, trademarks, service marks, copyrights, or trade secrets; or, (ii) an action by a party for temporary, preliminary, or permanent injunctive relief, whether prohibitive or mandatory, or provisional relief such as writs of attachments or possession. </p> <p> THE PARTIES AGREE THAT THIS AGREEMENT HAS BEEN ENTERED INTO AT DCR’S PLACE OF BUSINESS IN THE COUNTY OF SAN DIEGO, STATE OF CALIFORNIA, AND ANY ARBITRATION, LEGAL ACTION OR PROCEEDING ARISING OUT OF OR RELATING TO THIS AGREEMENT MUST BE COMMENCED AND TAKE PLACE IN THE COUNTY OF SAN DIEGO, STATE OF CALIFORNIA. </p> <p> 16. <strong>Modification to Service.</strong> DCR reserves the right at any time and from time to time to modify or discontinue, temporarily or permanently, the Service (or any part thereof) with or without notice. You agree that DCR shall not be liable to you or to any third party for any modification, suspension or discontinuance of the Service. </p> <p> 17. <strong>Waiver and Severability of Terms.</strong> The failure of DCR to exercise or enforce any right or provision of the Agreement shall not constitute a waiver of such right or provision. If any provision of the Agreement is found by a court of competent jurisdiction to be invalid, the parties nevertheless agree that the court should endeavor to give effect to the parties’ intentions as reflected in the provision, and the other provisions of the Agreement remain in full force and effect. </p> <p> 18. <strong>Disclosure of Your Information.</strong> You acknowledge, consent and agree that DCR may access, preserve, and disclose the information we collect about you if required to do so by law or in good faith belief that such access preservation or disclosure is reasonably necessary to: (i) comply with legal process; (ii) enforce the Agreement; (iii) respond to claims that any information or content violated the rights of the third parties; (iv) respond to your requests for customer service; or (v) protect the rights, property, or personal safety of DCR, its users and the public. </p> <p> 19. <strong>Entire Agreement.</strong> The Agreement constitutes the entire agreement between you and DCR and governs your use of the Service, superseding any prior agreements between you and DCR. You also may be subject to additional terms and conditions that may apply when you use or purchase certain when you use certain other DCR services, affiliate services, third party content or third party software. </p> <p> 20. <strong>Survival.</strong> The following paragraphs shall survive termination or your refusal to continue to use the Service: 4, 5, 6, 8, 9, 10, 11, and 15. </p> <p> 21. <strong>Statute of Limitations.</strong> YOU AGREE THAT REGARDLESS OF ANY STATUTE OR LAW TO THE CONTRARY, ANY CLAIM OR CAUSE OF ACTION ARISING OUT OF RELATED TO USE OF THE SERVICE OR THE AGREEMENT MUST BE FILED WITHIN ONE (1) YEAR AFTER SUCH CLAIM OR CAUSE OF ACTION AROSE OR BE FOREVER BARRED. </p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Our Results:</h2> <img src="images/tab-divider.png"> <p> Our job is to point you in the right direction, to steer you away from shady companies. If you believe the company we suggest to you is honest, law abiding, and reputable then we've done our job. </p> <p> Through various websites and companies our team has been a part of, we've helped well over 120,000 with suggestions for reliable debt solutions. Many of those people have successfully gone on to be debt free. Some of them benefitted greatly from the free consultation which provided invaluable advice as to what their options were. Others who didn't qualify were provided a referral to a different solution which was better suited for their individual situation. </p> <p> The point is that the more you know, the easier and smoother your journey to becoming debt free will be. There are solutions for you out there and we sleep great at night knowing we've helped guide so many people in the right direction. How can we help you? </p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Debt Consolidation:</h2> <img src="images/tab-divider.png"> <h4>What exactly is debt consolidation?</h4> <p>Debt consolidation is a term that's often thrown around when discussing different debt relief solutions. However, there is often confusion about exactly what it means. Debt consolidation itself is not a debt relief solution. Rather it is a by-product of such debt relief solution like credit counseling and debt settlement. With both types of programs you consolidate your debts into a single monthly payment. </p> <h4>How can I consolidate my debts?</h4> <p>Typically there are 3 primary ways to consolidate your debts:</p> <p>1. Enter a debt settlement program which is typically an 18-36 month program with a company who helps you negotiate down the amount of debts that you owe. You can read more about debt settlement here.</p> <p>2. Enter a credit counseling program which is typically a 2-5 year program where you pay back everything you owe but on a scheduled monthly plan with lower interest rates and fees. You can read more about credit counseling here.</p> <p>3. Get a consolidation loan. This option is harder to come by as most loans need some collateral such as a house with equity in it. Banks and other lenders will not lend to people unless they have something they can take from you if you are unable to repay the loan.</p> <h4>What debts qualify for debt consolidation?</h4> <p>In most cases people seek to consolidate their unsecured debts which are debts that are not backed by collateral (a house, a car, etc). The most common unsecured debts are credit cards but also utility bills and medical bills sometimes qualify.</p> <h4>What debts do not qualify for debt consolidation?</h4> <p>The most common are student loan debts, tax debts, and payday loan debts. There is help available for all three, however they are special situations which are typically handled by specialists. Debt settlement and credit counseling firms are unlikely to be able to assist you with these 3 types of debt.</p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> <?php include 'footer.php'; ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Debt Settlement:</h2> <img src="images/tab-divider.png"> <h4>What is debt settlement?</h4> <p>Plain and simple debt settlement is a negotiation process. You may owe $20,000 to a creditor but through negotiations, you may be able to lower that to say $10,000.</p> <h4>Why would creditors take less than I owe?</h4> <p>In many cases they'd rather get some of their money back than none at all. With the threat of not getting any money they may write off a portion of the amount you owe as "bad debt" and settle with you.</p> <h4>Can anyone do this?</h4> <p>Debt settlement is most common with credit card debt. Every situation is different and every creditor handles debt settlement negotiations differently so it really depends on your specific situation - who your creditors are, if you've missed payments, the amount of debt you have, even the state you live in. All those factors come into play to see if you qualify. This is why debt settlement companies offer a free consultation and will need to speak with you on the phone before you can enroll in their program.</p> <h4>Can I settle my own debts?</h4> <p>You can try. However, it is difficult as you need to deal with a myriad of red tape and departments at the large banks who are likely your creditors. Debt settlement companies exist because they know how the system works and have relationships inside the banks with the key people who decide which debts will be settled. You also benefit from the fact that debt settlement companies dela in volume so the banks are more likely to negotiate with them simply because the amount of debts they control can be so large once they aggregate all their clients.</p> <h4>What are the consequences?</h4> <p>There are drawbacks to debt settlement which you must consider. Most importantly understand that your credit score will be damaged while you are in the program and there may be tax consequences as the IRS might consider your saving as income. Be sure to discuss this with your debt settlement company and your tax advisor.</p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?><file_sep>$(document).ready(function(){ function trackEvent(category, action, label) { _gaq.push(['_trackEvent', category, action, label,, false]); } function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i); return pattern.test(emailAddress); }; //Default Animations $('.clouds').pan({fps: 20, speed: .60, dir: 'left'}); $('.debt-form-app .step-one button').click(function(event){ event.preventDefault(); window.Ammount = $(this).val(); trackEvent('Form Events', 'Step One', 'Completed'); $('.step-one').fadeOut(); $('.step-two').fadeIn(); }); $('.debt-form-app .step-two button').click(function(event){ event.preventDefault(); if (!$('.zip').val() || $('.zip').val().length != 5) { $('.zip').css({'border' : '1px solid #FF0000'}); alert('Please Enter A Valid Zip Code.'); } else { trackEvent('Form Events', 'Step Two', 'Completed'); $('.step-two').fadeOut(); $('.step-three').fadeIn(); } }); $("input").on("keydown", function (e) { return e.which !== 32; }); $('.debt-form-app .step-three button').click(function(event){ event.preventDefault(); if(!$('.first-name').val()) { $('.first-name').css({'border' : '1px solid #FF0000'}); alert('Please Enter Your First Name.'); } else if(!$('.last-name').val()) { $('.last-name').css({'border' : '1px solid #FF0000'}); alert('Please Enter Your Last Name.'); } else if(!$('.email').val() || !isValidEmailAddress($('.email').val()) || $.trim($('.email').val()).length < 3 ) { $('.email').css({'border' : '1px solid #FF0000'}); alert('Please Enter A Valid Email.'); } else if(!$('.areacode').val() || $('.areacode').val().length < 3 || !$('.prefix').val() || $('.prefix').val().length < 3 || !$('.suffix').val() || $('.suffix').val().length < 4 ) { $('.phone-lit').css({'border' : '1px solid #FF0000'}); alert('Please Enter a valid Phone Number.'); } else { trackEvent('Form Events', 'Step Three', 'Completed'); var DebtAmmount = window.Ammount; var ZipCode = $('.zip').val(); var FirstName = $('.first-name').val(); var LastName = $('.last-name').val(); var Email = $('.email').val(); var PhoneNumber = $('.areacode').val() + '-' + $('.prefix').val() + '-' + $('.suffix').val(); $.ajax({ type:"POST", url: "process.php", data: 'debt-ammount='+DebtAmmount+'&first-name='+FirstName+'&last-name='+LastName+'&email='+Email+'&phonenumber='+PhoneNumber+'&zip-code='+ZipCode, success: function(){} }); $('.step-three').hide(); $('.step-four').show(); } }); $('.submit-form-ajax').click(function(event){ if ($('.debt').val() == "nil") { $('.debt').css({'border' : '1px solid #FF0000'}); alert('Please choose a debt amount.'); } else if(!$('.zip').val()) { $('.zip').css({'border' : '1px solid #FF0000'}); alert('Please Enter Your Zip Code.'); } else if(!$('.fname').val()) { $('.fname').css({'border' : '1px solid #FF0000'}); alert('Please Enter Your First Name.'); } else if(!$('.lname').val()) { $('.lname').css({'border' : '1px solid #FF0000'}); alert('Please Enter Your Last Name.'); } else if(!$('.email').val() || !isValidEmailAddress($('.email').val()) || $.trim($('.email').val()).length < 3 ) { $('.email').css({'border' : '1px solid #FF0000'}); alert('Please Enter A Valid Email.'); } else if(!$('.areacode').val() || $('.areacode').val().length < 3 || !$('.prefix').val() || $('.prefix').val().length < 3 || !$('.suffix').val() || $('.suffix').val().length < 4 ) { $('.phone-lit').css({'border' : '1px solid #FF0000'}); alert('Please Enter a valid Phone Number.'); } else { var DebtAmmount = window.Ammount; var ZipCode = $('.zip').val(); var FirstName = $('.first-name').val(); var LastName = $('.last-name').val(); var Email = $('.email').val(); var PhoneNumber = $('.areacode').val() + '-' + $('.prefix').val() + '-' + $('.suffix').val(); if ($('.glow').html() < 6) { $('.glow').html('6'); $('.loading-screen').css('display','block'); loadingscreen(); var frm = $('.contactForm'); $.ajax({ type: frm.attr('method'), url: 'mailformprocess.php', data: frm.serialize(), success: function (data) { }, error: function(data){ } }); } } }); //Tab Functionality function TabBuffer() { $('.tab-one').hide(); $('.tab-two').hide(); $('.tab-three').hide(); $('.tab-four').hide(); $('.tab').removeClass('tab-hover'); }; $('.tab').click(function(){ if ( $(this).hasClass('one') ) { TabBuffer(); $(this).addClass('tab-hover'); $('.tab-one').show(); } if ( $(this).hasClass('two') ) { TabBuffer(); $(this).addClass('tab-hover'); $('.tab-two').show(); } if ( $(this).hasClass('three') ) { TabBuffer(); $(this).addClass('tab-hover'); $('.tab-three').show(); } if ( $(this).hasClass('four') ) { TabBuffer(); $(this).addClass('tab-hover'); $('.tab-four').show(); } }); $('.footer-privacy').click(function(){ $('.close-popout').css('display','block'); $('.privacy-popout').css('display','block'); $('html,body').animate({scrollTop: $('body').offset().top},'slow'); }); $('.footer-terms').click(function(){ $('.close-popout').css('display','block'); $('.terms-popout').css('display','block'); $('html,body').animate({scrollTop: $('body').offset().top},'slow'); }); $('.close-popout').click(function(){ $('.close-popout').css('display','none'); $('.privacy-popout').css('display','none'); $('.terms-popout').css('display','none'); }); function loadingscreen() { setInterval(function(){ if ($('.loading-text p').text() == "Processing.") { $('.loading-text p').text("Processing ."); } else if ($('.loading-text p').text() == "Processing .") { $('.loading-text p').text("Processing ."); } else if ($('.loading-text p').text() == "Processing .") { $('.loading-text p').text("Processing."); } },300); }; });<file_sep><?php // Prepare by setting a timezone, mail() uses this. date_default_timezone_set('America/New_York'); // Save some values to send an email, these might have come from any source: $to = '<EMAIL>'; $subject = 'A sample email - Dual Format plus attachment plus inline'; // Create a boundary string. It needs to be unique (not in the text) so ... // We are going to use the sha1 algorithm to generate a 40 character string: $sep = sha1(date('r', time())); // Define the headers we want passed. $headers = "From: php@example.com\r\nX-Mailer: Custom PHP Script"; // Add in our primary content boundary, and mime type specification: $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-{$sep}\""; // Also now prepare our inline image - Also read, encode, split: $inline = chunk_split(base64_encode(file_get_contents('http://www.debtcompanyresearch.com/images/Debt_CartoonLP_1a.jpg'))); // Now the body of the message. $body =<<<EOBODY --PHP-mixed-{$sep} Content-Type: multipart/alternative; boundary="PHP-alt-{$sep}" --PHP-alt-{$sep} Content-Type: multipart/related; boundary="PHP-related-{$sep}" --PHP-related-{$sep} Content-Type: text/html <a href="http://www.debtcompanyresearch.com/"><img src="cid:PHP-CID-{$sep}" /></a> <p style="width:600px;">If you do not wish to receive further promotions from Debt Company Research plaese unsubscribe <a href="http://www.debtcompanyresearch.com/optout/">here</a> or write: Debt Company Research 7975 Raytheon Rd #310 San Diego, CA 92111</p> --PHP-related-{$sep} Content-Type: image/jpg Content-Transfer-Encoding: base64 Content-ID: <PHP-CID-{$sep}> {$inline} --PHP-related-{$sep}-- --PHP-alt-{$sep}-- --PHP-mixed-{$sep}-- EOBODY; // Finally, send the email mail($to, $subject, $body, $headers); ?><file_sep><?php $DebtAmmount = $_POST['debt-ammount']; $ZipCode = $_POST['zip-code']; $FirstName = $_POST['first-name']; $LastName = $_POST['last-name']; $PhoneNumber = $_POST['phonenumber']; $toEmail = $_POST['email']; $to = '<EMAIL>, <EMAIL>, <EMAIL>'; $subject = 'New Approved Debt Lead'; $message = 'The Following Lead has passed all pre-screening elements. '.'Zip:'.$ZipCode.' '.'Name:'.$FirstName.' '.$LastName.' Phone Number:'.$PhoneNumber.' Email:'. $toEmail. ' Debt Amount:'. $DebtAmmount; $headers = 'From:'. $toEmail . "\r\n" . 'Reply-To: <EMAIL>' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); ?><file_sep><?php $debt = $_POST["debt"]; if ($debt == 5000) { $debt = 240904; } elseif ($debt == 7000) { $debt = 240905; } elseif ($debt == 10000) { $debt = 240906; } elseif ($debt == 15000) { $debt = 240907; } elseif ($debt == 20000) { $debt = 240908; } elseif ($debt == 30000) { $debt = 240909; } elseif ($debt == 50000) { $debt = 240910; } elseif ($debt == 70000) { $debt = 240911; } else { $debt = 0; } $fname = $_POST["fname"]; $lname = $_POST["lname"]; $zip = $_POST["zip"]; $email = $_POST["email"]; $phonefirst = $_POST["phonefirst"]; $phonesecond = $_POST["phonesecond"]; $phonethird = $_POST["phonethird"]; $phone = $phonefirst . '-' . $phonesecond . '-' . $phonethird; $country = "United States"; $sid = $_POST["sid"]; $pid = $_POST["pid"]; if ($fname && $lname && $zip && $email && $phone) { $url="http://leads.leadexec.net/processor/insert/AutoRedirect?VID=6160&LID=4204&AID=13079&Password=<PASSWORD>&Country=US&debt=".$debt."&email=".$email."&fname=".$fname."&lname=".$lname."&phone=".$phone."&pid=".$pid."&sid=".$sid."&zip=".$zip; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.6 (KHTML, like Gecko) Chrome/16.0.897.0 Safari/535.6'); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $content = curl_exec( $ch ); $return = curl_getinfo( $ch ); curl_close ( $ch ); $xml = new SimpleXMLElement($content); $validity = $xml->isValidPost; $QC = $xml->PendingQCReview; $redir = $xml->RedirectURL; if ($validity == true) { header("Location: http://www.debtcompanyresearch.com/thankyou/?chosen=cambridge"); } else { } if ($QC == "true") { header("Location: http://www.debtcompanyresearch.com/thankyou/?chosen=cambridge"); } elseif ($QC == "false") { header("Location: http://www.debtcompanyresearch.com/thankyou/?chosen=cambridge"); } else { header("Location: http://www.debtcompanyresearch.com/thankyou/?chosen=cambridge"); } } ?><file_sep><?php include 'header.php'; ?> <div class="container"> <div class="content"> <div class="tabbed-content"> <div class="tab-text"> <h2>Bankruptcy:</h2> <img src="images/tab-divider.png"> <h4>Who can just file bankruptcy?</h4> <p>Anyone can file bankruptcy to try and eliminate your debts however as few years ago the laws became much tougher. Filing bankruptcy used to be a rather uncomplicated process but now it requires more court oversight and approval before your debts are eliminated. It takes time and has serious consequences on your credit score and your personal financial standing. All types of applications for everything from jobs to home rental leases to car loans ask if you've ever filed bankruptcy. If you have to answer "yes" the consequences can be extremely damaging and difficult.</p> <h4>Is it fast?</h4> <p>No. The new laws have made bankruptcy a much more involved process that often includes entering a credit counseling program.</p> <h4>Do I need a lawyer?</h4> <p>Like any legal situation you can go to the courthouse and file papers on your own but it can be a confusing and time consuming process which is why people often hire bankruptcy attorneys to assist them.</p> </div> <img src="images/content-bottom.png"> </div> <?php include 'sidebar.php'; ?> </div> </div> </div> </div> <?php include 'footer.php'; ?>
b8d4fefdab07cbe3e97c9ca7e01e3ca024ddc94c
[ "JavaScript", "PHP" ]
19
PHP
bmstech/DebtCompanyResearch
2895bf96d78532213e8551351f228c244bdc9322
92c3f0e4e4de4637313583abf2911653979ca90f
refs/heads/master
<repo_name>scummerhill/Software-Engineering<file_sep>/src/q3.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <stdbool.h> enum PlayerType {OGRE,HUMAN,ELF,WIZARD}; enum SlotType {LEVEL_GROUND,HILL,CITY}; enum AttackType {NEAR, DISTANT, MAGIC}; struct Player newOgre(char playerName[100]); struct Player newHuman(char playerName[100]); struct Player newElf(char playerName[100]); struct Player newWizard(char playerName[100]); void createPlayers(); void populateSlots(); void addPlayersToRandomSlot(); void beginGame(); const char* getSlotName(enum SlotType slotType); const char* getPlayerTypeName(enum PlayerType playerType); void attackMode(struct Player * player); void alterStatsBasedOnPosition(struct Player * player); bool attackPlayer(struct Player * attacker, struct Player * attacked, enum AttackType attackType); int checkRightOutOfBounds(int column, int row); int checkLeftOutOfBounds(int column, int row); int checkTopOutOfBounds(int column, int row); int checkBottomOutOfBounds(int column, int row); int getUniqueSlotHash(int column, int row); struct Slot getSlot(int slotHash); void updatePlayerSlotLocation(struct Player * player, int slotId); void moveToAdjacentSlot(struct Player * player); void doNearAttack(struct Player * player); void doMagicAttack(struct Player * player); void nearAttack(struct Player * attacker, struct Player * attacked); int generateId(); void doDistantAttack(struct Player *player); void distantAttack(struct Player * attcker, struct Player * attacked); void magicAttack(struct Player * attacker, struct Player * attacked); bool isWithinRangeForDistantAttack(struct Slot currentPlayerSlot, struct Slot enemyPlayerSlot); void checkForWinner(); void printStatsOfPlayers(); bool giveDetailsOfPlayerAndChooseToAttack(struct Player * player, struct Player * enemyPlayer, enum AttackType attackType); struct Player{ int id; enum PlayerType type; char name[100]; double lifePoints; int smartness; int strength; int magicSkills; int luck; int dexterity; int slotId; bool isDefeated; }; struct Slot { int id; int row; int column; int leftSlotId; int rightSlotId; int topSlotId; int bottomSlotId; enum SlotType type; }; struct Player players[6]; struct Slot slots[7][7]; int numberOfPlayers; int numberOfSlots; int main() { setvbuf(stdout, NULL, _IONBF, 0); //Need to have this for printing to eclipse console createPlayers(); populateSlots(); addPlayersToRandomSlot(); beginGame(); } void beginGame(){ //Will loop indefinitely till the user quits, or if there's only one player left while(1) { printStatsOfPlayers(); for(int i = 0; i < numberOfPlayers; i++){ struct Player * player = &players[i]; //This is to prevent a user that has been defeated from making a move if(player->lifePoints <= 0){ continue; } char playerChoice; printf("\nIt is %s's turn. You are in position [%d,%d].\nDo you want to move to an adjacent slot [a], attack [b], or quit [c]? ", players[i].name, getSlot(players[i].slotId).column, getSlot(players[i].slotId).row); scanf("%s", &playerChoice); switch(playerChoice){ case 'a': moveToAdjacentSlot(&players[i]); break; case 'b': attackMode(&players[i]); break; case 'c': exit(1); default: printf("Typed %c", playerChoice); } checkForWinner(); } } } void printStatsOfPlayers(){ printf("\n-------Current Stats-----\n"); for(int j = 0; j < numberOfPlayers; j++){ struct Player player = players[j]; printf("Player: %s, Type: %s, Position: [%d,%d], Position Type: %s , lifepoints: %f, Strength: %d, Magic Skills: %d, Luck: %d, Dexterity: %d, Smartness: %d\n", player.name, getPlayerTypeName(player.type), getSlot(player.slotId).column, getSlot(player.slotId).row, getSlotName(getSlot(player.slotId).type), player.lifePoints, player.strength, player.magicSkills, player.luck, player.dexterity, player.smartness); } printf("------End Current Stats-----\n\n"); } //Checks to see if the user can move in a valid direction // And then update that players location once the user picks a direction void moveToAdjacentSlot(struct Player * player){ struct Slot currentSlot = getSlot(player->slotId); char slotChoice; printf("You can move "); //print slot positions if(currentSlot.topSlotId != -1){ printf("up [u] "); } if (currentSlot.bottomSlotId != -1){ printf("down [d] "); } if (currentSlot.leftSlotId != -1){ printf("left [l] "); } if (currentSlot.rightSlotId != -1){ printf("right [r] :"); } scanf("%s", &slotChoice); printf("You've selected %c\n", slotChoice); switch(slotChoice){ case 'u': updatePlayerSlotLocation(player, currentSlot.topSlotId); break; case 'd': updatePlayerSlotLocation(player, currentSlot.bottomSlotId); break; case 'l': updatePlayerSlotLocation(player, currentSlot.leftSlotId); break; case 'r': updatePlayerSlotLocation(player, currentSlot.rightSlotId); break; default: printf("Invalid choice, skipping turn\n"); } } void updatePlayerSlotLocation(struct Player * player, int slotId) { if(slotId == -1){ printf("Invalid choice, skipping turn\n"); return; } printf("Moving player to position [%d,%d]\n", getSlot(slotId).column, getSlot(slotId).row); player->slotId = slotId; } void createPlayers(){ printf("How many players do you want to create [Min 2, Max 6]? "); scanf("%d", &numberOfPlayers); if(numberOfPlayers > 6 || numberOfPlayers < 2){ printf("Please enter a valid number"); exit(0); } //Player creation is here. //User enters name and type, then the values for each type are generated int i; for(i = 0; i < numberOfPlayers; i++){ char playerName[100]; int playerType; struct Player player; printf("Enter name for Player %d : ", i + 1); scanf("%s", playerName); printf("Enter type for %s [0 = Ogre, 1 = Human, 2 = Elf, 3 = Wizard] : ", playerName); scanf("%d", &playerType); switch(playerType){ case OGRE: player = newOgre(playerName); break; case HUMAN: player = newHuman(playerName); break; case ELF: player = newElf(playerName); break; case WIZARD: player = newWizard(playerName); break; default: printf("Please choose a valid type"); exit(0); } players[i] = player; } } int generateId(){ static int id = 1; return id++; } struct Player newOgre(char playerName[100]){ struct Player player; strcpy(player.name,playerName); player.id = generateId(); player.lifePoints = 100.0; player.type = OGRE; player.magicSkills = 0; player.smartness = rand() % 20; player.strength = (rand() % 20) + 80; player.dexterity = (rand() % 20) + 80; player.luck = rand() % (50 - player.smartness); return player; } struct Player newHuman(char playerName[100]){ struct Player player; player.id = generateId(); strcpy(player.name,playerName); player.lifePoints = 100.0; player.type = HUMAN; int totalPoints = 300; player.magicSkills = rand() % 100; totalPoints -= player.magicSkills; player.smartness = rand() % 100; totalPoints -= player.smartness; if(totalPoints < 100 && totalPoints > -1){ player.strength = (rand() % totalPoints); totalPoints -= player.strength; if(totalPoints < 0){ totalPoints = 0; } } else { player.strength = (rand() % 100); } if(totalPoints < 100 && totalPoints > -1){ player.dexterity = (rand() % totalPoints); totalPoints -= player.dexterity; if(totalPoints < 0){ totalPoints = 0; } } else { player.dexterity = (rand() % 100); } if(totalPoints < 100 && totalPoints > -1){ player.luck = (rand() % totalPoints); totalPoints -= player.luck; if(totalPoints < 0){ totalPoints = 0; } } else { player.luck = (rand() % 100); } if(totalPoints < 100 && totalPoints > -1){ player.magicSkills = (rand() % totalPoints); totalPoints -= player.magicSkills; if(totalPoints < 0){ totalPoints = 0; } } else { player.magicSkills = (rand() % 100); } return player; } struct Player newElf(char playerName[100]){ struct Player player; player.id = generateId(); strcpy(player.name,playerName); player.lifePoints = 100.0; player.type = ELF; player.magicSkills = (rand() % 30) + 50; player.smartness = (rand() % 30) + 70; player.strength = rand() % 50; player.dexterity = (rand() % 20) + 80; player.luck = (rand() % 40) + 60; return player; } struct Player newWizard(char playerName[100]){ struct Player player; player.id = generateId(); strcpy(player.name,playerName); player.lifePoints = 100.0; player.type = WIZARD; player.magicSkills = (rand() % 80) + 20; player.smartness = (rand() % 10) + 90; player.strength = (rand() % 20); player.dexterity = (rand() % 100); player.luck = (rand() % 50) + 50; return player; } const char* getPlayerTypeName(enum PlayerType playerTypes) { switch (playerTypes) { case OGRE: return "Ogre"; case WIZARD: return "Wizard"; case HUMAN: return "Human"; case ELF: return "Elf"; default: return ""; } } const char* getSlotName(enum SlotType slotType) { switch (slotType) { case LEVEL_GROUND: return "Level Ground"; case HILL: return "Hill"; case CITY: return "City"; default: return ""; } } //Generate the slots using a random number generator void populateSlots(){ for(int i = 0; i < 7; i++){ for(int j = 0; j < 7; j++){ struct Slot slot; slot.id = getUniqueSlotHash(i, j); slot.column = i; slot.row = j; slot.leftSlotId = checkLeftOutOfBounds(i - 1, j); slot.rightSlotId = checkRightOutOfBounds(i + 1, j); slot.topSlotId = checkTopOutOfBounds(i, j - 1); slot.bottomSlotId = checkBottomOutOfBounds(i, j + 1); slot.type = rand() % 3; slots[i][j] = slot; } } } //This is a unique hash that is used to differentiate //between each slot using prime numbers; int getUniqueSlotHash(int column, int row) { return column * 17 + row * 37; } struct Slot getSlot(int slotHash) { for(int i = 0; i < 7; i++) { for(int j = 0; j < 7; j++) { if(slots[i][j].id == slotHash) { return slots[i][j]; } } } struct Slot slot; slot.row = -1; slot.column = -1; return slot; } int checkLeftOutOfBounds(int column, int row) { if(column < 0){ return -1; } return getUniqueSlotHash(column, row); } int checkRightOutOfBounds(int column, int row) { if (column > 6){ return -1; } return getUniqueSlotHash(column, row); } int checkTopOutOfBounds(int column, int row) { if (row < 0){ return -1; } return getUniqueSlotHash(column, row); } int checkBottomOutOfBounds(int column, int row) { if (row > 6){ return -1; } return getUniqueSlotHash(column, row); } void addPlayersToRandomSlot(){ int i; for(i = 0; i < numberOfPlayers; i ++){ players[i].slotId = getUniqueSlotHash(rand() % 7, rand() % 7); } } void attackMode(struct Player * player){ char attackChoice; printf("You have chosen to attack!\n"); printf("You can do a Near Attack[n], a Distant Attack[d] or a Magic Attack[m] : "); scanf(" %c", &attackChoice); switch (attackChoice){ case 'n': doNearAttack(player); break; case 'd': doDistantAttack(player); break; case 'm': doMagicAttack(player); break; } } void doMagicAttack(struct Player * player){ if(player->smartness + player->magicSkills > 150){ for(int i = 0; i < numberOfPlayers; i++){ struct Player * enemyPlayer = &players[i]; if(enemyPlayer->id != player->id && !enemyPlayer->isDefeated){ bool hasAttacked = giveDetailsOfPlayerAndChooseToAttack(player, enemyPlayer, 2); if(hasAttacked){ break; } } } } else { printf("Player's stats are not high enough to do a magic attack\n"); } } //Checks for players whose lifepoints are less than or equal to 0 //These players are removed from the game //Once there's only one player remaining, the winner is printed //And the game ends void checkForWinner(){ int numberOfLosers = 0; for(int i = 0; i < numberOfPlayers; i++){ if(players[i].lifePoints <= 0){ if(!players[i].isDefeated){ printf("player %s has been defeated!\n", players[i].name); players[i].isDefeated = true; } numberOfLosers++; } } if(numberOfLosers == numberOfPlayers - 1){ printf("We have a winner! The winner is... "); struct Player winner; for(int i = 0; i < numberOfPlayers; i++){ if(players[i].lifePoints > 0 && !players[i].isDefeated){ winner = players[i]; } } printf(" %s!\n", winner.name); exit(0); } } bool isAdjacentToPlayer(struct Slot currentPlayerSlot, int enemyPlayerSlotId){ return enemyPlayerSlotId == currentPlayerSlot.topSlotId || enemyPlayerSlotId == currentPlayerSlot.leftSlotId || enemyPlayerSlotId == currentPlayerSlot.bottomSlotId || enemyPlayerSlotId == currentPlayerSlot.rightSlotId || enemyPlayerSlotId == currentPlayerSlot.id; } //Starts the initial phase for an attack on an adjacent player, or a player who is on the same tile void doNearAttack(struct Player * player) { for(int i = 0; i < numberOfPlayers; i++){ struct Slot currentPlayerSlot = getSlot(player->slotId); struct Player * enemyPlayer = &players[i]; int enemyPlayerSlotId = enemyPlayer->slotId; int enemyPlayerId = enemyPlayer->id; if(isAdjacentToPlayer(currentPlayerSlot, enemyPlayerSlotId) && enemyPlayerId != player->id && !enemyPlayer->isDefeated){ bool hasAttacked = giveDetailsOfPlayerAndChooseToAttack(player, enemyPlayer, 0); if(hasAttacked){ break; } } } } //This gives the option to allow a player to attack an enemy bool giveDetailsOfPlayerAndChooseToAttack(struct Player * player, struct Player * enemyPlayer, enum AttackType attackType){ char playerChoice; printf("There is an enemy near you. Details -> Name : %s, Type: %s, Slot: %s\n", enemyPlayer->name, getPlayerTypeName(enemyPlayer->type), getSlotName(getSlot(enemyPlayer->slotId).type)); printf("Do you want to attack this player? y/n : "); scanf(" %c", &playerChoice); switch(playerChoice){ case 'y' : attackPlayer(player, enemyPlayer, attackType); return true; case 'n' : return false; } return false; } void doDistantAttack(struct Player * player) { for(int i = 0; i < numberOfPlayers; i++){ struct Slot currentPlayerSlot = getSlot(player->slotId); struct Player * enemyPlayer = &players[i]; int enemyPlayerSlotId = enemyPlayer->slotId; if(isWithinRangeForDistantAttack(currentPlayerSlot, getSlot(enemyPlayerSlotId)) && !enemyPlayer->isDefeated){ bool hasAttacked = giveDetailsOfPlayerAndChooseToAttack(player, enemyPlayer, 1); if(hasAttacked){ break; } } } } //Returns true when distance of enemy is between 1 and 5 bool isWithinRangeForDistantAttack(struct Slot currentPlayerSlot, struct Slot enemyPlayerSlot){ int rowDistance = abs(currentPlayerSlot.row - enemyPlayerSlot.row); int columnDistance = abs(currentPlayerSlot.column - enemyPlayerSlot.column); if(rowDistance > 1 && columnDistance < 5){ return true; } else if (columnDistance > 1 && columnDistance < 5){ return true; } return false; } //This is where the players stats are changed based on the terrain they currently are on void alterStatsBasedOnPosition(struct Player * player){ printf("Altering stats for %s based on slot type...\n", player->name); if(getSlot(player->slotId).type == HILL){ printf("On a Hill slot. "); if(player->dexterity < 50){ player->strength -= 10; if(player->strength < 0){ player->strength = 0; } printf("%s's strength decreased by 10 to %d.\n", player->name, player->strength); } else { player->strength += 10; if (player->strength > 100){ player->strength = 100; } printf("%s's strength increased by 10 to %d.\n", player->name, player->strength); } } else if(getSlot(player->slotId).type == CITY){ printf("On a City slot. "); if(player->smartness <= 50){ player->dexterity -= 10; if(player->dexterity < 0){ player->dexterity = 0; } printf("%s's strength decreased by 10 to %d.\n", player->name, player->strength); } else { player->magicSkills += 10; if (player->magicSkills > 100){ player->magicSkills = 100; } printf("%s's magic skills increased by 10 to %d.\n", player->name, player->strength); } } else if(getSlot(player->slotId).type == LEVEL_GROUND){ printf("On a Level Ground slot. %s's stats are unchanged.\n", player->name); } } //This is where the life points go down for the attacker/attacked based on strength bool attackPlayer(struct Player * attacker, struct Player * attacked, enum AttackType attackType){ alterStatsBasedOnPosition(attacker); alterStatsBasedOnPosition(attacked); printf("%s attacked %s!\n Attackers lifePoints = %f, attacked lifepoints = %f (Before)\n", attacker->name, attacked->name, attacker->lifePoints, attacked->lifePoints); switch(attackType){ case NEAR: nearAttack(attacker, attacked); break; case DISTANT: distantAttack(attacker, attacked); break; case MAGIC : magicAttack(attacker, attacked); break; } printf("%s's lifePoints = %f, %s's lifepoints = %f (After)\n", attacker->name, attacker->lifePoints, attacked->name, attacked->lifePoints); return true; } void magicAttack(struct Player * attacker, struct Player * attacked){ double damage = (0.5 * attacker->magicSkills) + (0.2 * attacker->smartness); printf("Attacking %s for %f\n", attacked->name, damage); attacked->lifePoints -= damage; if(attacked->lifePoints < 0){ attacked->lifePoints = 0; } } void nearAttack(struct Player * attacker, struct Player * attacked){ if(attacked->strength <= 70){ printf("Attacking for %f\n", (0.5 * attacker->strength)); attacked->lifePoints -= (0.5 * attacker->strength); } else { printf("Attacker is injured. Lifepoints drop by %f\n", (0.3 * attacked->strength)); attacker->lifePoints -= (0.3 * attacked->strength); } if(attacked->lifePoints < 0){ attacked->lifePoints = 0; } } void distantAttack(struct Player * attacker, struct Player * attacked){ if(attacked->dexterity >= attacker->dexterity){ printf("Dexterity of %s is higher than %s's. Attacking for 0\n", attacked->name, attacker->name); } else { printf("Attacking for %f\n", (0.3 * attacker->strength)); attacked->lifePoints -= (0.3 * attacker->strength); } if(attacked->lifePoints < 0){ attacked->lifePoints = 0; } }
0a95f1177be2890bc8fac280ed0f6dff25557240
[ "C" ]
1
C
scummerhill/Software-Engineering
918be668df5ac4347a0716906c162c830cf1a0a7
374cc178714006bc5496e0890caa9affc7e8fbed
refs/heads/main
<file_sep># pyPong Jogo de pong desenvolvido em python com biblioteca pygames <file_sep>import pygame, sys, random class Block(pygame.sprite.Sprite): def __init__(self,path,x_pos,y_pos): super().__init__() self.image = pygame.image.load(path) self.rect = self.image.get_rect(center = (x_pos,y_pos)) class Player(Block): def __init__(self,path,x_pos,y_pos,speed): super().__init__(path,x_pos,y_pos) self.speed = speed self.movement = 0 def screen_constrain(self): if self.rect.top <= 0: self.rect.top = 0 if self.rect.bottom >= screen_height: self.rect.bottom = screen_height def update(self,ball_group): self.rect.y += self.movement self.screen_constrain() class Ball(Block): def __init__(self,path,x_pos,y_pos,speed_x,speed_y,paddles): super().__init__(path,x_pos,y_pos) self.speed_x = speed_x * random.choice((-1,1)) self.speed_y = speed_y * random.choice((-1,1)) self.paddles = paddles self.active = False self.score_time = 0 def update(self): if self.active: self.rect.x += self.speed_x self.rect.y += self.speed_y self.collisions() else: self.reiniciarPontuacao() def collisions(self): if self.rect.top <= 0 or self.rect.bottom >= screen_height: pygame.mixer.Sound.play(plob_sound) self.speed_y *= -1 if pygame.sprite.spritecollide(self,self.paddles,False): pygame.mixer.Sound.play(plob_sound) collision_paddle = pygame.sprite.spritecollide(self,self.paddles,False)[0].rect if abs(self.rect.right - collision_paddle.left) < 10 and self.speed_x > 0: self.speed_x *= -1 if abs(self.rect.left - collision_paddle.right) < 10 and self.speed_x < 0: self.speed_x *= -1 if abs(self.rect.top - collision_paddle.bottom) < 10 and self.speed_y < 0: self.rect.top = collision_paddle.bottom self.speed_y *= -1 if abs(self.rect.bottom - collision_paddle.top) < 10 and self.speed_y > 0: self.rect.bottom = collision_paddle.top self.speed_y *= -1 def resetBall(self): self.active = False self.speed_x *= random.choice((-1,1)) self.speed_y *= random.choice((-1,1)) self.score_time = pygame.time.get_ticks() self.rect.center = (screen_width/2,screen_height/2) pygame.mixer.Sound.play(score_sound) def reiniciarPontuacao(self): current_time = pygame.time.get_ticks() countdown_number = 3 if current_time - self.score_time <= 700: countdown_number = 3 if 700 < current_time - self.score_time <= 1400: countdown_number = 2 pygame.mixer.Sound.play(apito) if 1400 < current_time - self.score_time <= 2100: countdown_number = 1 if current_time - self.score_time >= 2100: self.active = True time_counter = basic_font.render(str(countdown_number),True,accent_color) time_counter_rect = time_counter.get_rect(center = (screen_width/2,screen_height/2 + 30)) pygame.draw.rect(screen,bg_color,time_counter_rect) screen.blit(time_counter,time_counter_rect) class adversario(Block): def __init__(self,path,x_pos,y_pos,speed): super().__init__(path,x_pos,y_pos) self.speed = speed def update(self,ball_group): if self.rect.top < ball_group.sprite.rect.y: self.rect.y += self.speed if self.rect.bottom > ball_group.sprite.rect.y: self.rect.y -= self.speed self.constrain() def constrain(self): if self.rect.top <= 0: self.rect.top = 0 if self.rect.bottom >= screen_height: self.rect.bottom = screen_height class GameManager: def __init__(self,ball_group,paddle_group): self.player_score = 0 self.adversario_score = 0 self.ball_group = ball_group self.paddle_group = paddle_group op = self.adversario_score ps = self.player_score def run_game(self): # Drawing the game objects self.paddle_group.draw(screen) self.ball_group.draw(screen) # Updating the game objects self.paddle_group.update(self.ball_group) self.ball_group.update() self.resetBall() self.draw_score() def resetBall(self): if self.ball_group.sprite.rect.right >= screen_width: pygame.mixer.Sound.play(player_score_sond) self.adversario_score += 1 self.ball_group.sprite.resetBall() if self.ball_group.sprite.rect.left <= 0: pygame.mixer.Sound.play(score_sound) self.player_score += 1 self.ball_group.sprite.resetBall() def draw_score(self): player_score = basic_font.render(str(self.player_score),True,accent_color) adversario_score = basic_font.render(str(self.adversario_score),True,accent_color) player_score_rect = player_score.get_rect(midleft = (screen_width / 2 + 40,screen_height/2)) adversario_score_rect = adversario_score.get_rect(midright = (screen_width / 2 - 40,screen_height/2)) screen.blit(player_score,player_score_rect) screen.blit(adversario_score,adversario_score_rect) # Configurações pygame.mixer.pre_init(44100,-16,2,512) pygame.init() pygame.joystick.init() #Função com joystick clock = pygame.time.Clock() # Tela screen_width = 600 screen_height = 600 screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption('<NAME>, Guilherme - PONG') #Sons e cores bg_color = pygame.Color('#000000') accent_color = ('#FFFFFF') basic_font = pygame.font.Font('freesansbold.ttf', 32) plob_sound = pygame.mixer.Sound("sonds/Pong.wav") apito = pygame.mixer.Sound("sonds/Apito.wav") score_sound = pygame.mixer.Sound("sonds/score.ogg") player_score_sond = pygame.mixer.Sound("sonds/sucess.wav") middle_strip = pygame.Rect(screen_width/2 - 2,0,4,screen_height) # Jogador e Oponente player = Player('images/PaddlePlayer.png',20,screen_width/2,5) adversario = adversario('images/Paddle.png',screen_width - 20,screen_height/2,5) paddle_group = pygame.sprite.Group() paddle_group.add(adversario) paddle_group.add(player) #Adicionarndo sprite de bola ao objeto ball = Ball('images/Ball.png',screen_width/2,screen_height/2,2,4,paddle_group) ball_sprite = pygame.sprite.GroupSingle() ball_sprite.add(ball) #Apresenta a mensagem de fim de jogo def draw_mensage(): font = pygame.font.SysFont("comicsansms", 72) text = font.render("Fim de Jogo", True, (255, 255, 255)) pygame.draw.rect(screen, '#000000', pygame.Rect(100, 150, 400, 100)) pygame.draw.rect(screen, '#000000', pygame.Rect(280, 250, 40, 100)) pygame.draw.rect(screen, '#ffffff', pygame.Rect(100, 150, 400, 5)) pygame.draw.rect(screen, '#ffffff', pygame.Rect(100, 350, 400, 5)) pygame.draw.rect(screen, '#ffffff', pygame.Rect(100, 150, 5, 200)) pygame.draw.rect(screen, '#ffffff', pygame.Rect(500, 150, 5, 200)) screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2)) pygame.display.flip() clock.tick(0.4) game_manager = GameManager(ball_sprite,paddle_group) #Comandos com teclado while True: for event in pygame.event.get(): if event.type == pygame.QUIT: draw_mensage() pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: player.movement -= player.speed if event.key == pygame.K_DOWN: player.movement += player.speed if event.key == pygame.K_ESCAPE: draw_mensage() pygame.quit() sys.exit() if event.type == pygame.KEYUP: if event.key == pygame.K_UP: player.movement += player.speed if event.key == pygame.K_DOWN: player.movement -= player.speed joystick_count = pygame.joystick.get_count() # Comando com joystick: for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() hats = joystick.get_numhats() print(screen, "Number of hats: {}".format(hats)) for i in range(hats): hat = joystick.get_hat(i) if (str(hat[1])) == '1': player.movement -= player.speed/4 if (str(hat[1])) == '-1': player.movement += player.speed/4 pygame.display.flip() # Background Stuff screen.fill(bg_color) pygame.draw.rect(screen,accent_color,middle_strip) # Run the game game_manager.run_game() # Rendering pygame.display.flip() clock.tick(120)
c59fbddddca74484d3fbecab5fd735f733a1e145
[ "Markdown", "Python" ]
2
Markdown
MarKosVi/pyPong
95f69a59ef94eacfe84d4bee6c9190e3b803a601
5310c66bc2ddc15021466704a98a3e761555cb3a
refs/heads/master
<file_sep>import {FeatureGroup, LayerGroup, Util, Polyline, extend} from "leaflet"; /** * Builds the ant path polygon * @constructor * @extends {L.FeatureGroup} */ const AntPath = FeatureGroup.extend({ _path: null, _animatedPathId: null, _animatedPathClass: 'leaflet-ant-path', /* default options */ options: { paused: false, delay: 400, dashArray: [10, 20], pulseColor: '#FFFFFF' }, initialize (path, options) { LayerGroup.prototype.initialize.call(this); Util.setOptions(this, options); this._map = null; this._path = path; this._animatedPathId = 'ant-path-' + new Date().getTime(); this._draw(); }, onAdd (map) { this._map = map; this._map.on('zoomend', this._calculateAnimationSpeed, this); this._draw(); this._calculateAnimationSpeed(); }, onRemove (map) { this._map.off('zoomend', this._calculateAnimationSpeed, this); this._map = null; LayerGroup.prototype.onRemove.call(this, map); }, pause () { if (this.options.paused) { return false; } var animatedPolyElement = document.getElementsByClassName(this._animatedPathId); for (var i = 0; i < animatedPolyElement.length; i++) { animatedPolyElement[i].removeAttribute('style'); } return this.options.paused = true; }, resume () { this._calculateAnimationSpeed(); }, _draw () { var pathOpts = {}; var pulseOpts = {}; extend(pulseOpts, this.options); extend(pathOpts, this.options); pulseOpts.color = pulseOpts.pulseColor || this.options.pulseColor; pulseOpts.className = this._animatedPathClass + ' ' + this._animatedPathId; delete pathOpts.dashArray; this.addLayer(new Polyline(this._path, pathOpts)); this.addLayer(new Polyline(this._path, pulseOpts)); }, _calculateAnimationSpeed () { if (this.options.paused || !this._map) { return; } var zoomLevel = this._map.getZoom(); var animatedPolyElement = document.getElementsByClassName(this._animatedPathId); //Get the animation duration (in seconds) based on the given delay and the current zoom level var animationDuration = 1 + (this.options.delay / 3) / zoomLevel + 's'; //TODO Use requestAnimationFrame to better support IE var rulesSuffixes = ['-webkit-', '-moz-', '-ms-', '']; Array.prototype.map.call(animatedPolyElement, el => { rulesSuffixes.map((suffix)=> { el.setAttribute('style', `${suffix}animation-duration: ${animationDuration}`); }); }); } }); export default AntPath;
0b897507ee3e9207f7d309d2a09275d12df94c0d
[ "JavaScript" ]
1
JavaScript
thdtjsdn/leaflet-ant-path
e0288b7709d969c8f885eae6dfa0101283307eca
aee790ce47eb37402ad536fb55896a8ed20867a1
refs/heads/master
<repo_name>Zelanias/UTD-OPL<file_sep>/inclass10.py ADULT = 40 SENIOR = 30 CHILD = 20 Adult_Choice = 1 Child_Choice = 2 Senior_Choice = 3 Quit_Choice = 4 print "Health Club Membership Menu\n1. Standard Adult Membership\n2. Child Memebership\n3. Senior Citizen Membership\n4. Quit the Program\n\n" choice = int(raw_input("Enter your choice:")) if(choice==Adult_Choice): months = raw_input("For how many months? ") print "The total charges are $" + str(int(months)*ADULT) elif(choice==Child_Choice): months = raw_input("For how many months? ") print "The total charges are $" + str(int(months)*CHILD) elif(choice==Senior_Choice): months = raw_input("For how many months? ") print "The total charges are $" + str(int(months)*SENIOR) elif(choice == Quit_Choice): print "Program ending\n" else: print "The valid choices are 1 through 4.\nRun the program again and select one of those.\n"<file_sep>/HW3/Q6/q6.cpp #include <iostream> //Question 6 using namespace std; int main(){ int arr [1000][1000]; for(int i = 0; i < 1000; i++){ for(int o = 0; o < 1000; o++){ arr[i][o] = 10; } } int *pointer = NULL; pointer = &arr[0][0]; for(int i = 0; i < 1000; i++){ for(int o = 0; o < 1000; o++){ *(pointer + 4*i+o); } } }<file_sep>/HW6/2/nested.py import random first = random.randint(0,100) second = random.randint(0,100) third = random.randint(0,100) max = mid = min = 0 if(first > second): if(first > third): max = first if(second > third): mid = second min = third else: mid = third min = second else: max = third mid = first min = second elif(third > second): max = third mid = second min = first elif(first >third): max = second mid = first min = third else: max = second mid = third min = first print str(max) + " " + str(mid) + " " + str(min)<file_sep>/HW6/5/complex.cpp #include <iostream> using namespace std; class complex{ private: double real; double imaginary; public: complex(double r, double i){ real = r; imaginary = i; } complex(complex a, complex b){ real = a.real + b.real; imaginary = a.imaginary + b.imaginary; } complex(const complex& a){ real = a.real; imaginary = a.imaginary; } double getReal(){ return real; } double getImaginary(){ return imaginary; } complex operator+(const complex other){ complex temp(0,0); temp.real = real + other.real; temp.imaginary = imaginary + other.imaginary; return temp; } complex operator-(const complex other){ complex temp(0,0); temp.real = real - other.real; temp.imaginary = imaginary - other.imaginary; return temp; } complex operator*(const complex other){ complex temp(0,0); temp.real = real * other.real; temp.imaginary = imaginary * other.imaginary; return temp; } complex operator/(const complex other){ complex temp(0,0); temp.real = real / other.real; temp.imaginary = imaginary / other.imaginary; return temp; } void print(){ printf( "%.4f + %.4fi", real, imaginary); } }; int main(){ complex a(2,3); cout << "A real: " << a.getReal() << " A imaginary: " << a.getImaginary()<<endl; complex b = a + a; b.print(); cout << endl; b = a-a-a; b.print(); b = a*a; cout<<endl; b.print(); b = a/a; cout<<endl; b.print(); complex c(a,b); cout<<endl; c.print(); complex d(a+b+c); cout<<endl; d.print(); }<file_sep>/notes.txt LANG chp 6 Data type - defines a collectin of data values and set off predefined operations can not be defined in other terms - primative descriptor are the properties of the variable. STATIC descriptors are required at COMPILE time Dynamic During EXECUTION Integer Java - SIGNED byte short int long Others have unsigned Python - Long integer, unlimted length Floating points are only aproximations Fractions and exponent Complex data type, fortran and python Ordered pair of floating point values Python complex literal is specificed with J Decimal data type business data processing BCD binaryu coded decimal 1 digit or 2 per byte takes up more storage then binary representation Boolean single bit but is usually in a single byte C89 numeric expressions can use as conditionals C99 and C++ allow numeric Character types chars are cstored as ascii, numeric coding 8 bit - 128 chars 16 bit unicode 4 byte - UCS-4 UTF -32 String Assignment cat slice comp pattern matching usually stored in array of single hars c/c++ uses arrays java string is primative Python has it as a primative type and has operations Length options Static length string varying lengths - varying length with fixed maximum, as variable's definition. LImited dynamic length strings Varying length with no maximum - Dynamic length strings Static string - length - address Limited DYnamic string - Max length - current length - address C/C++ do not require run time descriptor Dynamic string - run time descriptor requires more complex storage management Ordinal type - can be associated with set of positive integers integer char boolean Enum type - all possible values are named constants are provied by user c++: enum colors{red,blue,green,yellow,black} readability and reliablity Record Element defined by names, accessed through offsets c struct python/ruby hashes Elliptical references, fields can be omitted Tuple elements are not named python immutable List Elements can be any data type Union variables store different type values at different times no language support for type checking is free unions with a type indicator is called Discriminated Heap dynamic variable, variable that are dynamically allocated from heap Dangling pointer reference - pointer that contains address of a heap dynamic variable that has been deallocated Solution, reference tomb stone Extra heap cell that is a pointer to the data Pointer -> tombstome -> variable Locks and keys Pointer values are represented as (Key, address) pairs Only gets value when lock and key are same, if variable is deallocated lock value is modified Lost Heap-Hynamic Variable - allocated heap hynamic variable that is no longer accessible. Heap management Reference counter Counter that counts references if 0, deallocate variable - becomes garbage Mark-sweep All cells are set to indicate as garbage Every pointer is traced into the heap, all reachable cells are marked as not garbage All cells that have not been marked are garbage Array homogenous aggregate of data elements aggregate name and subscripts finite mappings perl can do negative subscript range checking Java ML C# does Others dont 5 categories based on range binding and storage binding static array range and storage is static no dynamic allocation or deallocation storage is fixed fixed stack dynamic array range is static, allocation is done during execution space efficiency allocation and deallocation time is slower stack dynamic range and storage are dynamically bound then remain fixed during lifetime of variable Flexiable. fied heap dynamic both are fixed after allocatoin DIFFERENCE is that when user requests them during execution, storage is allocated from heap, not stack Flexiblity, array size always fits the problem. Allocation time for heap is longer then stack. heap dynamic ranges and storage is dynamic, can change any number of times in aray lifetime Arrays can grow and strink allocation and deallocation takes longer Assignment, cat, comp Associative Array Unordered collection, indexed by keys perl -> hashes, % _______________________________________________________________________________________ Names, binding, scoping ______________________________- Logical programming They are declarative not procedual only the specifications of desired results are stated Proposition logical statement that might be true of false Symbolic logic can be used to make formal logic express propositions express relationships between propositions decsribe how new propositions can be inferred First order predicate calculus Constant represents an object Variable is a symbol that represent different objects at different times Simpilist is atomic proposition, consist of compound terms Compound term is composed of two parts functor functino sumbol that names the relation ordered list of parameters Predicate calculus and proving theorems, Arithmetic IS operator in prolog All variables must already be instantiated Left side cannot be previously instantiated ________________ Fundamental abstraction fallacies Process abstraction Parameters in subprogram headers - formal parmeters Functino declaration Fucntino return type Fcuntino prototype/definition Paremeters should match Parameter matching is basec on position/order OR keyword parameter any order but need to know the name of the parameters default parameters are at the end Some langauges allows variable number of parameters c# params int[] list can pass a list or pass an arbitrary amoutn of sepearte parameters Python *args and **kwargs(key and value? like passing a dictionary to a fcuntion) def gaoewjaiwe(arg1, *argv) _______________________________________________ C uses pass by value. parameters that are subprograms 3 types shallow binding enviorment of the call statement deep binding ad hoc binding Pointer to function Overloding parameters if having one with default and one without any ther is ambiguity Coroutines ________________________________________________ Abstractions, data abstraction, encapsulation construct Functino/Classes can be a way of abstraction Only able to view most significant attributes Data abstraction 2 types: Data representation Subprograms 2 conditions: Syntatic unit Declaration of the type Advantages: It improvres reliability of a program, but making its contents hidden/immutable Reducing rang eof code and number of variables making name conflicts lessl ikely indirect access to hidden data Struct doesnt have any functions, only data. Encapsulation Data members menber functions All instances share single set of functions own sets of data members Class instances: static, stack dynamic, heap dynamic Static: Allocate memory before runtime, @compile time? Cannot have recursion with static Stack dynamic: Allocate at call on the stack, can have multiple memory location Heap Dynamic: Allocate on the heap, explicitly request to allocate at run time, and deallocation Inheritance: Class can be derived from existing class <file_sep>/HW3/Q2/homework.java class homework{ static void main(String args[]){ for(int i = 0; i < 1; i++){ //do nothing } System.out.print(i); } }<file_sep>/HW3/Q1/Homework.cpp #include <ctime> #include <iostream> using namespace std; void staticArray(); void stackArray(); void heapArray(); int main(){ clock_t begin = clock(); for(int i = 0; i < 300000; i++){ staticArray(); } cout << float( clock () - begin ) / CLOCKS_PER_SEC << endl; begin = clock(); for(int i = 0; i < 300000; i++){ stackArray(); } cout << float( clock () - begin ) / CLOCKS_PER_SEC << endl; begin = clock(); for(int i = 0; i < 300000; i++){ heapArray(); } cout << float( clock () - begin ) / CLOCKS_PER_SEC << endl; } void staticArray(){ int static arr[100000]; } void stackArray(){ int arr[100000]; } void heapArray(){ int * arr = new int[100000]; } <file_sep>/HW3/Q5/q5.cpp #include <iostream> using namespace std; int main(){ enum Color {red, green, blue, orange, white = 200, black, gray = red + green, silver, purple}; int n = orange; cout << n << endl; n = white - green; cout << n << endl; n = silver; cout << n << endl; n = black; cout << n << endl; white = 20; n = black; cout << n << endl; gray = 10; n = silver; cout << n << endl; red = -3; n = green; cout << n << endl; white = purple - red; n = white; cout << n << endl; n = purple; cout << n << endl; black = red * white; n = black; cout << n << endl; } <file_sep>/HW3/Q7/q7.java class q7{ public static void main(String args[]){ int x = 10; x = x + foo(x); System.out.println(x); x = 10; x = foo(x) + x; System.out.println(x); x = 10; x = x++ + foo(x); System.out.println(x); x = 10; x = foo(x) + ++x; System.out.println(x); x = 10; x = ++x + foo(x); System.out.println(x); } static public int foo(int x){ return x+3; } } <file_sep>/HW6/3/test.cpp #include <iostream> using namespace std; void reference(int &i){ i = i + 1; } void value(int i){ i = i + 1; } int main(){ int i = 1; reference(i); cout << i << endl; value(i); cout << i << endl; return 0; }<file_sep>/HW6/5/complex.py class complex: def __init__(self,real,imaginary): self.real = real self.imaginary = imaginary def getReal(self): return self.real def getImaginary(self): return self.imaginary def __add__(self,o): return complex(self.real + o.real, self.imaginary + o.imaginary) def __sub__(self,o): return complex(self.real - o.real, self.imaginary - o.imaginary) def __mul__(self,o): return complex(self.real * o.real, self.imaginary * o.imaginary) def __div__(self,o): return complex(self.real / o.real, self.imaginary / o.imaginary) def __str__(self): return str(self.real) + ", " + str(self.imaginary) + "i" a = complex(2,3) b = a + a c = b - a d = a * b e = b / a print(a) print(b) print(c) print(d) print(e) print(a.getReal()) print(a.getImaginary())<file_sep>/HW6/2/notnested.py import random first = random.randint(0,100) second = random.randint(0,100) third = random.randint(0,100) max = mid = min = 0 if(first > second > third): max = first mid = second min = third elif(first > third > second): max = first mid = third min = second elif(second > first > third): max = second mid = first min = third elif(second > third > first): max = second mid = third min = first elif(third > second > first): max = third mid = second min = first else: max = third mid = first min = second print str(max) + " " + str(mid) + " " + str(min) <file_sep>/HW3/Q3/q3.py a = 0 b = 0 x = 0 def one(): global a a = 1 global b b = 2 c = 0 d = 0 def two(): global b d = 4 nonlocal c c = 5 e = 10 b = 2 a = 3 def three(): nonlocal a a = 3 b = 20 global x x = 4 print(str(a)) print(str(b)) print(str(x)) one()
1663d9af80c27467542dea6240caabe5d36e2025
[ "Java", "Python", "Text", "C++" ]
13
Python
Zelanias/UTD-OPL
12f1784af2239954955ac36308ed30c6c0c27f0d
e5be3259d3d3367200328679f82d10b3c564f89f
refs/heads/master
<file_sep>package com.example.listadecomprasapp.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.RatingBar; import android.widget.Spinner; import com.example.listadecomprasapp.adapter.GeneroAdapter; import com.example.listadecomprasapp.model.Genero; import com.example.listadecomprasapp.model.Livro; import com.example.listadecomprasapp.repository.Repository; import com.example.listadecomprasapp.R; public class NovoLivroActivity extends Activity { private EditText editTitulo, editAno; private Spinner spinnerGenero; private RatingBar ratingLivro; private Repository repository; private Livro livro; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_novo_livro); editTitulo = findViewById(R.id.editTitulo); editAno = findViewById(R.id.editAno); spinnerGenero = findViewById(R.id.spinnerGenero); ratingLivro = findViewById(R.id.ratingNotaLivro); repository = new Repository(getApplicationContext()); livro = new Livro(); loadGeneros(); } private void loadGeneros() { final GeneroAdapter adapter = new GeneroAdapter(this,android.R.layout.simple_spinner_item,repository.getGeneroRepository().getAllGeneros()); spinnerGenero.setAdapter(adapter); spinnerGenero.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { Genero genero = (Genero) adapterView.getItemAtPosition(i); livro.setGeneroId(genero.getID()); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } public void salvarLivro(View view){ //Toast.makeText(this, ""+livro.getGeneroId(), Toast.LENGTH_SHORT).show(); //Livro livro = new Livro(); livro.setTitulo(editTitulo.getText().toString()); livro.setAno_producao(Integer.parseInt(editAno.getText().toString())); livro.setAvaliacao((int)ratingLivro.getRating()); repository.getLivroRepository().insert(livro); callMainActivity(); } private void callMainActivity() { Intent mainActivity = new Intent(NovoLivroActivity.this,MainActivity.class); startActivity(mainActivity); finish(); } } <file_sep>package com.example.listadecomprasapp.model; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "genero_table") public class Genero { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "ID") private long ID; private String nome; public Genero(){} public Genero(long ID, String nome) { this.ID = ID; this.nome = nome; } public long getID() { return ID; } public void setID(long ID) { this.ID = ID; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } } <file_sep>package com.example.listadecomprasapp.DAO; import androidx.room.Dao; import androidx.room.Embedded; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import java.util.List; import com.example.listadecomprasapp.model.Genero; import com.example.listadecomprasapp.model.Livro; @Dao public interface LivroDAO { @Insert void insert(Livro livro); @Update void update(Livro livro); @Query("SELECT * FROM livro_table WHERE livro_table.ID == :id") Livro loadLivroByID(Long id); @Query("DELETE FROM livro_table where livro_table.ID == :id") void delete(long id); @Query("SELECT * from livro_table ORDER BY avaliacao DESC") List<Livro> loadLivros(); @Query("SELECT livro_table.ID,livro_table.titulo,livro_table.ano_producao,livro_table.avaliacao, genero_table.ID as genero_ID ,genero_table.nome as genero_nome from livro_table INNER JOIN genero_table ON livro_table.genero_id = genero_table.ID ORDER BY avaliacao DESC") List<LivroJoin> loadLivrosJoin(); @Query("SELECT titulo from livro_table") List<String> loadLivrosNames(); static class LivroJoin{ @Embedded public Livro livro; @Embedded(prefix = "genero_") public Genero genero; } } <file_sep>package com.example.listadecomprasapp.repository; import android.content.Context; public class Repository { private LivroRepository livroRepository; private GeneroRepository generoRepository; public Repository(Context context){ livroRepository = new LivroRepository(context); generoRepository = new GeneroRepository(context); } public LivroRepository getLivroRepository() { return livroRepository; } public GeneroRepository getGeneroRepository() { return generoRepository; } } <file_sep>package com.example.listadecomprasapp.repository; import android.content.Context; import java.util.List; import com.example.listadecomprasapp.DAO.GeneroDAO; import com.example.listadecomprasapp.database.AppDatabase; import com.example.listadecomprasapp.model.Genero; public class GeneroRepository { private GeneroDAO mGeneroDAO; private List<Genero> mGeneros; public GeneroRepository(Context context){ AppDatabase db = AppDatabase.getDatabase(context); mGeneroDAO = db.generoDAO(); } public List<Genero> getAllGeneros(){ mGeneros = mGeneroDAO.loadGeneros(); return mGeneros; } /*public Genero loadGeneroByID(long ID) { return mGeneroDAO.loadGeneroByID(ID); }*/ public void insert(Genero genero){ mGeneroDAO.insert(genero); } public void update(Genero genero) {mGeneroDAO.update(genero);} } <file_sep>package com.example.listadecomprasapp.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.List; import com.example.listadecomprasapp.DAO.LivroDAO; import com.example.listadecomprasapp.adapter.LivroAdapter; import com.example.listadecomprasapp.repository.LivroRepository; import com.example.listadecomprasapp.R; public class MainActivity extends Activity implements AdapterView.OnItemClickListener{ private ListView listaLivros; private LivroRepository repository; ArrayAdapter<LivroDAO.LivroJoin> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listaLivros = findViewById(R.id.listaLivros); repository = new LivroRepository(getApplicationContext()); atualizarLivros(); listaLivros.setOnItemClickListener(this); } public void novoLivro(View view){ Intent novoLivro = new Intent(MainActivity.this,NovoLivroActivity.class); startActivity(novoLivro); } private void atualizarLivros(){ List<LivroDAO.LivroJoin> livros = repository.getAllLivrosJoin(); adapter = new LivroAdapter(getApplicationContext(), R.layout.livro_item, livros); listaLivros.setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { final LivroDAO.LivroJoin livroJoin = (LivroDAO.LivroJoin) adapterView.getItemAtPosition(i); AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this); dialog.setTitle("O que fazer com " + livroJoin.livro.getTitulo()).setItems(R.array.opcoes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int which) { if(which == 0) { repository.delete(livroJoin.livro.getId()); atualizarLivros(); } else if(which == 1){ callActivity(livroJoin.livro.getId()); } } }).create().show(); } private void callActivity(Long id) { Intent atualizar = new Intent(MainActivity.this,AtualizarLivroActivity.class); atualizar.putExtra("ID",id); startActivity(atualizar); } public void novoGenero(View view) { Intent novoGenero = new Intent(MainActivity.this,NovoGeneroActivity.class); startActivity(novoGenero); } }
a9cebbdbd1a2e1f09181e9a8e1c1286287034e99
[ "Java" ]
6
Java
HeraldoJunior/projetointegrador
6642f989d0dcd2bf6fa83415e4c4bb1c871ae27c
330de58412167dd796b4c5fe166b3a13ef22ee93
refs/heads/master
<file_sep>import styled from 'styled-components'; import {FROM_BG_COLOR, RATE_COLOR, TO_BG_COLOR} from '../../styles/constants'; export const Container = styled.div` position: absolute; bottom: -18px; z-index: 2; background-color: ${FROM_BG_COLOR}; border-radius: 18px; font-size: 14px; color: ${RATE_COLOR}; left: 50%; transform: translateX(-50%); padding: 8px 12px; border: solid 2px ${TO_BG_COLOR}; `; export const LoadingDot = styled.span` color: ${props => props.isLoading ? RATE_COLOR : FROM_BG_COLOR}; margin-left: 5px; margin-right: -5px; `; <file_sep>export const GET_RATES = 'GET_RATES'; export const SET_FROM_CURRENCY = 'SET_FROM_CURRENCY'; export const SET_FROM_VALUE = 'SET_FROM_VALUE'; export const SET_TO_CURRENCY = 'SET_TO_CURRENCY'; export const SET_TO_VALUE = 'SET_TO_VALUE'; export const EXCHANGE = 'EXCHANGE'; export const SET_RATES_LOADING = 'SET_RATES_LOADING'; export const SHOW_SUCCESS_MODAL = 'SHOW_SUCCESS_MODAL'; export const SET_RATES_ERROR = 'SET_RATES_ERROR'; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import {MenuItem, SelectField} from 'material-ui'; const CurrencySelect = ({name, value, onChange, isDisabled, balance}) => ( <SelectField id={name} name={name} value={value} onChange={onChange} disabled={isDisabled} labelStyle={{fontSize: '30px'}} > <MenuItem value="GBP" label="GBP" primaryText={`GBP · ${balance.GBP.toFixed(2)}`} /> <MenuItem value="EUR" label="EUR" primaryText={`EUR · ${balance.EUR.toFixed(2)}`} /> <MenuItem value="USD" label="USD" primaryText={`USD · ${balance.USD.toFixed(2)}`} /> </SelectField> ); CurrencySelect.propTypes = { name: PropTypes.string.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, isDisabled: PropTypes.bool.isRequired, balance: PropTypes.object.isRequired }; export default CurrencySelect; <file_sep>import { createStore } from 'redux'; import * as ActionTypes from '../actions/types'; import initialState from '../reducers/initial.state'; import rootReducer from '../reducers/index.reducer'; describe('Loading', () => { it('should get the correct loading.rates state when `SET_RATES_LOADING` action is dispatched', () => { // arrange const store = createStore(rootReducer, initialState); // act const action = { type: ActionTypes.SET_RATES_LOADING, isLoading: true}; store.dispatch(action); // assert const actual = store.getState(); expect(actual.loading.rates).toEqual(true); }); }); describe('Modal', () => { it('should get the correct modal.success state when `SHOW_SUCCESS_MODAL` action is dispatched', () => { // arrange const store = createStore(rootReducer, initialState); // act const action = { type: ActionTypes.SHOW_SUCCESS_MODAL, show: true}; store.dispatch(action); // assert const actual = store.getState(); expect(actual.modal.success).toEqual(true); }); }); describe('Rates', () => { it('should get the correct rates state when `GET_RATES` action is dispatched', () => { // arrange const store = createStore(rootReducer, initialState); // act const action = { type: ActionTypes.GET_RATES, rates: { GPB: 10, EUR: 1, USD: 4 }}; store.dispatch(action); // assert const actual = store.getState(); expect(actual.rates).toEqual({ GPB: 10, EUR: 1, USD: 4 }); }); }); describe('Errors', () => { it('should get the correct error.rates state when `SET_RATES_ERROR` action is dispatched', () => { // arrange const store = createStore(rootReducer, initialState); // act const action = { type: ActionTypes.SET_RATES_ERROR, error: 'error'}; store.dispatch(action); // assert const actual = store.getState(); expect(actual.errors.rates).toEqual('error'); }); }); describe('Exchange', () => { it('should get the correct balance state when `EXCHANGE` action is dispatched', () => { // arrange const store = createStore(rootReducer, initialState); // act const active = { fromCurrency: 'GBP', fromValue: 10, toCurrency: 'EUR', toValue: 11.36 }; const rates = { base: 'GBP', date: '2017-12-07', rates: { EUR: 1.1355, USD: 1.3383 } }; const action = { type: ActionTypes.EXCHANGE, active, rates}; store.dispatch(action); // assert const actual = store.getState(); expect(actual.balance).toEqual({ EUR: 11.355, GBP: 5, USD: 0, lastExchange: { fromCurrency: 'GBP', fromValue: 10, toCurrency: 'EUR', toValue: 11.355 } }); }); }); <file_sep>export const GlobalStyled = () => ` @font-face { font-family: 'Roboto', sans-serif; src: url('https://fonts.googleapis.com/css?family=Roboto'); } html, body { height: 100%; } body { font-family: 'Roboto', sans-serif; } #root { background-color: #0068E6; height: 100vh; display: flex; align-items: center; justify-content: center; } `; <file_sep>export * from './rates.actions'; export * from './active.actions'; export * from './balance.actions'; export * from './loading.actions'; export * from './errors.actions'; export * from './modal.actions'; <file_sep>import initialState from './initial.state'; import * as types from '../actions/types'; const setFromValue = (state, action) => { const {toCurrency} = state; const {fromValue, rates} = action; const toValue = fromValue * rates.rates[toCurrency]; return Object.assign({}, state, { fromValue: action.fromValue, toValue: toValue }); }; const setToValue = (state, action) => { const {toValue, rates} = action; const {toCurrency} = state; const fromValue = toValue / rates.rates[toCurrency]; return Object.assign({}, state, { toValue: action.toValue, fromValue: fromValue }); }; const setFromCurrency = (state, action) => { const {fromValue} = state; const {fromCurrency, rates} = action; const toCurrency = state.toCurrency === fromCurrency ? state.fromCurrency : state.toCurrency; const toValue = fromValue * rates.rates[toCurrency]; return Object.assign({}, state, { fromCurrency: action.fromCurrency, toValue: toValue, toCurrency: toCurrency }); }; const setToCurrency = (state, action) => { const {fromValue} = state; const {toCurrency, fromCurrency, rates} = action; const toValue = fromValue * rates.rates[toCurrency]; return Object.assign({}, state, { toCurrency: action.toCurrency, toValue: toValue, fromCurrency }); }; export default function activeReducer(state = initialState.active, action) { switch (action.type) { case types.SET_FROM_VALUE: return setFromValue(state, action); case types.SET_TO_VALUE: return setToValue(state, action); case types.SET_FROM_CURRENCY: return setFromCurrency(state, action); case types.SET_TO_CURRENCY: return setToCurrency(state, action); default: return state; } } <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import renderer from 'react-test-renderer'; import Rates from './Rates'; describe('Rates', () => { const props = { rates: {}, fromCurrency: 'EUR', toCurrency: 'GBP', isLoading: false }; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render( <Rates {...props} />, div ); }); test('has a valid snapshot', () => { const component = renderer.create( <Rates {...props} /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import {Container} from './Button.styles'; const Button = ({isDisabled, onClick, children}) => { return ( <Container disabled={isDisabled} onClick={onClick} > {children} </Container> ); }; Button.propTypes = { isDisabled: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired }; export default Button; <file_sep>import * as ActionTypes from './types'; import {getRates} from './rates.actions'; export const setFromValue = fromValue => (dispatch, getState) => { const rates = getState().rates; return dispatch({ type: ActionTypes.SET_FROM_VALUE, fromValue, rates }); }; export const setToValue = toValue => (dispatch, getState) => { const rates = getState().rates; return dispatch({ type: ActionTypes.SET_TO_VALUE, toValue, rates }); }; export const setFromCurrency = fromCurrency => (dispatch, getState) => { return dispatch(getRates(fromCurrency)) .then(() => { const rates = getState().rates; return dispatch({ type: ActionTypes.SET_FROM_CURRENCY, fromCurrency, rates }); }); }; export const setToCurrency = toCurrency => (dispatch, getState) => { const active = getState().active; const fromCurrency = active.fromCurrency === toCurrency ? active.toCurrency : active.fromCurrency; return dispatch(getRates(fromCurrency)) .then(() => { const rates = getState().rates; return dispatch({ type: ActionTypes.SET_TO_CURRENCY, fromCurrency, toCurrency, rates }); }); }; <file_sep>import reducer from './active.reducer' import * as types from '../actions/types' describe('active reducer', () => { it('should return the initial state', () => { expect(reducer(undefined, {})).toEqual({ fromCurrency: 'GBP', fromValue: '', toCurrency: 'EUR', toValue: '' }) }); it('should handle SET_FROM_VALUE', () => { expect( reducer({toCurrency: 'EUR'}, { type: types.SET_FROM_VALUE, rates: { base: 'GBP', date: '2017-12-07', rates: { EUR: 1.1355, USD: 1.3383 } }, fromValue: 1 } ) ).toEqual({ fromValue: 1, toCurrency: 'EUR', toValue: 1.1355 }); }); }); <file_sep>export const convertInputValueToTwoDigitsNumber = string => { string = string.replace('-', ''); let stringMod; if (string.includes('.') && string.indexOf('.') > string.length-1) { stringMod = parseFloat(string.replace(/[^\d.]/g, '')); return convertToTwoDigitsNumber(removeSecondPeriod(stringMod)); } else { stringMod = removeSecondPeriod(string.replace(/[^\d.]/g, '')); return stringMod; } }; const removeSecondPeriod = string => { let t=0; return string.replace(/\./g, match => { t++; return (t === 2) ? '' : match; }); }; export const convertToTwoDigitsNumber = (number) => { const decimal = (number.toString().split('.')[1] || []).length; return decimal > 2 ? Number(number).toFixed(2) : number; }; <file_sep>import {css} from 'styled-components'; export const media = { smallHorizontal: (...args) => css` @media (max-width: 420px) { ${ css(...args) } } `, smallVertical: (...args) => css` @media (max-height: 750px) { ${ css(...args) } } `, small: (...args) => css` @media (max-width: 420px) and (max-height: 750px) { ${ css(...args) } } ` }; <file_sep>import styled from 'styled-components'; import { EXCHANGE_BG_COLOR_DISABLED, EXCHANGE_BG_COLOR_ENABLED, EXCHANGE_BG_COLOR_HOVER, EXCHANGE_COLOR } from '../../styles/constants'; export const Container = styled.button` cursor: pointer; background-color: ${EXCHANGE_BG_COLOR_ENABLED}; color: ${EXCHANGE_COLOR}; border: none; width: 80%; padding: 15px; border-radius: 25px; box-shadow: 0 10px 10px 0 rgba(0,0,0,0.15); outline: none; position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); :hover { background-color: ${EXCHANGE_BG_COLOR_HOVER}; } &:disabled { background-color: ${EXCHANGE_BG_COLOR_DISABLED}; cursor: auto; } `; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import renderer from 'react-test-renderer'; import SuccessModal from './SuccessModal'; describe('SuccessModal', () => { const props = { lastExchange: { fromValue: 12.34, toValue: 43.21, }, handleHideModal: jest.fn() }; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render( <SuccessModal {...props} />, div ); }); test('has a valid snapshot', () => { const component = renderer.create( <SuccessModal {...props} /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import {Container} from './Balance.styles'; import {getCurrencySymbol} from '../../helpers/currency.helper'; const Balance = ({currency, balance}) => ( <Container> Balance: {getCurrencySymbol(currency)}{balance[currency].toFixed(2)} </Container> ); Balance.propTypes = { currency: PropTypes.string.isRequired, balance: PropTypes.object.isRequired }; export default Balance; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import renderer from 'react-test-renderer'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import ConvertFrom from './ConvertFrom'; describe('ConvertFrom', () => { const props = { fromCurrency: 'GBP', balance: { GBP: 15.00, EUR: 10, USD: 30, lastExchange: {} }, rates: {}, fromValue: 12, toCurrency: 'EUR', handleFromCurrencyChange: jest.fn(), handleFromValueChange: jest.fn(), ratesError: null, ratesLoading: false }; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render( <MuiThemeProvider> <ConvertFrom {...props} /> </MuiThemeProvider> , div); }); test('has a valid snapshot', () => { const component = renderer.create( <MuiThemeProvider> <ConvertFrom {...props} /> </MuiThemeProvider> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); <file_sep>import axios from 'axios'; import config from '../config'; export const getRatesFromApi = (base, symbols) => axios .get(`${config.apiUrl}?base=${base}&symbols=${symbols}`) .then(res => res.data); <file_sep>import initialState from './initial.state'; import * as types from '../actions/types'; export default function modalReducer(state = initialState.modal, action) { switch (action.type) { case types.SHOW_SUCCESS_MODAL: return Object.assign({}, state, {success: action.show}); default: return state; } } <file_sep>export default { rates: {}, active: { fromCurrency: 'GBP', fromValue: '', toCurrency: 'EUR', toValue: '' }, balance: { GBP: 15.00, EUR: 0, USD: 0, lastExchange: {} }, loading: { rates: false }, errors: { rates: null }, modal: { success: false } }; <file_sep>import styled from 'styled-components'; import {media} from '../../styles/mediaQuery'; import {INITIAL_HEIGHT, INITIAL_WIDTH} from '../../styles/constants'; export const Container = styled.div` width: ${INITIAL_WIDTH}; height: ${INITIAL_HEIGHT}; position: relative; box-shadow: 0 10px 10px 0 rgba(0,0,0,0.15); ${media.smallHorizontal` width: auto; `}; ${media.smallVertical` height: 100vh; `}; ${media.small` box-shadow: none; `}; `; export const FormWrapper = styled.div` display: flex; justify-content: space-between; `; <file_sep>import styled from 'styled-components'; import {TO_BG_COLOR} from '../../styles/constants'; import {media} from '../../styles/mediaQuery'; export const Container = styled.div` height: 50%; box-sizing: border-box; padding: 20px; background-color: ${TO_BG_COLOR}; position: relative; display: flex; flex-direction: column; justify-content: center; border-radius: 0 0 10px 10px; ${media.small` border-radius: 0; `}; `; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import renderer from 'react-test-renderer'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import {Main} from './Main'; describe('Main', () => { const props = { rates: {}, active: { fromValue: 1, fromCurrency: 'EUR', toValue: 2, toCurrency: 'GBP' }, balance: { GBP: 15.00, EUR: 0, USD: 0 }, modal: {}, setFromCurrencyFunc: jest.fn(), setFromValueFunc: jest.fn(), setToCurrencyFunc: jest.fn(), setToValueFunc: jest.fn(), exchangeFunc: jest.fn(), showSuccessModalFunc: jest.fn(), errors: { rates: null }, loading: { rates: false } }; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render( <MuiThemeProvider> <Main {...props} /> </MuiThemeProvider>, div ); }); test('has a valid snapshot', () => { const component = renderer.create( <MuiThemeProvider> <Main {...props} /> </MuiThemeProvider> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); <file_sep>import initialState from './initial.state'; import * as types from '../actions/types'; const exchange = (state, action) => { const {active, rates} = action; const echangedValue = active.fromValue * rates.rates[active.toCurrency]; return Object.assign({}, state, { [active.fromCurrency]: state[active.fromCurrency] - active.fromValue, [active.toCurrency]: state[active.toCurrency] + echangedValue, lastExchange: { fromValue: active.fromValue, toValue: echangedValue, fromCurrency: active.fromCurrency, toCurrency: active.toCurrency } }); }; export default function balanceReducer(state = initialState.balance, action) { switch (action.type) { case types.EXCHANGE: return exchange(state, action); default: return state; } } <file_sep>import initialState from './initial.state'; import * as types from '../actions/types'; export default function ratesReducer(state = initialState.rates, action) { switch (action.type) { case types.GET_RATES: return Object.assign({}, state, action.rates); default: return state; } } <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import renderer from 'react-test-renderer'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import CurrencySelect from './CurrencySelect'; describe('CurrencySelect', () => { const props = { name: 'fromValue', value: '0.15', onChange: jest.fn(), isDisabled: false, balance: { GBP: 15.00, EUR: 0, USD: 0, lastExchange: {} } }; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render( <MuiThemeProvider> <CurrencySelect {...props} /> </MuiThemeProvider>, div ); }); test('has a valid snapshot', () => { const component = renderer.create( <MuiThemeProvider> <CurrencySelect {...props} /> </MuiThemeProvider> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import FontAwesome from 'react-fontawesome'; import {getCurrencySymbol} from '../../helpers/currency.helper'; import {Container, LoadingDot} from './Rates.styles'; const Rates = ({rates, fromCurrency, toCurrency, isLoading}) => ( <Container> { rates.date && rates.rates[toCurrency] ? ( <div> <FontAwesome name='line-chart' style={{marginRight: '5px'}} /> <span> { getCurrencySymbol(fromCurrency)}1 = {getCurrencySymbol(toCurrency)}{rates.rates[toCurrency].toFixed(4) } </span> <LoadingDot isLoading={isLoading}> <FontAwesome name='circle' /> </LoadingDot> </div> ) : ( <div> <FontAwesome name='circle-o-notch' spin /> </div> ) } </Container> ); Rates.propTypes = { rates: PropTypes.object, fromCurrency: PropTypes.string, toCurrency: PropTypes.string, isLoading: PropTypes.bool }; export default Rates; <file_sep># Revolut - Web Development Home Task ## Implementation * React webapp implemented with React 16, Redux for state management and Styled Components for styling. ### Notes * Every 10 minutes the app checks FX rates on https://api.fixer.io/, an open-source API for current and historical foreign exchange rates. * If there are no FX rates data available all the input text fields are disabled. * Tha initial balance is 15GBP, 0EUR and 0USD. * If there are not enough founds to convert or if the initial value is 0, the exchange button is disabled. * If there is an error downloading the FX rates, an alert icon will apper in the top right corner. * If the error is fixed at the following api call, the alert icon disappers. * Every time the app downloads data, a blue dot appers for a second in the central oval panel. ## Available Scripts To install dependencies: ### `yarn` To run the project: ### `yarn start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. To run the tests: ### `yarn tests` ## Demo [http://umbrella.to/revolut](http://umbrella.to/revolut) <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import renderer from 'react-test-renderer'; import Button from './Button'; describe('Button', () => { const props = { isDisabled: false, onClick: jest.fn(), children: 'hello world' }; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render( <Button {...props} />, div ); }); test('has a valid snapshot', () => { const component = renderer.create( <Button {...props} /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); <file_sep>import styled from 'styled-components'; import {BALANCE_COLOR} from '../../styles/constants'; export const Container = styled.div` font-size: 14px; color: ${BALANCE_COLOR}; `; <file_sep>import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {setFromCurrency, setFromValue, setToCurrency, setToValue, exchange, showSuccessModal} from '../../actions'; import {convertInputValueToTwoDigitsNumber} from '../../helpers/string.helper'; import SuccessModal from '../SuccessModal/SuccessModal'; import FromComponent from '../ConvertFrom/ConvertFrom'; import ConvertTo from '../ConvertTo/ConvertTo'; import {Container} from './Main.styles'; export class Main extends Component { handleFromValueChange = event => this.props.setFromValueFunc( convertInputValueToTwoDigitsNumber(event.target.value) ); handleToValueChange = event => this.props.setToValueFunc( convertInputValueToTwoDigitsNumber(event.target.value) ); handleFromCurrencyChange = (event, index, value) => this.props.setFromCurrencyFunc(value); handleToCurrencyChange = (event, index, value) => this.props.setToCurrencyFunc(value); handleExchange = () => this.props.exchangeFunc(); handleHideModal = () => this.props.showSuccessModalFunc(false); render() { const {rates, active, balance, modal, errors, loading} = this.props; const {fromValue, fromCurrency, toValue, toCurrency} = active; const isExchangeButtonDisabled = balance[fromCurrency] < fromValue || balance[fromCurrency] === 0 || fromValue === 0 || fromValue === ''; const renderSuccessModal = modal.success && ( <SuccessModal handleHideModal={this.handleHideModal} lastExchange={balance.lastExchange} /> ); return ( <Container> {renderSuccessModal} <FromComponent balance={balance} fromCurrency={fromCurrency} fromValue={fromValue} toCurrency={toCurrency} rates={rates} handleFromCurrencyChange={this.handleFromCurrencyChange} handleFromValueChange={this.handleFromValueChange} ratesError={errors.rates} ratesLoading={loading.rates} /> <ConvertTo toCurrency={toCurrency} balance={balance} toValue={toValue} handleToCurrencyChange={this.handleToCurrencyChange} handleToValueChange={this.handleToValueChange} isExchangeButtonDisabled={isExchangeButtonDisabled} rates={rates} handleExchange={this.handleExchange} /> </Container> ); } } Main.propTypes = { rates: PropTypes.object.isRequired, active: PropTypes.object.isRequired, balance: PropTypes.object.isRequired, modal: PropTypes.object.isRequired, setFromCurrencyFunc: PropTypes.func.isRequired, setFromValueFunc: PropTypes.func.isRequired, setToCurrencyFunc: PropTypes.func.isRequired, setToValueFunc: PropTypes.func.isRequired, exchangeFunc: PropTypes.func.isRequired, showSuccessModalFunc: PropTypes.func.isRequired }; const mapStateToProps = state => ({ rates: state.rates, active: state.active, balance: state.balance, modal: state.modal, errors: state.errors, loading: state.loading, }); const mapDispatchToProps = dispatch => { return { setFromCurrencyFunc: bindActionCreators(setFromCurrency, dispatch), setFromValueFunc: bindActionCreators(setFromValue, dispatch), setToCurrencyFunc: bindActionCreators(setToCurrency, dispatch), setToValueFunc: bindActionCreators(setToValue, dispatch), exchangeFunc: bindActionCreators(exchange, dispatch), showSuccessModalFunc: bindActionCreators(showSuccessModal, dispatch), }; }; export default connect( mapStateToProps, mapDispatchToProps )(Main); <file_sep>import * as ActionTypes from './types'; export const setRatesError = error => ({ type: ActionTypes.SET_RATES_ERROR, error }); <file_sep>import * as ActionTypes from './types'; export const showSuccessModal = show => ({ type: ActionTypes.SHOW_SUCCESS_MODAL, show }); <file_sep>import React from 'react'; import FontAwesome from 'react-fontawesome'; import PropTypes from 'prop-types'; export const Error = error => ( <FontAwesome style={{ color: 'red', position: 'absolute', top: '20px', right: '20px', display: error.error ? 'block': 'none', cursor: 'pointer' }} name='exclamation-triangle' size='2x' title={error.error} /> ); Error.propTypes = { error: PropTypes.string }; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import CurrencySelect from '../CurrencySelect/CurrencySelect'; import ValueInput from '../ValueInput/ValueInput'; import Balance from '../Balance/Balance'; import Rates from '../Rates/Rates'; import {Error} from '../Error/Error'; import {Container} from './ConvertFrom.styles'; import {FormWrapper} from '../Main/Main.styles'; const ConvertFrom = ({ fromCurrency, balance, rates, fromValue, toCurrency, handleFromCurrencyChange, handleFromValueChange, ratesError, ratesLoading }) => ( <Container> <Error error={ratesError} /> <FormWrapper> <CurrencySelect name="fromCurrency" value={fromCurrency} balance={balance} isDisabled={!rates.date} onChange={handleFromCurrencyChange} /> <ValueInput name="fromValue" value={fromValue} onChange={handleFromValueChange} disabled={!rates.date} isFromValue={true} /> </FormWrapper> <Balance balance={balance} currency={fromCurrency} /> <Rates toCurrency={toCurrency} fromCurrency={fromCurrency} rates={rates} isLoading={ratesLoading} /> </Container> ); ConvertFrom.propTypes = { fromCurrency: PropTypes.string.isRequired, balance: PropTypes.object.isRequired, rates: PropTypes.object, fromValue: PropTypes.any.isRequired, toCurrency: PropTypes.string.isRequired, handleFromCurrencyChange: PropTypes.func.isRequired, handleFromValueChange: PropTypes.func.isRequired }; export default ConvertFrom;
a2be281cf872ee108f84e3edd0ec39b0f32e54da
[ "JavaScript", "Markdown" ]
35
JavaScript
ciabs/revolut-frontend-test
c2454e4f00ad23e59832798c412833c142ed8a74
3682f0b226f9ec0ae6518fd204af5a2a5c6b56a2
refs/heads/master
<file_sep>package spark.Service; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import spark.Pojo.PoiData; import spark.Util.FileUtils; import java.io.*; import java.util.UUID; import java.util.function.Consumer; public class PageCrawl { private int startPage,pageCount; private String url,distinctCode,savePath; private Consumer<String> updateWebSite; private Consumer<String> updateConsole; private Consumer<Integer> updateDetailProgress; private Consumer<Integer> updateTotalProgress; public PageCrawl(String url,String ditinctCode,String savePath,int startPage,int pageCount){ this.url = url; this.pageCount = pageCount; this.startPage = startPage; this.distinctCode = ditinctCode; this.savePath = savePath+ditinctCode+".csv"; } public void setWebSiteUpdator(Consumer<String> updateWebSite){ this.updateWebSite = updateWebSite; } public void setConsoleUpdator(Consumer<String> updateConsole){ this.updateConsole = updateConsole; } public void setDetailProgressUpdator(Consumer<Integer> updateDetailProgress){ this.updateDetailProgress = updateDetailProgress; } public void setTotalProgressUpdator(Consumer<Integer> updateTotalProgress){ this.updateTotalProgress = updateTotalProgress; } public void startTask(){ String requestUrl,displayMessage; for(int i = startPage;i<startPage+pageCount;i++){ requestUrl = url+"/"+distinctCode+"/"+i+".html"; displayMessage = getOnePageData(requestUrl); updateWebSite.accept(requestUrl); updateConsole.accept(displayMessage); updateTotalProgress.accept(((i-startPage+1)*100)/pageCount); } } private String getOnePageData(String requestUrl) { try(FileOutputStream fileOutputStream = new FileOutputStream(FileUtils.CreateIfNotExist(savePath),true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8"); BufferedWriter bufferCsv = new BufferedWriter(outputStreamWriter)) { bufferCsv.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF })); Document docPage = Jsoup.connect(requestUrl).timeout(5000) .userAgent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)").get(); if(docPage!=null) { Elements tablePage = docPage.select("table"); Elements trPage = tablePage.select("tr"); Elements tdPage;String line=""; PoiData poiData = new PoiData(); for(int i=0;i<trPage.size();i++){ tdPage = trPage.get(i).select("td"); if(tdPage.size()==4) { poiData.setId(UUID.randomUUID().toString()); poiData.setName(tdPage.get(0).select("a").text()); poiData.setUrl(tdPage.get(0).select("a").attr("href")); poiData.setAddress(tdPage.get(1).text()); poiData.setPhone(tdPage.get(2).text()); poiData.setCatogray(tdPage.get(3).text()); line = poiData.getId()+","+poiData.getName()+","+poiData.getUrl()+","+poiData.getAddress()+","+poiData.getPhone()+","+poiData.getCatogray(); bufferCsv.write(line); bufferCsv.newLine(); bufferCsv.flush(); } if(updateDetailProgress!=null) { updateDetailProgress.accept(((i+1)*100)/ trPage.size()); } if(updateConsole!=null){ updateConsole.accept(line); } } } } catch (FileNotFoundException e) { e.printStackTrace(); return "FileNotFoundException"; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return "UnsupportedEncodingException"; } catch (IOException e) { e.printStackTrace(); return "IOException"; } return ""; } } <file_sep>package spark.UI; import spark.UI.Button.MyIconButton; import spark.UI.Panel.CrawlCityPanel; import spark.UI.Panel.TaskInfoPanel; import spark.UI.Panel.ToolBarPanel; import spark.Util.PropertyUtil; import javax.swing.*; import java.awt.*; public class MainAppUI { private static JFrame frame; private static JPanel mainPanel; public static JPanel mainPanelCenter; public static CrawlCityPanel cityPanel; public static TaskInfoPanel taskPanel; public static void main(String[] args) { // 设置系统默认样式 try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } frame = new JFrame(); frame.setBounds(ConstantsUI.MAIN_WINDOW_X, ConstantsUI.MAIN_WINDOW_Y, ConstantsUI.MAIN_WINDOW_WIDTH, ConstantsUI.MAIN_WINDOW_HEIGHT); frame.setTitle(ConstantsUI.APP_NAME); frame.setIconImage(ConstantsUI.IMAGE_ICON); frame.setBackground(ConstantsUI.MAIN_BACK_COLOR); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainPanel = new JPanel(true); mainPanel.setBackground(Color.white); mainPanel.setLayout(new BorderLayout()); ToolBarPanel panelToolBar = new ToolBarPanel(); mainPanel.add(panelToolBar,BorderLayout.WEST); cityPanel = new CrawlCityPanel(); taskPanel = new TaskInfoPanel(); mainPanelCenter = new JPanel(true); mainPanelCenter.setLayout(new BorderLayout()); mainPanelCenter.add(cityPanel,BorderLayout.CENTER); mainPanel.add(mainPanelCenter,BorderLayout.CENTER); frame.add(mainPanel); frame.setVisible(true); } } <file_sep># LocationCrawl 爬取poi兴趣点的Jave Swing程序 使用Java Swing开发的爬取POI的桌面程序,爬取某poi信息网上的高德poi数据,以csv文件的形式保存在指定目录下。 UI参考了github上的开源项目。目前还是雏形,有时间会继续完善。 ![效果图](/screenShoot1mini.png) ![效果图](/screenShoot2mini.png) <file_sep>sp.ui.status.title = 爬取城市列表 sp.ui.database.title = 爬取POI sp.ui.setting.title = 设置 <file_sep>package spark.Pojo; public class PoiData { private String id; private String url; private String name; private String address; private String phone; private String catogray; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCatogray() { return catogray; } public void setCatogray(String catogray) { this.catogray = catogray; } }
10d8de893a5edf32d213fade2a151220a57df129
[ "Markdown", "Java", "INI" ]
5
Java
WongSpark/LocationCrawl
511d0b484023feaceb867b7d0de98c3dcb20a2e0
b0018bff6e256f314a76adbfe43e3e9afab6e648
refs/heads/master
<file_sep>using System.Threading.Tasks; using Brreg.Http.Models; namespace Brreg.Http.Abstractions { public interface IBrregHttpClient { Task<OrganizationModel> FetchOrganizationAsync(string orgNumber); } }<file_sep>using System; namespace Brreg.Http.Models { public class OrganizationModel { public string Organisasjonsnummer { get; set; } public string Navn { get; set; } public DateTime RegistreringsdatoEnhetsregisteret { get; set; } public DateTime Stiftelsesdato { get; set; } public bool RegistrertIMvaregisteret { get; set; } } }<file_sep>using System; using System.Threading.Tasks; using Brreg.Controllers; using Brreg.Http.Abstractions; using Brreg.Http.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Moq; using Moq.AutoMock; using Xunit; namespace Brreg.UnitTests.Controllers { public class OrganizationControllerTests { private AutoMocker _mocker = new AutoMocker(); [Fact] public async Task When_Input_is_valid_Should_call_IBrregHttpClient_once() { var sut = _mocker.CreateInstance<OrganizationController>(); await sut.Index("919300388"); _mocker.Verify<IBrregHttpClient, Task<OrganizationModel>>(p => p.FetchOrganizationAsync("919300388"), Times.Once); } [Fact] public async Task When_Input_is_valid_Should_return_OkResultObject() { _mocker.Setup<IBrregHttpClient, Task<OrganizationModel>>(p => p.FetchOrganizationAsync("919300388")) .ReturnsAsync(new OrganizationModel { Navn = "NOVO SOLUTIONS AS", Organisasjonsnummer = "919300388" }); var sut = _mocker.CreateInstance<OrganizationController>(); var result = await sut.Index("919300388"); Assert.IsType<OkObjectResult>(result); } [Fact] public async Task When_org_not_found_Should_return_404() { var sut = _mocker.CreateInstance<OrganizationController>(); var result = await sut.Index("919300388"); Assert.IsType<NotFoundResult>(result); } [Fact] public async Task When_Input_is_valid_Should_return_name_and_orgnumber() { var sut = _mocker.CreateInstance<OrganizationController>(); _mocker.Setup<IBrregHttpClient, Task<OrganizationModel>>(p => p.FetchOrganizationAsync("919300388")) .ReturnsAsync(new OrganizationModel { Navn = "NOVO SOLUTIONS AS", Organisasjonsnummer = "919300388" }); var result = (OkObjectResult)await sut.Index("919300388"); var type = result.Value.GetType(); var nameProp = type.GetProperty("Name"); var orgNumberProp = type.GetProperty("OrganizationNumber"); Assert.NotNull(nameProp); Assert.NotNull(orgNumberProp); var name = nameProp.GetValue(result.Value); var org = orgNumberProp.GetValue(result.Value); Assert.Equal("NOVO SOLUTIONS AS", name.ToString()); Assert.Equal("919300388", org.ToString()); Assert.IsType<OkObjectResult>(result); } [Theory] [InlineData("abc")] [InlineData("9193003888")] [InlineData("91930038")] [InlineData("abc123456")] [InlineData("abcdefghi")] public async Task When_input_is_invalid_Should_return_BadRequest(string orgNumber) { var sut = _mocker.CreateInstance<OrganizationController>(); var result = await sut.Index(orgNumber); Assert.IsType<BadRequestResult>(result); } } }<file_sep>namespace Brreg.Http { public static class ApplicationConstants { public const string BRREG_ORG_URL = "https://data.brreg.no/enhetsregisteret/api/enheter/"; } }<file_sep>using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace Brreg.Controllers { public class OrganizationController : Controller { // 1. Fetch org from brreg using IBrregHttpClient // 2. Implement IMemoryCache and clear cache after 30 seconds, so we dont refetch data we already have // 3. Validate and return badrequest if orgnumber is less then 9 digits // 4. Api output should contain organizationNumber and name //https://data.brreg.no/enhetsregisteret/api/enheter/919300388 // GET public Task<IActionResult> Index(string org) { return Task.FromResult<IActionResult>(Ok()); } } }
ac1e34364f0e68914ee4a5cc8fa46b2cda1fb9dc
[ "C#" ]
5
C#
lasrol/gp.test
f0eea394e225de53c04887a159032a94d5e2ddba
1cb7ae08cf71c24088fda8770f2db165f6b67103
refs/heads/main
<repo_name>ergonlima/AvancadoPHP<file_sep>/README.md # AvancadoPHP Curso de PHP avançado (Strings, Listas, Functions e Web) <file_sep>/Listas.php <?php $idade = [0, 15, 17, 58]; echo $idade[3]; <file_sep>/Banco.php <?php require_once 'Funcoes.php'; $contasCorrentes = [ '123.456.789-15' => [ 'titular' => 'Ergon', 'saldo' => 1000 ], '156.165.452-21' => [ 'titular' => 'Aliane', 'saldo' => 500000 ], '165.983.521-15' => [ 'titular' => 'Vinicius', 'saldo' => 1500 ] ]; $contasCorrentes['156.165.452-21'] = sacar( 500, $contasCorrentes['156.165.452-21']); $contasCorrentes['156.165.452-21'] = depositar(6000, $contasCorrentes['156.165.452-21']); titularComLetrasMaiusculas($contasCorrentes['156.165.452-21']); unset($contasCorrentes['156.165.452-21']); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>Contas correntes</h1> <dl> <?php foreach ($contasCorrentes as $cpf => $conta){?> <dt> <h3> <?= $conta['titular'];?> <?= $cpf;?> </h3> </dt> <dd> Saldo: <?= $conta['saldo'];?> </dd> <?php }?> </dl> </body> </html> <file_sep>/ContasCorrentes.php <?php $conta1 = [ 'titular' => 'Ergon', 'saldo' => 1000 ]; $conta2 = [ 'titular' => 'Aliane', 'saldo' => 500000 ]; $conta3 = [ 'titular' => 'Vinicius', 'saldo' => 1500 ]; $contasCorrentes = [$conta1, $conta2, $conta3]; for ($contador = 0; $contador <= count($contasCorrentes); $contador++) { echo $contasCorrentes[$contador]['titular'].PHP_EOL; } <file_sep>/LoopLista.php <?php $idadeLista = [18, 25, 65, 56, 35, 16, 17]; for ($contador = 0; $contador<=count($idadeLista); $contador++) { echo $idadeLista[$contador].PHP_EOL; }<file_sep>/Foreach.php <?php $contasCorrentes = [ '123.456.789-15' => [ 'titular' => 'Ergon', 'saldo' => 1000 ], '156.165.452-21' => [ 'titular' => 'Aliane', 'saldo' => 500000 ], '165.983.521-15' => [ 'titular' => 'Vinicius', 'saldo' => 1500 ] ]; $contasCorrentes['265.265.148-19'] = [ 'titular' => 'Carlos', 'saldo' => 1500 ]; foreach ($contasCorrentes as $cpf => $conta) { echo $cpf." ". $conta['titular']. PHP_EOL; } <file_sep>/Funcoes.php <?php function exibeMensagem(String $mensagem) { echo $mensagem . '<br>'; } function sacar(float $valorASacar, array $conta): array { if($valorASacar>$conta){ exibeMensagem("Você não pode Sacar!!"); } else{ $conta['saldo'] -= $valorASacar; } return $conta; } function depositar(float $valorADepositar, array $conta): array { if($valorADepositar>0) { $conta['saldo'] += $valorADepositar; } else{ exibeMensagem("Deposito deve ser maior que zero!!"); } return $conta; } function titularComLetrasMaiusculas(array &$conta) { $conta['titular'] = strtoupper($conta['titular']); } function exibeConta(array $conta) { echo "<li>Titulaar: {$conta['titular']}. Saldo: {$conta['saldo']}} </li>"; }
702b4069b37c58d7949c0145f28bb1043da0554e
[ "Markdown", "PHP" ]
7
Markdown
ergonlima/AvancadoPHP
c5781b56e6d012d50812ef1390675687d6711651
ac148d4f6054f6cab876a604ffd9b3e2371eb7db
refs/heads/master
<file_sep>var itemQueue = [ { name: 'banana', price: 0.29 }, { name: 'smoothie', price: 4.00 }, { name: 'car', price: 10000 }, { name: 'apple', price: 0.59 }, { name: 'soda', price: 2.50 }, { name: 'boat', price: 50000 }, { name: 'yacht', price: 2000000 }, { name: 'jet', price: 16000000 }, { name: '<NAME>', price: 100000000 }, { name: 'cat', price: 800 }, { name: 'dog', price: 1 }, { name: 'bird', price: 25 }, { name: 'toad', price: 2000 }, { name: '<NAME>', price: 1.73 }, { name: 'greg', price: 10000000000000 }, ]; function calculateTotal (array) { var count = 1; var priceArray = []; var items = array; var currentProduct = items.shift(); while (currentProduct !== undefined) { if (count%15 === 0) { priceArray.push(currentProduct.price * 0.7); } else if (count%5 === 0) { priceArray.push(currentProduct.price * 0.8); } else if (count%3 === 0) { priceArray.push(currentProduct.price * 0.9); } else { priceArray.push(currentProduct.price); } currentProduct = items.shift(); count += 1; } console.log(priceArray); var sum = priceArray.reduce(function(a, b) { return a + b; }, 0); return sum; } var total = calculateTotal(itemQueue); console.log(total);
6fa545e4e70a784385a053036b2a88224c9bf5e8
[ "JavaScript" ]
1
JavaScript
gregbrunk/stacks-and-queues
4f976dc7ce2752afdfa1252087c678680b1f1a67
7cac99ee294f24623f4b6048529d62775970b725
refs/heads/main
<repo_name>luluvann/lighthouselabs-python-challenge<file_sep>/day13.py # Day 13 import pandas as pd wine_df = pd.read_csv('day13.csv') #Q1 - Which wines had a quality of 8 or higher and a residual sugar level above 5? filter_wine = wine_df['residual sugar'] > 5.00 filtered_df = wine_df[filter_wine] new_df = filtered_df.sort_values(by=['quality','residual sugar'], ascending = False) print(new_df) print("Wine 0 and 1") #Q2 - How many wines in total had a quality of 5 and 4 and a citric acid level below 0.4? filter_wine_2 = wine_df['citric acid'] < 0.4 filtered_df_2 = wine_df[filter_wine_2] new_df_2 = filtered_df_2['quality'].value_counts() print(new_df_2) print("9 wines have a quality of 5(7) and 4(2) and a citric acid level below 0.4")<file_sep>/day12.py # Day 12 - in which year or years did both conventional and organic avocados have had average prices above $2? import pandas as pd df = pd.read_csv('day12.csv', index_col = 0) user_filter = df['AveragePrice'] >= 2 filtered_df = df[user_filter] count_prices = filtered_df.groupby(['year','type']).count() print(count_prices) print("In 2016, both conventional and organic avocados have had average prices above 2$")<file_sep>/day5.py # Day 5 - Abstain from buying products that are 10% more expansive at the local convenient store than at the city's convenient store # Cleaning Supplies List (19 items) cleaningsupplies_list = ['Broom', 'Mop', 'Dustpan', 'Garbage Bags', 'Glass Cleaner', 'Vinegar', 'Soap', 'Bleach', 'Duster', 'Floor Cleaner', 'Sponges', 'Dish Soap', 'Drain Cleaner', 'Paper Towels', 'Cleaning Rags', 'Toilet Cleaner', 'Rubber Gloves', 'Alcohol Wipes', 'Squeegee'] # City Price city_price = [6.49, 4.99, 3.39, 4.29, 3.99, 1.99, 1.50, 3.99, 4.99, 5.99, 2.99, 2.99, 5.99, 2.99, 3.49, 6.99, 2.99, 1.98, 11.99] # Country Price country_price = [5.49, 4.69, 4.42, 5.99, 5.99, 2.50, 1.25, 2.49, 4.50, 6.75, 2.49, 1.99, 6.25, 3.99, 3.59, 4.99, 1.69, 1.87, 10.99] # Solution abstain_buying_list = [] for i in range(len(cleaningsupplies_list)): percent_higher = (country_price[i] - city_price[i]) / city_price[i] * 100 if percent_higher > 10: abstain_buying_list.append(cleaningsupplies_list[i]) print(abstain_buying_list) <file_sep>/day7.py # Day 7 - Bubble sorting user_boxes = {'weight': [4,2,18,21,14,13], 'box_name': ['box1','box2', 'box3', 'box4', 'box5', 'box6'] } def sort_box(user_boxes): weight = user_boxes["weight"] box = user_boxes["box_name"] box_sorted = [] for i in range(len(weight)): for j in range(len(weight)-1): if weight[j] > weight[j+1]: value = weight[j] value1 = box[j] weight[j] = weight[j+1] box[j] = box[j+1] weight[j+1] = value box[j+1] = value1 print(weight,box) sort_box(user_boxes)<file_sep>/day4.py # Day 4 - Buy bulk at wholesale price or buy at retail price ? item_list = ['Oak Wood', 'Blue Paint', 'White Paint', 'Paint Finish'] quantity_list = [600,150,15,165] wholesale_bulk_list = [7000, 1000, 1000, 800] retail_price_list = [12.99, 8.99, 9.99, 3.99] # Solution choice = [] for i in range(len(item_list)): if amount_list[i]*retail_price[i] > wholesale_price_list[i]: choice.append(f'{item_list[i]}: Yes') else : choice.append(f'{item_list[i]}: No') print(f'Buy Wholesale ? {choice}') # Output: Buy Wholesale ? ['Oak Wood: Yes', 'Blue Paint: Yes', 'White Paint: No', 'Paint Finish: No'] <file_sep>/day15.py # Day 15 - Data Vizualization import numpy as np import matplotlib.pyplot as plt seeds = { 'Vegetable' : ['Carrots', 'Tomatoes', 'Potatoes', 'Eggplant', 'Cucumbers'], 'Seeds_Count' : [300,10,90,100,15], 'Each_Seed_Produces': [1,140,10,5, 90] } items = seeds["Vegetable"] a = np.array(seeds["Seeds_Count"]) b = np.array(seeds["Each_Seed_Produces"]) production = a*b plt.figure() plt.bar(x = items, height = production) plt.show()<file_sep>/day6.py # Day 6 - use Panda to calculate stats import random import pandas as pd random.seed(34) hole_sizes = [random.randint(1, i) for i in range(1, 101)] random.shuffle(hole_sizes) # hole sizes in mm series = pd.Series(hole_sizes) #Small (less than 20 mm) $1.30 #Medium (above or equal to 20 mm AND less than 70mm) $1.60 #Large (above or equal to 70 mm) $2.10 # Solution # what is the hole sizes mean ? print(series.mean()) # What is the unit cost mean cost = [] for i in range(len(hole_sizes)): if hole_sizes[i] < 20: cost.append(1.3) elif hole_sizes[i] < 70: cost.append(1.6) else: cost.append(2.1) series_cost = pd.Series(cost) print(series_cost.mean()) # What is the total cost total_cost = 0 for i in range(len(hole_sizes)): if hole_sizes[i] < 20: total_cost += 1.3 elif hole_sizes[i] < 70: total_cost += 1.6 else: total_cost += 2.1 print(total_cost) <file_sep>/day1.py # Day1 - Modify a lease agreement with your signature without changing the original lease variable. lease = '''Dear Dot, This document validates that you are beholden to a monthly payment of rent for this house. Rent is to be paid by the first of every month. Fill in your signature to agree to these terms. ------------- Please Sign Here: ''' signature = 'MySignature' # Solution new_lease_signed = f'{lease} {signature} print(new_lease_signed) <file_sep>/day11.py # Day 11 - Find the average cost in Albany in 2017 import pandas as pd df = pd.read_csv('day11.csv', index_col = 0) filtered_df = df.loc[df.Region=='Albany'] avg_cost_per_year = filtered_df.groupby(["Year"]).mean() print(avg_cost_per_year)<file_sep>/README.md # About I am taking the Lighthouse Labs 21-day Python data challenge (from February 17th, 2021 to March 10th, 2021) [https://data-challenge.lighthouselabs.ca/] There is a .py file for each day<file_sep>/day9.py # Day 9 - Fillna and statistics import pandas as pd df = pd.read_csv('data9.csv') print(df.head(3)) #How many entries NaN in each column print(df.info()) #Fill the NaN entries with the median for each column median_milk = df['Monthly milk production: pounds per cow'].median() df['Monthly milk production: pounds per cow'] = df['Monthly milk production: pounds per cow'].fillna(value = median_milk) #What is the average for monthly milk production? mean_milk = df['Monthly milk production: pounds per cow'].mean() print(f'Mean milk prod: {mean_milk}') #What is the standard deviation for monthly milk production? std_milk = df['Monthly milk production: pounds per cow'].std() print(f'Standard deviation milk prod: {std_milk}') #What is the average number of cows used? median_num_cow = df['Number of Cows'].median() df['Number of Cows'] = df['Number of Cows'].fillna(value = median_num_cow) mean_num_cow = df['Number of Cows'].mean() print(f'Mean number of Cows: {mean_num_cow}')<file_sep>/day16.py # Day 16 - Boxplot import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("day16.csv") df.head(2) plt.figure() plt.boxplot(df['num_pages'], vert = False) plt.show()
2e3394f6f9b27fd2af78820529e95682ae32ba23
[ "Markdown", "Python" ]
12
Python
luluvann/lighthouselabs-python-challenge
fdca30a2dc2eb5dd009a080b569b61b629316e5f
75dda016974cb7f0c2057827136b0b87311d78a9
refs/heads/master
<repo_name>realkotob/rooms2d-bot<file_sep>/src/commands/rooms.rs use serenity::framework::standard::{macros::command, CommandResult}; use serenity::model::prelude::*; use serenity::prelude::*; #[command] async fn rooms(ctx: &Context, msg: &Message) -> CommandResult { room_command(ctx, msg).await } #[command] async fn room(ctx: &Context, msg: &Message) -> CommandResult { room_command(ctx, msg).await } #[command] async fn private(ctx: &Context, msg: &Message) -> CommandResult { private_command(ctx, msg).await } async fn private_command(ctx: &Context, msg: &Message) -> CommandResult { let embed_field_msg = format!(" {}", { if msg.guild_id.unwrap_or_default().as_u64() == &(799783945499443231 as u64) { "" } else { "\n\nJoin the [Rooms2D discord](https://discord.gg/Egnyj8hbm5) to discover secret features!" } }); let dm_result = msg .author .dm(&ctx.http, |m| { m.content(""); // m.tts(true); m.embed(|mut e| { e.title("Rooms2D"); e.url("https://rooms2d.com"); // e.description("Available commands"); e.field( "Available commands", format!( "**room** - create a Rooms2D for a channel.\n**private** - create link to a new private room.{}", embed_field_msg), false, ); e }); m }) .await; if let Err(why) = dm_result { println!("Error sending help message: {:?}", why); } else { let _ = msg.react(&ctx, '✅').await; }; Ok(()) } pub async fn room_command(ctx: &Context, msg: &Message) -> CommandResult { let user_name = &msg.author.name; let user_name: String = user_name .chars() .filter_map(|x| match x { 'A'..='Z' => Some(x), 'a'..='z' => Some(x), '0'..='9' => Some(x), ' ' | '-' | ',' => Some('-'), '_' => Some('_'), _ => None, }) .collect(); let channel_op = msg.channel(&ctx).await; match channel_op { Some(channel) => { match channel.guild() { Some(channel_guild) => { // println!("It's a guild channel named {}!", channel_guild.name); let channel_name = &channel_guild.name; let channel_name: String = channel_name .chars() .filter_map(|x| match x { 'A'..='Z' => Some(x), 'a'..='z' => Some(x), '0'..='9' => Some(x), ' ' | '-' | ',' => Some('-'), '_' => Some('_'), _ => None, }) .collect(); let parent_guild_op = channel_guild.guild(&ctx).await; match parent_guild_op { Some(parent_guild) => { // println!("It's a guild channel named {}!", channel_guild.name); let guild_name = &parent_guild.name; let guild_name: String = guild_name .chars() .filter_map(|x| match x { 'A'..='Z' => Some(x), 'a'..='z' => Some(x), '0'..='9' => Some(x), ' ' | '-' | ',' => Some('-'), '_' => Some('_'), _ => None, }) .collect(); msg.channel_id .say( &ctx.http, format!( "https://www.rooms2d.com/r/{}-{}", guild_name, channel_name ), ) .await?; } None => { // println!("Parent guild name not found!"); msg.channel_id .say( &ctx.http, format!("https://www.rooms2d.com/r/{}", channel_name), ) .await?; } }; } None => { // println!("It's not a guild channel!"); msg.channel_id .say( &ctx.http, format!("https://www.rooms2d.com/r/{}", user_name), ) .await?; } }; } None => { // println!("Channel for message not found"); msg.channel_id .say( &ctx.http, format!("https://www.rooms2d.com/r/{}", user_name), ) .await?; } }; Ok(()) } <file_sep>/Cargo.toml [package] name = "rooms-bot" version = "0.1.0" authors = ["asheraryam <<EMAIL>>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # [profile.release] # opt-level = 'z' # Optimize for size. # lto = true # panic = 'abort' [dependencies] dotenv = "0.15" tracing = "0.1" tracing-subscriber = "0.2" tracing-futures = "0.2" # needed so intrument works with async functions. [dependencies.tokio] version = "1.0" features = ["macros", "signal", "rt-multi-thread"] [dependencies.serenity] version = "0.10.2" features = ["cache", "framework", "standard_framework", "rustls_backend", "unstable_discord_api"]<file_sep>/src/commands/mod.rs pub mod math; pub mod meta; pub mod owner; pub mod rooms; <file_sep>/src/main.rs mod commands; use serenity::{ async_trait, client::bridge::gateway::ShardManager, framework::{standard::macros::group, StandardFramework}, http::Http, model::{ channel::Message, event::ResumedEvent, gateway::{Activity, Ready}, interactions::Interaction, }, prelude::*, utils::MessageBuilder, }; use std::{collections::HashSet, env, sync::Arc}; use tracing::{error, info}; use tracing_subscriber::{EnvFilter, FmtSubscriber}; use commands::{math::*, meta::*, owner::*, rooms::*}; pub struct ShardManagerContainer; impl TypeMapKey for ShardManagerContainer { type Value = Arc<Mutex<ShardManager>>; } struct Handler; #[async_trait] impl EventHandler for Handler { async fn ready(&self, _ctx: Context, ready: Ready) { info!("Connected as {}", ready.user.name); _ctx.set_activity(Activity::listening(&String::from("!help"))) .await; // ctx.http.create_guild_application_command(); } async fn resume(&self, _: Context, _: ResumedEvent) { info!("Resumed"); } async fn message(&self, ctx: Context, msg: Message) { if (msg.content == "! Room" || msg.content == "! room" || msg.content == "! Rooms" || msg.content == "! rooms") { let _ = commands::rooms::room_command(&ctx, &msg).await; } else if (msg.content == "!help" || msg.content == "! help" || msg.content == "! Help" || msg.content == "!Help") { let embed_field_msg = format!(" {}", { if msg.guild_id.unwrap_or_default().as_u64() == &(799783945499443231 as u64) { "" } else { "\n\nJoin the [Rooms2D discord](https://discord.gg/Egnyj8hbm5) to discover secret features!" } }); // let mut user_in_rooms2d = { // if let Ok(guilds) = msg.author.guilds(&http).await { // for (index, guild) in guilds.into_iter().enumerate() { // if (guild.guild_id.unwrap_or_default().as_u64() // == &(799783945499443231 as u64)) // { // true; // }; // } // false // }; // }; let dm_result = msg .author .dm(&ctx.http, |m| { m.content(""); // m.tts(true); m.embed(|mut e| { e.title("Rooms2D"); e.url("https://rooms2d.com"); // e.description("Available commands"); e.field( "Available commands", format!( "**room** - create a Rooms2D for a channel.\n**private** - create link to a new private room.{}", embed_field_msg), false, ); e }); m }) .await; if let Err(why) = dm_result { println!("Error sending help message: {:?}", why); } else { let _ = msg.react(&ctx, '✅').await; }; }; } // async fn interaction_create(&self, _ctx: Context, _interaction: Interaction) {} } #[group] #[commands(multiply, ping, quit, room, rooms, private)] struct General; #[tokio::main] async fn main() { // This will load the environment variables located at `./.env`, relative to // the CWD. dotenv::dotenv().expect("Failed to load .env file"); // Initialize the logger to use environment variables. // // In this case, a good default is setting the environment variable // `RUST_LOG` to debug`. let subscriber = FmtSubscriber::builder() .with_env_filter(EnvFilter::from_default_env()) .finish(); tracing::subscriber::set_global_default(subscriber).expect("Failed to start the logger"); let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment"); let http = Http::new_with_token(&token); // We will fetch your bot's owners and id let (owners, _bot_id) = match http.get_current_application_info().await { Ok(info) => { let mut owners = HashSet::new(); owners.insert(info.owner.id); (owners, info.id) } Err(why) => panic!("Could not access application info: {:?}", why), }; // Create the framework let framework = StandardFramework::new() .configure(|c| c.owners(owners).prefix("!")) .group(&GENERAL_GROUP); let mut client = Client::builder(&token) .framework(framework) .event_handler(Handler) .await .expect("Err creating client"); { let mut data = client.data.write().await; data.insert::<ShardManagerContainer>(client.shard_manager.clone()); } let shard_manager = client.shard_manager.clone(); tokio::spawn(async move { tokio::signal::ctrl_c() .await .expect("Could not register ctrl+c handler"); shard_manager.lock().await.shutdown_all().await; }); if let Err(why) = client.start().await { error!("Client error: {:?}", why); } } <file_sep>/Makefile.toml [env] RUST_LOG = "info" [tasks.build] command = "cargo" args = ["build"] [tasks.build_release] extend = "build" args = ["build", "--release"] [tasks.run] command = "cargo" args = ["run"] [tasks.run_release] extend = "run" args = ["run", "--release"] dependencies = ["build"]<file_sep>/README.md # Rooms2D Discord Bot Discord bot for the [Rooms2D app](https://github.com/asheraryam/rooms2d). Invite the bot to your discord [with this link](https://discord.com/api/oauth2/authorize?client_id=797931723907268698&permissions=8&redirect_uri=https%3A%2F%2Fdiscord.com%2Fapi%2Foauth2%2Fauthorize%3Fclient_id%3D797931723907268698%26permissions%3D68672%26scope%3Dbot&scope=bot). [Join the Discord](https://discord.gg/Egnyj8hbm5) to learn secret features and follow development! ## Development Example .env file: ``` # This declares an environment variable named "DISCORD_TOKEN" with the given # value. When calling `kankyo::load()`, it will read the `.env` file and parse # these key-value pairs and insert them into the environment. # Environment variables are separated by newlines and must not have space # around the equals sign (`=`). DISCORD_TOKEN=<KEY> # Declares the level of logging to use. Read the documentation for the `log` # and `env_logger` crates for more information. RUST_LOG=debug ```
d8664dcf03e3113da5c1062c69d0021708019e3c
[ "TOML", "Rust", "Markdown" ]
6
Rust
realkotob/rooms2d-bot
a8822aab73bb2fad1bdb46d501f92aeeadbad2e2
a63d59aacc173b920c5fd10a84105b0e86be9e8c
refs/heads/master
<file_sep>using System; namespace Chapter8ReadingAndWriting { class Program { static void Main(string[] args) { Console.Write("The quick brown"); Console.WriteLine("fox jumps"); Console.Write("over the"); Console.WriteLine("lazy dog"); Console.WriteLine(""); string input = Console.ReadLine(); } } }
e4728e90e5a2427a629c2562608ca5f0492c288b
[ "C#" ]
1
C#
laceywalkerr/ReadingAndWriting
c562e12fef157071578eae954aa08f79f08054af
826b4128d659e1f6871ecfaaf484eee2bc0782e1
refs/heads/main
<file_sep>import React, { Component } from 'react' import { Button, Form, Container, Header } from 'semantic-ui-react' import axios from 'axios' import './App.css' require('dotenv').config() export default class App extends Component { constructor(props) { super(props) this.state = { name: '', age: '', salary: '', hobby: '', restartButton: false } this.changeHandler = this.changeHandler.bind(this) this.handleError = this.handleError.bind(this) } changeHandler = (e) => { this.setState({ [e.target.name]: e.target.value }) } handleRefresh = (e) => { e.preventDefault() window.location.reload() } handleError = () => { const header = document.getElementById('header') const form = document.getElementById('form') this.setState({ restartButton: true }) header.innerHTML = 'Mhmm, something went wrong' form.innerHTML = 'Looks like something did work as expected, but no worries. Refresh and try again!' console.log('Something didn\'t work as expected... Upsi 😅') } submitHandler = e => { e.preventDefault() axios.post('process.env.REACT_APP_SPREADSHEET_URL', this.state) .then(res => { const header = document.getElementById('header') const form = document.getElementById('form') if (res.status === 200) { header.innerHTML = 'Great! Thanks for submitting!' form.classList.add('hidden') } else { this.handleError() } }) .catch(e => { this.handleError() }) } render() { const { name, age, salary, hobby } = this.state return ( <Container fluid className="container"> <Header as='h2' id="header">React Google Sheets!</Header> <Form className="form" id="form" onSubmit={this.submitHandler}> <Form.Field> <label>Name</label> <input placeholder='Enter your name' type="text" name="name" value={name} onChange={this.changeHandler} /> </Form.Field> <Form.Field> <label>Age</label> <input placeholder='Enter your age' type="number" name="age" value={age} onChange={this.changeHandler} /> </Form.Field> <Form.Field> <label>Salary</label> <input placeholder='Enter your salary' type="number" name="salary" value={salary} onChange={this.changeHandler} /> </Form.Field> <Form.Field> <label>Hobby</label> <input placeholder='Enter your hobby' type="text" name="hobby" value={hobby} onChange={this.changeHandler} /> </Form.Field> <Button color="blue" type='submit'>Submit</Button> </Form> {this.state.restartButton && <Button color="red" onClick={this.handleRefresh} id='refreshButton'> Refresh the page </Button> } </Container> ) } } <file_sep># Turning G-Spreadsheets into a REST API <img src="excel-is-not.jfif" width="300" alt="Excel is not a database" /> Hey! Check out this, is quiet nice way to connect to your spreadsheets via API. For the whole explanation, check this [tutorial from freeCodeCamp](https://www.freecodecamp.org/news/react-and-googlesheets/) I followed from [@nishant-666](https://github.com/nishant-666). It's pretty well explained and super fast to do. ## tl;dr For this you need an access to a Drive to create the file, obviously, and to register for free in [sheet.best](https://sheet.best/), sheet.best turns spreadsheets into REST APIs for you to connect it to anything. Simple and fast, start now and see the possibilities. Also here's the [documentation](https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env) for handling .env with `create-react-app` ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `yarn build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. with love 🖤, in berlin 🍻, with freecodecamp 👨‍💻 and vscode.
d293142a9ef137b97d604ac3c9beab1fbab2c272
[ "JavaScript", "Markdown" ]
2
JavaScript
learodrigo/react-googlesheets
dfe2d71611b05844d0e395cfb93da7fc7c8005c1
aab62556e7c72cb9ff05a3f18964fd5c45c5556f
refs/heads/master
<repo_name>vandys/chore<file_sep>/__init__.py import config, handlers, loadxml, www, server, www, authen, net, utils import pong <file_sep>/net.py # # net.py # Utility/support functions of a networking-ish nature # import socket, ipaddr, fcntl, struct # Say it's a DNS-ish name if it has letters def isDNS(s): return any(c.isalpha() for c in s) # Say if this IP address @host matches any address of the # DNS name @s def match_DNS(host, s): try: tups = list(socket.getaddrinfo(s, None)) except: tups = () for tup in tups: # (family, socktype, proto, canonname, (sockaddr,sock-family)) # 0 1 2 3 4 if host == tup[4][0]: return True return False # Tell if this IP matches any on the list def ok_ip(masks, addr): a = ipaddr.IPv4Address(addr) # Check each valid source for m in masks: # DNS name; lets us check against dynamic DNS addresses if isinstance(m, str): return match_DNS(addr, m) # Otherwise simple network mask match if m.Contains(a): return True return False # Turn a string into something which names an acceptable # address (netmask for DNS name) def parseaddr(m): if isDNS(m): return m return ipaddr.IPv4Network(m) # Get listen IP address given interface def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: res = socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) return res except: raise Exception, "Invalid interface name: %s" % (ifname,) <file_sep>/utils.py # # utils.py # Various utilities # import threading, string, time # A "with" serialization mechanism class Exclusion(object): def __init__(self): self.mutex = threading.Lock() def __enter__(self): self.mutex.acquire() def __exit__(self, typ, val, traceback): self.mutex.release() # Filter out to just simple ASCII chars def toascii(s): return str(filter(lambda c: c in string.printable, s)) # uncharenc # Decode encoded chars from a MIME message # # I don't know who thought up all these goddam encodings, but this is # just my ad hoc way of removing/converting the ones I run into. # # We follow this table of mappings. # Matches of > length 1 are sequences; if "strict" is set true we # will flag sequences which end in something we don't recognize _mappings = ( ((0xc,), '\n\n'), ((0xa2,), 'c'), ((0xa6,), '--'), ((0xa9,), '(c)'), ((0xb0,), 'o'), ((0xc9,), 'E'), ((0xe8,), 'e'), ((0xe9,), 'e'), ((0xeb,), 'e'), ((0xf1,), 'n'), ((0xc3, 0x81), 'A'), ((0xc3, 0x82), ' '), ((0xc3, 0x83), 'a'), ((0xc3, 0x86), 'ae'), ((0xc3, 0xa1), 'a'), ((0xc3, 0xa2), 'a'), ((0xc3, 0xad), 'i'), ((0xc3, 0xa8), 'i'), ((0xc3, 0xb1), 'n'), ((0xc3, 0xb6), 'o'), ((0xc3, 0xba), 'u'), ((0xc3, 0xa7), 'c'), ((0xc3, 0xa9), 'e'), ((0xc3, 0xad), 'i'), ((0xc2, 0xa0), ' '), ((0xc2, 0xaf), ' '), ((0xc2, 0xb1), '+-'), ((0xc2, 0xb9), '1'), ((0xc2, 0xbf), '?'), ((0xcc, 0x82, 0x20), 'cio'), ((0xa1, 0xa6), "'"), ((0xa1, 0xa7), "'"), ((0xa1, 0xa8), "'"), ((0xef, 0xac, 0x81), 'fi'), ((0xef, 0xac, 0x82), 'fl'), ((0xef, 0xbb, 0xbf), ''), ((0xe2, 0x80, 0x93), '--'), ((0xe2, 0x80, 0x94), '--'), ((0xe2, 0x80, 0x9c), '"'), ((0xe2, 0x80, 0x9d), '"'), ((0xe2, 0x80, 0x98), "'"), ((0xe2, 0x80, 0x99), "'"), ((0xe2, 0x80, 0xa6), '...'), ((0xe2, 0x94, 0x8c), '+'), ((0xe2, 0x94, 0x90), '+'), ((0xe2, 0x94, 0x98), '+'), ((0xe2, 0x94, 0x94), '+'), ((0xe2, 0x94, 0xac), '+'), ((0xe2, 0x94, 0xb4), '+'), ((0xe2, 0x94, 0x9c), '+'), ((0xe2, 0x94, 0xa4), '+'), ((0xe2, 0x94, 0x80), '-'), ((0xe2, 0x94, 0x82), '|'), ) # Index this table with starting char and # expected length of sequence _prefixes = {} for tup in _mappings: # Don't care about mapping result tup = tup[0] # First byte; verify all match and # then index c = tup[0] if c in _prefixes: assert len(tup) == _prefixes[c] else: _prefixes[c] = len(tup) # Minimize namespace del tup, c # Convert string, return updated one def _procs(s, strict): global _mappings, _prefixes res = "" sidx = 0 resid = len(s) while resid > 0: c = s[sidx] sidx += 1 resid -= 1 cv = ord(c) # No mapping, just emit and continue pl = _prefixes.get(cv) if (pl is None) or (pl > resid): res += c continue # We've already "eaten" the first byte of the prefix pl -= 1 # Assemble sequence from input ours = [cv] for _rest in xrange(pl): c = s[sidx+_rest] cv = ord(c) ours.append(cv) ours = tuple(ours) sidx += pl resid -= pl # Match from table? for tup in _mappings: if tup[0] == ours: res += tup[1] break else: # Unmatched sequence; emit original if strict: res += '**' for cv in ours: res += unichr(cv) return res # Convert a string, return a new one with all the encoded stuff # flattened. def uncharenc(s): # Convert string, non-strict # (struct=True would be for debugging/dev, I suppose) res = _procs(s, False) # Any unknown code points just drop to something inoffensive return toascii(res) # Provide time-ish stamps, but always guaranteed unique in this # process. LastStamp = int(time.time()) LastSuffix = 0 def tstamp(): global LastStamp, LastSuffix # Integer time t = int(time.time()) # Make the stamp unique if needed if t == LastStamp: LastSuffix += 1 else: # New base timestamp LastStamp = t LastSuffix = 0 return "%d.%d" % (t, LastSuffix) if LastSuffix \ else str(t) <file_sep>/pong.py # # pong.py # UDP notifications infrastructure # vim: expandtab # # Ugh, Ubuntu Phone seems to have pretty much gone to Python 3, so # here we are. This file is written to load under Python 2 or 3. # # The protocol uses a JSON-encoded string carried over UDP. # The message structure is documented below, but at a high # level the protocol advances in three stages. First, # the client sends a request to the notification server. # Among other items, it indicates the last event serial # seen. # The server immediately responds to the client's port and # address. If its response indicates new events, then # the exchange is over. The client will presumably post # notifications and eventually start a new protocol exchange. # If the server returns an indication that the client has # already seen the latest event, it will specify a # timeout. If a new event occurs before that timeout, the # server will send the event. Otherwise, at the timeout # interval, the server will send a message specifying # (still) no new messages. # In both cases of the previous paragraph, the exchange is # considered finished. A new exchange from the beginning # must be undertaken to receive subsequent notifications. # # Normal NAT practice (specifically, the conntrack module of the Linux # Netfilter implementation) specifies a NAT state timeout for # UDP exchanges. Until the NAT sees both a packet sent and # a response packet received, it runs a relatively short (default, # 30 seconds) timeout. Once it has seen the response, the connection # is considered "assured", and a longer NAT state timeout # is observed (default, 180 seconds). # To fit within this model, PONG provides "ting" suffix subop's, # which are decoded but not otherwise seen by the users of the PONG # transport. So a notification/get will see a notification/getting # if the Notification server does not yet have a new event for you. # This otherwise useless packet has the effect of moving the UDP # NAT state to "assured", with its longer NAT state timeout. # This suffix is reserved and applies to all operations, thus # config/set -> config/setting, mode/put -> mode/putting # and so forth. # # The relative transience of an exchange, and the lack of # any ongoing network connection is intentional. The client # might change its own address, or it might be behind a NAT # device which changes its address. The most that can be # disrupted by such a change is a single span of exchanges # within the bounds of one timeout period. # Thus, each exchange starts with the client creating a # fresh socket so that no long-term network state is carried. # # The initial version of this protocol implements authentication # of its operations, but not privacy (i.e., crypto). Because # all the messages are JSON, it's easy to imagine further fields # which would configure crypto. This is TBD. # The initial version's authentication uses SHA-256 along with # a nonce to protect packets from spoofing, modification, or # replay. # # Each packet thus has a nonce (generated by the system's crypto- # quality random number generator) and a SHA-256 derived # signature reflecting the shared secret. # import socket, sys, json, time, os from hashlib import sha256 from Crypto.Cipher import AES import pdb # Straddle Python[23] worlds. # Thanks, Guido: http://vsta.org/andy/python3.html PY3 = (sys.version_info.major == 3) # How long to wait for initial/immediate response # (This is the starting timeout, which backs off with each # retry.) WAITRESP = 1 # How long to hold off network activity after seeing a # network failure WAITNET = 60 # Max sized message # (You can turn this up, but you really need to start thinking # about REST and TCP.) MAXMSG = 1024 # Display bytes in hex and back def tohex(buf): if PY3: return ''.join(("%02x" % (c,)) for c in buf) return ''.join(("%02x" % (ord(c),)) for c in buf) def fromhex(buf): res = bytearray() while buf: res.append(int(buf[:2], 16)) buf = buf[2:] return bytes(res) # Hook for logging def log(s): sys.stderr.write(s) sys.stderr.write('\n') # XOR a byte range into one half its size def fold(buf): assert (len(buf) & 1) == 0 l = int(len(buf)/2) if PY3: return bytes((c1 ^ c2) for c1,c2 in zip(buf[:l], buf[l:])) return "".join(chr(ord(c1) ^ ord(c2)) for c1,c2 in zip(buf[:l], buf[l:])) # SHA256 rep of password string def pwhash(pw): sh = sha256() if PY3: pw = pw.encode("utf8") sh.update(pw) return sh.digest() # Views of the packet being sent class Packet(object): def __init__(self, inner, outer, buf): self.inner = inner self.outer = outer if PY3: self.buf = buf.encode("utf8") else: self.buf = buf # When appropriate, this is the (host,port) tuple # of a recvfrom() self.who = None class PONG(object): def __init__(self): # Defend against replays self.used_nonces = set() # Both client and server maintain a socket, though with # very different usage patterns self.sock = None # SHA256 adapted signature def calchash(self, buf, passwd, nonce): sh = sha256() if PY3: buf = buf.encode("utf8") passwd = passwd.encode("utf8") sh.update(buf) sh.update(nonce) sh.update(passwd) return fold(fold(sh.digest())) # Encode and sign this message # # We're using 64 bits of nonce, and 64 bits of folded SHA256 # @d may have its contents modified. def wrap_msg(self, uname, d_inner, outer): # String rep of actual operation inner = json.dumps(d_inner) # 64 bits of nonce nonce = os.urandom(8) # And collapse 256 bits of sha256 to 64 bits too # (We hash the content, nonce, and shared secret.) passwd = self.get_password(uname) if passwd is None: # Unknown account return None sig = self.calchash(inner, passwd, nonce) # Outer signature of inner if outer is None: outer = {} outer["sig"] = tohex(sig) outer["nonce"] = tohex(nonce) # Encrypt? if "crypto" in outer: assert outer["crypto"] == "AES" # Ask our instance for the hashed version of the # PSK with this uname hashedpw = self.get_hashed_password(uname) # Pad to block boundary with spaces (JSON's OK with # white space) li = len(inner) bs = AES.block_size resid = li % bs if resid: inner += (" " * (bs - resid)) # Encrypt the inner. It's going into JSON, so # represent it in hex. a = AES.new(hashedpw, AES.MODE_CFB, nonce) inner = tohex(a.encrypt(inner)) # Signed and possibly encrypted inner content outer["inner"] = inner # As a JSON string buf = json.dumps(outer) assert len(buf) < MAXMSG return Packet(d_inner, outer, buf) # Decode JSON of message, return Packet or None def unwrap_msg(self, buf, pakseq, uname=None): try: # Decode outer = json.loads(buf) inner = outer["inner"] nonce = fromhex(outer["nonce"]) # Protect nonce value if nonce in self.used_nonces: log(" dup nonce") return None # Crypto? if uname is None: uname = str(outer["user"]) passwd = self.get_password(uname) if passwd is None: log("No password for " + uname) return None if "crypto" in outer: if outer["crypto"] != "AES": log(" unknown crypto " + outer["crypto"]) return None hashedpw = self.get_hashed_password(uname) a = AES.new(hashedpw, AES.MODE_CFB, nonce) inner = a.decrypt(fromhex(inner)) # Verify sig sig = self.calchash(inner, passwd, nonce) if sig != fromhex(outer["sig"]): log(" bad sig") return None # Convert inner inner = json.loads(inner) if (pakseq is not None) and (inner["pakseq"] != pakseq): # Answers to this op? log(" mismatch pakseq") return None except: log(" malformed") return None # Don't use this nonce again self.used_nonces.add(nonce) # Here's something signed by our peer log(" good pak") return Packet(inner, outer, buf) class Server(PONG): def __init__(self, port): PONG.__init__(self) self.sock = sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', port)) # Build response message to request in @inpak # Like PONG.Client.ping(), this routine also modifies the # dict @resp if it's provided. def pong(self, inpak, subop, resp=None): if resp is None: resp = {} resp["op"] = inpak.inner["op"] resp["subop"] = subop resp["pakseq"] = inpak.inner["pakseq"] # Sign/encrypt this response return self.wrap_msg(inpak.outer["user"], resp, None) # Wait for the next (legit) message def next_msg(self): while True: buf,who = self.sock.recvfrom(MAXMSG) log("Msg rx %s %s: %s" % (who, time.asctime(), buf)) pak = self.unwrap_msg(buf, None) if pak is not None: pak.who = who return pak # Subclass hooks to look up user account def get_password(self, uname): assert False, "Not Implemented" return None def get_hashed_password(self, uname): assert False, "Not Implemented" return None # Craft reply to this request def reply(self, inpak, outpak): try: self.sock.sendto(outpak.buf, inpak.who) except: log(" reply failed") # Build request, server version. # Return JSON encoding of it. # Unlike a client, we don't specify a username when answering # back. We also mirror their pakseq, rather than using a # counter of our own. def msg(self, uname, pakseq, op, subop, req=None): # Start with any params they specified if req is None: req = {} # Plug in some standard fields req["op"] = op req["subop"] = subop req["pakseq"] = pakseq # Sign and maybe encrypt # As a client, we put our username in the outer JSON return self.wrap_msg(uname, req, None) class Client(PONG): def __init__(self, server, port, uname, password): PONG.__init__(self) self.server = server self.port = port self.uname = uname self.password = <PASSWORD> self.pakseq = 0 # Used as crypto key (calculated on first use) self.hashedpw = None # Password access def get_password(self, uname): assert uname == self.uname return self.password def get_hashed_password(self, uname): assert uname == self.uname if self.hashedpw is None: self.hashedpw = pwhash(self.password) return self.hashedpw # Build request, signed, all that stuff # Return JSON encoding of it. # Note this routine scribbles on the dict @req if it is # passed in. def msg(self, op, subop, req=None): # Start with any params they specified if req is None: req = {} # Plug in some standard fields req["op"] = op req["subop"] = subop req["pakseq"] = self.pakseq self.pakseq += 1 # Sign and maybe encrypt # As a client, we put our username in the outer JSON return self.wrap_msg(self.uname, req, {"user": self.uname}) # Get running connection, opening if needed def get_sock(self): sock = self.sock if sock is not None: return sock self.sock = sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return sock # We've seen an error or something, so close out this socket # so we'll get a new one next time. def close_sock(self): sock = self.sock if sock is None: return sock.close() self.sock = None # Receive a message, with timeout # The message is verified for correct sig def recv_msg(self, pakseq, timeout): sock = self.get_sock() targtm = time.time() + timeout while True: # No more time tmo = targtm - time.time() if tmo <= 0: log(" out of time") self.close_sock() return None # Receive, with timeout sock.settimeout(tmo) try: buf,who = sock.recvfrom(MAXMSG) except: # Timeout log(" timeout") self.close_sock() return None if PY3: buf = buf.decode("utf8") log("pak %s from %s\n" % (buf, who)) # Valid? pak = self.unwrap_msg(buf, pakseq, uname=self.uname) if pak is not None: # A result pak.who = who return pak # Ping-Pong message exchange. We said something to them, # and we expect to hear something back. # JSON in each direction. def pingpong(self, pak): # Adaptive timeout sock = self.get_sock() tmo = WAITRESP pakseq = pak.inner["pakseq"] while True: log("sending %r" % (pak.buf,)) try: sock.sendto(pak.buf, (self.server, self.port)) except: log(" send failed") self.close_sock() # With a network outage, hang back for a bit time.sleep(WAITNET) return None # Get back a response, or None for timeout resp = self.recv_msg(pakseq, tmo) if resp is not None: log(" answered") return resp # Didn't reach our server log(" timeout") tmo *= 2 if tmo > WAITNET: # Backed off to failure self.close_sock() return None # Ping...Pong message behavior. # This is long polling with UDP. We send a request, and we expect to # hear back from them when they have something, or a null closing # message at the timeout. def ping_pong(self, pak, timeout): # Request sock = self.get_sock() buf = pak.buf log("sending %r" % (buf,)) try: sock.sendto(buf, pak.who) except: log(" send failed") self.close_sock() # With a network outage, hang back for a bit time.sleep(WAITNET) return None # Get back a response, or None for timeout resp = self.recv_msg(pak.inner["pakseq"], timeout) # None (timeout) or a response return resp <file_sep>/server.py # # server.py # Code for firing up a server # import sys, threading, time import www class Server(object): def __init__(self, config, apphandler): # Sanity if "service" not in config: raise Exception, "Please configure your service name" # Our HTTP server(s) self.servers = [] self.apphandler = apphandler # Our timeout service thread self.timer = None # Callbacks when time expires # List of tuples; (expires-tm, call-fn, call-arg) self.timeouts = None # Global dict of config self.config = config # Per-user config (usually populated by account server) self.uconfig = {} # Time based service def run_timer(self): while True: time.sleep(TIME_GRANULARITY) tm = time.time() # Sweep pending user transactions, release # any which have timed out. for name,user in self.users.iteritems(): pend = user.pending for tup in tuple(pend): if tup[0] <= tm: # Expired; release semaphore and # thus wake them up pend.remove(tup) tup[1].release() # Invoke this if you use run_timer() and related timeout # services. def start_timers(self): # Here's where you add them self.timeouts = [] # Our timeout thread. t = self.timer = threading.Thread(target=self.run_timer) t.start() # Return the ports we use for http and https. # It's always a 2-tuple, with None for an unconfigured protocol def http_ports(self): res = [None, None] for (proto, cfg) in self.config["serve"]: if proto == "http": res[0] = int(cfg.get("port", 80)) elif proto == "https": res[1] = int(cfg.get("port", 443)) else: # Not HTTP; UDP/PONG, for instance pass return tuple(res) # Invoke this if you want web server interface(s) def start_http(self): # Run HTTP. All activity is rooted from HTTP transactions # coming in. for (proto, cfg) in self.config["serve"]: sys.stderr.write("start %r\n" % (proto,)) # Build a server if proto in ("http", "https"): web = www.HTTP(proto, cfg, self.apphandler, self) else: web = self.serve_proto(proto, cfg) # Give it a thread t = threading.Thread(target=web.run) # Keep track (mostly for debugging) self.servers.append( (t, web) ) # Spin up the thread t.start() # Wait for it to choose a port while web.port is None: time.sleep(0.1) sys.stderr.write("http server(s) started\n") # Sublcass can intercept, and runs proto service, # never returning. def serve_proto(self): return <file_sep>/loadxml.py # # loadxml.py # Support routines to pull in XML via SAX # from xml import sax # Logging; make UTF8 printable to my screen def justascii(s): return "".join(filter(lambda x: ord(x)<128, s)) # XML walker with hooks to drive Python representation class XMLHandler(sax.ContentHandler): # Clear out our ivars def do_init(self): self.nrec = self.depth = self.nskip = 0 self.ob = self.content = None self.path = [] def __init__(self): self.do_init() # Dispatchers # Each is (("path1", "path2", ...), field-type, dest-elem) # ("path1", "path2") would match <path1><path2>...</path2></path1> # field-type is "int", "int0", "str", "intlist", # "strlist", or "strlistl" # ("strlistl" is a string list with elements mapped to lower case) # self.ob[dest-elem] = <value> # Receives the result self.dispatchers = {} # Superclass setup sax.ContentHandler.__init__(self) # Caller is all done with us def close(self): self.do_init() # Hook to do any cleanup after reading in an XML element # Returns True to keep record, False to discard it def pre_insert(self): # Default: yes, keep it return True # Hook to note attrs for an element def elem_attrs(self, depth, name, attrs): pass # <foo>... is opening def startElement(self, name, attrs): depth = self.depth self.depth += 1 self.content = u"" # print " "*depth, "startElement", name, dict(attrs) # Root document; <outermost>...</outermost> EOF if depth == 0: return # Successive <item> ...data... </item> under the root document # "items" if depth == 1: # New object to be assembled self.ob = {} # Hook if there's element attrs if attrs: self.elem_attrs(depth, name, attrs) # <outermost><item> ignored for self.path[] purposes if depth == 1: return # Paths start within root and top element # So <artists><artist><name> is the path ("name",) self.path.append(name) # If you don't have this, why are you using this module? def insert_elem(self, d): raise Exception, "Missing insert_elem() handler" # End of an element def endElement(self, name): self.depth -= 1 depth = self.depth # print " "*self.depth, "endElement", name d = self.ob # End of file if depth == 0: print "End of elements, inserted:", self.nrec print " skipped:", self.nskip return # End of record if depth == 1: # Cleanup/finalization hook if self.pre_insert(): # Let our user run with this record self.insert_elem(d) # print "insert", d, "(skipped %d)" % (self.nskip,) # pdb.set_trace() # Log progress self.nrec += 1 else: self.nskip += 1 # Ready for next record self.ob = None return # Unwind path, noting current if we're going # to need it. content = self.content if content: path = tuple(self.path) pname = self.path.pop() assert pname == name if not content: # No content, just return return # Dispatch? # print "path", path tup = self.dispatchers.get(path) if tup is None: return typ,dest= tup # Integer? if typ == "int": assert dest not in d d[dest] = int(content) return # Integer w. default 0? if typ == "int0": assert dest not in d try: d[dest] = int(content) except: d[dest] = 0 return # String value if typ == "str": assert dest not in d d[dest] = content return # List of strings if typ.startswith("strlist"): # List of *lower case* strings if typ == "strlistl": # List of lower case strs content = content.lower() # Flatten spaces to single content = u" ".join(content.split(u" ")) # Store to newly started list, or append if dest not in d: d[dest] = [content] else: d[dest].append(content) return # List of int's if typ == "intlist": content = int(content) if dest not in d: d[dest] = [content] else: d[dest].append(content) return raise Exception, "Unknown dispatch type: %s" % (typ,) # <foo> ...content... </foo> # But we get it in chunks (even if buffer_text, sigh) so we # assemble here and commit at end of element def characters(self, content): # print " "*self.depth, "characters", justascii(content) if content: self.content += content <file_sep>/authen.py # # authen.py # Mixin providing various approaches to authentication # import sys, os, time, base64, string, threading, json import socket, grp # Extra chars from base64 ALTCHARS="_+" # Why Python lacks isxdigit(), dunno Xdigits = set(string.digits) Xdigits.update( ['a', 'b', 'c', 'd', 'e', 'f'] ) Xdigits.update( ['A', 'B', 'C', 'D', 'E', 'F'] ) Xdigits = frozenset(Xdigits) # Re-login every 30 days LoginInterval = 60*60*24*30 # Parse the cookie from our expected format def parse_cookie(s): global Xdigits # Require "<user>-<cookie>" tup = s.split('-') if (len(tup) != 2) or any(not t for t in tup): return None # User is letters and digits user,cookie = tup if any((not c.isalnum) for c in user): return None # Cookie is a hex value if any((c not in Xdigits) for c in cookie): return None return tup # Wrapper for all the state of dealing with an # account server # When a server derives its authentication from an account server, it # creates one of these to hold all the state of using that server. class AccountServer(object): def __init__(self, approot): self.approot = approot # Socket open to account server self.acct_server = None # Path name to our own Unix-domain socket (UDS) self.path = None # Unique index for an op self.serial = 0L # For pending operation, serial->mutex. For completed # operation, serial->response. self.ops = {} # Barrier to when we're registered with accounts server self.ready = False # [http,https] ports for accounts server self.ports = None # Our PID, mostly for debugging self.pid = os.getpid() # Name of our service, for authorization self.service = approot.config["service"] # Common code to launch a request to the server, # and optionally get back an answer def send_server(self, op, req, await): # Add on mandatory fields req["op"] = op req["reply-to"] = self.path req["service"] = self.service req["pid"] = self.pid ser = req["serial"] = self.serial self.serial += 1 if await: # Register for this op to have a completion release # We make sure it's in place before any completion # could possibly return. mutex = threading.Semaphore(0) self.ops[ser] = (mutex, req) # Send out the request self.acct_server.send(json.dumps(req)) # No waiting if not await: return None # Hold here for completion mutex.acquire() # Now we're back with a result. It's basically # a copy of our request with a "response" field # (and, somtimes, a few other added fields) tup = self.ops[ser] del self.ops[ser] return tup[1] # Do initial registration, then endlessly serve # operations back from the account server. def serve_account(self): # Decode HTTP/HTTPS config for port #'s used approot = self.approot cfg = approot.config # Establish our own UDS endpoint self.path = "/tmp/%s-%s" % \ (cfg["service"], cfg.get("domain", "chore")) try: # File from previous run os.unlink(self.path) except: pass s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: os.unlink(self.path) except: pass s.bind(self.path) os.chmod(self.path, 0660) os.chown(self.path, os.getuid(), grp.getgrnam(cfg.get("group", "chore")).gr_gid) # Register with the account server req = {"service": cfg["service"], "port": approot.http_ports()} sys.stderr.write("Start account server connection\n") self.send_server("start", req, False) # And stay here, servicing our own UDS port while True: sys.stderr.write(" account server loop\n") # Next operation buf = s.recv(65536) sys.stderr.write("serve_account got %s\n" % (buf,)) # Decode and sanity check try: req = json.loads(buf) except: sys.stderr.write("Invalid UDS: %s\n" % (buf,)) continue op = req.get("op") if op is None: sys.stderr.write("No operation: %s\n" % (buf,)) continue # Is it a response? if "result" in req: ser = req["serial"] # Our server ack's our registration if op == "start": self.ports = tuple(req["port"]) self.ready = True continue # Done with this op # If they're waiting, release them and # also swap for request version of JSON # to the result. if ser in self.ops: # (mutex, request-dict) tup = self.ops[ser] # Update with response-dict self.ops[ser] = (tup[0], req) # And release the waiting thread tup[0].release() # Hmmm. else: sys.stderr.write("Account response not result: %s\n" % (req,)) # Set up to use an account server # Connect to it, get its paramters, and spin up a thread # to serve our side. def setup_account_server(self): # Connection to account server if self.acct_server is None: approot = self.approot cfg = approot.config dom = cfg.get("domain", "chore") s = self.acct_server = \ socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) sname = "/tmp/acct-%s" % (dom,) sys.stderr.write("Connect to account server\n") s.connect(sname) # Our service thread # (It'll do the initial registration of our app # into the account server.) t = threading.Thread(target=self.serve_account) t.start() # Wait for confirmation with all of its dope if not self.ready: sys.stderr.write(" sync wait for account server\n") while not self.ready: # Busy-wait until we're connected to the accounts server time.sleep(0.1) sys.stderr.write(" Account server ready\n") # When they need to get logged in, go talk here # This API serves a couple of purposes. It launches our # connection the account server on first use. It also # gates us to make sure that connection is established # (with answering ack from account server which contains # needed information). Only then does it return the # [non-ssl, ssl] port pair so our caller can build a # suitable redirection URL. def redir_server(self): # Hook to sync up with account server self.setup_account_server() # Here's how to talk to the account server return self.ports # The user has presented a cookie. It isn't cached & valid, # so we need to ask our account server if it minted this # cookie. # Returns (user, cookie, expires-time), or None for failure def verify_cookie(self, cookie): # We're going to talk to'em, maybe for the first time self.setup_account_server() req = {"cookie": cookie} res = self.send_server("cookie?", req, True) if res["result"][0] == '?': # Login failure return None # Per-user config included? Cache it. user = res["user"] if "config" in res: self.approot.uconfig[user] = res["config"] return (user, cookie, res["expires"]) # Shared authentication state across all connections # This is part of the root of the app. Authentication-less # apps don't need it, otherwise it provides ivars and # methods for both local (file based) authentication, as # well as system-wide account server authentication. # # cookies{} - Map from username to (expires, "cookie value") # authentication[] - List of authentication methods to try class Authen_Server_mixin(object): def __init__(self): self.cookies = {} # Cookie name self.login_token = "loginToken" # No authentication by default. Init here # then adds it on. self.authentication = [] # Get cookie from cache, or filesystem # Return (cookie, expires-tm) or None if there is no current # cookie value. # As a side effect, it detects expired cookies, scrubbing # them as needed. def load_cookie(self, user): # In-memory cache tup = self.cookies.get(user) if tup is not None: sys.stderr.write(" server cached cookie %r\n" % (user,)) ftm = tup[1] else: # Filesystem try: f = open("var/cookies/" + user, "r") fcookie = f.readline().strip() ftm = float(f.readline().strip()) f.close() sys.stderr.write(" got filesystem cookie %r\n" % (user,)) tup = (fcookie, ftm) self.cookies[user] = tup except: sys.stderr.write(" no saved cookie %r\n" % (user,)) return None # Expired yet? if ftm <= time.time(): sys.stderr.write(" cookie expired %r\n" % (user,)) # Scrub from filesystem try: os.unlink("var/cookies/" + user) except: pass # And from cache if user in self.cookies: del self.cookies[user] return None # Here's our cookie with its expiration return tup # By default, each cookie for user U is stored in # the file var/cookies/U. Once looked up, it is stored in # the self.cookies dict as well. def valid_cookie(self, user, cookie): # Any saved cookie? tup = self.load_cookie(user) if tup is None: return False # Make sure they're talking about the current one if cookie != tup[0]: sys.stderr.write(" cookie does not match for %r\n" % (user,)) return False # Good cookie, yum sys.stderr.write(" cookie passes checks %r\n" % (user,)) return True # We're going to use an account server, set up connection def init_acct_server(self): assert not hasattr(self, "acct_server") srv = self.acct_server = AccountServer(self) srv.setup_account_server() # Authentication handling for WWW connections # This is the counterpart to Authen_Server_mixin above; that one # is common to all connections, this one is part of a particular # connection. It supplies the methods a connection would use # to handle authentication. class Authen_mixin(object): # Each mixin gets this hook def __init__(self): pass # Default, don't disable authentication def handle_noauth(self): # By default, let them see the site icon if (self.command == "GET") and (self.path == "/favicon.ico"): return True return False # Apply current authentication # # Various return formats: # "string" - 200 response with this string as body # int,str - Given response # with str as error message # True - Authen OK, let rest of WWW handling proceed def authenticate(self): srv = self.server approot = srv.approot # Web server level authentication? authlist = srv.authentication if authlist is None: authlist = approot.authentication # No authen, keep going if not authlist: return True # Authen bypassed, keep going if self.handle_noauth(): return True # Find first authen method which produces an # answer for auth in authlist: # The server has an unbound function, so invoke # it as bound to us. res = auth(self) # The result is supplied if res is not None: if res is True: # Hook to notice a user allowed on. self.auth_ok() return res # Generic authen failed return 401,None # Default hook: no-op # When somebody successfully authenticates, this gets called def auth_ok(self): pass # Decode Cookie: header option def get_cookie(self, target): # Header present? cookies = self.headers.get("cookie") if not cookies: return None # Parse into cookies; each is "key=value", with # semicolon separating them (if more than one) # TBD, use Python's Cookie module? cookies = [c.strip().split('=') for c in cookies.split(';')] for tup in cookies: if len(tup) != 2: continue # Here's a match if tup[0] == target: return tup[1] # Don't have that cookie return None # Save cookie; record for ongoing use now, and # try to save a cookie across server restarts # Default (simple) implementation: in the filesystem def save_cookie(self, user, cookie, tm): srv = self.server approot = srv.approot approot.cookies[user] = (cookie, tm) try: # Save to filesystem too f = open("var/cookies/" + user, "w") f.write(cookie + "\n" + str(tm) + "\n") f.close() except: # Oh, well. It's good for the session. pass # Supply default cookie expiration def cookie_expires(self): global LoginInterval return LoginInterval # Default, 16-byte cookies (128 bits) def cookie_bytes(self): return 16 # Place this cookie into our header def cookie_header(self, user, cookie, expires): srv = self.server approot = srv.approot # Header format of expiration time tm = time.strftime("%a, %d %b %Y %T GMT", time.gmtime(expires)) if srv.ssl: # Be more circumspect when using SSL; clear usually means # you're using your media server at home. SSL means # you're out in the Big Bad World. extras = '; Secure; HttpOnly' else: # Note Secure on non-SSL just makes the cookie unusable, # since you've given them a cookie they can never send # back. extras = '' # The user's stored cookie is encoding "<user>-<cookie>" to # tie account name together with cookie value. self.extra_headers.append( ("Set-Cookie", "%s=%s; Expires=%s; Path=/%s" % (approot.login_token, user + "-" + cookie, tm, extras)) ) # We need a new cookie # Fills in to approot.cookies{} def new_cookie(self, user): srv = self.server approot = srv.approot # If this is a new login (device, or local versus remote), # use any existing cookie first. tup = approot.load_cookie(user) if tup is not None: cookie,expires = tup else: # Generate hex representation of cookie value cookie = "" for x in xrange(self.cookie_bytes()): cookie += ("%02x" % (ord(os.urandom(1)),)) # Expires some day expires = time.time() + self.cookie_expires() # Save it into short- and long-term storage self.save_cookie(user, cookie, expires) # Put it into our header self.cookie_header(user, cookie, expires) return cookie # Try to authenticate with a cookie def auth_cookie(self): approot = self.server.approot # See if they can satisfy us with an authentication cookie sys.stderr.write("authen cookie\n") cookie = self.get_cookie(approot.login_token) if cookie is None: sys.stderr.write(" no cookie\n") return None # Defensively parse cookie from header tup = parse_cookie(cookie) if tup is None: sys.stderr.write(" malformed cookie %r\n" % (cookie,)) return None user,cookie = tup # Look up if approot.valid_cookie(user, cookie): sys.stderr.write(" cookie OK %s\n" % (user,)) self.user = str(user) return True sys.stderr.write(" cookie, but not known %s\n" % (user,)) return None # Use this to always let them through def auth_accept(self): return True # Generate a 401 error return along with the # needed Authenticate header def send401(self, msg=None): if msg is None: msg = "Authentication Required" approot = self.server.approot appname = approot.config.get("service", "Web Application Interface") self.extra_headers.append( ('WWW-Authenticate', 'Basic realm="%s"' % (appname,)) ) return (401,msg) # Use user/pass from accounts file def auth_password(self): sys.stderr.write("authen password\n") # We're going to need a user/pass auth = self.headers.getheader('Authorization') if auth is None: sys.stderr.write(" request authen\n") return self.send401("Authentication required") sys.stderr.write(" authen present\n") # Do we accept it? auth = base64.b64decode(auth[6:], altchars=ALTCHARS) tup = auth.split(":") user,pw = tup if (len(tup) != 2) or (not user) or (not pw): return self.send401(" Malformed authentication response") if not self.check_password(user, pw): return self.send401(" Incorrect username or password") # Generate new cookie, record self.user = str(user) sys.stderr.write(" password OK %r\n" % (user,)) cookie = self.new_cookie(user) # Welcome on return True # Look up the username in a file, see if it's the right password # Return True if they are OK, else 401 error # # This will often be overridden by the app, which will have # its own password storage technique. def check_password(self, user, pw): srv = self.server accts = srv.config["accounts"] f = open(accts, "r") for l in f: l = l.strip() if (not l) or l.startswith("#"): continue # <user> <pass> [ <app-specific>... ] tup = l.split() if len(tup) < 2: continue # For this user, do you know the password? if tup[0] == user: f.close() if tup[1] == pw: return True return self.send401("Incorrect username or password\r\n") f.close() return self.send401("Incorrect username or password\r\n") # Authentication type where we use a central account # server for the host. def auth_server(self): # First see if we're already good to go res = self.auth_cookie() if res is True: return True # See if they're presenting a cookie srv = self.server approot = srv.approot aserver = approot.acct_server cookie = self.get_cookie(approot.login_token) if cookie is not None: # Ask the account server if it's OK? tup = aserver.verify_cookie(cookie) if tup is not None: # Cookie verified, consider them logged in user,cookie,exptm = tup self.user = str(user) # Trim to non-user format of cookie assert cookie.startswith(user + '-') cookie = cookie[(len(user)+1):] # Cache it approot.cookies[user] = (cookie, exptm) return True # Go talk to the account server, log in, then we'll # see you back here. s_ports = aserver.redir_server() desturl = "http%s://%s:%d" % \ (("s" if srv.ssl else ""), self.headers.get("host").split(":")[0], s_ports[1 if srv.ssl else 0]) res = self.gen_redir(desturl) return res <file_sep>/config.py # # config.py # Handle loading of config file # import itertools # Configuration input instance class Config(object): # Set up our fields def __init__(self): self.mults = set() # ...those which can appear multiple times self.floats = set() # Elems whose value is a float self.ints = set() # ...int's self.noarg = set() # Things with no arguments self.onearg = set() # ...with a single arg self.args = set() # ...any number # Basic config # # Administrative name of the service we're supplying self.onearg.add( ("service",) ) # Group ID number for our primary group; defaults # to "chore" self.onearg.add( ("group",) ) # Accept input line, return line as lexed # into words def lex(self, l): words = [] curword = "" inquote = False while l: # Pull next char from input line c = l[0] l = l[1:] # Looking for beginning of next word if not curword: # Whitespace between words if c.isspace(): continue # Beginning of quoted string if c == '"': inquote = True else: curword += c # Quoted text elif inquote: if c == '"': inquote = False words.append(curword) curword = "" else: curword += c # End of current word elif c.isspace(): words.append(curword) curword = "" # Another char in current word else: curword += c # End of line without closing quote if inquote: self.err("Unterminated quote") # Last word on line if curword: words.append(curword) return(tuple(words)) # Tell if this op takes one argument def oneargs(self, op): return (op in self.onearg) or \ (op in self.floats) or (op in self.ints) # Report err WRT file/line# def err(self, msg): raise Exception, "Error in %s at line %d: %s\n" % \ (self.cfg_file, self.lnum, msg) # Tell how many spaces this is indented, interpreting # tabs as needed. def depth(self, s): col = 0 for c in s: # End of leading spaces if not c.isspace(): break # Tab, calculate modulo-8 jump if c == '\t': col += (8 - (col%8)) continue # Space col += 1 return col # Tell if this element path has sub-elements def subconfig(self, lkey): llen = len(lkey) for tup in itertools.chain(self.args, self.ints, self.floats, self.onearg): if len(tup) > llen: if tup[:llen] == lkey: return True return False # Load config file into dict def load_cfg_file(self, fn, f): # Stack of indentations # [ (spaces, "elem", val/vals, subconfig/None), ... ] indents = [ (-1, None, None, {}) ] self.cfg_file = fn self.lnum = 0 for l in f: self.lnum += 1 # Comment/blank ls = l.strip() if (not ls) or ls.startswith('#'): continue # Basic format is: # keyword [args...] ldepth = self.depth(l) words = self.lex(ls) op = words[0] words = words[1:] # Pop off until we're at our parent while ldepth <= indents[-1][0]: indents.pop() # Generate element key lkey = tuple(tup[1] for tup in indents[1:]) + (op,) # Verify this is a valid construct if not any( (lkey in f) for f in (self.onearg, self.args, self.ints, self.floats, self.noarg)): self.err("unknown config item") # Simple flag if lkey in self.noarg: if len(words): self.err("no argument is allowed") val = None # Parse item's value elif self.oneargs(lkey): if len(words) != 1: self.err("expect a single value") if lkey in self.ints: val = int(words[0]) elif lkey in self.floats: val = float(words[0]) else: val = words[0] else: val = tuple(words) # This element has sub-configuration if self.subconfig(lkey): # Our "value" includes our subconfig if we have # such. lsubs = {} val = (val, lsubs) else: lsubs = None # Register it under our parent parsubs = indents[-1][3] if parsubs is None: self.err("unexpected subconfig") if lkey in self.mults: if op in parsubs: parsubs[op].append(val) else: parsubs[op] = [val] else: if op in indents[-1][3]: self.err("Multiple of singleton config item") parsubs[op] = val # Hang config in stack; this lets us do all the regular # sanity checking, even if this config item won't ever # have sub-config indents.append( (ldepth, op, val, lsubs) ) # Here's our finished dict of config stuff return indents[0][3] # Load config, filename version def load_cfg(self, cfg_file): f = open(cfg_file, "r") res = self.load_cfg_file(cfg_file, f) f.close() return res <file_sep>/handlers.py # # handlers.py # Handling for actual web server bits # import socket, sys, json, os, time from BaseHTTPServer import BaseHTTPRequestHandler from sendfile import sendfile # When moving data ourselves, how much to move at a time Bufsize = 64*1024 # Tell if this pathname looks questionable def sketchy(fn): # No chance of up-relative if ".." not in fn: return False # See if any are actual up-refs tup = fn.split("/") if any( (s == "..") for s in tup ): return True # Ok return False # Return value for a digit (hex) def digval(c): if c.isdigit(): return ord(c) - ord('0') c = c.lower() if (c < 'a') or (c > 'f'): return None return (ord(c) - ord('a')) + 10 # Remove %XX hex char values from form input string # I just cannot effin believe this isn't somewhere already... def unescape(s): res = "" c1 = c2 = idx = None for c in s: if idx is None: if c != '%': res += c else: idx = 1 continue if idx == 1: c1 = digval(c) idx = 2 continue assert idx == 2 idx = None if c1 is None: res += "?" else: c2 = digval(c) if c2 is None: res += "?" else: res += chr((c1 << 4) + c2) c1 = c2 = None return res # An instance of this runs to dispatch a given HTTP request # # An actual app will inherit this and add app-specific dispatchers. # # self.server gets set to our web server's state class Chore_Handler(BaseHTTPRequestHandler): # Default config def __init__(self, conn, addr, webserver, inits): # /js/..., /imgs/..., and such just serve files self.lits = ("js", "imgs", "css", "html") # Code which, in turn, tries to dispatch ops # (Each is (op, fn), e.g., ("GET", self.do_get1)) self.dispatchers = [ ("GET", self.base_get), ] # Add on others (mixins) for i in inits: i(self) # Default title self.title = "web server" # These get dicts if there are options self.vals = self.rvals = None # Hook for custom headers self.extra_headers = [] # If authentication is active self.user = None # This both init's, and runs the web service # (BTW, this sucks. Break out instance creation and # service start--always.) BaseHTTPRequestHandler.__init__(self, conn, addr, webserver) # Hook to set up SSL def old_OpenSSL_setup(self): self.connection = self.request self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) self.wfile = socket._fileobject(self.request, "wb", self.wbufsize) # Find & dispatch handler def dispatch(self, op, *args): # Always decode <path>?<opts> self.options() # Find handler for tup in self.dispatchers: if tup[0] == op: dispatched,res = tup[1](*args) if dispatched: return res # Nobody could make heads or tails of it self.send_error(404) return None # HTTP GET operation def do_GET(self): sys.stderr.write("GET: %s\n" % (self.path,)) self.base_op = "GET" buf = self.dispatch("GET") sys.stderr.write("GET back\n") if buf: self.wfile.write(buf) # HTTP HEAD; header of a GET result, no body def do_HEAD(self): sys.stderr.write("HEAD: %s\n" % (self.path,)) self.base_op = "HEAD" buf = self.dispatch("GET") sys.stderr.write("HEAD back\n") # Default POST/PUT size cap def check_post_len(self, val): # Default, 1 meg if val > 1024*1024: return True return False # POST and PUT; very similar def postput(self, typ): sys.stderr.write("%s: %s\n" % (typ, self.path)) self.base_op = typ # Decode options in path self.options() # How much data? content_len = int(self.headers.getheader('content-length', 0)) # Try to hand off to a raw resource handler rawtyp = typ+"_raw" dispatched = False for tup in self.dispatchers: if tup[0] == rawtyp: dispatched,buf = tup[1](content_len) if dispatched: break # Hook; cap transfer size # We let raw handlers go first, since the whole point of raw # transfers is to avoid buffering to memory, accomodating # large sizes. if self.check_post_len(content_len): self.send_error(400, "Content Length too big") return # Then get a local buffer of the POST/PUT content and # call simple string-based handler buf = None if not dispatched: dbuf = self.rfile.read(content_len) for tup in self.dispatchers: if tup[0] == typ: dispatched,buf = tup[1](dbuf) if dispatched: break # No match if not dispatched: self.send_error(404) return # Push any result if buf: self.wfile.write(buf) sys.stderr.write("%s back\n" % (typ,)) def do_POST(self): self.postput("POST") def do_PUT(self): self.postput("PUT") # Standard header for web pages def build_header(self, title=None): if title is None: title = self.title buf = '<html><head><title>%s</title>' % (title,) buf += ' <meta name="viewport"' \ ' content="width=device-width, initial-scale=1">\n' buf += ' <link rel="stylesheet"' \ ' href="/css/normalize.css">\n' buf += ' <link rel="stylesheet"' \ ' href="/css/main.css">\n' buf += '</head><body>\n' return buf # Tack on end of HTML def build_tailer(self, buf): buf += "</body></html>\n" return buf # Map file extension to MIME type # Returns (isbin?, mime-type) or None def get_mtype(self, fn): if fn.endswith(".js"): return False, "application/javascript" if fn.endswith(".jpg"): return True,"image/jpeg" if fn.endswith(".png"): return True,"image/png" if fn.endswith(".svg"): return True,"image/svg+xml" if fn.endswith(".gif"): return True,"image/gif" if fn.endswith(".ico"): return True,"image/vnd.microsoft.icon" if fn.endswith(".wav"): return True,"audio/x-wav" if fn.endswith(".mp3"): return True,"audio/mpeg" if fn.endswith(".flac"): return True,"audio/flac" if fn.endswith(".ogg"): return True,"audio/ogg" if fn.endswith(".html"): return False,"text/html" if fn.endswith(".htm"): return False,"text/html" if fn.endswith(".txt"): return False,"text/plain" if fn.endswith(".json"): return False,"text/plain" if fn.endswith(".css"): return False,"text/css" # Unknown file type return None # Decode a "range:" header option, return # (offset,length) or None if we don't like # the region (TBD, multiple ranges and # multipart) # We're passed the file's os.stat as well as # the range: field value. def decode_range(self, st, range): # Byte units, please if not range.startswith("bytes="): return None range = range[6:] # Single range if ',' in range: return None # Start to offset if range[0] == '-': range = range[1:] if not range.isdigit(): return None val1 = int(range) if val1 >= st.st_size: return None return (0, val1) # Offset to end... elif range[-1] == '-': range = range[:-1] if not range.isdigit(): return None val2 = int(range) if val2 >= st.st_size: return None return (val2, st.st_size - val2) # Offset1 to offset2 else: parts = range.split('-') if len(parts) != 2: return None if not all(p.isdigit() for p in parts): return None val1 = int(parts[0]) val2 = int(parts[1]) if val1 >= val2: return None return (val1, val2-val1) # Try to serve the named file def send_files(self, fn): global Bufsize # Hanky-panky? if sketchy(fn): self.send_error(404) return None # Make sure we know its MIME type tup = self.get_mtype(fn) if tup is None: # Unknown file type self.send_error(404) return None isbin,mtyp = tup try: f = open(fn, "rb" if isbin else "r") except: self.send_error(404) return None # Get dope on file overall st = os.fstat(f.fileno()) startoff = 0 nbyte = st.st_size ranged = False # Sub-ranged output if 'range' in self.headers: tup = self.decode_range(st, self.headers['range']) if tup is None: # Bad range self.send_error(416) return None ranged = True startoff,nbyte = tup else: startoff = 0 nbyte = st.st_size # For media files, use sendfile() rather than passing # it all through this process. # We also support ranges here. if isbin: # Ranged or normal response if ranged: self.send_response(206) else: self.send_response(200) self.send_header("Content-type", mtyp) self.send_header("Content-Length", nbyte) if ranged: self.send_header("Content-Range", "bytes %d-%d/%d" % (startoff, startoff+nbyte-1, st.st_size)) self.send_header("Last-Modified", time.asctime(time.localtime(st.st_mtime))) self.end_headers() # Don't push out body if they're just asking us about # the file's size via HEAD if self.base_op == "GET": # SSL encap apparently isn't compatible with # the nicely efficient sendfile(), so move # it "by hand" if self.server.ssl: f.seek(startoff) nleft = nbyte while nleft > 0: req = min(nleft, Bufsize) buf = f.read(req) self.wfile.write(buf) nleft -= len(buf) self.wfile.flush() else: sendfile(self.wfile.fileno(), f.fileno(), startoff, nbyte) # We've pushed it, tell the upper layers buf = None # Text, just shuffle bytes around as a whole # TBD are gigabyte text files... an encyclopedia, anybody? # But don't forget the DOS-style line endings; can't just # use sendfile() if you honor that. else: buf = f.read() self.changed = st.st_mtime buf = self.send_result(buf, mtyp, cacheable=True) # Done with the file f.close() # Return contents (or None if we already pushed it out) return buf # Common code to strip and decode options # Also bursts the path to self.paths[] def options(self): p = self.path # Options? if "?" in p: idx = p.rindex("?") if self.parseKV(p[idx+1:]) is None: return None self.path = p = p[:idx] # Burst path self.paths = pp = p.strip("/").split("/") # Helper; match path to given one def path_match(self, *elems): pp = self.paths if len(elems) != len(pp): return False if any( (p1 != p2) for p1,p2 in zip(elems, pp) ): return False return True # Basic GET functions def base_get(self): # Top level pp = self.paths if (not pp) or ((len(pp) == 1) and not pp[0]): return True,self.send_top() # Service file content if pp[0] in self.lits: fname = os.path.join(*pp) return True,self.send_files(fname) # Special case, bleh if (len(pp) == 1) and (pp[0] == "favicon.ico"): return True,self.send_files("imgs/favicon.ico") # Couldn't help return False,None # Intercept after request is parsed; apply HTTP authentication def parse_request(self): # Make sure it's well-formed res = BaseHTTPRequestHandler.parse_request(self) if not res: return False # Check whether this request can proceed if not hasattr(self, "authenticate"): return True # Authentication is present, go ask res = self.authenticate() # Supplied body is the completion of the request if isinstance(res, str): res = self.send_result(res, "text/html") # self.base_op hasn't been decoded yet, so # just snoop the operation type directly if not self.requestline.startswith("HEAD"): self.wfile.write(res) # We did the whole request, so don't have # handle_one_request() try also return False # HTML error; code and message if isinstance(res, (tuple,list)): self.send_error(res[0], res[1]) return False # Only other valid return format is True; keep # going if res is not True: raise Exception, "TBD, check this code path" assert res is True return True # Send header # Also canonicalize to DOS-style line endings (ew) # This code only handles textual responses; binary/large # media is handled inline. def send_result(self, buf, mtyp, cacheable=False): # Rewrite to DOS line endings buf = buf.replace("\n", "\r\n") # Send response self.send_response(200) self.send_header("Content-type", mtyp) self.send_header("Content-Length", len(buf)) if not cacheable: self.send_header("Cache-Control", "no-cache") else: self.send_header("Last-Modified", time.asctime(time.localtime(self.changed))) self.end_headers() return buf # Hook to add on any specified extra headers def end_headers(self): # Add on any extras we've calculated if self.extra_headers: for tag,val in self.extra_headers: self.send_header(tag, val) del self.extra_headers[:] # Now do the basic action BaseHTTPRequestHandler.end_headers(self) # Generate a meta REFRESH body def gen_redir(self, url, msg=None): if msg is None: timeout = 0 msg = "Refreshing..." else: # If we have something to say, give'em 5 seconds # to admire its wisdom. timeout = 5 buf = \ """ <html> <head> <title>%s</title> <meta http-equiv="REFRESH" content="%d;url=%s" /> </head> <body> %s </body> </html> """ % (self.title, timeout, url, msg) return buf # Generate meta REFRESH body, send it def send_redir(self, url, msg=None): buf = self.gen_redir(url, msg) buf = self.send_result(buf, "text/html") return buf # In <url>[?key[=val][&key[=val...]]], parse key[/val] and # put into self.vals{} and self.rvals{} # Returns the input @buf, or None if there was a problem def parseKV(self, buf): # Walk each key/val, in the format "k[=v]" # vals{} assembles vals[k] = v, and # rvals{} assembles rvals[v] = k self.vals = vals = {} self.rvals = rvals = {} for kv in buf.split("&"): # Split to k and v tup2 = kv.split("=") if len(tup2) == 1: k = tup2[0] v = True elif len(tup2) == 2: k,v = tup2 else: # x=y=z, something like that? self.send_error(404) return None # Field name should be folded to lower case, as case # sensitivity varies by browser. k = k.lower() if isinstance(v, bool): vals[k] = v else: # The show/artist/track can have spaces, which have # turned into plus signs. v = v.replace("+", " ") vals[k] = unescape(v) rvals[v] = k # Success; @buf untouched return buf # Take the JSON-ish dict @d, and send its JSON # encoding back to our client def send_json(self, d): buf = json.dumps(d) buf = self.send_result(buf, "application/json") return buf # Common code for failing to parse a request def bad_request(self): self.send_error(400) return True,None # Utility to pull file contents def readf(self, fn): f = open(fn, "r") res = f.read() f.close() return res <file_sep>/www.py # # www.py # Code to run a web server on a specific port and protocol # import sys, socket, threading import net DEBUG=1 # This is slow/heavy to import import ssl # from OpenSSL import SSL # Enable config for our HTTP listener(s) def add_config(c): # A web server here; we can serve multiple ports, protocols, # and interfaces c.onearg.add( ("serve",) ) c.mults.add( ("serve",) ) # Which network interface, authen, SSL stuff for sub in ("iface", "publicCert", "privateKey", "accounts"): lkey = ("serve",) + (sub,) c.onearg.add(lkey) # An account--authentication c.args.add( ("serve", "accounts") ) # Protect by IP addr c.args.add( ("serve", "permit") ) # TCP port # c.ints.add( ("serve", "port") ) # HTTP server, listens and spins up threads for each request class HTTP(object): # Our connection back to the root app state # # @proto indicates http[s] # The rest of the config params are in the @config dict # # @apphandler is an HTTP request handler, rooted # from chore.handlers.Chore_Handler # @approot is rooted from chore.server.Server def __init__(self, proto, config, apphandler, approot): self.proto = proto # This is the sub-config for a given HTTP server # entry. self.config = config self.apphandler = apphandler self.approot = approot # The socket we'll open and its address self.socket = None self.addr = self.port = None # Authentication? Or None. self.authentication = config.get("accounts") self.cookies = None # Once we read the config self.ssl = None # We're on our own thread, handle request def launch(self, conn, tup): # SSL setup if self.ssl: try: conn.do_handshake() except: sys.stderr.write(" SSL failed %r\n" % (tup,)) try: conn.close() except: pass sys.exit(0) # Main web handler # "real" version if DEBUG: # This version for debug # We'll see any exceptions thrown handler = self.apphandler(conn, tup, self) conn.close() else: try: try: handler = self.apphandler(conn, tup, self) except: # Probably a closed socket on us pass # The __init__ runs the service; when it returns # we're already done. # Do our best to make that socket go away finally: try: conn.close() except: pass # Done sys.exit(0) # Process web clients; each gets their own thread def run(self): # Base socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Wrap in SSL? c = self.config if self.proto == "https": # Sanity--SSL configured if not c.get("privateKey"): raise Exception, "Private SSL key not configured" if not c.get("publicCert"): raise Exception, "Public SSL certificate not configured" # Create socket s = ssl.wrap_socket(s, c["privateKey"], c["publicCert"], server_side = True, suppress_ragged_eofs = False, do_handshake_on_connect=False) # ctx = SSL.Context(SSL.SSLv23_METHOD) # ctx.use_privatekey_file(c["privateKey"]) # ctx.use_certificate_file(c["publicCert"]) # s = SSL.Connection(ctx, s) # Default port port = c.get("port", 443) # Flag that SSL is active self.ssl = True else: assert self.proto == "http" # Default port port = c.get("port", 80) # In the clear self.ssl = False # Set up incoming address filtering? self.permit = None if "permit" in c: # Get list of permitted addresses/prefixes v = c["permit"] self.permit = [] for m in v: self.permit.append(net.parseaddr(m)) # Standard options for socket self.socket = s s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ifname = c.get("iface") if ifname: addr = net.get_ip_address(ifname) else: addr = "" s.bind( (addr, port) ) s.listen(20) # Stash away in case our server threads need to know self.addr,self.port = s.getsockname() # Endless service loop sys.stderr.write("Handler for %r started on %r:%r\n" % (self.proto, self.addr, self.port)) while True: conn,tup = s.accept() sys.stderr.write("HTTP %sfrom %r\n" % (("(ssl) " if self.ssl else ""), tup)) # See if we want to talk if self.permit and (not net.ok_ip(self.permit, tup[0])): sys.stderr.write(" rejected\n"); conn.close() continue t = threading.Thread(target=self.launch, args=(conn,tup)) t.start() <file_sep>/README.md This is a growing suite of supporting code to implement standalone web applications in Python. It evolved from a number of Python application servers I developed over the last couple years, and represents my evolving ideas in how to efficiently factor out the repetitious bits. The most recent major change is the factoring of login and cookie management to its own server, accessed via datagram Unix-domain sockets. Web architecture intends cookies to be per *host*, and so it is much more natural to factor accounts, passwords, and their resulting cookie to a single point. This permits a single cookie to suffice to access any authorized service on the serving host. <file_sep>/css/README.md These are CSS files which provide a useful baseline of configuration for typical web page elements. They were gleaned from the net, and are available under the terms of the original authors.
90e4185eb39c78b678b74b739ed94287ea2188c2
[ "Markdown", "Python" ]
12
Python
vandys/chore
038eb83e093d5d79cea1d3c3101ebbd59d10a355
66a394526a4e249ffa672f15c0393700259a946a
refs/heads/master
<repo_name>ellisbywater/Unity-Base-StackedFSM<file_sep>/Assets/Scripts/Player.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private Vector3 movementVector; private Animator _animator; private float speed; private Rigidbody _rigidbody; private Health _health; // Start is called before the first frame update void Start() { _health = GetComponent<Health>(); _animator = transform.GetChild(0).GetComponent<Animator>(); _rigidbody = GetComponent<Rigidbody>(); speed = 1.5f; _health.SetHealth(20); } // Update is called once per frame void Update() { CalculateMovement(); if (movementVector != Vector3.zero) { transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movementVector), 0.25f ); } _animator.SetBool("Walking", movementVector != Vector3.zero); } void CalculateMovement() { movementVector = new Vector3(Input.GetAxis("Horizontal"), _rigidbody.velocity.y, Input.GetAxis("Vertical")); _rigidbody.velocity = new Vector3(movementVector.x * speed, movementVector.y, movementVector.z * speed); } public void Hurt(int amount, float delay = 0.5f) { StartCoroutine(_health.TakeDamageDelayed(amount, delay)); } } <file_sep>/Assets/Scripts/Zombie.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using UnityEngine.UI; public class Zombie : MonoBehaviour { private StateMachine brain; private Animator _animator; [SerializeField] private Text stateNote; private NavMeshAgent _agent; private Player _player; private bool playerIsNear; private bool withinAttackRange; private float changeMind; private float attackTimer; // Start is called before the first frame update void Start() { _player = FindObjectOfType<Player>(); _agent = GetComponent<NavMeshAgent>(); _animator = transform.GetChild(0).GetComponent<Animator>(); brain = GetComponent<StateMachine>(); playerIsNear = false; withinAttackRange = false; brain.PushState(Idle, OnIdleEnter, OnIdleExit); } // Update is called once per frame void Update() { playerIsNear = Vector3.Distance(transform.position, _player.transform.position) < 5; withinAttackRange = Vector3.Distance(transform.position, _player.transform.position) < 1; } void OnIdleEnter() { stateNote.text = "Idle"; _agent.ResetPath(); } void Idle() { changeMind -= Time.deltaTime; if (playerIsNear) { brain.PushState(Chase, OnChaseEnter, OnChaseExit); } else if (changeMind <= 0) { brain.PushState(Wander, OnWanderEnter, OnWanderExit); changeMind = Random.Range(4, 10); } } void OnIdleExit() { } void Chase() { _agent.SetDestination(_player.transform.position); if (Vector3.Distance(transform.position, _player.transform.position) > 5.5f) { brain.PopState(); brain.PushState(Idle, OnIdleEnter, OnIdleExit); } if (withinAttackRange) { brain.PushState(Attack, OnAttackEnter, null); } } void OnChaseEnter() { _animator.SetBool("Chase", true); stateNote.text = "Chase"; } void OnChaseExit() { _animator.SetBool("Chase", false); } void Wander() { if (_agent.remainingDistance <= .25f) { _agent.ResetPath(); brain.PushState(Idle, OnIdleEnter, OnIdleExit); } if (playerIsNear) { brain.PushState(Chase, OnChaseEnter, OnChaseExit); } } void OnWanderEnter() { stateNote.text = "Wander"; _animator.SetBool("Chase", true); Vector3 wanderDirection = (Random.onUnitSphere * 4f) + transform.position; NavMeshHit navMeshHit; NavMesh.SamplePosition(wanderDirection, out navMeshHit, 3f, NavMesh.AllAreas); Vector3 destination = navMeshHit.position; _agent.SetDestination(destination); } void OnWanderExit() { _animator.SetBool("Chase", false); } void Attack() { attackTimer -= Time.deltaTime; if (!withinAttackRange) { brain.PopState(); } else if (attackTimer <= 0) { _animator.SetTrigger("Attack"); _player.Hurt(2, 1f); attackTimer = 2f; } } void OnAttackEnter() { _agent.ResetPath(); stateNote.text = "Attack"; } }
0d68ff4c3586c16bb3a0fd3cbcdb3841a70fbef0
[ "C#" ]
2
C#
ellisbywater/Unity-Base-StackedFSM
18ae146635a711318676a4cce81dd698d561f037
c4ab6ba9067580e0bd0bbf0431e0a2bd4c543623
refs/heads/master
<repo_name>ikebo/spoon<file_sep>/tests/test_loal.py import sys import os sys.path[0] = os.path.abspath('../') from sugars.local import Local def test(): lc.a = 'test' print('lc.a in test: ', lc.a) if __name__ == '__main__': lc = Local() lc.a = 1 print('lc.a in Main: ', lc.a) import threading t = threading.Thread(target=test, args=()) t.start()<file_sep>/sugars/local.py # coding: utf-8 try: from greenlet import greenlet get_current_greenlet = greenlet.getcurrent del greenlet except: get_current_greenlet = int from thread import get_ident as get_current_thread, allocate_lock if get_current_greenlet is int: get_ident = get_current_thread else: get_ident = lambda: (get_current_thread(), get_current_thread()) class Local(object): """ 类似ThreadLocal的实现, 可以应付协程场景。 """ __slots__ = ('__storage__', '__lock__') def __init__(self): object.__setattr__(self, '__storage__', {}) object.__setattr__(self, '__lock__', allocate_lock()) def __iter__(self): return self.__storage__.iteritems() def __release_local__(self): self.__storage__.pop(get_ident(), None) def __setattr__(self, key, value): self.__lock__.acquire() try: ident = get_ident() if ident in self.__storage__: self.__storage__[ident][key] = value else: self.__storage__[ident] = {key: value} finally: self.__lock__.release() def __getattr__(self, item): self.__lock__.acquire() try: return self.__storage__[get_ident()][item] except KeyError: raise AttributeError(item) finally: self.__lock__.release() def __delattr__(self, item): self.__lock__.acquire() try: del self.__storage__[get_ident()][item] except KeyError: raise AttributeError(item) finally: self.__lock__.release() class LocalStack(object): """ Local封装, 可以用使用Stack的方式压入弹出变量 可优雅处理请求上下文 """ def __init__(self): self._local = Local() self._lock = allocate_lock() def push(self, obj): self._lock.acquire() try: rv = getattr(self._local, 'stack', None) if rv is None: self._local.stack = rv = [] rv.append(obj) finally: self._lock.release() def pop(self): self._lock.acquire() try: stack = getattr(self._local, 'stack', None) if stack is None: return None if len(stack) == 1: del self._local.stack return stack.pop() finally: self._lock.release() @property def top(self): try: return self._local.stack[-1] except(AttributeError, IndexError): return None class LocalProxy(object): """ 代理Local中特定对象, 如: lc = Local() lc.a = 1 lc.b = 2 a = LocalProxy(lc, 'a') 则不同的上下文中a的值就是当前上下文的a,对于使用者来说相当于全局变量, 但内部又是 动态绑定的,优雅不 :) 当传入的不是一个Local对象时, 则会调用这个参数, 如: _request_ctx_stack = LocalStack() _request_ctx_stack.push(_RequestContext()) request = LocalProxy(lambda: _request_ctx_stack.top.request) 每次使用request时,都会动态获得当前上下文的request :) """ __slots__ = ('__local__', '__dict__', '__name__') def __init__(self, local, name=None): object.__setattr__(self, '__local__', local) object.__setattr__(self, '__name__', name) def _get_current_object(self): if not isinstance(self.__local__, Local): return self.__local__() try: return getattr(self.__local__, self.__name__) except AttributeError: raise RuntimeError('no object bound to %s' % self.__name__) @property def __dict__(self): try: return self._get_current_object().__dict__ except RuntimeError: return AttributeError('__dict__') def __repr__(self): try: obj = self._get_current_object() except RuntimeError: return '<%s unbound>' % self.__class__.__name__ return repr(obj) def __nonzero__(self): try: return bool(self._get_current_object()) except RuntimeError: return False def __unicode__(self): try: return unicode(self._get_current_object()) except RuntimeError: return repr(self) def __getattr__(self, item): return getattr(self._get_current_object(), item) def __dir__(self): try: return dir(self._get_current_object()) except RuntimeError: return [] def __setitem__(self, key, value): self._get_current_object()[key] = value def __delitem__(self, key): del self._get_current_object()[key] def __setslice__(self, i, j, seq): self._get_current_object()[i:j] = seq def __delslice__(self, i, j): del self._get_current_object()[i:j] __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v) __delattr__ = lambda x, n: delattr(x._get_current_object(), n) __str__ = lambda x: str(x._get_current_object()) __lt__ = lambda x, o: x._get_current_object() < o __le__ = lambda x, o: x._get_current_object() <= o __eq__ = lambda x, o: x._get_current_object() == o __ne__ = lambda x, o: x._get_current_object() != o __gt__ = lambda x, o: x._get_current_object() > o __ge__ = lambda x, o: x._get_current_object() >= o __cmp__ = lambda x, o: cmp(x._get_current_object(), o) __hash__ = lambda x: hash(x._get_current_object()) __call__ = lambda x, *a, **kw: x._get_current_object()(*a, **kw) __len__ = lambda x: len(x._get_current_object()) __getitem__ = lambda x, i: x._get_current_object()[i] __iter__ = lambda x: iter(x._get_current_object()) __contains__ = lambda x, i: i in x._get_current_object() __getslice__ = lambda x, i, j: x._get_current_object()[i:j] __add__ = lambda x, o: x._get_current_object() + o __sub__ = lambda x, o: x._get_current_object() - o __mul__ = lambda x, o: x._get_current_object() * o __floordiv__ = lambda x, o: x._get_current_object() // o __mod__ = lambda x, o: x._get_current_object() % o __divmod__ = lambda x, o: x._get_current_object().__divmod__(o) __pow__ = lambda x, o: x._get_current_object() ** o __lshift__ = lambda x, o: x._get_current_object() << o __rshift__ = lambda x, o: x._get_current_object() >> o __and__ = lambda x, o: x._get_current_object() & o __xor__ = lambda x, o: x._get_current_object() ^ o __or__ = lambda x, o: x._get_current_object() | o __div__ = lambda x, o: x._get_current_object().__div__(o) __truediv__ = lambda x, o: x._get_current_object().__truediv__(o) __neg__ = lambda x: -(x._get_current_object()) __pos__ = lambda x: +(x._get_current_object()) __abs__ = lambda x: abs(x._get_current_object()) __invert__ = lambda x: ~(x._get_current_object()) __complex__ = lambda x: complex(x._get_current_object()) __int__ = lambda x: int(x._get_current_object()) __long__ = lambda x: long(x._get_current_object()) __float__ = lambda x: float(x._get_current_object()) __oct__ = lambda x: oct(x._get_current_object()) __hex__ = lambda x: hex(x._get_current_object()) __index__ = lambda x: x._get_current_object().__index__() __coerce__ = lambda x, o: x.__coerce__(x, o) __enter__ = lambda x: x.__enter__() __exit__ = lambda x, *a, **kw: x.__exit__(*a, **kw) <file_sep>/README.md # spoon 🥄 一个勺子 ## 简介 学习Flask v0.1源码的产物,先理解,然后尝试自己写出来。工具类由Werkzeug提供, 如路由,Session, 静态文件托管中间件等。 Werkzeug的Local实现很巧妙,我照着它的设计也写了一个。模板引擎由jinja2提供。 ## 依赖 Werkzeug>=0.6.1 Jinja2>=2,4 ## 使用 ``` python from spoon import Spoon app = Spoon(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == '__main__': app.run(debug=True) ``` <file_sep>/Makefile .PHONY: clean-pyc test all: test clean-pyc test: python tests/spoon_tests.py clean-pyc: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + <file_sep>/examples/test/test.py # coding: utf8 import sys import os from hashlib import md5 from datetime import datetime sys.path[0] = os.path.abspath('../../') from spoon import Spoon from spoon import request from spoon import render_template from spoon import session app = Spoon(__name__) app.secret_key = "spoon" def add(a, b): return a + b def date_format(date_str): do = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') return do.strftime('%b %d, %Y') def gravatar_url(email, size=80): """Return the gravatar image for the given email address.""" return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \ (md5(email.strip().lower().encode('utf-8')).hexdigest(), size) app.jinja_env.globals.update(add=add, date_format=date_format) app.jinja_env.filters["gavatar"] = gravatar_url import sys @app.route('/', methods=['GET']) def index(): # session["username"] = "Joe" session["username"] = 'Joe' return render_template("index.html") def print_request(rq): for index, item in enumerate(rq): sys.stdout.write('%s, ' % item) if index % 7 == 0: print '\n' @app.route('/spoon/<int:spoon_id>', methods=['POST', 'GET']) def spoon(spoon_id): print("method: ", request.method) print("headers: ", request.headers) return 'Hello, Spoon, NO.{}'.format(spoon_id) @app.errorhandler(404) def handle_404(e): return 'not found', 404 @app.errorhandler(500) def handle_500(e): return 'server internel error', 500 app.run( 'localhost', 5000, debug=True ) <file_sep>/sugars/__init__.py # coding: utf8 """ sugars:: 工具包. """<file_sep>/spoon.py # coding: utf8 """ Spoon:: 学习Flask源码过程中,理解之后再仿造出的Wsgi framework. 目前设计模式基本与Flask相同, 也是依赖Werkzeug和Jinja2. 后面可能会参照其他wsgi framework(如bottle, tornado)的设计进行改造. :copyright: (c) 2019.07 by <NAME>. """ import os import sys from jinja2 import PackageLoader, Environment from werkzeug.contrib.securecookie import SecureCookie from werkzeug.routing import Map, Rule from werkzeug.test import create_environ from werkzeug.wrappers import Request as BaseRequest from werkzeug.wrappers import Response as BaseResponse from werkzeug.exceptions import HTTPException from werkzeug.wsgi import SharedDataMiddleware from werkzeug.utils import redirect from werkzeug.exceptions import abort from jinja2 import Markup, escape from sugars.local import LocalStack, LocalProxy class Request(BaseRequest): """ 请求对象,其中包含当前请求的详细信息 """ pass class Response(BaseResponse): """ 相应对象,其中包含响应信息,是一个wsgi application, 当调用response(environ, start_response)时才真正向客户端输出响应 """ default_mimetype = 'text/html' class _RequestGlobals(object): """ 用于保存当前请求的全局变量,如: g = _request_ctx_stack.top.g g.db = connect_db() from spoon import g cursor = g.db.cursor() """ pass class _RequestContext(object): """ 请求上下文:: 当server接到一个请求时, 会调用spoon中的application函数这个wsgi application, 这时application 首先用environ和其他自身对象构造出请求上下文,也就是这个类的实例, 在请求结束 之前, 当使用定义过的LocalProxy, 如这里的app, url_adapter, request, g等, 则会动态获取这个实例 的对应对象。巧妙之处就在这里。 """ def __init__(self, app, environ): self.app = app self.url_adapter = app.url_map.bind_to_environ(environ) self.request = app.request_class(environ) self.session = app.open_session(self.request) self.g = _RequestGlobals() self.flashes = None def __enter__(self): _request_ctx_stack.push(self) def __exit__(self, exc_type, exc_val, exc_tb): if exc_tb is None or not self.app.debug: _request_ctx_stack.pop() def flash(message): session['_flashes'] = (session.get('_flashes', [])) + [message] def get_flashed_messages(): flashes = _request_ctx_stack.top.flashes if flashes is None: _request_ctx_stack.top.flashes = flashes = \ session.pop('_flashes', []) return flashes def _get_package_path(name): """ 根据模块名获取包的路径, 用于构造jinja2的PackageLoader :param name: :return: """ try: return os.path.abspath(os.path.dirname(sys.modules[name].__file__)) except (KeyError, AttributeError): return os.getcwd() def render_template(template_name, **context): """ 渲染模版, 先更新context(如加入request, session, g等.), 再用jinja_env渲染(jinja_env.global.update, 可添加自定义函数) :param template_name: :param context: :return: """ current_app.update_template_context(context) return current_app.jinja_env.get_template(template_name).render(context) def _default_template_ctx_processor(): """ 添加额外的context :return: """ reqctx = _request_ctx_stack.top return dict( request=reqctx.request, session=reqctx.session, g=reqctx.g ) def url_for(endpoint, **values): """ 根据endpoint和参数构造url, 默认结果是相对路径 :param endpoint: :param values: :return: """ return _request_ctx_stack.top.url_adapter.build(endpoint, values) class Spoon: # 请求类,默认为Request,可更改 request_class = Request # 响应类, 默认为Response, 可更改 response_class = Response jinja_options = dict( autoescape=True, extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'] ) static_path = '/static' secret_key = None session_cookie_name = 'session' def __init__(self, package_name): self.package_name = package_name self.root_path = _get_package_path(self.package_name) self.url_map = Map() # 路由Map self.view_funcs = {} self.before_request_funcs = [] self.after_request_funcs = [] self.error_handlers = {} self.debug = False self.template_context_processors = [_default_template_ctx_processor] self.jinja_env = Environment(loader=self.create_jinja_loader(), **self.jinja_options) self.jinja_env.globals.update( url_for=url_for, get_flashed_messages=get_flashed_messages, ) if self.static_path is not None: """ 用werkzeug中的SharedDataMiddleware托管静态文件 """ self.url_map.add(Rule(self.static_path + '/<filename>', build_only=True, endpoint='static')) target = os.path.join(self.root_path, 'static') self.wsgi_app = SharedDataMiddleware(self.wsgi_app, { self.static_path: target }) def before_request(self, func): """ 所有请求转发之前都要经过的函数的装饰器 :param func: :return: """ self.before_request_funcs.append(func) return func def after_request(self, func): """ 所有请求经视图函数处理完成后都要经过的函数的装饰器 :param func: :return: """ self.after_request_funcs.append(func) return func def preprocess_request(self): for func in self.before_request_funcs: rv = func() if rv is not None: return rv def process_response(self, response): session = _request_ctx_stack.top.session if session is not None: self.save_session(session, response) for handler in self.after_request_funcs: response = handler(response) return response def open_session(self, request): key = self.secret_key if key is not None: return SecureCookie.load_cookie(request, self.session_cookie_name, secret_key=key) def save_session(self, session, response): if session is not None: session.save_cookie(response, self.session_cookie_name) def create_jinja_loader(self): return PackageLoader(self.package_name) def context_processor(self, func): """ 添加模板变量的函数 :param func: :return: """ self.template_context_processors.append(func) return func def request_context(self, environ): return _RequestContext(self, environ) def test_request_context(self, *args, **kwargs): return self.request_context(create_environ(*args, **kwargs)) def update_template_context(self, context): """ 更新jinja2上下文 :param context: :return: """ for func in self.template_context_processors: context.update(func()) def errorhandler(self, code): """ 错误处理函数装饰器 :param code: 错误状态码, 如404,500等。 """ def decorator(func): self.error_handlers[code] = func return func return decorator def make_response(self, rv): """ 根据视图函数的返回结果构造Response对象, 最终发给客户端的响应则是调用Response对象生成的 :param rv: 视图函数的返回结果 :return: Response object """ if isinstance(rv, self.response_class): return rv if isinstance(rv, basestring): return self.response_class(rv) if isinstance(rv, tuple): return self.response_class(*rv) return self.response_class.force_type(rv, _request_ctx_stack.top.request.environ) def dispatch_request(self): """ 路由转发 :return: 路由处理函数的返回结果 或 抛出异常 """ try: endpoint, values = _request_ctx_stack.top.url_adapter.match() return self.view_funcs[endpoint](**values) except HTTPException, e: handler = self.error_handlers.get(e.code) if handler is None: return e return handler(e) except Exception, e: handler = self.error_handlers.get(500) if self.debug or handler is None: raise return handler(e) def wsgi_app(self, environ, start_response): """ 真正的wsgi application, 路由转发, 构造Response对象, 最后调用response对象(也是一个 wsgi application)生成最终响应 :param environ: 上下文字典 :param start_response: server的start_response,用于发送status code & headers :return: """ with _RequestContext(self, environ): rv = self.preprocess_request() if rv is None: rv = self.dispatch_request() response = self.make_response(rv) response = self.process_response(response) return response(environ, start_response) def add_url_rule(self, rule, endpoint, **options): """ 添加路由 :param rule: 路由规则 :param endpoint: 处理函数对应的key :param options: 其他参数, 构造Rule时用到, 如methods=['POST', 'PUT'] :return: """ options['endpoint'] = endpoint options.setdefault('methods', ('GET',)) self.url_map.add(Rule(rule, **options)) def route(self, rule, **options): """ 添加路由的装饰器函数 :param rule: :param options: :return: """ def decorator(func): self.add_url_rule(rule, func.__name__, **options) self.view_funcs[func.__name__] = func return func return decorator def test_client(self): from werkzeug.test import Client return Client(self, self.response_class, use_cookies=True) def run(self, host='localhost', port=5000, **options): """ 启动wekzeug中的简单server, 可用于调试 :param host: 主机地址, 设置为0.0.0.0可开放访问 :param port: 端口 :param options: :return: """ from werkzeug.serving import run_simple if 'debug' in options: self.debug = options.pop('debug') use_reloader = use_debugger = self.debug run_simple(host, port, self, use_reloader=use_reloader, use_debugger=use_debugger) def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response) # 请求上下文栈 _request_ctx_stack = LocalStack() # 请求上下文的request LocalProxy,可动态获取当前上下文的request request = LocalProxy(lambda: _request_ctx_stack.top.request) current_app = LocalProxy(lambda: _request_ctx_stack.top.app) session = LocalProxy(lambda: _request_ctx_stack.top.session) g = LocalProxy(lambda: _request_ctx_stack.top.g)
df7b88b3ad38a79124e8a01f189bda4cc34d00e9
[ "Markdown", "Python", "Makefile" ]
7
Python
ikebo/spoon
2ab2ecf692e3b0a862467afca856cbb81e62876b
4838301c8976c1bff10c26e37449aabacc713792
refs/heads/master
<repo_name>enfogroup/aws_utilities<file_sep>/awsp_zsh/aws_aliases #!/bin/bash # This bash script sets up 3 aliases: # # awsall - list all available AWS profiles # awswho - shows the current active AWS profile # awsp - Switch to the provided profile name # # If a profile has the configuration entry "mfa_serial", its value is expected to # be a serial ID for an MFA device used with that profile account. # The "mfa_serial" configuration is normally only used by role profiles by the AWS CLI, # but the awsp alias supports this in order to allow MFA usage with regular user profiles. # function _getCredentialsFile() { local credentialFileLocation=${AWS_SHARED_CREDENTIALS_FILE}; if [ -z $credentialFileLocation ]; then credentialFileLocation=~/.aws/credentials fi echo $credentialFileLocation }; function _awsListAll() { local credentialFileLocation=$(_getCredentialsFile) while read line; do if [[ $line == "["* ]]; then echo "$line"; fi; done < $credentialFileLocation; }; function _awsSwitchProfile() { if [ -z $1 ]; then echo "Usage: awsp profilename"; return; fi local role_arn="$(aws configure get role_arn --profile $1)" local key_exists="$(aws configure get aws_access_key_id --profile $1)" local mfa_serial="$(aws configure get mfa_serial --profile $1)" if [[ -n $key_exists ]]; then aws configure set aws_access_key_id "$(aws configure get aws_access_key_id --profile $1)" aws configure set aws_secret_access_key "$(aws configure get aws_secret_access_key --profile $1)" aws configure set aws_session_token "$(aws configure get aws_session_token --profile $1)" aws configure set region "$(aws configure get region --profile $1)" echo "Switched to AWS Profile as default: $1"; if [[ -n $mfa_serial ]]; then _awsMfaAuthenticate $mfa_serial $1 fi aws configure list elif [[ -n $role_arn ]]; then _awsAssumeRole $role_arn $1 echo "Assumed role associated with profile $1" aws configure list fi }; function _awsAssumeRole() { local role_arn=$1 local profile=$2 local source_profile=$(aws configure get source_profile --profile "${profile}") local role_session_name=$(aws iam get-user --query User.UserName --output text --profile "${source_profile}") local mfa_serial="$(aws configure get mfa_serial --profile ${source_profile})" if [[ -n $mfa_serial ]]; then read "mfa_token?Enter MFA token (6 digits) for profile ${profile}:" local credentials_text=$(aws sts assume-role --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --role-arn "${role_arn}" --role-session-name cli-"${role_session_name}" --serial-number "${mfa_serial}" --token-code "${mfa_token}" --duration-seconds 43200 --profile "${source_profile}" --output text) else local credentials_text=$(aws sts assume-role --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --role-arn "${role_arn}" --role-session-name cli-"${role_session_name}" --profile "${source_profile}" --output text) fi if [[ -n ${credentials_text} ]]; then read access_key_id secret_access_key session_token <<<${credentials_text} aws configure set default.aws_access_key_id "$access_key_id" aws configure set default.aws_secret_access_key "$secret_access_key" aws configure set default.aws_session_token "$session_token" fi }; function _awsMfaAuthenticate() { local mfa_serial=$1 local profile=$2 read "mfa_token?Enter MFA token (6 digits) for profile ${profile}:" local credentials_text=$(aws sts get-session-token --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --serial-number "${mfa_serial}" --token-code "${mfa_token}" --profile ${profile} --output text --duration-seconds 129600) if [[ -n ${credentials_text} ]]; then read access_key_id secret_access_key session_token <<<${credentials_text} aws configure set default.aws_access_key_id "$access_key_id" aws configure set default.aws_secret_access_key "$secret_access_key" aws configure set default.aws_session_token "$session_token" aws configure set aws_access_key_id "${access_key_id}" --profile "${profile}"-temp aws configure set aws_secret_access_key "${secret_access_key}" --profile "${profile}"-temp aws configure set aws_session_token "${session_token}" --profile "${profile}"-temp echo "Enabled temporary session for profile ${profile} as default and ${profile}-temp" else echo "***>>> Invalid MFA code and/or serial id, not authenticated with MFA <<<***" fi }; function _awsSetEnv() { local profilename="$1" if [[ -z "$profilename" ]]; then unset AWS_ACCESS_KEY_ID unset AWS_SECRET_ACCESS_KEY unset AWS_SESSION_TOKEN unset AWS_REGION else export AWS_ACCESS_KEY_ID=$(aws configure get ${profilename}.aws_access_key_id) export AWS_SECRET_ACCESS_KEY=$(aws configure get ${profilename}.aws_secret_access_key) export AWS_SESSION_TOKEN=$(aws configure get ${profilename}.aws_session_token) export AWS_REGION=$(aws configure get ${profilename}.aws_region) fi } alias awsall="_awsListAll" alias awsp="_awsSwitchProfile" alias awswho="aws configure list" alias awsenv="_awsSetEnv" <file_sep>/awsp_zsh/README.md # README # ## What is this repository for? ## This is a repository to collect various utilities/scripts etc that may not be big enough to warrant their own repositories and does not belong to a specific project or solution. ## Utilities ## ### aws_aliases ### A bash script that provides some conveniance aliases for command line to switch and list between AWS profiles. It assumes that the AWS CLI is installed, as well as that python 2.x is available, if MFA support is to be used. * Copy the script to the home directory of your account * In your $HOME/.zshrc, add an entry . $HOME/aws_aliases * When a new command line window (with bash) is opened, three commands will be available: - awsall - List all available profiles - awswho - Show info about current profile - awsp _profile_ - Switch to profile _profile_. - awsenv [_profile_] - set environment variables with data from _profile_ If the profile entry in $HOME/.aws/credentials has a config entry mfa_serial=arn:aws:iam::1234567890:mfa/user_account_name then it is assumed that switching to that profile will require MFA and it will ask for an MFA token from the MFA device configured. The value to set is the serial id for the MFA device. This can be found in the IAM user account information, under tab "Security credentials", field "Assigned MFA device". The ARN is used if the MFA device is a virtual device, hardware MFA devices uses a different format. The session token when authenticated with MFA will be valid for 12 hours, or until the profile is changed or the cache is cleared; whichever comes first. If a profile entry has role_arn entry set, then it will try to execute assume-role on that role, using the current active/default profile as source profile. For setups that require environment variables to be set with credentials, the alias *awsenv* can be used to set the environment variables based on the profile configuration specified. If no profile is specified, then *awsenv* unsets the corresponding environment variables. The variables affected are: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY - AWS_SESSION_TOKEN - AWS_REGION If *awsp* has been used to switch to a specific profile, then executing prompt>awsenv default will set the environment variables to that same target profile. <file_sep>/awsp_windows/README.md # awsp ## Pre-reqs - AWS CLI - Windows: - Download from [docs.aws.mazon.com/cli](https://docs.aws.amazon.com/cli/latest/userguide/install-windows.html) - Linux: - sudo apt-get install python-pip - pip install awscli --upgrade --user - Clone https://bitbucket.org/emanYourProfile/aws_utilities - Windows: use `awsp.cmd` in `awsp_windows`. - Mac/Linux: modify `.bashrc`: `. <path to aws_aliases>` - Create access keys in AWS. - AWS root account -> IAM -> Users -> Security Credentials -> Generate Access key - Modify the configuration files: - Windows: `C:\Users\<name>\.aws\credentials` and `config`. - Mac/Linux: `~/.aws/credentials` and `config`. ### Config ```[profile YourProfile] output = json region = eu-west-1 mfa_serial = arn:aws:iam::123456789012:mfa/user_account_name [default] region = eu-west-1 [profile some-project] region = eu-west-1 role_arn = arn:aws:iam::123456789012:role/Your-Role source_profile = YourProfile-temp output = json ``` ### Credentials ``` [some-project] region = eu-west-1 role_arn = arn:aws:iam::123456789012:role/Your-Role source_profile = YourProfile-temp output = json [YourProfile] aws_access_key_id=<the key you created earlier> aws_secret_access_key=<the key you created earlier> ``` Change `YourProfile` to a name of your choosing. ## Usage - `awsp <your base profile> <mfa code>`, example: `awsp daniel 123456`. - `aws s3 ls` (should give access denied) - `aws s3 ls --profile <profile name>` (should work) - `awsp <profile>`, example: `awsp some-project`
c42365388d794996ed43ff90dc07f27c8cd1c2db
[ "Markdown", "Shell" ]
3
Shell
enfogroup/aws_utilities
58debdae2c763eed0b02c3c3b4d03cbef567c0ff
207647841c07f2cc0f4e9720c7ac482e2a57f500
refs/heads/main
<file_sep># ricochet_robots.py: Template para implementação do 1º projeto de Inteligência Artificial 2020/2021. # Devem alterar as classes e funções neste ficheiro de acordo com as instruções do enunciado. # Além das funções e classes já definidas, podem acrescentar outras que considerem pertinentes. # Grupo al017: # 93696 <NAME> # 93750 <NAME> from search import Problem, Node, astar_search, breadth_first_tree_search, \ depth_first_tree_search, greedy_search, recursive_best_first_search, InstrumentedProblem import sys import copy import numpy as np import math import time class RRState: state_id = 0 def __init__(self, board): self.board = board self.id = RRState.state_id RRState.state_id += 1 def __lt__(self, other): """ Este método é utilizado em caso de empate na gestão da lista de abertos nas procuras informadas """ return self.id < other.id def __eq__(self, other): return self.board.robots == other.board.robots def __hash__(self): sorted_keys = self.board.robots.keys() values = self.board.robots.values() return hash(str(sorted_keys) + str(values)) class Board: """ Representacao interna de um tabuleiro de Ricochet Robots. """ def __init__(self): self.size = 0 self.robots = {} self.target = [] self.walls = {} self.cost_board = [] def parsed_to_board(self, size, robots, target, walls): """ Recebe os atributos do board parsed e converte para a representacao interna """ self.size = size self.set_walls(walls) self.set_target(target[0], target[1]) self.set_cost_board() self.set_robots(robots) def set_all(self, size, robots, target, walls, cost_board): """ Mete os atributos a apontar para os pointers passados como argumentos """ self.size = size self.robots = robots self.target = target self.walls = walls self.cost_board = cost_board def set_robots(self, robots): """ Adiciona os robots """ for robot in robots: self.set_robot(robot[0], robot[1]) def set_robot(self, colour, position): """ Adiciona um robot """ self.robots[colour] = position pass def set_cost_board(self): """ Cria o tabuleiro de custos """ def expand(position): """ Expande uma posicao que teve o seu custo alterado e altera o custo de todas as posicoes a que tem acesso """ cost = self.cost_board[position[0]-1, position[1]-1] + 1 directions = [] for e in self.possible_moves_robot(self.target[0], position): directions += e[1] result = [] original_position = position for direction in directions: position = original_position while ((self.target[0], direction) in self.possible_moves_robot(self.target[0], position)): if direction == 'l' and self.cost_board[position[0]-1, position[1]-2] == -1: position = (position[0], position[1] - 1) elif direction == 'r' and self.cost_board[position[0]-1, position[1]] == -1: position = (position[0], position[1] + 1) elif direction == 'd' and self.cost_board[position[0], position[1]-1] == -1: position = (position[0] + 1, position[1]) elif direction == 'u'and self.cost_board[position[0]-2, position[1]-1] == -1: position = (position[0] - 1, position[1]) else: break result += [position] self.cost_board[position[0]-1, position[1]-1] = cost return result self.cost_board = np.full((self.size, self.size), -1, dtype=int) self.cost_board[self.target[1][0]-1,self.target[1][1]-1] = 0 to_expand = [(self.target[1][0], self.target[1][1])] while(to_expand): next_position = to_expand.pop(0) to_expand += expand(next_position) def set_walls(self, walls): """ Adiciona as walls """ self.set_outside_walls() for wall in walls: self.set_wall(wall[0], wall[1]) if wall[1] == 'r': self.set_wall((wall[0][0], wall[0][1] + 1), 'l') elif wall[1] == 'l': self.set_wall((wall[0][0], wall[0][1] - 1), 'r') elif wall[1] == 'u': self.set_wall((wall[0][0] - 1, wall[0][1]), 'd') elif wall[1] == 'd': self.set_wall((wall[0][0] + 1, wall[0][1]), 'u') def set_outside_walls(self): """ Adiciona as walls exteriores """ for i in range(1, self.size + 1): self.set_wall((i, 1), 'l') self.set_wall((1, i), 'u') self.set_wall((i, self.size), 'r') self.set_wall((self.size, i), 'd') def set_wall(self, position, side): """ Adiciona uma parede """ if position in self.walls.keys(): self.walls[position] += side else: self.walls[position] = [side] def set_target(self, colour, position): """ Adiciona o target """ self.target = [colour, position] def robot_position(self, robot: str): """ Devolve a posição atual do robô passado como argumento. """ return self.robots[robot] pass def possible_moves(self): """ Devolve os movimentos possiveis """ moves = [] for robot in self.robots.keys(): moves += self.possible_moves_robot(robot, self.robot_position(robot)) return moves def possible_moves_robot(self, robot, position): """ Devolve os movimentos possiveis de um dado robot """ moves = [] if (position not in self.walls.keys() or 'l' not in self.walls[position]) and (position[0], position[1] - 1) not in self.robots.values(): moves.append((robot, 'l')) if (position not in self.walls.keys() or 'r' not in self.walls[position]) and (position[0], position[1] + 1) not in self.robots.values(): moves.append((robot, 'r')) if (position not in self.walls.keys() or 'u' not in self.walls[position]) and (position[0] - 1, position[1]) not in self.robots.values(): moves.append((robot, 'u')) if (position not in self.walls.keys() or 'd' not in self.walls[position]) and (position[0] + 1, position[1]) not in self.robots.values(): moves.append((robot, 'd')) return moves def move_robot(self, action): """ Move um robot segundo uma dada direcao """ robot = action[0] position = self.robots[robot] direction = action[1] while ((robot, direction) in self.possible_moves_robot(robot, position)): if direction == 'l': position = (position[0], position[1] - 1) elif direction == 'r': position = (position[0], position[1] + 1) elif direction == 'd': position = (position[0] + 1, position[1]) elif direction == 'u': position = (position[0] - 1, position[1]) else: break self.robots[action[0]] = position def parse_instance(filename: str) -> Board: """ Lê o ficheiro cujo caminho é passado como argumento e retorna uma instância da classe Board. """ f = open(filename, 'r') board_size = eval(f.readline()) board_robots = [] for i in range(4): args = f.readline().split(" ") board_robots += [[args[0], (eval(args[1]), eval(args[2]))]] args = f.readline().split(" ") board_target = [args[0], (eval(args[1]), eval(args[2]))] board_walls = [] for i in range(eval(f.readline())): args = f.readline().replace('\n', ' ').split(" ") board_walls += [[(eval(args[0]), eval(args[1])), args[2]]] f.close() board = Board() board.parsed_to_board(board_size, board_robots, board_target, board_walls) return board class RicochetRobots(Problem): def __init__(self, board: Board): """ O construtor especifica o estado inicial. """ self.initial = RRState(board) pass def actions(self, state: RRState): """ Retorna uma lista de ações que podem ser executadas a partir do estado passado como argumento. """ return state.board.possible_moves() pass def result(self, state: RRState, action): """ Retorna o estado resultante de executar a 'action' sobre 'state' passado como argumento. A ação retornada deve ser uma das presentes na lista obtida pela execução de self.actions(state). """ robots = copy.deepcopy(state.board.robots) board = Board() board.set_all(state.board.size, robots, state.board.target, state.board.walls, state.board.cost_board) board.move_robot(action) return RRState(board) pass def goal_test(self, state: RRState): """ Retorna True se e só se o estado passado como argumento é um estado objetivo. Deve verificar se o alvo e o robô da mesma cor ocupam a mesma célula no tabuleiro. """ return state.board.robots[state.board.target[0]] == state.board.target[1] pass def h(self, node: Node): """ Função heuristica utilizada para a procura A*. """ colour = node.state.board.target[0] target_position = node.state.board.target[1] robot_position = node.state.board.robot_position(colour) dx = abs(target_position[0] - robot_position[0])**2 dy = abs(target_position[1] - robot_position[1])**2 return math.sqrt(dx + dy) + node.state.board.cost_board[robot_position[0]-1][robot_position[1]-1] if __name__ == "__main__": start_time = time.time() board = parse_instance(sys.argv[1]) problem = InstrumentedProblem(RicochetRobots(board)) # node = breadth_first_tree_search(problem) # node = depth_first_tree_search(problem) # node = greedy_search(problem) # node = astar_search(problem) node = recursive_best_first_search(problem) print(len(node.solution())) for e in node.solution(): print(e[0], e[1]) print("Time = ",time.time() - start_time) print(problem) pass<file_sep># -*- coding: utf-8 -*- """ Grupo al017 Student <NAME> #93696 Student <NAME> #93750 """ import numpy as np import random import math import copy def createdecisiontree(D,Y, noise = False): D = D.astype(int).tolist() Y = Y.astype(int).tolist() nAttributes = len(D[0]) attributes = list(range(nAttributes)) examples = [] for e in range(len(D)): examples += [D[e] + [Y[e]]] maxDepth = nAttributes * 0.5 tree = decisionTreeLearning(examples, attributes, examples, maxDepth, noise) tree = switchRedux(tree) if type(tree) == int: tree = [0, tree, tree] return tree def plurality_value(examples): n0 = 0 n1 = 0 for example in examples: if example[-1] == 0: n0 += 1 else: n1 += 1 if n0 == n1: return random.choice([0,1]) else: return 0 if n0 > n1 else 1 def allHaveSameY(examples): y = examples[0][-1] for example in examples: if example[-1] != y: return False return True def getAValueExamples(examples, A, value): AValueExamples = [] for example in examples: if example[A] == value: AValueExamples += [example] return AValueExamples def Importance(attributes, examples): higherGain = (attributes[0], Gain(attributes[0], examples)) for attribute in attributes[1:]: temp = Gain(attribute, examples) if temp > higherGain[1]: higherGain = (attribute, temp) return higherGain[0] def Gain(attribute, examples): total = len(examples) positives = 0 pk = [0, 0] nk = [0, 0] for example in examples: if example[-1] == 1: positives += 1 if example[attribute] == 1: pk[1] += 1 else: pk[0] += 1 else: if example[attribute] == 1: nk[1] += 1 else: nk[0] += 1 b = B(positives / total) r = Remainder(pk, nk, total) return b - r def B(q): if q in [0, 1]: return 0 return -(q * math.log2(q) + (1 - q) * math.log2(1 - q)) def Remainder(pk, nk, total): if pk[0] + nk[0] == 0: p0 = 0 else: p0 = ((pk[0] + nk[0]) / total) * B(pk[0] / (pk[0] + nk[0])) if pk[1] + nk[1] == 0: p1 = 0 else: p1 = ((pk[1] + nk[1]) / total) * B(pk[1] / (pk[1] + nk[1])) return p0 + p1 def decisionTreeLearning(examples, attributes, parent_examples, maxDepth, noise): if not examples: return plurality_value(parent_examples) elif allHaveSameY(examples): return examples[0][-1] elif not attributes: return plurality_value(examples) elif noise and maxDepth == 0: return plurality_value(examples) else: A = Importance(attributes, examples) tree = [A] for value in [0,1]: AValueExamples = getAValueExamples(examples, A, value) nattributes = copy.deepcopy(attributes) nattributes.remove(A) subtree = decisionTreeLearning(AValueExamples, nattributes, examples, maxDepth - 1, noise) tree += [subtree] return tree # In case of both children being equal, the father is removed def redux(tree): if type(tree) == int: return tree elif type(tree[1]) == list and type(tree[1]) == list and tree[1] == tree[2]: tree[0] = tree[1][0] tree[2] = tree[1][2] tree[1] = tree[1][1] elif tree[1] == tree[2]: tree = tree[1] return tree tree[1] = redux(tree[1]) tree[2] = redux(tree[2]) return tree # If both fathers are the same attribute, does switches between father's and grandfather's nodes and applies redux in the resultant trees def switchRedux(tree): if type(tree) == int: return tree elif type(tree[1]) == list and type(tree[2]) == list and tree[1][0] == tree[2][0]: newTree = copy.deepcopy(tree) newTree = switchFatherGrandFather(newTree) tree = redux(tree) newTree = redux(newTree) if len(str(newTree)) < len(str(tree)): tree = newTree tree[1] = switchRedux(tree[1]) tree[2] = switchRedux(tree[2]) return tree # Switches the father's nodes with grandfather's node def switchFatherGrandFather(tree): temp = tree[0] tree[0] = tree[1][0] tree[1][0] = temp tree[2][0] = temp temp = tree[2][1] tree[2][1] = tree[1][2] tree[1][2] = temp return tree<file_sep># Artificial Intelligence 2020/2021 **Contributors:** [<NAME>](https://github.com/rfssAndrade) and [<NAME>](https://github.com/danielquintas8) ## **Project 1** * [Enunciado](https://github.com/rfssAndrade/Artificial-Intelligence/blob/main/Proj1/Enunciado.pdf) (in Portuguese) * [Code](https://github.com/rfssAndrade/Artificial-Intelligence/tree/main/Proj1/code) * [Report]() #### **Grade:** 12,00 (Automatic Tests) + 2,73 (Private Tests) + 3,05 (Report) = 17,78 / 20 --- ## **Project 2** * [Enunciado](https://github.com/rfssAndrade/Artificial-Intelligence/blob/main/Proj2/Enunciado.pdf) (in Portuguese) * [Code](https://github.com/rfssAndrade/Artificial-Intelligence/tree/main/Proj2/code) * [Report]() #### **Grade:** 18,00 (Private Tests) + 2,00 (Report) = 20 / 20
214c0735161420e39db452372f0bdbc1fe800a94
[ "Markdown", "Python" ]
3
Python
rfssAndrade/Artificial-Intelligence
e223aa1f05785041b7971539ac4d239c7931b701
d73fc436cd203a1d0f61ec5487d19bbf942e48fb
refs/heads/master
<repo_name>elijah-semenov/Interstellar<file_sep>/webpack.config.js const path = require('path') const webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, module: { rules: [ { test: /\.js$/, loader: 'eslint-loader', enforce: 'pre' }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.glsl$/, use: 'raw-loader' } ] }, devtool: '#source-map', optimization: { minimize: true } }
852b8327d447393a53a13f790726473e28bcf9c7
[ "JavaScript" ]
1
JavaScript
elijah-semenov/Interstellar
820945ee664c938afb1fedb3e1a73380a4058007
42c7f9ff4d19b5d321bf79d4548442c9f84c6d82
refs/heads/master
<file_sep>package com.dmi.studiumWS.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; @Configuration public class Config { @Bean public Jaxb2Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("it.unict.soap.studium"); return marshaller; } } <file_sep>package com.dmi.studiumWS.service; import it.unict.soap.studium.TBCheckSubscription; import it.unict.soap.studium.TBCheckSubscriptionResponse; import it.unict.soap.studium.TBGetCourses; import it.unict.soap.studium.TBGetCoursesResponse; import it.unict.soap.studium.TBGetDepartmentContent; import it.unict.soap.studium.TBGetDepartmentContentResponse; import it.unict.soap.studium.TBGetDepartments; import it.unict.soap.studium.TBGetDepartmentsResponse; import it.unict.soap.studium.TBGetYears; import it.unict.soap.studium.TBGetYearsResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.stereotype.Service; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.soap.client.core.SoapActionCallback; @Service public class SOAPClient { @Autowired private Jaxb2Marshaller marshaller; private final String BASE_URL = "http://ws1.unict.it/stdata/"; private WebServiceTemplate getTemplate() { final WebServiceTemplate template = new WebServiceTemplate(marshaller); template.setDefaultUri("https://ws1.unict.it/wscea/wsstudium/StudentService.asmx"); return template; } public TBGetYearsResponse getYears(String token) { final SoapActionCallback soapActionCallback = new SoapActionCallback(BASE_URL + "TB_GetYears"); TBGetYears request = new TBGetYears(); request.setToken(token); TBGetYearsResponse response = (TBGetYearsResponse) getTemplate().marshalSendAndReceive(request,soapActionCallback); return response; } public TBGetDepartmentsResponse getDepartments(String token, String aa) { final SoapActionCallback soapActionCallback = new SoapActionCallback(BASE_URL + "TB_GetDepartments"); TBGetDepartments request = new TBGetDepartments(); request.setToken(token); request.setAa(aa); // Anno Accademico TBGetDepartmentsResponse response = (TBGetDepartmentsResponse) getTemplate().marshalSendAndReceive(request, soapActionCallback); return response; } public TBGetDepartmentContentResponse getCdL(String token, String aa, String idDepartment) { final SoapActionCallback soapActionCallback = new SoapActionCallback(BASE_URL + "TB_GetDepartmentContent"); TBGetDepartmentContent request = new TBGetDepartmentContent(); request.setToken(token); request.setAa(aa); request.setId(idDepartment); TBGetDepartmentContentResponse response = (TBGetDepartmentContentResponse) getTemplate().marshalSendAndReceive(request, soapActionCallback); return response; } public TBGetCoursesResponse getCourses(String token, String aa, String idCdL) { final SoapActionCallback soapActionCallback = new SoapActionCallback(BASE_URL + "TB_GetCourses"); TBGetCourses request = new TBGetCourses(); request.setToken(token); request.setAa(aa); request.setId(idCdL); TBGetCoursesResponse response = (TBGetCoursesResponse) getTemplate().marshalSendAndReceive(request, soapActionCallback); return response; } private TBCheckSubscriptionResponse _checkSubscription(String token, String aa, String idCourse, String userCF) { final SoapActionCallback soapActionCallback = new SoapActionCallback(BASE_URL + "TB_CheckSubscription"); TBCheckSubscription request = new TBCheckSubscription(); request.setToken(token); request.setAa(aa); request.setCourse(idCourse); request.setUser(userCF); TBCheckSubscriptionResponse response = (TBCheckSubscriptionResponse) getTemplate().marshalSendAndReceive(request, soapActionCallback); return response; } public boolean checkSubscription(String token, String aa, String idCourse, String userCF) { return (_checkSubscription(token,aa,idCourse,userCF).getTBCheckSubscriptionResult().equals("si")); } } <file_sep>package com.dmi.studiumWS.controller; import com.dmi.studiumWS.service.SOAPClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("api/studium") public class StudiumController { @Value("${ws.token}") private String token; @Autowired private SOAPClient soap; @RequestMapping("/getYears") public String getYears() { return soap.getYears(token).getTBGetYearsResult(); } @RequestMapping("/getDepartments/{aa}") public String getDepartments(@PathVariable String aa) { return soap.getDepartments(token, aa).getTBGetDepartmentsResult(); } @RequestMapping("/getCdL/{aa}/{id}") public String getCdL(@PathVariable String aa, @PathVariable String id) { return soap.getCdL(token, aa, id).getTBGetDepartmentContentResult(); } @RequestMapping("/getCourses/{aa}/{id}") public String getCourses(@PathVariable String aa, @PathVariable String id) { return soap.getCourses(token,aa,id).getTBGetCoursesResult(); } @RequestMapping("/checkSubscription/{aa}/{course}/{user}") public boolean checkSubscription(@PathVariable String aa, @PathVariable String course, @PathVariable String user) { return soap.checkSubscription(token, aa, course, user); } } <file_sep>server.port = 8082 ws.token = <file_sep>package com.dmi.studiumWS; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StudiumWsApplication { public static void main(String[] args) { SpringApplication.run(StudiumWsApplication.class, args); } }
d2da72ab456e47b2b879c8d4b0b04142cd792ea9
[ "Java", "INI" ]
5
Java
Pierpaolo791/Studium-WStoSOAP
3bc48bfe0c88637e2df81b81453ab51a6f10e939
1ca2ae0ced37fec87f2318fd921f4f82fd8dbec4
refs/heads/main
<file_sep>/* API IVA */ const express = require('express'); const cors = require('cors'); const { getIva } = require('./modules/iva'); // Global app object const app = express(); // Middlware config app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.get('/', function (req, res) { // Aquí pueden hacer lo que ustedes quieran const price = req.query.price; if (typeof req.query.price === "undefined") { res.status(400).send({"error": "`price` query param required"}) } res.send(getIva(price)); }) app.post('/', function (req, res) { // Aquí pueden hacer lo que ustedes quieran const prices = req.body.prices; const pricesWithIva = prices.map(price => getIva(price)); res.send(pricesWithIva); }) // Bootstrap server const server = app.listen(process.env.PORT || 3000, function () { console.log(`Escuchando en el puerto ${server.address().port}`); });
775f5d8a112b0f261049e02c525504ad235abb69
[ "JavaScript" ]
1
JavaScript
MarioHdpz/api-iva
5ef3835c95d440f2aa6d4a577290aa0266ab39c6
06f046ade4bfba517939adb4239e4a6ef4d4d3a7
refs/heads/master
<file_sep>let map; //Elementos const app = document.getElementById('residence'); const container = document.createElement('div'); const country = document.getElementById("country"); const loadMore = document.createElement('a'); //____Funções____ function init() { container.setAttribute('class', 'container') loadMore.setAttribute('id', 'loadMore') loadMore.setAttribute('data-index', 10) loadMore.textContent = '<NAME>' app.appendChild(container) app.appendChild(loadMore) } //Inicia mapa api google function initMap(latitude, longitude) { latitude = (typeof latitude !== 'undefined') ? latitude : 55.70074897777983; longitude = (typeof longitude !== 'undefined') ? longitude : 12.500224174892924; map = new google.maps.Map(document.getElementById('map'), { center: {lat: latitude, lng: longitude}, zoom: 5 }); } function loadResidence(dataIndex, country, guests, diffDays, destroy) { if(destroy == true){ container.innerHTML=""; } let latitude let longitude if(country == "United States"){ latitude = 34.88593094; longitude = -81.5625; }else if(country == "Spain"){ latitude = 39.3262345; longitude = -4.8380649; }else if(country == "Italy"){ latitude = 42.6384261; longitude = 12.674297; }else{ latitude = 55.70074897777983; longitude = 12.500224174892924; } initMap(latitude,longitude) // Atribui um novo objeto XMLHttpRequest pra variável. country = (country === "") ? "" : "&refine.country="+country; guests = (typeof guests !== 'undefined') ? guests : 1; var request = new XMLHttpRequest(); // Abre uma nova conexão usando GET //api modelo: https://public.opendatasoft.com/explore/dataset/airbnb-listings/api/?disjunctive.host_verifications&disjunctive.amenities&disjunctive.features&rows=10&sort=last_scraped&q=accommodates%3D4&refine.country=Italy request.open( "GET", // "https://api.sheety.co/30b6e400-9023-4a15-8e6c-16aa4e3b1e72", // "https://public.opendatasoft.com/api/records/1.0/search/?dataset=airbnb-listings&q=&rows=10&start=0&sort=last_scraped&facet=host_response_time&facet=host_response_rate&facet=host_verifications&facet=city&facet=country&facet=property_type&facet=room_type&facet=bed_type&facet=amenities&facet=availability_365&facet=cancellation_policy&facet=features", `https://public.opendatasoft.com/api/records/1.0/search/?dataset=airbnb-listings&q=&rows=10&start=${dataIndex}&sort=last_scraped${country}`, true ); request.onload = function () { // Tratar o objeto JSON var data = JSON.parse(this.response); // console.log(data); if (request.status >= 200 && request.status < 400) { data.records.forEach((residence) => { // console.log(residence.fields); const item = residence.fields if (typeof item.price !== 'undefined' ) { const card = document.createElement('section') card.setAttribute('class', 'card') const h3 = document.createElement('h3') h3.textContent = item.name const wrap_info = document.createElement('div') wrap_info.className = 'wrap_info' const property_type = document.createElement('p') property_type.textContent = `Tipo: ${item.property_type}` const imgResidence = document.createElement('div') imgResidence.setAttribute('class', 'img-residence') const img = document.createElement('img') if (typeof item.medium_url !== 'undefined') { img.setAttribute('src', item.medium_url) } else { img.setAttribute('src', 'https://ichef.bbci.co.uk/news/1024/cpsprodpb/3E5D/production/_109556951_airbnb.png') } const precoDiv = document.createElement('div') precoDiv.setAttribute('class', 'preco') const totalDays = diffDays*guests; const preco = document.createElement('span') preco.textContent = (item.price*totalDays).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) // console.log("preco.textContent") // console.log(diffDays) // console.log(guests) // console.log(item.price.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })) // console.log(preco.textContent) // console.log("/preco.textContent") var latLng = new google.maps.LatLng(item.latitude, item.longitude); var marker = new google.maps.Marker({ position: latLng, map: map, label: item.price.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }), animation: google.maps.Animation.DROP, title: item.name }); container.appendChild(card) card.appendChild(h3) card.appendChild(imgResidence) imgResidence.appendChild(img) card.appendChild(wrap_info) wrap_info.appendChild(property_type) wrap_info.appendChild(precoDiv) precoDiv.appendChild(preco) } }); } else { const errorMessage = document.createElement('marquee') errorMessage.textContent = `Deu ruim!` app.appendChild(errorMessage) } }; // Envia o request request.send(); } function loadMoreBtn(){ document.getElementById('loadMore').addEventListener('click', function (e){ const dataIndex = this.getAttribute('data-index') loadResidence(dataIndex, country.value, 1, 1, false) loadMore.setAttribute('data-index', parseInt(dataIndex, 10) + 10) }) } function submitFilter(){ const dataAtual = new Date().toISOString().substr(0, 10); const oneDay = 24 * 60 * 60 * 1000; const checkin = document.getElementById('checkin'); const checkout = document.getElementById('checkout'); checkin.value = dataAtual checkin.setAttribute('min', dataAtual) checkout.setAttribute('min', dataAtual) const guests = document.getElementById('guests') const searchBtn = document.getElementById('search'); searchBtn.addEventListener('click', function(e){ e.preventDefault(); const dayCompare = compareDates(); const dateCheckin = new Date(checkin.value); const dateCheckout = new Date(checkout.value); const diffDays = Math.round(Math.abs((dateCheckin.getTime() - dateCheckout.getTime()) / (oneDay))); if(dayCompare){ if(diffDays >= 1){ if(guests.value >= 1){ loadResidence(0, country.value, guests.value, diffDays, true); }else{ swal('Selecione pelo menos 1 hóspede'); } }else{ swal('Selecione uma data maior que a do check-in'); } }else{ swal('Selecione uma data maior que a do check-in'); } }); } function compareDates() { //Get the text in the elements const from = document.getElementById('checkin').value; const to = document.getElementById('checkout').value; //Generate an array where the first element is the year, second is month and third is day const splitFrom = from.split('/'); const splitTo = to.split('/'); //Create a date object from the arrays const fromDate = Date.parse(splitFrom[0], splitFrom[1] - 1, splitFrom[2]); const toDate = Date.parse(splitTo[0], splitTo[1] - 1, splitTo[2]); //Return the result of the comparison return fromDate < toDate; } window.addEventListener('load', function(){ init(); submitFilter(); loadResidence(0, country.value, 1, 1, true); loadMoreBtn(); });
dc0f9e063eb2915da6fa3600db1918a91acaab3f
[ "JavaScript" ]
1
JavaScript
nathanprestes/gama-airbnb
53debae4e411fa3fa41ccda19fced238e7fc3779
5a9001bba70c8c6eac647671b4fa582074152adc
refs/heads/master
<repo_name>maciejk77/gg-app<file_sep>/README.md #GG App 1. ```https://github.com/maciejk77/gg-app.git``` repo to your local via command line/terminal 2. ```cd gg-app``` to change into the folder 3. ```npm install``` to install packages 4. ```npm start``` to run app, will be on localhost:3000 <file_sep>/src/components/plan_goal.js import React from "react"; import { Link } from "react-router-dom"; import StepsBar from "./steps_bar"; import propTypes from "prop-types"; const PlanGoal = ({ state: { goal, saved, save_daily, date: { day, month, year } }, step, changeGoal, changeSaved, handleDateChange }) => { const MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; const dateNow = new Date(); const yearMin = dateNow.getFullYear(); const yearMax = yearMin + 20; const length = yearMax - yearMin; const years = Array.from({ length }, (_, i) => { return ( <option key={i} value={yearMin + i}> {yearMin + i} </option> ); }); const months = MONTHS.map((month_const, i) => ( <option key={i} value={i}> {month_const} </option> )); const days = Array.from({ length: 31 }, (_, i) => ( <option key={i} value={i + 1}> {i + 1} </option> )); return ( <div className="plan-goal"> <StepsBar step={step} /> <h3 className="plan-goal__title">Set your goal</h3> <form className="goal-form"> <div className="goal-form__element"> <input type="number" value={goal} onChange={changeGoal} /> <label>Total amount to save</label> </div> <div className="goal-form__element goal-form__element--flex"> <div> <select className="goal-form__select" name="day" value={day} onChange={handleDateChange} > {days} </select> <select className="goal-form__select" name="month" value={month} onChange={handleDateChange} > {months} </select> <select className="goal-form__select" name="year" value={year} onChange={handleDateChange} > {years} </select> </div> <label>Saved by</label> </div> <div className="goal-form__element"> <input type="number" value={saved} onChange={changeSaved} /> <label>Amount saved so far</label> </div> <div className="goal-form__element"> <input className="save_daily" value={save_daily} disabled /> <label>Saving needed per day</label> </div> </form> <div className="button-group"> <Link to="/" className="button-group__next"> {" "} Save my goal{" "} </Link> <Link to="/title" className="button-group__back"> {" "} &lt;back{" "} </Link> </div> </div> ); }; export default PlanGoal; PlanGoal.propTypes = { state: propTypes.object, changeGoal: propTypes.func, changeSaved: propTypes.func, handleDateChange: propTypes.func, step: propTypes.number }; <file_sep>/src/components/plan_item.js import React, { Component } from 'react'; import propTypes from 'prop-types'; class PlanItem extends Component { render() { const { goal, source, id, selected } = this.props; let activeClass = (selected ? 'plan-item--active' : 'plan-item--nonactive'); return ( <div className={`plan-item ${activeClass}`} data-id={id} onClick={this.props.handle_click}> <img className="plan-item__image" src={`/images/${source}.png`} style={{ width: "40%" }} alt="" /> {goal} </div> ) } } export default PlanItem; PlanItem.propTypes = { goal: propTypes.string, source: propTypes.string, getTitle: propTypes.func, id: propTypes.number };
b397190c4c2bd1ee8f463e952270aebb130dc4f6
[ "Markdown", "JavaScript" ]
3
Markdown
maciejk77/gg-app
b9fe318027c076271cda19b305cd538c1cf63bc1
7d5d94c48b187bbea641f803f956873c515ee6d4
refs/heads/master
<file_sep><?php /** * * VigLink extension for the phpBB Forum Software package. * * @copyright (c) 2014 phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine // // Some characters you may want to copy&paste: // ’ » “ ” … // $lang = array_merge($lang, array( 'ACP_VIGLINK_SETTINGS' => 'VigLink asetukset', 'ACP_VIGLINK_SETTINGS_EXPLAIN' => 'VigLink on kolmannen osapuolen palvelu joka huomaamatta monetisoi foorumisi käyttäjien lähettämät linkit ilman että käyttäjäkokemus muuttuu. Kun käyttäjä klikkaa foorumilta pois vievää linkkiä tuotteisiin tai palveluihin ja ostaa jotain, kauppiaat maksavat VigLinkille palkkion josta osa lahjoitetaan phpBB-projektille. Ottamalla VigLinkin käyttöön ja lahjoittamalla tuotot phpBB-projektille, tuet avoimen lähdekoodin organisaatiotamme varmistamalla taloudellista turvaamme.', 'ACP_VIGLINK_SETTINGS_CHANGE' => 'Voit muuttaa näitä asetuksia milloin vain “<a href="%1$s">VigLink asetukset</a>” -sivulla.', 'ACP_VIGLINK_ENABLE' => 'Käytä VigLinkiä', 'ACP_VIGLINK_ENABLE_EXPLAIN' => 'Sallii VigLink-palveluiden käyttämisen.', 'ACP_VIGLINK_EARNINGS' => 'Vaadi oma osuutesi (vapaaehtoinen)', 'ACP_VIGLINK_EARNINGS_EXPLAIN' => 'Voit vaatia omat tuottosi kirjautumalla Viglink Convert -tilille.', 'ACP_VIGLINK_DISABLED_PHPBB' => 'VigLink-palvelut ovat poissa käytöstä phpBB:n toimesta.', 'ACP_VIGLINK_CLAIM' => 'Vaadi oma osuutesi', 'ACP_VIGLINK_CLAIM_EXPLAIN' => 'Voit vaatia foorumisi tuotot VigLinkin monetisoimista linkeistä sen sijaan että lahjoittaisit ne phpBB-projektille. Hallitaksesi tilisi asetuksia, luo “VigLink Convert” -tili valitsemalla “Convert-tili”.', 'ACP_VIGLINK_CONVERT_ACCOUNT' => 'Convert-tili', 'ACP_VIGLINK_NO_CONVERT_LINK' => 'VigLink convert -tilin linkkiä ei voitu hakea.' )); <file_sep># phpBB 3 Finnish Translation Finnish Translation for [phpBB](https://www.phpbb.com) 3.x forum software Validated version is available from [phpBB.com Language pack page](https://www.phpbb.com/customise/db/translation/finnish/). ## Contributing * Clone/fork this project to your own account and make edits there. * When complete, you can make pull request to [this repository](https://github.com/pettis/phpbb3-finnish). * If translation files are properly edited, they will be merged into this project. * Open source contributing guide by GitHub: https://guides.github.com/activities/contributing-to-open-source/ ##Translators * Lurttinen * harritapio * Pettis * Coder * Potku * n.lintulaakso
4b4bdd2b5a782d722c88a4718596ce4d10236784
[ "Markdown", "PHP" ]
2
PHP
Amskii/phpbb3-finnish
95ef77b6f3a8dc4ed16a1013aa5c5856d2bd7a72
17d950662b623ed3186383c2334f3a659864db31
refs/heads/master
<file_sep>package com.example.find_text import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { } <file_sep># Find text This repository contains examples to find text from PDF documents in Flutter apps using Syncfusion PDF Flutter library. ## Steps to find text from a PDF document: 1. Checkout and open the project in your favorite editor. 2. Run the following commands to get the required package. ```dart $ flutter pub get ``` 3. Run the below commands to execte the project. ```dart $ flutter run ```
75f057372bac727bed6b5c10dcbdce08ee1f7fee
[ "Markdown", "Kotlin" ]
2
Kotlin
TheArchitect123/Find-text-in-PDF-document-Flutter
4a092318710e43e8ed95d298f80692f6e2c11fd1
3906c6856a0028876b7db4a00f9bd677a0b0deeb
refs/heads/master
<file_sep>package com.b5m.plugincms.entity; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import com.b5m.dao.annotation.Id; public abstract class EntityDomain { @Id protected Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } } <file_sep>package com.b5m.plugincms.common; public class SysGlobal { } <file_sep>package com.b5m.plugincms.entity; import java.util.Date; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import com.b5m.dao.annotation.Column; import com.b5m.dao.annotation.Id; import com.b5m.dao.annotation.Table; import com.b5m.dao.domain.ColType; /** * @Company B5M.com * @description * * @author echo * @since 2013-7-12 * @email <EMAIL> */ @Table("t_html_page_info") public class HtmlPageInfo{ @Id protected Long id; @Column(name = "albums_content", type = ColType.TEXT) private String albumsContent; @Column(name = "photos_content", type = ColType.TEXT) private String photosContent; @Column(name = "ad_a_content", type = ColType.TEXT) private String adAContent; @Column(name = "ad_b_content", type = ColType.TEXT) private String adBContent; @Column(name = "ad_c_content", type = ColType.TEXT) private String adCContent; @Column(name = "text_a_content", type = ColType.TEXT) private String textAContent; @Column(name = "text_b_content", type = ColType.TEXT) private String textBContent; @Column(name = "text_c_content", type = ColType.TEXT) private String textCContent; @Column private String version; @Column(name = "effective_start_date", type = ColType.TIMESTAMP) private Date effectiveStartDate; @Column(name = "effective_end_date", type = ColType.TIMESTAMP) private Date effectiveEndDate; @Column(name = "create_date", type = ColType.TIMESTAMP) private Date createDate; @Column(name = "last_modify_date", type = ColType.TIMESTAMP) private Date lastModifyDate; //备用字段 @Column(name = "bak_photos_content1", type = ColType.TEXT) private String bakPhotosContent1; @Column(name = "bak_ad_content_1", type = ColType.TEXT) private String bakAdContent1; @Column(name = "bak_ad_content_2", type = ColType.TEXT) private String bakAdContent2; @Column(name = "bak_text_content_1", type = ColType.TEXT) private String bakTextContent1; @Column(name = "bak_text_content_2", type = ColType.TEXT) private String bakTextContent2; @Column(name = "bak_content_1", type = ColType.TEXT) private String bakContent1; @Column(name = "bak_content_2", type = ColType.TEXT) private String bakContent2; public String getAlbumsContent() { return albumsContent; } public void setAlbumsContent(String albumsContent) { this.albumsContent = albumsContent; } public String getPhotosContent() { return photosContent; } public void setPhotosContent(String photosContent) { this.photosContent = photosContent; } public String getAdAContent() { return adAContent; } public void setAdAContent(String adAContent) { this.adAContent = adAContent; } public String getAdBContent() { return adBContent; } public void setAdBContent(String adBContent) { this.adBContent = adBContent; } public String getAdCContent() { return adCContent; } public void setAdCContent(String adCContent) { this.adCContent = adCContent; } public String getTextAContent() { return textAContent; } public void setTextAContent(String textAContent) { this.textAContent = textAContent; } public String getTextBContent() { return textBContent; } public void setTextBContent(String textBContent) { this.textBContent = textBContent; } public String getTextCContent() { return textCContent; } public void setTextCContent(String textCContent) { this.textCContent = textCContent; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Date getEffectiveStartDate() { return effectiveStartDate; } public void setEffectiveStartDate(Date effectiveStartDate) { this.effectiveStartDate = effectiveStartDate; } public Date getEffectiveEndDate() { return effectiveEndDate; } public void setEffectiveEndDate(Date effectiveEndDate) { this.effectiveEndDate = effectiveEndDate; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getLastModifyDate() { return lastModifyDate; } public void setLastModifyDate(Date lastModifyDate) { this.lastModifyDate = lastModifyDate; } public String getBakPhotosContent1() { return bakPhotosContent1; } public void setBakPhotosContent1(String bakPhotosContent1) { this.bakPhotosContent1 = bakPhotosContent1; } public String getBakAdContent1() { return bakAdContent1; } public void setBakAdContent1(String bakAdContent1) { this.bakAdContent1 = bakAdContent1; } public String getBakAdContent2() { return bakAdContent2; } public void setBakAdContent2(String bakAdContent2) { this.bakAdContent2 = bakAdContent2; } public String getBakTextContent1() { return bakTextContent1; } public void setBakTextContent1(String bakTextContent1) { this.bakTextContent1 = bakTextContent1; } public String getBakTextContent2() { return bakTextContent2; } public void setBakTextContent2(String bakTextContent2) { this.bakTextContent2 = bakTextContent2; } public String getBakContent1() { return bakContent1; } public void setBakContent1(String bakContent1) { this.bakContent1 = bakContent1; } public String getBakContent2() { return bakContent2; } public void setBakContent2(String bakContent2) { this.bakContent2 = bakContent2; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public String toString() { return ReflectionToStringBuilder.toString(this); } } <file_sep>package com.b5m.plugincms.common.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * file name:CollectionUtils.java * description: * <br/> * <br/> * <font> * 这个类是用来处理List Map等集合的一个工具类 * </font> * <br/> * <br/> * author: echo; * JDK version: <1.6.0> * project : plugin-cms <1.0> <br> * modified history <br> * date | author | desc <br> */ public class CollectionUtils { public static <T> List<T> newList(){ return new ArrayList<T>(); } public static <T> List<T> newList(T... ts){ List<T> list = newList(); for(T t : ts){ list.add(t); } return list; } public static <K, V> Map<K, V> newMap(){ return new HashMap<K, V>(); } public static <K, V> Map<K, V> newMap(K k, V v){ Map<K, V> map = newMap(); map.put(k, v); return map; } /** * description: * 获取一个List集合中以pageIndex为开始 pageSize大小的子集合 * @param list * @param pageSize * @param pageIndex * @return */ public static <T> List<T> subPage(List<T> list, int pageSize, int pageIndex){ int totalSize = list.size(); int totalPage = totalSize/pageSize; if(totalSize % pageSize != 0){ totalPage = totalPage + 1; } int toIndex = pageSize * pageIndex; if(totalSize < toIndex){ toIndex = totalSize; } List<T> sublist = new ArrayList<T>(); //如果开始的index 比 总数要大 则直接返回为空 int fromIndex = pageSize * (pageIndex-1); if(totalSize < fromIndex){ return sublist; }else{ for(int i = pageSize * (pageIndex-1); i < toIndex; i++){ sublist.add(list.get(i)); } return sublist; } } /** * description: * 获取一个List集合中以pageIndex为开始 pageSize大小的子集合 * @param list * @param pageSize * @param pageIndex * @return */ public static <T> List<T> subList(List<T> list, int startIndex, int endIndex){ int totalSize = list.size(); List<T> sublist = new ArrayList<T>(); if(totalSize < startIndex) return sublist; if(totalSize < endIndex) endIndex = totalSize; if(endIndex < startIndex) return sublist; for(int i = startIndex; i < endIndex; i++){ sublist.add(list.get(i)); } return sublist; } /** * description: * 获取集合以pageSize为每页大小的 总页数 * @param list * @param pageSize * @return */ public static int getTotalPage(List list, int pageSize){ int totalSize = list.size(); int totalPage = totalSize/pageSize; if(totalSize % pageSize != 0){ totalPage = totalPage + 1; } return totalPage; } /** * description: * 判断 o这个对象是否是List对象 * @param o * @return */ public static boolean isList(Object o){ if(o.getClass().getSimpleName().equals(List.class.getSimpleName())) return true; for(Class cls : o.getClass().getInterfaces()){ if(cls.getSimpleName().equals(List.class.getSimpleName())) return true; } return false; } /** * description: * 将map 转化成 List * @param map * @return * @date 2012-7-28 * @author xiuqing.weng */ public static <K, V> List<Map<K, V>> toList(Map<K, V> map){ List<Map<K, V>> list = newList(); for(K k : map.keySet()){ Map<K, V> m = newMap(); m.put(k, map.get(k)); list.add(m); } return list; } /** * description: * 取第一个,如果没有,则返回null * @param ts * @return */ public static <T> T first(List<T> ts){ if(ts.isEmpty()) return null; return ts.get(0); } } <file_sep>package com.b5m.plugincms.common.utils; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URLDecoder; import java.text.DecimalFormat; /** * @Company B5M.com * @description * 操作字符串的 工具类 * @author echo * @since 2013-7-12 * @email <EMAIL> */ public class StringUtils { public static String fillNull(String str){ return (str == null || isNaN(str) ? "" : str).trim(); } public static String fillNull(Object o){ if(o == null) return ""; return fillNull(o.toString()); } public static BigDecimal toBigDecimal(Object o){ if(o == null) return null; if(isEmpty(o.toString())) return null; return new BigDecimal(o.toString()); } public static boolean isNaN(String str){ if("NaN".equals(str)) return true; return false; } public static String toStrNotNull(Object o){ if(null != o) return o.toString(); return ""; } public static boolean isEmpty(String str) { if(str == null) return true; str = str.trim(); return "".equals(str); } public static boolean isNotEmpty(String str){ return !isEmpty(str); } public static String toString(BigDecimal value){ if(value == null) return "0.00"; return toCurrencyString(value.toString()); } /** * description: * 转化为币种 * @param value * @return * @date 2012-8-15 * @author xiuqing.weng */ public static String toCurrencyString(String value){ if(value == null) return "0.00"; DecimalFormat decimalFormat = new DecimalFormat("###,##0.00"); return decimalFormat.format(Double.valueOf(value)); } /** * description: * 通过文件路径地址获取文件名 * @param filePath * @return * @date 2012-8-14 * @author xiuqing.weng */ public static String getFileName(String filePath){ String url = filePath; if(url.indexOf("\\") >= 0) url = url.substring(url.lastIndexOf("\\") + 1);//如果是以\\结尾的按\\进行截取 if(url.indexOf("/") >= 0) url = url.substring(url.lastIndexOf("/") + 1);//如果是以/结尾的按/进行截取 try { return URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { return url; } } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.b5m</groupId> <artifactId>plugin-cms</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>plugin-cms</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.spring>3.0.6.RELEASE</version.spring> <version.spring.webmvc>3.0.5.RELEASE</version.spring.webmvc> <version.spring.h3>2.0.8</version.spring.h3> <version.spring.test>3.0.5.RELEASE</version.spring.test> <version.jstl>1.2</version.jstl> <version.mysql>5.1.6</version.mysql> <version.c3p0>0.9.1.2</version.c3p0> <version.servlet>2.5</version.servlet> <version.junit>4.10</version.junit> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.9</version> </dependency> <!-- spring框架的依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${version.spring.webmvc}</version> </dependency> <dependency> <groupId>com.b5m.dao</groupId> <artifactId>b5m-dao</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${version.spring.test}</version> <scope>test</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${version.jstl}</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <!-- Mysql的JDBC驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${version.mysql}</version> <scope>runtime</scope> </dependency> <!-- 数据池的依赖,c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${version.c3p0}</version> <scope>runtime</scope> </dependency> <!-- Servlet的依赖库 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${version.servlet}</version> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymockclassextension</artifactId> <version>3.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId> <version>3.1</version> <type>pom</type> <scope>test</scope> </dependency> </dependencies> </project>
c4741ba8c0c951e76b28027715aa3355a80f85b6
[ "Java", "Maven POM" ]
6
Java
echo-weng/plugin-cms
0d9d5e794b34c27e889b882ea3a0e652e9bb3943
446c9d8284ce49cb09a341f2e5246550aa52544a
refs/heads/master
<file_sep> #include <Windows.h> #include <gl/GL.h> #include <gl/GLU.h> #include <string> #pragma comment (lib, "OpenGL32.lib") #pragma comment (lib, "GLU32.lib") #define WINDOW_TITLE "OpenGL Window" void setPerspective(); void drawBg(); void drawRobot(); void drawSpike(); void drawBolt(); GLUquadricObj* myQuadricObject = gluNewQuadric(); int slices = 50; int stacks = 50; float camX = 0.5; float camY = 2.0; float camZ = 10.0; float lookX = 0.0; float lookY = 0.5; float lookZ = 0.0; float rotateX = 0.0; float rotateY = 0.0; float rotateZ = 0.0; float translateX = 0.0; float translateY = 0.0; float translateZ = 0.0; float lightX = 0.0; float lightY = -2.0; float lightZ = 5.0; float zoom = 1.0; GLuint texture = 0, texture_earth_spike = 1, texture_ocean = 2; BITMAP BMP; boolean draw_Spike = false, draw_bolt = false; float raise_Spike = -3.0, boltheight = 0.0, boltradius = 0.3; LRESULT WINAPI WindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_DESTROY: PostQuitMessage(0); break; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: { PostQuitMessage(0); break; } case 0x41: // A { camX -= 0.1; break; } case 0x44: // D { camX += 0.1; break; } case 0x57: // W { camY += 0.1; break; } case 0x53: // S { camY -= 0.1; break; } case 0x51: // Q { camZ -= 0.1; break; } case 0x45: // E { camZ += 0.1; break; } case 0x4A: // J { lookX -= 0.1; break; } case 0x4C: // L { lookX += 0.1; break; } case 0x49: // I { lookY += 0.1; break; } case 0x4B: // K { lookY -= 0.1; break; } case 0x55: // U { //lookZ += 0.1; if (zoom < 4.0) { zoom += 0.05; setPerspective(); } break; } case 0x4F: // O { //lookZ -= 0.1; if (zoom >= 0.25) { zoom -= 0.05; setPerspective(); } break; } case VK_LEFT: // LEFT { translateX += 0.1; break; } case VK_RIGHT: // RIGHT { translateX -= 0.1; break; } case VK_UP: // UP { translateZ += 0.1; break; } case VK_DOWN: // DOWN { translateZ -= 0.1; break; } case VK_OEM_COMMA: // , { translateY += 0.1; break; } case VK_OEM_PERIOD: // . { translateY -= 0.1; break; } case VK_NUMPAD1: // 1 { //lightX += 0.1; rotateY += 1; break; } case VK_NUMPAD3: // 3 { //lightX -= 0.1; rotateY -= 1; break; } case VK_NUMPAD5: // 5 { //lightY -= 0.1; rotateX += 1; break; } case VK_NUMPAD2: // 2 { //lightY += 0.1; rotateX -= 1; break; } case VK_NUMPAD4: // 4 { //lightZ -= 0.1; rotateZ += 0.1; break; } case VK_NUMPAD6: // 6 { //lightZ += 0.1; rotateZ -= 0.1; break; } case VK_SPACE: { camX = 0.0; camY = 0.0; camZ = 7.0; lookX = 0.0; lookY = 0.0; lookZ = 0.0; rotateX = 0.0; rotateY = 0.0; rotateZ = 0.0; translateX = 0.0; translateY = 0.0; translateZ = 0.0; lightX = 0.0; lightY = 0.0; lightZ = 2.0; zoom = 1.0; break; } case 0x31: { draw_Spike = !draw_Spike; raise_Spike = -3.0; break; } case 0x32: { draw_bolt = !draw_bolt; break; } break; } default: break; } return DefWindowProc(hWnd, msg, wParam, lParam); } //-------------------------------------------------------------------- bool initPixelFormat(HDC hdc) { PIXELFORMATDESCRIPTOR pfd; ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR)); pfd.cAlphaBits = 8; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.cStencilBits = 0; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iLayerType = PFD_MAIN_PLANE; pfd.iPixelType = PFD_TYPE_RGBA; pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; // choose pixel format returns the number most similar pixel format available int n = ChoosePixelFormat(hdc, &pfd); // set pixel format returns whether it sucessfully set the pixel format if (SetPixelFormat(hdc, n, &pfd)) { return true; } else { return false; } } //-------------------------------------------------------------------- void display() { //-------------------------------- // OpenGL drawing //-------------------------------- glMatrixMode(GL_MODELVIEW); glClearColor(0.2f, 0.2f, 0.2f, 0.2f); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glLoadIdentity(); gluLookAt(camX, camY, camZ, lookX, lookY, lookZ, 0.0, 1.0, 0.0); glRotatef(rotateX, 1, 0, 0); glRotatef(rotateY, 0, 1, 0); glRotatef(rotateZ, 0, 0, 1); GLfloat lightposition[] = { lightX, lightY, lightZ, 0.1 }; glLightfv(GL_LIGHT0, GL_POSITION, lightposition); GLfloat disfuse[] = { 0.7, 0.7, 0.7, 0 }; glLightfv(GL_LIGHT0, GL_DIFFUSE, disfuse); GLfloat ambient0[] = { 0.7, 0.7, 0.7, 0 }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambient0); drawRobot(); //-------------------------------- // // Draw Here // //-------------------------------- glTranslatef(translateX, translateY, translateZ); drawBg(); glLightfv(GL_LIGHT0, GL_AMBIENT, ambient0); glBegin(GL_QUADS); glColor3f(0.0, 0.0, 0.0); glVertex3f(-2.0, -1.0, 0.0); glVertex3f(-2.0, 1.0, 0.0); glVertex3f(0.0, 1.0, 0.0); glVertex3f(0.0, -1.0, 0.0); glEnd(); glBegin(GL_QUADS); glColor3f(1, 1, 1); glVertex3f(1.0, -1.0, 0.0); glVertex3f(1.0, 1.0, 0.0); glVertex3f(2.41421, 1.0, -1.41421); glVertex3f(2.41421, -1.0, -1.41421); glEnd(); //-------------------------------- // End of OpenGL drawing //-------------------------------- } //-------------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int nCmdShow) { WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.hInstance = GetModuleHandle(NULL); wc.lpfnWndProc = WindowProcedure; wc.lpszClassName = WINDOW_TITLE; wc.style = CS_HREDRAW | CS_VREDRAW; if (!RegisterClassEx(&wc)) return false; HWND hWnd = CreateWindow(WINDOW_TITLE, WINDOW_TITLE, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 800, NULL, NULL, wc.hInstance, NULL); //-------------------------------- // Initialize window for OpenGL //-------------------------------- HDC hdc = GetDC(hWnd); // initialize pixel format for the window initPixelFormat(hdc); // get an openGL context HGLRC hglrc = wglCreateContext(hdc); // make context current if (!wglMakeCurrent(hdc, hglrc)) return false; glEnable(GL_DEPTH_TEST); setPerspective(); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); HBITMAP hBMP = (HBITMAP)LoadImage(GetModuleHandle(NULL), "Sky.bmp", IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE); GetObject(hBMP, sizeof(BMP), &BMP); glEnable(GL_TEXTURE_2D); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, BMP.bmWidth, BMP.bmHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BMP.bmBits); glTexCoord2f(0.0f, 0.0f); HBITMAP hBMP2 = (HBITMAP)LoadImage(GetModuleHandle(NULL), "earth_spike.bmp", IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE); GetObject(hBMP2, sizeof(BMP), &BMP); glEnable(GL_TEXTURE_2D); glGenTextures(1, &texture_earth_spike); glBindTexture(GL_TEXTURE_2D, texture_earth_spike); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, BMP.bmWidth, BMP.bmHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BMP.bmBits); glTexCoord2f(0.0f, 0.0f); HBITMAP hBMP3 = (HBITMAP)LoadImage(GetModuleHandle(NULL), "ocean.bmp", IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE); GetObject(hBMP3, sizeof(BMP), &BMP); glEnable(GL_TEXTURE_2D); glGenTextures(1, &texture_ocean); glBindTexture(GL_TEXTURE_2D, texture_ocean); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, BMP.bmWidth, BMP.bmHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BMP.bmBits); glTexCoord2f(0.0f, 0.0f); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); //-------------------------------- // End initialization //-------------------------------- ShowWindow(hWnd, nCmdShow); MSG msg; ZeroMemory(&msg, sizeof(msg)); while (true) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } display(); SwapBuffers(hdc); } UnregisterClass(WINDOW_TITLE, wc.hInstance); return true; } void drawRobot() { /* glPushMatrix(); glColor3f(0.0, 1, 0.0); glRotatef(90, 1, 0, 0); gluSphere(myQuadricObject, 0.5, slices, stacks); glPopMatrix();*/ glPushMatrix(); glRotatef(45, 0, 1, 0); glColor3f(1.0, 0.0, 0.0); glBegin(GL_QUADS); glVertex3f(-0.5, 0.5, 0.5); glVertex3f(-0.5, -0.5, 0.5); glVertex3f(0.5, -0.5, 0.5); glVertex3f(0.5, 0.5, 0.5); glEnd(); glColor3f(0.0, 1.0, 0.0); glBegin(GL_QUADS); glVertex3f(0.5, 0.5, 0.5); glVertex3f(0.5, -0.5, 0.5); glVertex3f(0.5, -0.5, -0.5); glVertex3f(0.5, 0.5, -0.5); glEnd(); glColor3f(0.0, 0.0, 1.0); glBegin(GL_QUADS); glVertex3f(0.5, 0.5, -0.5); glVertex3f(0.5, -0.5, -0.5); glVertex3f(-0.5, -0.5, -0.5); glVertex3f(-0.5, 0.5, -0.5); glEnd(); glColor3f(1.0, 1.0, 0.0); glBegin(GL_QUADS); glVertex3f(-0.5, 0.5, -0.5); glVertex3f(-0.5, -0.5, -0.5); glVertex3f(-0.5, -0.5, 0.5); glVertex3f(-0.5, 0.5, 0.5); glEnd(); glColor3f(1.0, 0.0, 1.0); glBegin(GL_QUADS); glVertex3f(-0.5, 0.5, -0.5); glVertex3f(-0.5, 0.5, 0.5); glVertex3f(0.5, 0.5, 0.5); glVertex3f(0.5, 0.5, -0.5); glEnd(); glColor3f(0.0, 1.0, 1.0); glBegin(GL_QUADS); glVertex3f(0.5, -0.5, 0.5); glVertex3f(-0.5, -0.5, 0.5); glVertex3f(-0.5, -0.5, -0.5); glVertex3f(0.5, -0.5, -0.5); glEnd(); glPopMatrix(); if (draw_Spike) drawSpike(); if (draw_bolt || boltheight >= 0.0) drawBolt(); } void drawSpike() { gluQuadricDrawStyle(myQuadricObject, GLU_FILL); gluQuadricNormals(myQuadricObject, GLU_SMOOTH); gluQuadricOrientation(myQuadricObject, GLU_INSIDE); gluQuadricTexture(myQuadricObject, GL_TRUE); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture_earth_spike); if (raise_Spike <= 0.0) raise_Spike += 0.03; glPushMatrix(); glTranslatef(0, -1.2 + raise_Spike, 0); glPushMatrix(); glTranslatef(1.5, 0, 2.95); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.16, 0.0, 2.0, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(1.0, 0, 2.28); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.11, 0.0, 1.8, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(0.5, 0, 2.38); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.08, 0.0, 1.6, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, 0, 2.53); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.06, 0.0, 1.5, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-0.5, 0, 2.24); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.13, 0.0, 1.9, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-1.0, 0, 2.12); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.1, 0.0, 1.6, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0, 2.85); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.2, 0.0, 1.2, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(1.5, 0, 1.70); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.08, 0.0, 1.6, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(1.0, 0, 1.48); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.06, 0.0, 1.5, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(0.5, 0, 1.38); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.16, 0.0, 2.0, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, 0, 1.53); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.11, 0.0, 1.8, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-0.5, 0, 1.44); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.13, 0.0, 1.9, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-1.0, 0, 1.32); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.2, 0.0, 1.2, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0, 1.65); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.1, 0.0, 1.6, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(1.5, 0, 3.50); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.08, 0.0, 1.6, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(1.0, 0, 3.28); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.1, 0.0, 1.6, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(0.5, 0, 3.18); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.2, 0.0, 1.2, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, 0, 3.33); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.11, 0.0, 1.8, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-0.5, 0, 3.24); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.13, 0.0, 1.9, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-1.0, 0, 3.12); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.06, 0.0, 1.5, 20, 20); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0, 3.45); glRotatef(-90, 1, 0, 0); gluCylinder(myQuadricObject, 0.16, 0.0, 2.0, 20, 20); glPopMatrix(); glPopMatrix(); glDisable(GL_TEXTURE_2D); } void drawBolt() { gluQuadricDrawStyle(myQuadricObject, GLU_FILL); gluQuadricNormals(myQuadricObject, GLU_SMOOTH); gluQuadricOrientation(myQuadricObject, GLU_INSIDE); gluQuadricTexture(myQuadricObject, GL_TRUE); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture_ocean); glPushMatrix(); if (boltheight < 20 && draw_bolt) { boltheight += 0.02; } else if (boltheight > 0.0 && !draw_bolt) { boltheight -= 0.02; glTranslatef(0, 0, 20); glRotatef(180, 1, 0, 0); } glColor3f(0.678, 0.847, 0.902); gluCylinder(myQuadricObject, boltradius, boltradius, boltheight, 50, 50); glDisable(GL_TEXTURE_2D); glColor3f(0, 0, 1.0); glLineWidth(10.0f); glBegin(GL_LINE_STRIP); for (float z = 0.0, angle = 0; z < boltheight; z+=0.05, angle+=0.1) { glVertex3f((boltradius + 0.01) * sin(angle), (boltradius +0.01) * cos(angle), z); } glEnd(); glPopMatrix(); } void setPerspective() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45 / zoom, 1, 1, 100); } void drawBg() { glPushMatrix(); glColor3f(0.8, 0.6, 0.3); glScalef(30, 1, 30); glBegin(GL_QUADS); glVertex3f(-1, -1, 1); glVertex3f(1, -1, 1); glVertex3f(1, -1, -1); glVertex3f(-1, -1, -1); glEnd(); glPopMatrix(); gluQuadricDrawStyle(myQuadricObject, GLU_FILL); gluQuadricNormals(myQuadricObject, GLU_SMOOTH); gluQuadricOrientation(myQuadricObject, GLU_INSIDE); gluQuadricTexture(myQuadricObject, GL_TRUE); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); GLfloat ambient1[] = { 1.0, 1.0, 1.0, 0 }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambient1); glPushMatrix(); glScalef(30, 5, 30); glTranslated(0, -0.4, 0); glRotatef(75, 0, 1, 0); glRotatef(270, 1, 0, 0); // glColor3f(1.0, 0.3, 0.2); gluCylinder(myQuadricObject, 1.0, 1.0, 15.0, slices, stacks); glPopMatrix(); glDisable(GL_TEXTURE_2D); } //--------------------------------------------------------------------
2a48298613e4627eb37ec6ccb08d58ef5d4436d6
[ "C++" ]
1
C++
TkTioNG/Robots
f9b8a8cfbc8e8bcff9d0862403051573f33d2f41
27e17ae0204a510b9e6acb652e344e5208ef2e82
refs/heads/main
<repo_name>NishantGhanate/react-learning<file_sep>/router-app/README.md ## https://reactrouter.com/web/guides/quick-start ## https://reacttraining.com/react-router/web/example/auth-workflow <file_sep>/hoc-menu/src/MenuHoc.js import React , {Component} from "react" import {withToggler} from "./hocs/withToggler" class MenuHoc extends Component{ render(){ console.log(this.props) return( <div> <button onClick={this.props.toggle}> {this.props.on ? "Show" : "Hide"} Menu </button> <nav style={{display : this.props.on ? "block" : "none"}}> <h6>Menu with HOC </h6> <span>{this.props.on}</span> </nav> </div> ) } } export default withToggler(MenuHoc,{defaultOnValue: true}) // const SuperchargedFavoriteComponent = withToggler(MenuHoc) // export default SuperchargedFavoriteComponent <file_sep>/context-app/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import App1 from "./App1" import FormApp from "./form/App" import {UserContextProvider as FormContextProivder} from "./form/userContext" import UserContext from "./userContext" import {ThemeContextProvider} from "./themeContext" ReactDOM.render( <div> <UserContext.Provider value = {"dark"}> <App/> </UserContext.Provider> <hr/> <ThemeContextProvider> <App1/> </ThemeContextProvider> <hr/> <FormContextProivder> <FormApp/> </FormContextProivder> </div> ,document.getElementById('root') ); <file_sep>/README.MD ## REACT-JS ```sh Summary : This repo contains a list of react-js apps from easy to advanced which I have learnt from scrimba platform . Thanks to my friend who motivated me to learn react : https://github.com/SandeepGamot ```` ## List of apps: > 1 &nbsp; [counter-app](https://github.com/NishantGhanate/react-learning/tree/main/counter-app) > 2 &nbsp; [card-default-props](https://github.com/NishantGhanate/react-learning/tree/main/card-default-prop) > 3 &nbsp; [hoc-menu](https://github.com/NishantGhanate/react-learning/tree/main/hoc-menu) > 4 &nbsp; [component-tree](https://github.com/NishantGhanate/react-learning/tree/main/component-tree) > 5 &nbsp; [context-app](https://github.com/NishantGhanate/react-learning/tree/main/context-app) > 6 &nbsp; [speed-typing-game](https://github.com/NishantGhanate/react-learning/tree/main/speed-typing-game) > 7 &nbsp; [router-app](https://github.com/NishantGhanate/react-learning/tree/main/router-app) > 8 &nbsp; [pics-cart](https://github.com/NishantGhanate/react-learning/tree/main/pics-cart) > 9 &nbsp; [pics-cart](https://github.com/NishantGhanate/react-learning/tree/main/todo-list)<file_sep>/context-app/src/Button1.js import React from "react" import PropTypes from "prop-types" function Button1(props){ console.log(props) const {theme , toggleTheme } = props.context return( <button onClick={toggleTheme} className={`${theme}-theme`}> {theme} Theme</button> ) } Button1.propTypes = { theme: PropTypes.oneOf(["light", "dark"]) } Button1.defaultProps = { theme: "light" } export default Button1<file_sep>/component-tree/README.md # Component Tree ### 1. shouldComponentUpdate ```sh Update child components whenever top level node values changes. This is done by comparing state / data value in child nodes. ``` <hr/> ### 2. PureComponent ```sh It automatically implements the above function and take cares of props equality check. File : GrandParent1.js ``` <hr/> ### 3. React.memo ```sh This is cache based quick refernce lookup on props data for functional components File : functional_components/GrandParentFun.js ``` <hr/><file_sep>/context-app/README.md # Context-app ```sh React.context allows you to directly pass props to reciever, If a n-th child needs data from root node then props needs to be passed from root to n-th child while intermediate nodes has no use of the props and thus acting as tunnel to the pass props. With React.context There is Context provider & consumer which eleminates props tunneling by directly passing props to to required node. ``` ## https://reactjs.org/docs/context.html#before-you-use-context<file_sep>/component-tree/src/functional_components/GrandChildFun.js import React from "react" function GrandChildFun(props) { console.log("[ ] [ ] [ ] [👶🏻] rendered") return ( <div> <p>I'm a GrandChild Function Component</p> </div> ) } export default GrandChildFun<file_sep>/router-app/src/pages/services/ServicesDetail.js import React from "react" import {useParams} from "react-router-dom" import ServicesData from "./ServicesData" function ServicesDetail(){ const {serviceId} = useParams() console.log(serviceId) // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find const thisService = ServicesData.find(service => service._id === serviceId) return( <div> <h1> Service detail page</h1> {thisService.name} - {thisService.description} </div> ) } export default ServicesDetail<file_sep>/hoc-menu/README.md # Higher Order Component ```sh What is an HOC? A Higher Order Component can be described as functionality enhancer, HOC itself is an component which takes another component as a paramter and add new functional, state logic to the passed component . ``` <file_sep>/hoc-menu/src/MenuToggle.js import React from "react" function MenuToggle(props){ return( <div> <button onClick={props.toggle}> {props.on ? "Show" : "Hide"} Menu </button> <nav style={{display : props.on ? "block" : "none"}}> <span>Using Toggle Component to logic & data to MenuToggle </span> </nav> </div> ) } export default MenuToggle<file_sep>/todo-list/src/components/TodoForm.js import {useState, useContext} from "react" import {Context} from "../Context" function TodoForm(props){ const [input, setInput] = useState({id:null,text:'',isCompleted:false}) const [id, setId] = useState(0) const {addTodo} = useContext(Context) const handleSubmit = (e) => { e.preventDefault() console.log(id) input.id = id addTodo(input) // add input obj to Context todoItems setInput((prevState)=> { return({ ...prevState, id:null, text: '', isCompleted:false }) }) increment() } const increment = () => { setId(id+1) } const handleInput = (e) => { const {value} = e.target console.log(input) setInput((prevState)=> { return({ ...prevState, text: value, }) }) } return( <form className="todo-form" onSubmit={handleSubmit}> <input className="todo-input" type="text" name="input" placeholder="Add Todo item" value={input.text} onChange={handleInput} /> <button className="todo-button" type="submit"> Add </button> </form> ) } export default TodoForm<file_sep>/todo-list/src/pages/TodoPage.js import TodoForm from "../components/TodoForm" import TodoList from "../components/TodoList" function TodoPage(params) { return( <div> <h1>Yo! What's the Plan for Today?</h1> <TodoForm/> <TodoList/> </div> ) } export default TodoPage<file_sep>/card-default-prop/src/Card.js import React from "react" import PropTypes from "prop-types" function Card(props){ const styles = { backgroundColor : props.cardColor, height : props.height, width : props.width, } return( <div style = {styles}></div> ) } // validators Card.propTypes = { cardColor : PropTypes.string.isRequired, height : PropTypes.oneOf([170,150]).isRequired, width : PropTypes.number } Card.defaultProps = { height : 100, width : 100 } export default Card<file_sep>/todo-list/src/Context.js import React, {useState} from "react" const Context = React.createContext() function TodoContextProvider({children}){ const [todoItems, setTodoItems] = useState([]) function addTodo(input){ setTodoItems(() => ([...todoItems,input]) ) } console.log(todoItems) function editTodo(id,value){ const updatedTodos = todoItems.map((item) => { if (item.id === id){ console.log(id) return{ ...item, text:value } } return item }) setTodoItems(updatedTodos) } function toggleTodo(id){ const updatedTodos = todoItems.map((item) => { if (item.id === id){ console.log(id) return{...item, isCompleted:!item.isCompleted} } return item }) setTodoItems(updatedTodos) } function removeTodo(id){ setTodoItems(prevItems => prevItems.filter(item => item.id !== id)) } function clearTodoList(){ setTodoItems([]) } return( <Context.Provider value={ { todoItems, addTodo, editTodo, toggleTodo, removeTodo, clearTodoList }}> {children} </Context.Provider> ) } export {TodoContextProvider,Context}<file_sep>/context-app/src/App1.js import React, {Component} from "react" import Button1 from "./Button1" import Header1 from "./Header1" import {ThemeContextConsumer} from "./themeContext" class App1 extends Component{ render(){ return( <div> <main> <p> Hello from html App1 </p> </main> <ThemeContextConsumer> {context =>( <Header1 context={context} /> )} </ThemeContextConsumer> <ThemeContextConsumer> {context =>( <Button1 context={context} /> )} </ThemeContextConsumer> </div> ) } } export default App1; <file_sep>/pics-cart/README.md https://cdn.jsdelivr.net/npm/remixicon@2.3.0/fonts/remixicon.css # 1 Challenge Set up the Context for our app. 1. In a new file, create a new context with React 2. In that same file, create a custom component that renders the Provider of the context you created 3. For now, just pass in an empty string "" as the context provider's value prop 4. Export the custom Provider component and the full context object (so we can pass it to the useContext hook eventually) 5. Set up your index.js to use the custom context Provider you created. (You can wrap it as a parent of the Router component) # 2 Challenge Add state to our context and pass it through the Provider 1. Add state to hold the array of all photos our app gets from the API 2. Pass the array of all photos through the value of the provider so it's available anywhere the app accesses the context # 3 Challenge Get the JSON data with the photos information from the API and save it to context state 1. As soon as the ContextProvider component renders, get the JSON data from this url: https://raw.githubusercontent.com/bobziroll/scrimba-react-bootcamp-images/master/images.json 2. Save the array of data that comes back to state. Review data fetching in React using `fetch`: https://scrimba.com/p/p7P5Hd/c79Jask # 4 Add to cart Change the plus icon to a full shopping cart icon when an image is already in the cart. This should display whether the image is being hovered or not (like the favorite icon). Icon to use when item already in cart: <i className="ri-shopping-cart-fill cart"></i> Hints: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://stackoverflow.com/a/8217584 # 5 Sum # Challenge Calculate the total cost of the items in the cart and display it on the Cart page 1. Usually the item in the database will have it's own cost saved, but we're assuming every item we sell costs $5.99, so you can just hard code that cost in 2. To very easily display the total cost in US dollars (or whatever currency you want), use the following: `<number>.toLocaleString("en-US", {style: "currency", currency: "USD"})` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString <file_sep>/todo-list/README.md # Todo react app using useContext hook <file_sep>/router-app/src/profile/Profile.js import React from "react" import {Link, Switch, Route, useRouteMatch} from "react-router-dom" import Info from "./Info" import Settings from "./Settings" function Profile() { const {path, url} = useRouteMatch() return( <div> <h1>Profile page</h1> <br/> <ul> <li> <Link to={`${url}/info`}> Info </Link> </li> <li> <Link to={`${url}/settings`}> Settings </Link> </li> </ul> <Switch> <Route path={`${path}/info`}> <Info/> </Route> <Route path={`${path}/settings`}> <Settings/> </Route> </Switch> </div> ) } export default Profile<file_sep>/component-tree/src/functional_components/ChildFun.js import React from "react" import GrandChildFun from "./GrandChildFun" function ChildFun() { console.log("[ ] [ ] [🧒🏻] [ ] rendered") return ( <div> <p>I'm a Child Function Component</p> <GrandChildFun /> <GrandChildFun /> </div> ) } export default ChildFun<file_sep>/hoc-menu/src/App.js import React from "react" import Menu from "./Menu" import Favorite from "./Favorite" import MenuHoc from "./MenuHoc" import FavoriteHoc from "./FavoriteHoc" import FavoriteHocFun from "./FavoriteHocFun" import FavoriteToggle from "./FavoriteToggle" import MenuToggle from "./MenuToggle" import Toggle from "./Toggle" function App() { return( <div> <Menu/> <Favorite/> <hr/> <MenuHoc/> <FavoriteHoc/> <hr/> <FavoriteHocFun/> <hr/> <FavoriteToggle/> <hr/> {/* <Toggle defaultOnValue={true}> { ({on,toggle}) => { return( <MenuToggle on={on} toggle={toggle}/> ) } } </Toggle> */} </div> ) } export default App; <file_sep>/component-tree/src/functional_components/GrandParentFun.js import React from "react" import ParentFun from "./ParentFun" function GrandParentFun(props) { console.log("[👴🏼] [ ] [ ] [ ] rendered") return ( <div> <p>I'm a GrandParent Function Component</p> <ParentFun /> <ParentFun /> </div> ) } export default React.memo(GrandParentFun)<file_sep>/hoc-menu/src/hocs/withToggler.js import React, {Component} from "react" /* A higher order function takes compoent as parameter to add new features to it Naming convection starts from [ with ] prefix, inline export, nested function */ class Toggler extends Component{ state = { on : this.props.defaultOnValue } toggle = () =>{ this.setState(prevState => { return { on : !prevState.on } }) } render(){ const {component: C, defaultOnValue, ...props} = this.props return( <C on={this.state.on} toggle={this.toggle} {...this.props}/> ) } } export function withToggler(component, optionsObj){ // TODO: add some default value in optionsObj if key doesn't exists return function(props){ return( <Toggler component = {component} defaultOnValue = {optionsObj.defaultOnValue} {...props}/> ) } } <file_sep>/card-default-prop/README.md ## Learning about : ```sh 1. Function & class based default props 2. PropsTypes & validation 3. Components Re-use ``` ### Document : [source link ](https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes) <file_sep>/hoc-menu/src/FavoriteHocFun.js import React from "react" import {withToggler} from "./hocs/withToggler" function FavoriteHocFun(props){ return( <div> <h3>Click on heart to favorite </h3> <h1> <span onClick={props.toggle}> {props.on ? "❤️" : "♡"} </span> </h1> <p>This is with Function based HOC </p> </div> ) } export default withToggler(FavoriteHocFun,{defaultOnValue: true}) <file_sep>/hoc-menu/src/Menu.js import React , {Component} from "react" class Menu extends Component{ state = { show : false } toggleShow = () =>{ this.setState(prevState => { return{ show : !prevState.show } }) } render(){ return( <div> <button onClick={this.toggleShow}> {this.state.show ? "Show" : "Hide"} Menu </button> <nav style={{display : this.state.show ? "block" : "none"}}> <h6>Signed as somevar</h6> <span>profile : </span> </nav> </div> ) } } export default Menu<file_sep>/router-app/src/pages/services/ServicesList.js import React from "react" import {Link} from "react-router-dom" import ServicesData from "./ServicesData" function ServicesList(){ const services = ServicesData.map(service => ( <h3 key={service._id}> <Link to={`/services/${service._id}`}> {service.name} </Link> -{service.price} </h3> )) return( <div> <h1> Services list page </h1> {services} </div> ) } export default ServicesList<file_sep>/router-app/src/profile/Settings.js import React from "react" function Settings(params) { return( <div> <h1>Profile settings loaded </h1> </div> ) } export default Settings<file_sep>/router-app/src/pages/services/ServicesData.js export default [ { "name": "<NAME>", "price": 69, "_id": "1", "description": "Phir yera pheri boi." }, { "name": "<NAME>", "price": 420, "_id": "2", "description": "Awara Paagal Deewana (2002) - Johnny Lever as Chhota ..." }, { "name": "Weeding", "price": 50, "_id": "3", "description": "Don't let the invaders ruin your yard." }, { "name": "<NAME>", "price": 100, "_id": "4", "description": "Keep your irrigation system top-notch." } ]<file_sep>/card-default-prop/src/App.js import React from "react" import Card from "./Card" import CardClass from "./CardClass" import RoundImage from "./RoundImage" import Banner from "./Banner" function App(){ return( <div> <Card cardColor='Purple' height={150} width={150}/> <CardClass cardColor='Maroon' height={150} width={150}/> <RoundImage src="https://picsum.photos/id/237/300/300" borderRadius="10px"/> <Banner headline="Data from props"> <p>Some harcoded text </p> </Banner> <Banner > <RoundImage src="https://picsum.photos/id/237/300/300" borderRadius="10px"/> <figcaption>Just look at those innocent eyes !</figcaption> </Banner> </div> ) } export default App; <file_sep>/card-default-prop/src/RoundImage.js import React from "react" import PropTypes from 'prop-types' function RoundImage(props){ return( <img src={props.src} alt="doggo" style={{borderRadius: props.borderRadius}} className="round-img" /> ) } RoundImage.propTypes = { src : PropTypes.string.isRequired } RoundImage.defaultProps = { borderRadius : "50px" } export default RoundImage
f7539e4ee02f11db1cba780aff6fdce993e26a79
[ "Markdown", "JavaScript" ]
31
Markdown
NishantGhanate/react-learning
d0a2d21df8a2a4cc7f0974b739aa1e7ec40728b2
1bb079850cbeda761f0d75803fa4766802342596
refs/heads/master
<repo_name>KidA001/soundfound<file_sep>/Gemfile source 'https://rubygems.org' # ruby '2.1.1' ruby '2.0.0' # PostgreSQL driver gem 'pg' gem 'shotgun' gem 'awesome_print' # Sinatra driver gem 'sinatra' gem 'sinatra-contrib' gem 'bcrypt-ruby' gem 'httparty' gem 'sidekiq' # Use Thin for our web server gem 'thin' gem 'soundcloud' gem 'activesupport', '~>4.1' gem 'activerecord', '~>4.1' gem 'rake' group :test do gem 'shoulda-matchers' gem 'rack-test' end group :test, :development do gem 'dotenv' gem 'debugger' gem 'rspec' gem 'factory_girl' gem 'faker' end <file_sep>/db/migrate/20150118115800_create_tracks.rb class CreateTracks < ActiveRecord::Migration def change create_table :tracks do |t| t.integer :soundcloud_track_id t.integer :duration t.boolean :downloadable t.string :url t.string :genre t.string :tags t.string :title t.integer :bpm t.datetime :posted_at t.string :art_url t.integer :play_count t.integer :likes_count t.string :artists_soundcloud_username t.integer :artists_soundcloud_id t.string :embedable_by t.timestamps end end end <file_sep>/app/controllers/index.rb get '/authenticate' do get_authentication redirect '/close' end get '/close' do erb :close end get '/' do erb :index end get '/load_known_tracks' do current_user.load_known_tracks redirect '/' end get '/build_recommendations' do current_user.build_recommendations redirect '/tracks' end get '/login' do redirect authenticate_url end get '/logout' do clear_session redirect '/' end get '/tracks' do current_user.load_known_tracks @track_data = current_user.users_tracks if current_user if current_user status 201 erb :tracks, layout: false else redirect '/' end end post '/like/:sc_id' do soundcloud_user.put("/me/favorites/#{params[:sc_id]}") update_discovery status 201 "Nice! We've added #{@track.title} to your SoundCloud Likes." end post '/nolike/:sc_id' do update_discovery status 201 "We won't show you #{@track.title} again." end get '/bubbles' do erb :bubbles, layout: false end get '/magic' do status 201 make_magic.to_json end get '/oembed/:sc_id' do oembed_html = get_oembed status 400 if oembed_html.nil? status 200 oembed_html end <file_sep>/db/migrate/20150118115900_create_displays.rb class CreateDisplays < ActiveRecord::Migration def change create_table :displays do |t| t.belongs_to :user, index:true t.belongs_to :track, index:true t.boolean :display, default: true t.integer :soundcloud_track_id t.integer :result_count, default: 0 t.timestamps end end end <file_sep>/app/models/sc_helper.rb module SCHelper extend self def parse_track(track) {soundcloud_track_id: track["id"], #not working? artists_soundcloud_username: track["user"]["username"], artists_soundcloud_id: track["user"]["id"], duration: track["duration"], downloadable: track["downloadable"], url: track["permalink_url"], genre: track["genre"], tags: track["tag_list"], title: track["title"], bpm: track["bpm"], posted_at: track["created_at"], art_url: track["artwork_url"], play_count: track["playback_count"], likes_count: track["favoritings_count"], embedable_by: track["embeddable_by"], artists_avatar_url: track["user"]["avatar_url"], waveform_url: track["waveform_url"]} end def soundcloud_user Soundcloud.new(access_token: self.access_token) if self.access_token end def client_id ENV['SC_CLIENT_ID'] end end <file_sep>/db/migrate/20150202083600_add_artistsavatarurl_to_tracks.rb class AddArtistsavatarurlToTracks < ActiveRecord::Migration def change add_column :tracks, :artists_avatar_url, :string end end<file_sep>/app/helpers/helpers.rb helpers do def soundcloud_client Soundcloud.new(client_id: ENV['SC_CLIENT_ID'], client_secret: ENV['SC_CLIENT_SECRET'], redirect_uri: ENV['SC_REDIRECT_URL']) end def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def current_users_avatar current_user.avatar_url.gsub("large","badge") if current_user end def soundcloud_user Soundcloud.new(access_token: current_user.access_token) if current_user end def user_exists? User.find_by(soundcloud_user_id: @sc_id) != nil end def create_session session[:user_id] = User.find_by(soundcloud_user_id: @sc_id).id end def clear_session session.delete(:user_id) @current_user = nil end def get_authentication puts "got to helper authenticate" @sc_user_keys = soundcloud_client.exchange_token(code: params[:code]) @sc_id = Soundcloud.new(access_token: @sc_user_keys.access_token).get('/me').id user_exists? ? create_session : create_user end def create_user user = User.create(soundcloud_user_id: @sc_id) create_session user.update_attributes(access_token: @sc_user_keys.access_token, name: Soundcloud.new(access_token: @sc_user_keys.access_token).get('/me').full_name, username: Soundcloud.new(access_token: @sc_user_keys.access_token).get('/me').username, avatar_url: Soundcloud.new(access_token: @sc_user_keys.access_token).get('/me').avatar_url) current_user.build_recommendations end def client_id return ENV['SC_CLIENT_ID'] end def authenticate_url "https://soundcloud.com/connect?scope=non-expiring&response_type=code&display=popup&client_id=#{ENV['SC_CLIENT_ID']}&redirect_uri=#{ENV['SC_REDIRECT_URL']}&" end def update_discovery @track = Track.find_by(soundcloud_track_id: params[:sc_id]) p @track p params p "*********************" discovery = Display.find_or_create_by(track_id: @track.id, user_id: current_user.id) discovery.update_attributes(display: false) end def make_magic query = "SELECT tracks.artists_soundcloud_username as artist, count(tracks.artists_soundcloud_username) as likes FROM tracks INNER JOIN displays ON tracks.id = displays.track_id WHERE displays.user_id = #{current_user.id} GROUP BY tracks.artists_soundcloud_username" results = ActiveRecord::Base.connection.execute(query) all_results = [] results.each do |result| hex = "#" + "%06x" % (rand * 0xffffff) result["hex"] = hex all_results << result end all_results end def get_oembed track = Track.find_by(soundcloud_track_id: params[:sc_id]) if track.oembed.nil? oembed_info = soundcloud_client.get('/oembed', :url => track.url, :maxwidth => "600px", :maxheight => "145px", :auto_play => true) track.update_attributes(oembed: oembed_info['html']) oembed_info['html'] else track.oembed end end end <file_sep>/app/models/HardWorker.rb require 'rubygems' require 'uri' require 'pathname' require 'soundcloud' require 'json' require 'awesome_print' require 'sidekiq' require 'sidekiq/web' require 'redis' require 'sidekiq/api' require 'pg' require 'active_record' require 'logger' require 'erb' require 'bcrypt' require 'HTTParty' require_relative 'user' class HardWorker include Sidekiq::Worker def perform(user_id = nil) # ActiveRecord::Base.User.connection # User.connection # User.connection user = User.find(user_id) user.update_attributes(background_job_running: true) ####################### user.build_recommendations(true) #DAT WORK ####################### user.update_attributes(all_tracks_ready: true) user.update_attributes(background_job_running: false) end end <file_sep>/SoundCloudPseudocode.md # Song recomendation * Get a list of the client's liked Songs * From that list of Artists && From Artists they're following * Get a list of THEIR(The artist's) liked tracks * Create instances of a song linked to that user * If entry for that song exists, add a +1 to a counter, returned_count * Primary sort by returned_count * Secondary sort by # of likes * Tertiary sort by Post Date * Exclude results that the user has already thumbs down(Ref table in local DB) # ToDos * Change Displays table to Discoveries * Add Suggested Artist field and start tracking * When song ends, it plays the next one. * How do I fucking know that? SC tell me? * Sorting * Show me more popular music * Filter by Tags * Ban likes from certain artist * Show which artist/user liked that song * Tracks that are selected display as photos, elegantly and responsively. - DONE * On hover a transparent overlay with a play button fades in/out * on click-down it lights up * When a song is clicked to play, it opens at the bottom of the screen - DONE * Transparent overlay * If you click anywhere on the site, it will keep playing (ajax...in layout) * Still have some control to like, unlike music * Loading animation when * Ajax call to load_known_tracks * Ajax call to Build recomendations * Page loads in AJAX * When tracks display use fade in * On load of show tracks, hide them, then iterate through and fade each one in * Show More * logic * Fix max width * Maybe you can sort in search query? * get('/tracks', created_at={'from':'2013-01-01 00:00:00','to':'2013-01-07 00:00:00'}, genre='house', types=['recording','remix','original'], limit=limit_size, offset=offset) # Open Questions * How to handle all teh trakz * Show loading percentage * number of artists * Divide by artists array index that you are getting liked tracks from * Don't show user songs from artists they are following? Too limiting. * With find or create by...what if attributes change. How can have it find by a few fields - DONE * Legit question. Download status may change, may change genre...etc. * Maybe just find/create by the soudncloud track id...but how to pass it other info... * Edge case for user who has 0 likes? * What sorting can I get from soundcloud API call? -None? * Offset....how can I build this logic? - DONE * Handle bad response...downtime? Check HTTP Response? * Handle 403 for oEmbed # Other Notes: * Optimize logic in View like the memoization of oembed...etc * Setup oAuth...no user login - DONE * Update current user, session, logout to what stu showed you for dynamic todos - DONE * Use d3 to display data * Artists you like (based on liked songs + following) * Artists your artists like * Load user's liked & reposted songs into DB - DONE, 'cept reposts * Don't ever show them these songs in their results * Scrape reposts??? * Change ID's to soundcloud_id instead of track_id...shits too confusing - DONE * Are results actually being ordered by 'hotness'? - NO * NO, feature disabled. Manually calculate hotness by: favoritings\_count and playback\_count. * Add DB Validations to stop duplicates * How does this work with a Display/Discovery for another user? - TESTED, fine. * Test by: Creating a new SC User, following an artists who's song is already(false) - TESTED, FINE * ^^FUCK THAT^^ Make your own entries in the DB and test it that way - TESTED, FINE # Code Snippets ```ruby "/users/{id}/followings" #list of users who are followed by the user profile = soundcloud_user.get('/me') favorites = soundcloud_user.get('/me/favorites', :limit => 200) def get_liked_tracks JSON.parse(`curl http://api.soundcloud.com/users/#{soundcloud_user.id}/favorites?client_id=#{client_id}&limit=200`) end #Can order by hotness tracks = soundcloud_user.get("/me/favorites", order: 'hotness', :limit => 25) - nope oEmbed: <% embed_info = soundcloud_client.get('/oembed', :url => track.url) %> <%= embed_info['html'] %> $(document).ready(function () { $('#popoverData').popover(); $('#popoverOption').popover({ trigger: "hover" }); }); <a id="popoverData" class="btn" href="#" data-content="ya fucked up" rel="popover" data-placement="bottom" data-original-title="Title" data-trigger="hover">Thumb Up</a> ``` # User Stories: ## As a user: * I want to find new music that is relevant * I don't want to see songs I've already liked or reposted * I don't want to see songs I've told you I don't like * I sort by posted date, likes, reposts, genre, BPM, downloadable # P10 Learnings * Offset * Find or Create By with Changing Data from API (play count...etc) * API downtime * Simple design = easier * Don't let the user see/experience the complexity * Efficient data <% if track.oembed.nil? %> <% embed_info = soundcloud_client.get('/oembed', :url => track.url, :maxwidth => "200px", :maxheight => "200px") %> <% track.update_attributes(oembed: embed_info['html']) %> Brian: 1214446 Adell: 13054612<file_sep>/app/models/track.rb class Track < ActiveRecord::Base has_many :displays, dependent: :destroy has_many :users, through: :displays end <file_sep>/sidekiq/config.ru require 'sidekiq' Sidekiq.configure_server do |config| database_url = ENV['DATABASE_URL'] if database_url ENV['DATABASE_URL'] = "#{database_url}?pool=25" ActiveRecord::Base.establish_connection end end Sidekiq.configure_client do |config| config.redis = { :size => 1 } end require 'sidekiq/web' run Sidekiq::Web <file_sep>/app/models/user.rb require_relative "sc_helper" class User < ActiveRecord::Base has_many :displays, dependent: :destroy has_many :tracks, through: :displays include BCrypt include SCHelper include HTTParty def password @password ||= <PASSWORD>(password_<PASSWORD>) end def password=(new_<PASSWORD>) @password = Password.<PASSWORD>(new_<PASSWORD>) self.password_hash = @password end def load_known_tracks query_size[:known_tracks].call liked_tracks_for(self.soundcloud_user_id).each do |track| inst_of_track = find_or_create(parse_track(track)) set_discovery(inst_of_track) end end def build_recommendations(size = :small) query_size[size].call prepare_tracks clean_data! end def users_tracks tracks = [] genre = [] artists = [] self.displays.where(display: true).limit(@query_limit).each do |display| #set magic order? curr_track = Track.find(display.track_id) tracks << curr_track genre.push(curr_track.genre) unless curr_track.genre == "" artists << curr_track.artists_soundcloud_username end {tracks: tracks.sample(9), genres: genre.uniq, artists: artists} #fuck the genres and artits for now end # private def query_size { small: ->{ @query_limit, @offset_limit, @sc_result_offset, @followings = 30, 20, 10, 50}, large: ->{ @query_limit, @offset_limit, @sc_result_offset, @followings = 400, 200, 100, 100}, known_tracks: ->{ @offset_limit, @sc_result_offset = 400, 200}} end def clean_data! destroy_unstreamable! destroy_nil_waveforms! update_nil_art! destroy_unpopular! end def find_or_create(track) result = Track.find_by(soundcloud_track_id: track[:soundcloud_track_id]) result.nil? ? self.tracks.create(track) : result end def set_discovery(track, boolean = false) discovery = Display.find_or_create_by(track_id: track.id, user_id: self.id, soundcloud_track_id: track.soundcloud_track_id) discovery.update_attributes(display: boolean) end def destroy_unstreamable! self.tracks.where(embedable_by: 'me').destroy_all self.tracks.where(embedable_by: 'none').destroy_all end def destroy_nil_waveforms! Track.where(waveform_url: nil).destroy_all end def destroy_unpopular! Track.where("likes_count < ? AND play_count < ? OR likes_count is ? OR play_count is ?", 150, 1000, nil, nil).destroy_all end def update_nil_art! Track.where(art_url: nil).each do |t| t.update_attributes(art_url: t.artists_avatar_url) t.destroy if t.artists_avatar_url.nil? end end def all_artists (followed_artists + artists_of_liked_tracks).uniq end def all_tracks tracks = [] all_artists.each { |artist| tracks += liked_tracks_for(artist) } tracks.uniq end def artists_of_liked_tracks liked_tracks_for(self.soundcloud_user_id).map { |track| track["user"]["id"] } end def followed_artists artists = soundcloud_user.get('/me/followings', :limit => @followings) artists.map { |artist| artist.id } end def prepare_tracks all_tracks.each do |track| if (discovery = Display.find_by(user_id: self.id, soundcloud_track_id: track["id"])) self.tracks.find_or_create_by(parse_track(track)) ##why this? Can be removed? discovery.update_attributes(result_count: discovery.result_count +=1 ) else self.tracks.find_or_create_by(parse_track(track)) end end end def liked_tracks_for(user_id) offset_cap = 0 tracks = [] url = "http://api.soundcloud.com/users/#{user_id}/favorites.json?client_id=#{client_id}&limit=#{@sc_result_offset}&offset=#{offset_cap}" until HTTParty.get(url).empty? || offset_cap == @offset_limit url = "http://api.soundcloud.com/users/#{user_id}/favorites.json?client_id=#{client_id}&limit=#{@sc_result_offset}&offset=#{offset_cap}" track_data = HTTParty.get(url) tracks += track_data if track_data.first != nil and track_data.first["kind"] == "track" offset_cap += @sc_result_offset end tracks end end
1632396758c6caff074c951e04d5ecd70d383f87
[ "Markdown", "Ruby" ]
12
Ruby
KidA001/soundfound
f51f394c2df6aa0e10baa0918ac40b14c6dde5b3
bf628b6fd11eb1e201befdfcb10c3ae0f171e955
refs/heads/master
<file_sep>// <copyright file="StarshipManager.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SwapiDemo.Infrastructure; using SwapiDemo.Models; /// <summary> /// The <see cref="StarshipManager"/> class /// </summary> public class StarshipManager : IDisposable { #region Private Fields /// <summary> /// method to detect redundant disposes /// </summary> private static bool disposedValue = false; #endregion Private Fields #region Public Constructors /// <summary> /// Initialises a new instance of the <see cref="StarshipManager"/> class. /// </summary> /// <param name="webHelper">the interface for the web helper</param> public StarshipManager(IWebHelper webHelper) { this.WebHelper = webHelper; } #endregion Public Constructors #region Private Properties private static String StarshipCollectionEndPoint { get { return "https://swapi.co/api/starships/"; } } /// <summary> /// Gets or sets the list of starship ranges /// </summary> private static ConcurrentBag<StarshipRange> StarshipRanges { get; set; } /// <summary> /// Gets or sets the web helper that will retrieve the data. /// </summary> private IWebHelper WebHelper { get; set; } #endregion Private Properties #region Public Methods /// <summary> /// Public dispose patterm /// </summary> public void Dispose() { this.Dispose(true); } /// <summary> /// Method to retrieve all starships form the api /// </summary> /// <param name="endPoint"> the end point</param> /// <returns>a task</returns> public async Task GetAllStarShipsAsync(String endPoint = null) { List<Starship> ships = await this.WebHelper.GetMultiPagedResponseAsync<Starship>(endPoint ?? StarshipCollectionEndPoint); StarshipRanges = new ConcurrentBag<StarshipRange>(); Parallel.ForEach(ships, (ship) => ProcessShip(ship)); } /// <summary> /// returns the processed list of star ships /// </summary> /// <returns>a list of starship ranges</returns> public List<StarshipRange> GetListofStarships() { return StarshipRanges.ToList(); } /// <summary> /// Gets the string generating the number of stops required /// </summary> /// <param name="distance">the distance</param> /// <returns>a list of strings</returns> public List<String> GetNumberOfStops(Double distance) { List<StarshipRange> collection = StarshipRanges.Where(x => x.HasRange).ToList(); List<String> result = new List<String>(); foreach (StarshipRange item in collection) { result.Add($"{item.Starship.Name} : {((Double)Math.Floor(distance / item.MGLTRange)).ToString("N0")}"); } return result; } /// <summary> /// Gets the count of star ships /// </summary> /// <returns>a count integer</returns> public Int32 StarShipCount() { return StarshipRanges != null ? StarshipRanges.Count : 0; } /// <summary> /// Gets the count of star ships tha thave no range /// </summary> /// <returns>a count integer</returns> public Int32 StarShipCountWithNoRange() { return StarshipRanges.Count(x => !x.HasRange); } #endregion Public Methods #region Protected Methods /// <summary> /// dispose method /// </summary> /// <param name="disposing">true</param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { this.WebHelper.Dispose(); } disposedValue = true; } } #endregion Protected Methods #region Private Methods /// <summary> /// Process the ship information /// </summary> /// <param name="ship">the ship</param> private static void ProcessShip(Starship ship) { StarshipRange shipRange = new StarshipRange() { Starship = ship }; shipRange.DaysWithConsumables = StarWarsConverter.ConvertConsumablesToDays(ship.Consumables); if (Int32.TryParse(ship.MGLT, out Int32 mglt)) { ship.MGLTValue = mglt; shipRange.MGLTRange = StarWarsConverter.GetMGLTRange(ship.MGLTValue, shipRange.DaysWithConsumables); shipRange.HasRange = shipRange.MGLTRange > 0 ? true : false; } StarshipRanges.Add(shipRange); } #endregion Private Methods } }<file_sep>// <copyright file="StarWarsConverter.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo.Infrastructure { using System; using System.Collections.Generic; /// <summary> /// A basic converter for a star wars standards /// </summary> internal class StarWarsConverter { #region Private Fields /// <summary> /// Gets the converter to multiply MGLT to a day range /// </summary> private const Int32 MGLTToDayConverter = 24; /// <summary> /// Json descriptor separator /// </summary> private const String Separator = " "; /// <summary> /// Gets a dictionary to convert star wars months and years to days /// https://starwars.fandom.com/wiki/Galactic_Standard_Calendar /// based on the coruscant solar cycle 368 days in a year, /// 10 months 3 festival weeks and 3 holidays in a year, /// 30.8 days in a month in a month (this difers to the official calendar of 35), /// 7 days in a week (this difers to the official calendar of 5) /// 24 hours in a day, /// 60/60 h/m /// </summary> private static readonly Dictionary<Char, Double> DayPerCalenderDefinition = new Dictionary<Char, Double>() { { 'y', 368 }, { 'm', 35 }, { 'w', 5 }, { 'd', 1 }, { 'h', 1 / 24 } }; #endregion Private Fields #region Public Methods /// <summary> /// converts a star wars calendar period into days /// </summary> /// <param name="consumables">the text retrieved</param> /// <returns>a Double represententing the days</returns> public static Double ConvertConsumablesToDays(String consumables) { Double consumableValue = 0; String[] consumablesArray = consumables.Trim().Split(Separator, StringSplitOptions.RemoveEmptyEntries); if (consumablesArray.Length > 1 && Double.TryParse(consumablesArray[0], out Double result)) { Char definition = consumablesArray[1].ToLower().Trim()[0]; if (DayPerCalenderDefinition.ContainsKey(definition)) { consumableValue = DayPerCalenderDefinition.GetValueOrDefault(definition) * result; } } return consumableValue; } /// <summary> /// Gets the megalight range of the ship /// </summary> /// /// <param name="megaLights">the megalight text retrieved</param> /// <param name="consumableDays">the calculated days duration to replenish</param> /// <returns>a Double represententing the range</returns> public static Double GetMGLTRange(Int32 megaLights, Double consumableDays) { Double megaLightRange = megaLights * MGLTToDayConverter * consumableDays; return megaLightRange; } #endregion Public Methods } }<file_sep>// <copyright file="WebHelper.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo.Infrastructure { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using SwapiDemo.Models; /// <summary> /// the <see cref="WebHelper"/> class. /// </summary> public class WebHelper : IWebHelper { #region Private Fields /// <summary> /// Gets or sets a displosed value for redundant calls /// </summary> private static bool disposedValue = false; #endregion Private Fields #region Private Properties /// <summary> /// Gets the Http Client /// </summary> private static HttpClient HttpClient { get; } = new HttpClient(); #endregion Private Properties #region Public Methods /// <summary> /// Dispose of the <see cref="HttpClient"/> /// </summary> public void Dispose() { this.Dispose(true); } /// <summary> /// Gets a collection of type T from the swapi service /// </summary> /// <typeparam name="T">the type of collection type to retrieve</typeparam> /// <param name="url">the url endpoint</param> /// <returns>a list of type T</returns> public async Task<List<T>> GetMultiPagedResponseAsync<T>(String url) { List<T> results = new List<T>(); do { PagedResponse<T> page = await this.GetPageAsync<PagedResponse<T>>(url); url = page.Next; results.AddRange(page.Results); } while ( url != null && url.StartsWith("http", StringComparison.CurrentCultureIgnoreCase)); return results; } /// <summary> /// Gets a single page /// </summary> /// <typeparam name="T">the type to retrieve</typeparam> /// <param name="url">the url</param> /// <returns>a Response Page</returns> public async Task<T> GetSinglePageAsync<T>(String url) { T itemPage = await this.GetPageAsync<T>(url); return itemPage; } #endregion Public Methods #region Protected Methods /// <summary> /// the protected method for dispose /// </summary> /// <param name="disposing">disposing boolean</param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { HttpClient.Dispose(); } disposedValue = true; } } #endregion Protected Methods #region Private Methods /// <summary> /// Gets a single page /// </summary> /// <typeparam name="T">the generic mapping type</typeparam> /// <param name="url">the url</param> /// <returns>a gerically mapped type</returns> private async Task<T> GetPageAsync<T>(String url) { HttpResponseMessage httpResponseMessage = await HttpClient.GetAsync(url); httpResponseMessage.EnsureSuccessStatusCode(); String responseBody = await httpResponseMessage.Content.ReadAsStringAsync(); T page = JsonConverter.ConvertToObject<T>(responseBody); return page; } #endregion Private Methods } }<file_sep>// <copyright file="JsonConverter.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo.Infrastructure { using System; using System.Text.Json; /// <summary> /// Converts a Json String to a defined object /// </summary> public static class JsonConverter { #region Private Fields private static readonly JsonSerializerOptions DefaultOptionSetting = new JsonSerializerOptions { AllowTrailingCommas = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true }; #endregion Private Fields #region Private Properties /// <summary> /// Gets or sets the deserialization options /// </summary> private static JsonSerializerOptions Options { get; set; } = DefaultOptionSetting; #endregion Private Properties #region Public Methods /// <summary> /// Convert object to json /// </summary> /// <typeparam name="T">the type</typeparam> /// <param name="item">the item to serialize</param> /// <returns>a string</returns> public static String ConvertToJson<T>(T item) { String jsonString = JsonSerializer.Serialize<T>(item, Options); return jsonString; } /// <summary> /// Convert json data to object /// </summary> /// <typeparam name="T">the type</typeparam> /// <param name="jsonString">the String</param> /// <returns>a type object cloned</returns> public static T ConvertToObject<T>(String jsonString) { T itemCollectionPage = JsonSerializer.Deserialize<T>(jsonString, Options); return itemCollectionPage; } /// <summary> /// Sets the deserialization options /// </summary> /// <param name="options">the <see cref="JsonSerializerOptions"/></param> public static void SetDeSerializationOptions(JsonSerializerOptions options = null) { Options = options ?? DefaultOptionSetting; } #endregion Public Methods } }<file_sep>// <copyright file="Starship.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo.Models { using System; /// <summary> /// The basic starship details for the <c>swapi</c> /// </summary> public class Starship { #region Public Properties /// <summary> /// Gets or sets the maximum amount of time the ship can provide consumables to the crew without resupply /// </summary> public String Consumables { get; set; } /// <summary> /// Gets or sets the number of mega lights a ship can travel in a standard hour /// for measuring speed of a starship /// </summary> public String MGLT { get; set; } /// <summary> /// Gets or sets the number of mega lights a ship can travel in a standard hour /// for measuring speed of a starship /// </summary> public Int32 MGLTValue { get; set; } /// <summary> /// Gets or sets the starship name /// </summary> public String Name { get; set; } #endregion Public Properties } }<file_sep>// <copyright file="StarshipRange.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo.Models { using System; /// <summary> /// Calculated Ranges based on /// </summary> public class StarshipRange { #region Public Properties /// <summary> /// Gets or sets the period a starship can go without replenishing /// </summary> public Double DaysWithConsumables { get; set; } /// <summary> /// Gets or sets a value indicating whether the starship has a definable range /// </summary> public Boolean HasRange { get; set; } /// <summary> /// Gets or sets the range for a star ship /// DaysWithConsumables * 24 * MGLT; /// </summary> public Double MGLTRange { get; set; } /// <summary> /// Gets or sets the starShip /// </summary> public Starship Starship { get; set; } #endregion Public Properties } }<file_sep>// <copyright file="MockWebHelper.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemoTest { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; using SwapiDemo.Infrastructure; using SwapiDemo.Models; /// <summary> /// The web service to retrieve data from /// </summary> public class MockWebHelper : IWebHelper { #region Private Fields /// <summary> /// Gets or sets a displosed value for redundant calls /// </summary> private static bool disposedValue = false; #endregion Private Fields #region Private Properties /// <summary> /// Gets the Http Client /// </summary> private static HttpClient HttpClient { get; } = null; #endregion Private Properties #region Public Methods /// <summary> /// This code added to correctly implement the disposable pattern. /// </summary> public void Dispose() { this.Dispose(true); } /// <summary> /// Gets a collection of type T from the swapi service /// </summary> /// <typeparam name="T">the type</typeparam> /// <param name="url">the url</param> /// <returns>a list of type T</returns> public async Task<List<T>> GetMultiPagedResponseAsync<T>(String url) { List<T> items = new List<T>(); await Task.Yield(); PagedResponse<T> itemPage = JsonConverter.ConvertToObject<PagedResponse<T>>(File.ReadAllText(url)); items.AddRange(itemPage.Results); return items; } /// <summary> /// Gets a single page /// </summary> /// <typeparam name="T">the type to retrieve</typeparam> /// <param name="url">the url</param> /// <returns>a PagedResponse</returns> public async Task<T> GetSinglePageAsync<T>(String url) { await Task.Yield(); throw new NotImplementedException(); } #endregion Public Methods #region Protected Methods /// <summary> /// the protected method for dispose /// </summary> /// <param name="disposing">disposing boolean</param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { HttpClient?.Dispose(); } disposedValue = true; } } #endregion Protected Methods } }<file_sep>// <copyright file="IWebHelper.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo.Infrastructure { using System; using System.Collections.Generic; using System.Threading.Tasks; using SwapiDemo.Models; /// <summary> /// The <see cref="IWebHelper"/> class. /// </summary> public interface IWebHelper : IDisposable { #region Public Methods /// <summary> /// Gets a collection of type T from the swapi service /// </summary> /// <typeparam name="T">the type of object to retrieve</typeparam> /// <param name="url">the url endpoint</param> /// <returns>a list of type T</returns> Task<List<T>> GetMultiPagedResponseAsync<T>(String url); /// <summary> /// Gets a single page of a collection /// </summary> /// <typeparam name="T">the type to retrieve</typeparam> /// <param name="url">the url</param> /// <returns>a Response Collection</returns> Task<T> GetSinglePageAsync<T>(String url); #endregion Public Methods } }<file_sep>// <copyright file="PagedResponse.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo.Models { using System; using System.Collections.Generic; /// <summary> /// The <see cref="PagedResponse{T}"/> class. /// </summary> /// <typeparam name="T">The type T collection</typeparam> public class PagedResponse<T> { #region Public Properties /// <summary> /// Gets or sets the count parameter /// </summary> public Int32 Count { get; set; } /// <summary> /// Gets or sets the next url /// </summary> public String Next { get; set; } /// <summary> /// Gets or sets the previous url /// </summary> public String Previous { get; set; } /// <summary> /// Gets or sets the results /// </summary> public List<T> Results { get; set; } #endregion Public Properties } }<file_sep>// <copyright file="Program.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemo { using System; using System.Threading; using System.Threading.Tasks; using SwapiDemo.Infrastructure; /// <summary> /// the main program /// </summary> public class Program { #region Private Properties /// <summary> /// Gets or sets the user entered distance to determine /// </summary> private static Double DistanceEntered { get; set; } private static StarshipManager StarShipManager { get; set; } #endregion Private Properties #region Public Methods /// <summary> /// The program entry point /// </summary> /// <returns>a task</returns> public static async Task Main() { try { Boolean proceed = await InitializeAsync(); if (proceed) { CycleUIInteraction(); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } finally { StarShipManager?.Dispose(); } } #endregion Public Methods #region Private Methods /// <summary> /// cycle the user interaction until exit /// </summary> private static void CycleUIInteraction() { String input; do { Console.Clear(); Console.WriteLine("Please enter a distance in MGLT (megalights), or x to exit?"); input = Console.ReadLine(); Boolean isValidNumber = Double.TryParse(input, out Double result); if (isValidNumber) { DistanceEntered = result; ProcessStarshipsOutput(); } else if (input.Trim().ToLower() != "x") { Console.WriteLine("...That entry was invalid, press any key to continue"); Console.ReadKey(); } } while (input != "x"); Console.WriteLine("...Bye!"); } /// <summary> /// Initialises the information to process; /// </summary> /// <returns>a task</returns> private static async Task<Boolean> InitializeAsync() { Console.WriteLine("Retrieve ships from website (y)?"); ConsoleKeyInfo key = Console.ReadKey(); if (key.Key != ConsoleKey.Y) { //// user does not want to proceed return false; } Console.WriteLine(); Console.WriteLine("Initialising and retrieving starships from the swapi service, please wait...."); IWebHelper webHelper = new WebHelper(); StarShipManager = new StarshipManager(webHelper); await StarShipManager.GetAllStarShipsAsync(); Int32 count = StarShipManager.StarShipCount(); String shipText = count == 1 ? "ship" : "ships"; Console.WriteLine($".....Retrieved {count} {shipText} "); Thread.Sleep(2000); Console.WriteLine("Press Any key to continue..."); Console.ReadKey(); return true; } /// <summary> /// Process the start ship output values; /// </summary> private static void ProcessStarshipsOutput() { if (StarShipManager.StarShipCount() == 0) { throw new Exception("No Ships retrieved"); } Console.WriteLine(); Console.WriteLine("Number of stops each starship requires:"); Console.WriteLine($"Number of starships that cannot be determined: {StarShipManager.StarShipCountWithNoRange()}"); foreach (String entry in StarShipManager.GetNumberOfStops(DistanceEntered)) { Console.WriteLine(entry); } Console.WriteLine(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } #endregion Private Methods } }<file_sep>// <copyright file="UnitTests.cs" company="<NAME>"> // Copyright (c) 2019 <NAME>. All rights reserved. // </copyright> namespace SwapiDemoTest { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using SwapiDemo; using SwapiDemo.Infrastructure; using SwapiDemo.Models; using Xunit; /// <summary> /// The basic unit tests /// </summary> public class UnitTests { #region Private Fields /// <summary> /// the test url /// </summary> private const String TestUrl = "https://swapi.co/api/starships/"; /// <summary> /// the page test /// </summary> private const String TestUrlPage = "https://swapi.co/api/starships/?page=2"; /// <summary> /// The web query to use /// </summary> private IWebHelper webQuery; #endregion Private Fields #region Public Constructors /// <summary> /// Initialises a new instance of the <see cref="UnitTests"/> class /// </summary> public UnitTests() { String root = AppContext.BaseDirectory; root = root.Substring(0, root.IndexOf("\\bin")); DataSetsFolder = Path.Combine(root, "dataSets"); } #endregion Public Constructors #region Private Destructors /// <summary> /// Finalises an instance of the <see cref="UnitTests"/> class. /// </summary> ~UnitTests() { this.webQuery.Dispose(); } #endregion Private Destructors #region Private Properties /// <summary> /// gets or sets the data sets folder /// </summary> private static String DataSetsFolder { get; set; } #endregion Private Properties #region Public Methods /// <summary> /// Tests the basic json conversion to the Response Collection object /// </summary> [Fact] public void TestJson_Success() { //// Arrange String filePath = Path.Combine(DataSetsFolder, "StarShipPage.txt"); String content = File.ReadAllText(filePath); //// Act PagedResponse<Starship> pagedResponse = JsonConverter.ConvertToObject<PagedResponse<Starship>>(content); //// Assert Assert.True(pagedResponse.Count == 4, "Count = 4"); Assert.True(pagedResponse.Next.StartsWith("http"), "next has path"); Assert.True(pagedResponse.Previous == null, "previous has null"); Assert.True(pagedResponse.Results.Count == 2, "2 results returned"); for (Int32 i = 0; i < pagedResponse.Results.Count; ++i) { Assert.True(pagedResponse.Results[i].Consumables.Length > 0, $"consumables {i} populated"); Assert.True(pagedResponse.Results[i].MGLT.Length > 0, $"MGLT {i} populated"); Assert.True(pagedResponse.Results[i].Name.Length > 0, $"name {i} populated"); } } /// <summary> /// Tests the basic json conversion to the Response Collection object /// </summary> [Fact] public void TestJson_Unknown_Success() { //// Arrange String filePath = Path.Combine(DataSetsFolder, "StarShipPage2.txt"); String content = File.ReadAllText(filePath); //// Act PagedResponse<Starship> pagedResponse = JsonConverter.ConvertToObject<PagedResponse<Starship>>(content); //// Assert Assert.True(pagedResponse.Count == 5, "Count = 5"); Assert.True(pagedResponse.Next.StartsWith("http"), "next has path"); Assert.True(pagedResponse.Previous != null, "previous has null"); Assert.True(pagedResponse.Results.Count == 3, "3 results returned"); for (Int32 i = 0; i < pagedResponse.Results.Count; ++i) { Assert.True(pagedResponse.Results[i].Consumables.Length > 0, $"consumables {i} populated"); Assert.True(pagedResponse.Results[i].MGLT.Length > 0, $"MGLT {i} populated"); Assert.True(pagedResponse.Results[i].Name.Length > 0, $"name {i} populated"); } } /// <summary> /// Tests a single web reuqest /// </summary> /// <returns>a task</returns> [Fact] public async Task TestManager_MockWebService_Success() { //// Arrange IWebHelper webHelper = new MockWebHelper(); List<StarshipRange> pagedResponse = null; String filePath = Path.Combine(DataSetsFolder, "StarShipPage2.txt"); //// Act using (StarshipManager manager = new StarshipManager(webHelper)) { await manager.GetAllStarShipsAsync(filePath); pagedResponse = manager.GetListofStarships(); } //// Assert Assert.True(pagedResponse != null, "response != null"); Assert.True(pagedResponse.Count == 3, "response count == 3"); foreach (StarshipRange ship in pagedResponse) { if (ship.HasRange) { Assert.True(ship.MGLTRange > 0, $"response[0].MGLTRange > 0"); Assert.True(ship.DaysWithConsumables > 0, "response[0].DaysWithConsumables > 0"); } else { Assert.True(ship.MGLTRange == 0 || ship.DaysWithConsumables == 0, $"response {ship.Starship.Name} no range"); } } Int32 noRange = pagedResponse.Count(x => !x.HasRange); Int32 hasRange = pagedResponse.Count(x => x.HasRange); Assert.True(hasRange == 2, "has range == 2"); Assert.True(noRange == 1, "no range = 1"); } /// <summary> /// Tests a single web reuqest /// </summary> /// <returns>a task</returns> [Fact] public async Task TestWebCollectionMultiPageQuery_Live_Success() { //// Arrange IWebHelper webService = this.GetWebHelper(); //// Act List<Starship> pagedResponse = await webService.GetMultiPagedResponseAsync<Starship>(TestUrlPage); //// Assert Assert.True(pagedResponse != null, "collection not null"); Assert.True(pagedResponse.Count >= 27, "Count = 27 (skipped first page)"); for (Int32 i = 0; i < pagedResponse.Count; ++i) { Assert.True(pagedResponse[i].Consumables.Length > 0, "consumables {i} populated"); Assert.True(pagedResponse[i].MGLT.Length > 0, "MGLT {i} populated"); Assert.True(pagedResponse[i].Name.Length > 0, "name {i} populated"); } } /// <summary> /// Tests a single web reuqest /// </summary> /// <returns>a task</returns> [Fact] public async Task TestWebQuery_SecondPage_Live__Success() { //// Arrange IWebHelper webService = this.GetWebHelper(); //// Act PagedResponse<Starship> pagedResponse = await webService.GetSinglePageAsync<PagedResponse<Starship>>(TestUrlPage); //// Assert Assert.True(pagedResponse != null, "collection not null"); Assert.True(pagedResponse.Count == 37, "Count = 37"); Assert.True(pagedResponse.Next.StartsWith("http"), "next has path"); Assert.True(pagedResponse.Previous != null, "previous != null"); Assert.True(pagedResponse.Results.Count == 10, "10 results returned"); for (Int32 i = 0; i < pagedResponse.Results.Count; ++i) { Assert.True(pagedResponse.Results[i].Consumables.Length > 0, "consumables {i} populated"); Assert.True(pagedResponse.Results[i].MGLT.Length > 0, "MGLT {i} populated"); Assert.True(pagedResponse.Results[i].Name.Length > 0, "name {i} populated"); } } /// <summary> /// Tests a single web reuqest /// </summary> /// <returns>a task</returns> [Fact] public async Task TestWebQuery_SinglePage_Live_Success() { //// Arrange IWebHelper webService = this.GetWebHelper(); //// Act PagedResponse<Starship> pagedResponse = await webService.GetSinglePageAsync<PagedResponse<Starship>>(TestUrl); //// Assert Assert.True(pagedResponse.Count == 37, "Count = 37"); Assert.True(pagedResponse.Next.StartsWith("http"), "next has path"); Assert.True(pagedResponse.Previous == null, "previous has null"); Assert.True(pagedResponse.Results.Count == 10, "10 results returned"); for (Int32 i = 0; i < pagedResponse.Results.Count; ++i) { Assert.True(pagedResponse.Results[i].Consumables.Length > 0, "consumables {i} populated"); Assert.True(pagedResponse.Results[i].MGLT.Length > 0, "MGLT {i} populated"); Assert.True(pagedResponse.Results[i].Name.Length > 0, "name {i} populated"); } } #endregion Public Methods #region Private Methods private IWebHelper GetWebHelper() { if (this.webQuery == null) { this.webQuery = new WebHelper(); } return this.webQuery; } #endregion Private Methods } }
5bc8232e34c7bb3d6319bfb796130b040a3a5bde
[ "C#" ]
11
C#
LaurenceMHoward/SwapiDemo
569f741224ef173d91189bb1fa2fea0170a96410
b14d6a69d70951d2055d5f833cb7ca698c33f1ec
refs/heads/master
<file_sep>sequences = {} def add_new_sequences(new_sequences,count): global sequences for key,val in new_sequences.items(): if val == count: sequences[key] = val else: sequences[key] = count - val def colletz_cnt_from_int(n): global sequences cur = n count = 1 new_sequence_cnts = {} while cur != 1: if cur in sequences: count += sequences[cur] break else: new_sequence_cnts[cur] = count if cur % 2 == 0: cur /= 2 else: cur = (cur * 3) + 1 count += 1 new_sequence_cnts[n] = count add_new_sequences(new_sequence_cnts, count) for r in range(1,1000000): colletz_cnt_from_int(r) max_value = max(sequences.values()) for key,val in sequences.items(): if val == max_value: print(key) break <file_sep>#Euler 5 - The smallest positive number that is evenly divisible by all of the numbers from 1 to 20 int_list = [] num = 1 def prime_check (z): if z >= 0 and z <=3: return True else: for y in range (2,int(z**0.5)+1,1): #print (str(z)+"%"+str(y)+" - "+str(z%y)) if z%y==0: return False return True for x in range (2,21,1): if prime_check(x)==True: w = x while w*x < 20: w *= x int_list.append(w) for v in int_list: num *= v print(int_list) print (num)<file_sep># Project Euler 100 problem Challenge Each person has their own directory track their progress. As you finish a problem add a new file with the solution to your directory and submit a pull request. The problems can be found at [Project Euler](https://projecteuler.net/archives) <file_sep>#Euler 15 - Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? import math print (math.factorial(40)/(math.factorial(20)*math.factorial(20))) def fac (z): total = 1 for x in range(1,z+1,1): total *= x return (total) print (fac(40)/(fac(20)**2))<file_sep>import math def isPalindrome(num): half_num = math.floor(len(str(num)) / 2) str_num = str(num) rev_str = ''.join(reversed(str_num[half_num: ])) if (len(str(num)) % 2 != 0): half_num += 1 if (str_num[0 : half_num] == rev_str): return True else: return False start = 999 largest_palindrome = 0 for x in range(start,0,-1): for y in range(x, 0, -1): if (isPalindrome(x*y)): if ((x*y) > largest_palindrome): largest_palindrome = x*y break break print(largest_palindrome) <file_sep>#Euler 12 - What is the value of the first triangle number to have over five hundred divisors fac_list = {} def next_tri (y): tri = int((y*(y+1)/2)) return (tri) def prime_fac(num): global fac_list count = 0 while num % 2 == 0: num /= 2 count += 1 fac_list[2] = count div_by = 3 while num != 1: count = 0 while num % div_by == 0: num /= div_by count += 1 fac_list[div_by] = count div_by += 2 num = 1 tot_div = 0 while tot_div < 500: cur_tri = next_tri(num) prime_fac(cur_tri) tot_div = 1 for key,value in fac_list.items(): tot_div *= (value+1) if (tot_div > 500): print (cur_tri,": ",fac_list) print (tot_div) num += 1 fac_list = {}<file_sep>""" Project Euler - Problem 3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ import math factors = [] primes = [] num = 600851475143 for i in range(2, num + 1): primes.append(i) i = 2 while(i <= int(math.sqrt(num))): if i in primes: for j in range(i * 2, num + 1, i): if j in primes: primes.remove(j) i += 1 for x in primes: if num % x == 0: factors.append(x) print(factors[-1])<file_sep>#Euler 7 - The 10,001st prime number p_list = [] x = 0 def prime_check (z): if z >= 0 and z <=3: return True else: for y in range (2,int(z**0.5)+1,1): #print (str(z)+"%"+str(y)+" - "+str(z%y)) if z%y==0: return False return True while len(p_list) < 10001: if prime_check(x) == True: p_list.append(x) x += 1 print(len(p_list)) print (p_list[10000])<file_sep>#Euler 6 - Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. s_sq = 0 sq_s = 0 for z in range (1,101,1): s_sq += z**2 sq_s += z #print (s_sq) print (sq_s) sq_s = sq_s**2 print (sq_s,"-",s_sq," = ",sq_s-s_sq)<file_sep>#Euler 10 - Find the sum of all the primes below two million. int_list = [] num = 0 def prime_check (z): if z >= 0 and z <=3: return True else: if z%2 == 0: return False for y in range (3,int(z**0.5)+1,2): #print (str(z)+"%"+str(y)+" - "+str(z%y)) if z%y==0: return False return True for x in range (3,2000000,2): if x==3: num += 1+2+3 #int_list.append(1,2,3) elif prime_check(x)==True: num += x #int_list.append(x) #print(int_list) print (num)<file_sep>#Euler 16 - What is the sum of the digits of the number 2**1000? z = str(2**1000) sum = 0 for y in range(len(z)): sum += int(z[y]) print(z) print(sum)<file_sep>#Euler 4 - Find the largest palindrome made from the product of two 3-digit numbers. z = 999 y = 999 x = 0 p = 0 floor = 0 digit = 0 length = 0 pal = -1 while y >= floor: x = z*y length = len(str(x)) digit = int(length/2) p=x #print(str(digit)) for a in range (0,digit,1): print (str(z*y)+" - "+str(x)[a]+" "+str(x)[length-a-1]) if str(x)[a] != str(x)[length-a-1]: p = 0 break if p > 0 and p > pal: #print (str(p)) pal = p floor = y z -= 1 y = z elif y == floor: z -= 1 y = z else: y -= 1 print (str(z)+" x "+str(y)) print (str(pal)) for x in range (0,10,1): print(str(x))<file_sep>freq = {} def reduce_by_factor(number,factor): count = 0 cur_num = number while cur_num % factor == 0: cur_num /= factor count += 1 if factor in freq: if freq[factor] < count: freq[factor] = count elif count > 0: freq[factor] = count return cur_num def populateFactors(x): cur_num = reduce_by_factor(x, 2) factor = 3 while cur_num != 1: cur_num = reduce_by_factor(cur_num, factor) factor += 2 for r in range (2,21): populateFactors(r) total = 1 for key,value in freq.items(): total *= (key ** value) print(total)<file_sep>import java.util.ArrayList; public class EvenFibonacci{ public static void main (String[] args){ ArrayList<Integer> myFib = new ArrayList<Integer>(); int sum = 0; myFib = fibonacci(4000000); for (int num : myFib){ if ((num % 2) == 0){ sum += num; } } System.out.println(sum); } public static ArrayList<Integer> fibonacci(int end){ ArrayList<Integer> fib = new ArrayList<Integer>(); fib.add(1); fib.add(1); do{ fib.add(fib.get(fib.size() - 1) + fib.get(fib.size() - 2)); } while ((fib.get(fib.size() - 1) + fib.get(fib.size() - 2)) < end); return fib; } }<file_sep># This solutino is kind of slow... # I am wondering if you can relate the factors of the previous triangle number to the next. That would speed it up. freq = {} def find_triag_num(n): return (n * (n+1)) / 2 def reduce_by_factor(number,factor): global freq count = 0 cur_num = number while cur_num % factor == 0: cur_num /= factor count += 1 freq[factor] = count return cur_num def populateFactors(x): cur_num = reduce_by_factor(x, 2) factor = 3 while cur_num != 1: cur_num = reduce_by_factor(cur_num, factor) factor += 2 x = 1 while True: num = find_triag_num(x) populateFactors(num) num_of_divisors = 1 for key,value in freq.items(): num_of_divisors *= (value + 1) if num_of_divisors > 500: print(num) break freq = {} x += 1 <file_sep># problem5 # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20 startingNum = 20 originalArray = [] for x in range(1, startingNum + 1): originalArray.append(x) def getMultiples(num): finalDict = {} for x in range(2, num + 1): while (num % x == 0 and num > 1): num /=x if x in finalDict: finalDict[x] += 1 else: finalDict[x] = 1 return finalDict def lowestMultiple(array): multiple = {} for x in array: returnedMultiples = getMultiples(x) for y in returnedMultiples: if (y in multiple and returnedMultiples[y] >= multiple[y]) or (y not in multiple): multiple[y] = returnedMultiples[y] return multiple final = lowestMultiple(originalArray) multiply = 1 for x in final: print("x = ", x) for y in range(1, final[x] + 1): print('final = ', y) multiply *= x <file_sep>#Euler 3 - Largest prime factor of the number 600851475143 seed = 600851475143 factor = seed div_by = 2 plist = "All prime factors: " while factor%2 == 0: factor /= 2 plist += str(div_by)+',' print (factor) print (plist) div_by = 3 while div_by <= factor/2: if factor%div_by == 0: factor /= div_by plist += str(div_by)+',' else: div_by += 2 plist += str(factor) print (plist) print ("Largest prime factor: "+str(factor))<file_sep>#Euler 2 - By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. total = 0 prev = 1 cur = 2 while cur < 4000000: if cur%2==0: total += cur cur += prev prev = (cur-prev) print ("Total : "+str(total))<file_sep>#sum 1 to n is (n(n + 1))/2 sum_to_100_squared = ((100 * 101) / 2) ** 2 # sum of squares to n is (n(n+1)(2n+1)) / 6 sum_squared_to_100 = (100 * 101 * 201) / 6 print(sum_to_100_squared - sum_squared_to_100)<file_sep>import math end = 600851475143 factors = [] factor = 2 while factor < math.ceil((end/2) + 1): if end % factor == 0: end /= factor if factor not in factors: factors.append(factor) else: factor += 1 factors.append(end) print(end) <file_sep>#Euler 009 - There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. z = 4 a = 0 b = 0 c = 0 total = 0 factor = 0 while z <= 332: a = z if a%2==0: b = ((a/2)**2)-1 c = ((a/2)**2)+1 else: b = ((a**2)/2)-0.5 c = ((a**2)/2)+0.5 total = a+b+c factor = 1 while total <= 1000: #print (total,'(',factor,')') if total == 1000: a *= factor b *= factor c *= factor z = 999 break else: total += a+b+c factor += 1 z += 1 print (a,"+",b,"+",c," = ",total) print (a*b*c)<file_sep>""" Project Euler - Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ fib_list = [0,1] def fib_builder(lim): while fib_list[-1] < lim: temp = fib_list[len(fib_list) - 2] + fib_list[len(fib_list) - 1] fib_list.append(temp) return even_fib_sum(fib_list) def even_fib_sum(list): sum = 0 for x in list: if x % 2 == 0: sum += x return sum print(fib_builder(4000000)) print(fib_list)<file_sep>#Euler 14 - Which starting number, under one million, produces the longest chain in the collatz sequence? seq_totals = {} x = 1 cur = 1 high = 1 start = 1 def col_seq_count(num): count = 0 while num != 1: if num % 2 == 0: num /= 2 count += 1 else: num *= 3 num += 1 count += 1 if num in seq_totals: count += seq_totals[num] return (count) return (count) while x < 1000000: cur = col_seq_count(x) seq_totals[x] = cur if high < cur: high = cur start = x x += 1 print (len(seq_totals)) print (start," : ",high)<file_sep> def fac(n, result): if n == 1: return result else: return fac(n-1, result*n) print(sum([int(x) for x in str(fac(100,1))]))<file_sep>ceiling = 2000000 def sieve_of_eratosthenes (ceiling): values = [True] * ceiling for r in range(2, int(ceiling ** 0.5) + 1): if values[r] == True: for j in range(r*r, ceiling, r): values[j] = False primes = [r for r in range(ceiling) if values[r] == True] return primes[2:] solution = sum(sieve_of_eratosthenes(ceiling)) print(solution)<file_sep>#Euler 1 - Find the sum of all the multiples of 3 or 5 below 1000. total = 0 for r in range(1,1000,1): if r%3==0: total += r elif r%5==0: total += r print (total)<file_sep>solution = 0 def check_multiples(a,b,c): global solution prod = a + b + c if 1000 % prod != 0: return False factor = 1 while prod < 1000: factor += 1 prod = (a * factor) + (b * factor) + (c * factor) if prod == 1000: solution = (a * factor) * (b * factor) * (c * factor) return True return False m = 2 n = 1 while solution == 0: for r in range(m,498): a = (r ** 2) - (n ** 2) b = 2 * r * n c = (r ** 2) + (n ** 2) if check_multiples(a,b,c): break n += 1 m = n + 1 print("Solution: " + str(solution)) <file_sep># observing a given path in a (NxN) grid shows you must move right N times and down N times # This redues to a n choose k problem # n!/((k!)*((n-k)!)) def calc_fac(n,m): if m == 1: return n else: return calc_fac(n*(m-1), m-1) grid_size = 20 n = grid_size * 2 k = grid_size n_fac = calc_fac(n,n) k_fac = calc_fac(k,k) print(n_fac / ((k_fac) * (k_fac))) <file_sep>""" Project Euler - Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def multiples_sum(num): sum = 0 for x in range(num): if x % 3 == 0 or x % 5 == 0: sum += x print(x) print(sum) multiples_sum(1000) <file_sep>print(sum([int(i) for i in list(str(2**1000))]))<file_sep>def sieve_of_eratosthenes (ceiling): values = [True] * ceiling for r in range(2, int(ceiling ** 0.5) + 1): if values[r] == True: for j in range(r*r, ceiling, r): values[j] = False primes = [r for r in range(ceiling) if values[r] == True] return primes[1:] prime_list = sieve_of_eratosthenes(150000) print(prime_list[10001])
c3bbaa40894d68e95ff42516bf3812ba2c06f766
[ "Markdown", "Java", "Python" ]
31
Python
phillips0616/euler100
3c535c3ea88c2fa1af845de1e9a8594ce10baefb
fabda1b06a70a2cb31fbde9ff09921c7f35f76c1
refs/heads/master
<file_sep>//byte[]数组的大小会决定传输的快慢,但是不是越大越好 import java.io.FileInputStream; import java.io.FileOutputStream; public class Exercise4 { public static void main(String[] args)throws Exception { FileInputStream in=new FileInputStream("zrn.jpg"); FileOutputStream out=new FileOutputStream("copyzrn.jpg"); int i=0; byte[]b=new byte[1024]; long begin=System.currentTimeMillis(); while((i=in.read(b))!=-1){ out.write(b,0,i); } long end=System.currentTimeMillis(); System.out.println("复制所花的时间"+(end-begin)+"毫秒"); in.close(); out.close(); } }
0be17139ea220a6e7d7ece20aa957baae6ca38be
[ "Java" ]
1
Java
abraler/2019-10-20
d29c2b8af96325101e427bc35d1e0365ddc4ca49
c03756f878f13fab8477055ac2cb478d89f62844
refs/heads/master
<file_sep>using System; namespace oop_6115261020_w05 { class Program { static void Main(string[] args) { Building b4 = new Building ("5", "Building 4", "222", "333"); Room r424 = new Room ("424", "Room 424", "3", "3", "computer",b4); Subject S = new Subject ("615261020", "ced", "3", "2", "2"); Lecturer nathee = new Lecturer ("Tao", "naka", "lecturer"); Section ced1 = new Section ("15", "8.00", "8.01", r424 , S , nathee ); Console.WriteLine(r424.ToString()); Console.WriteLine(ced1.ToString()); } } }
5eceef2d83cdb3d648bf66b0a817d2a17bf59ac1
[ "C#" ]
1
C#
Tao141516/oop-6115261020-w05
ed2eac324109f7e941ecfb0c703aec7300c70942
bf529fe3cce663c96494f61bd8ecddfa311e5740
refs/heads/master
<repo_name>jp-ganis/DireWolfAlpha<file_sep>/direwolf.py import sys; sys.path.insert(0, './fireplace') from hearthstone.enums import CardClass, CardType from fireplace.card import Card import numpy as np import fireplace.cards import fireplace import time import random import sys import os import copy import logging; logging.getLogger("fireplace").setLevel(logging.WARNING) def get_murloc_paladin_deck(): n = [] # n += 2*["Gentle Megasaur"] ## probably also can't do adapt (Sea Giant + Black Knight) # n += 2*["Hydrologist"] ## discover is busted (Bluegill Warrior) # n += 2*["Unidentified Maul"] ## NYI (Truesilver Champion) # n += 2*["Truesilver Champion"] ## can't do weapons n += 2*["Murloc Tidecaller"] n += 2*["Rockpool Hunter"] n += 2*["Call to Arms"] n += 2*["Bluegill Warrior"] n += 2*["Righteous Protector"] n += 2*["Lost in the Jungle"] n += 2*["Coldlight Seer"] n += 2*["Murloc Warleader"] n += 2*["Nightmare Amalgam"] n += 1*["The Black Knight"] n += 1*["Sea Giant"] n += 1*["Sunkeeper Tarim"] n += 1*["Vinecleaver"] n += 1*["Fungalmancer"] n += 1*["Divine Favor"] n += 1*["Spellbreaker"] n += 1*["Blessing of Kings"] n += 1*["Silver Hand Recruit"] n += 1*["Grimscale Oracle"] deck = [(c, fireplace.cards.filter(name=c)[0]) for c in n if len(fireplace.cards.filter(name=c)) > 0] deck += 2*[("Knife Juggler","NEW1_019")] return deck def get_odd_warrior_deck(): n = [] n += 1*["Gorehowl"] n += 1*["Baku the Mooneater"] n += 1*["King Mosh"] n += 2*["Ironbeak Owl"] n += 2*["Shield Slam"] n += 2*["Whirlwind"] n += 2*["Town Crier"] n += 1*["Gluttonous Ooze"] n += 2*["Rabid Worgen"] n += 2*["Reckless Flurry"] n += 2*["Shield Block"] n += 1*["Big Game Hunter"] n += 2*["Brawl"] n += 1*["<NAME>"] n += 2*["Direhorn Hatchling"] n += 2*["Rotten Applebaum"] n += 1*["Hungry Crab"] n += 1*["Harrison Jones"] n += 1*["<NAME>"] n += 1*["Acolyte of Pain"] return [(c, fireplace.cards.filter(name=c)[0]) for c in n if len(fireplace.cards.filter(name=c)) > 0] og_deck = [] og_deck_names =[] og_deck_names += ["Brawl"] ## rng effect! og_deck_names += ["Spider Tank"] og_deck_names += ["Magma Rager"] og_deck_names += ["Chillwind Yeti"] og_deck_names += ["Oasis Snapjaw"] og_deck_names += ["Wild Pyromancer"] og_deck_names += ["Frostbolt"] og_deck_names += ["Flamestrike"] og_deck_names += ["Nightblade"] og_deck_names += ["Boulderfist Ogre"] og_deck_names += ["Fireball"] og_deck_names += ["Bittertide Hydra"] og_deck_names += ["Doomsayer"] og_deck_names += ["Execute"] og_deck_names += ["Darkscale Healer"] og_deck_names += ["Whirlwind"] og_deck_names += ["Mind Control Tech"] og_deck_names += ["Defile"] og_deck_names += ["Blessing of Kings"] og_deck_names += ["River Crocolisk"] og_deck_names += ["Snowflipper Penguin"] # random.shuffle(og_deck_names) og_deck = [fireplace.cards.filter(name=n)[0] for n in og_deck_names] warrior_deck = [c[1] for c in get_odd_warrior_deck()] warrior_deck_names = [c[0] for c in get_odd_warrior_deck()] paladin_deck = [c[1] for c in get_murloc_paladin_deck()] paladin_deck_names = [c[0] for c in get_murloc_paladin_deck()] def enumerate_actions(game): actions = set() ## set of (function, arg) tuples player = game.current_player heropower = player.hero.power if heropower.is_usable(): if heropower.requires_target(): for t in heropower.targets: actions.add((heropower.use, t)) else: actions.add((heropower.use, None)) for card in player.hand: if card.is_playable(): if card.requires_target(): for t in card.targets: actions.add((card.play, t)) else: actions.add((card.play, None)) for character in player.characters: if character.can_attack(): for t in character.targets: actions.add((character.attack, t)) return actions def setup_game(): from fireplace.game import Game from fireplace.player import Player fireplace.cards.filter(name="Garrosh") player1 = Player("OddWarrior", warrior_deck, CardClass.WARRIOR.default_hero) player2 = Player("MurlocPaladin", paladin_deck, CardClass.PALADIN.default_hero) game = Game(players=(player1,player2)) game.start() for player in game.players: mull_count = 0 cards_to_mulligan = [] player.choice.choose(*cards_to_mulligan) game.begin_turn(player) return game if __name__ == '__main__': from fireplace.player import Player from fireplace.game import Game from fireplace.card import Card print("\n\n") for c in sorted(get_odd_warrior_deck()): print('1 x {}'.format(c)) card = Card(c[1]) print("\n\n") for c in sorted(get_murloc_paladin_deck()): print('1 x {}'.format(c)) card = Card(c[1]) print("\n\n") <file_sep>/z_jps/jps.py from ..utils import * class GIL_580: """Town Crier""" play = Find(FRIENDLY_DECK + RUSH) & ForceDraw(RANDOM(FRIENDLY_DECK + RUSH)) class GIL_547: """<NAME>""" events = Attack(SELF, MINION + MORTALLY_WOUNDED).after(Buff(SELF, "GIL_547e")) GIL_547e = buff(+2, +2) class UNG_957: """Direhorn Hatchling""" deathrattle = Shuffle(CONTROLLER, "UNG_957t1") class LOOT_364: """Reckless Flurry""" play = Hit(ALL_MINIONS, ARMOR(FRIENDLY_HERO)), Hit(FRIENDLY_HERO, ARMOR(FRIENDLY_HERO)) class UNG_933: """<NAME>""" play = Destroy(ALL_MINIONS + DAMAGED) class UNG_946: """Gluttonous Ooze""" play = GainArmor(FRIENDLY_HERO, ATK(ENEMY_WEAPON)), Destroy(ENEMY_WEAPON) class UNG_073: """Rockpool Hunter""" powered_up = Find(FRIENDLY_MINIONS + MURLOC) play = Buff(TARGET, "UNG_073e") UNG_073e = buff(+1, +1) class UNG_960: """Lost in the Jungle""" play = Summon(CONTROLLER, "CS2_101t") * 2 class UNG_015: """<NAME>""" play = Buff(ALL_MINIONS - SELF, "UNG_015e") class UNG_015e: atk = SET(3) max_health = SET(3) class UNG_950: """Vinecleaver""" events = Attack(FRIENDLY_HERO).after(Summon(CONTROLLER, "CS2_101t") * 2) class LOOT_167: """Fungalmancer""" play = Buff(SELF_ADJACENT, "LOOT_167e") LOOT_167e = buff(+2, +2) class GIL_667: """Rotten Applebaum""" deathrattle = Heal(FRIENDLY_HERO, 5) class LOOT_093: """Call to Arms""" play = Find(FRIENDLY_DECK + MINION + (COST <= 2)) & (Summon(CONTROLLER, RANDOM(FRIENDLY_DECK + MINION + (COST <= 2))) * 3) <file_sep>/HearthstoneGame.py import sys; sys.path.insert(0, '../fireplace'); sys.path.insert(0, './fireplace') from fireplace.exceptions import GameOver from hearthstone.enums import Zone import fireplace.cards import numpy as np import pytest import copy import py try: import direwolf as direwolf except: import hs.direwolf as direwolf import logging; logging.getLogger("fireplace").setLevel(logging.WARNING) def pr(player): return 0 if player == 1 else 1 def test_pr(): assert(pr(1) == 0) assert(pr(-1) == 1) class HearthstoneGame(): def __init__(self): self.startingHealth = 20 self.maxMinions = 7 self.minionSize = 5 self.deckSize = len(direwolf.warrior_deck) self.player1_deck = direwolf.warrior_deck self.player1_deck_names = direwolf.warrior_deck_names self.player2_deck = direwolf.paladin_deck self.player2_deck_names = direwolf.paladin_deck_names assert len(self.player1_deck) == len(self.player2_deck), "Players must have equal sized decks." self.decklists = [None, self.player1_deck, self.player2_deck] self.decknames = [None, self.player1_deck_names, self.player2_deck_names] self.enemyTargets = 9 self.totalTargets = 16 self.passTarget = self.enemyTargets - 1 self.faceTarget = self.passTarget - 1 self.maxMinionTargetIndex = self.enemyTargets * self.maxMinions self.maxCardTargetIndex = self.maxMinionTargetIndex + 10 * self.totalTargets self.boardMinionIndices = [i*self.minionSize for i in range(self.maxMinions)] self.playerCardsInHandIndex = -1 self.playerManaIndex = -2 self.playerMaxManaIndex = -3 self.playerHealthIndex = -4 self.playerTurnTrackerIndex = -5 self.playerCanHeroPowerIndex = -6 self.playerArmorIndex = -7 self.deckTrackerStartingIndex = -8 self.deckTrackerIndices = [i for i in range(self.deckTrackerStartingIndex, self.deckTrackerStartingIndex-self.deckSize, -1)] self.handTrackerStartingIndex = self.deckTrackerIndices[-1] - 1 self.handTrackerIndices = [i for i in range(self.handTrackerStartingIndex, self.handTrackerStartingIndex-self.deckSize, -1)] self.playerSize = sum([1 for _ in [self.playerHealthIndex, self.playerManaIndex, self.playerMaxManaIndex, self.playerTurnTrackerIndex, self.playerArmorIndex]]) + len(self.deckTrackerIndices) + len(self.handTrackerIndices) self.minionAttackIndex = 0 self.minionHealthIndex = 1 self.minionCanAttackIndex = 2 self.minionIdIndex = 3 self.minionDivineShieldIndex = 4 def getInitBoard(self): """ Returns: startBoard: a representation of the board (ideally this is the form that will be the input to your neural network) """ board = np.zeros(self.getBoardSize()) for i in [0,1]: row = board[i] decklist = self.decklists[i+1] row[self.playerHealthIndex] = self.startingHealth row[self.playerManaIndex] = 0 row[self.playerMaxManaIndex] = 0 for j in self.handTrackerIndices[:3]: row[j] = 1 for j in self.deckTrackerIndices[3:]: row[j] = 1 row[self.playerCardsInHandIndex] = sum([row[i] for i in self.handTrackerIndices]) board[0][self.playerTurnTrackerIndex] = 1 return board def getBoardSize(self): """ Returns: (x,y): a tuple of board dimensions """ ## player array size = 7 * minionSize + hp + mana + #cards_in_hand + deck_tracker self.boardRowSize = self.maxMinions * self.minionSize + self.playerSize return (2, self.boardRowSize) def getActionSize(self): ## actions 0-63 are minion 1-7 attacking targets 1-9 (face is 8, pass is 9) ## actions 64-223 are playing cards 1-10 at targets 1-16 (7 minions 1 face per player) ## actions 224-240 are hero power targets 1-16 ## action 240 is pass return 240 def getMinionActionIndex(self, minionIdx, targetIdx): return minionIdx * self.enemyTargets + targetIdx def extractMinionAction(self, idx): base = int(idx / self.enemyTargets) remainder = idx % self.enemyTargets return base, remainder def getCardActionIndex(self, cardIdx, targetIdx): return self.maxMinionTargetIndex + cardIdx * self.totalTargets + targetIdx def getHeroPowerActionIndex(self, targetIdx): return self.maxCardTargetIndex + targetIdx def extractCardAction(self, idx): idx -= self.maxMinionTargetIndex base = int(idx / self.totalTargets) remainder = idx % self.totalTargets return base, remainder def getHeroPowerActionIndex(self, targetIdx): return self.maxCardTargetIndex + targetIdx def extractHeroPowerAction(self, idx): idx -= self.maxMinionTargetIndex idx -= self.totalTargets remainder = idx % self.totalTargets return 0, remainder def extractAction(self, action): if action < self.maxMinionTargetIndex: a,b = self.extractMinionAction(action) return ("attack", a, b) elif action < self.maxCardTargetIndex: a,b = self.extractCardAction(action) return ("card", a, b) elif action < self.getActionSize() - 1: a,b = self.extractHeroPowerAction(action) return ("hero_power", a, b) elif action == self.getActionSize() - 1: return ("pass", 0 , 0) return ("{} INVALID".format(action), ("ATTACK",self.extractMinionAction(action)), ("CARD",self.extractCardAction(action))) def getNextState(self, board, player, action): b = np.copy(board) idx = pr(player) jdx = pr(-player) if board[idx][self.playerTurnTrackerIndex] == 0: return (b, -player) game = self.injectBoard(b) try: if action < self.maxMinionTargetIndex: attacker, target = self.extractMinionAction(action) minion = game.players[idx].field[attacker] if target == self.faceTarget: minion.attack(game.players[jdx].characters[0]) elif target == self.passTarget: minion.num_attacks = minion.max_attacks + 1 ## exhaust minion on pass else: minion.attack(game.players[jdx].characters[target+1]) elif action < self.maxCardTargetIndex: cardIdx, target = self.extractCardAction(action) card = game.players[idx].hand[cardIdx] if not card.requires_target(): card.play() ## 0 = own face, 1-7 = own minions ## 8-14 = enemy minions, 15 = enemy face elif target == 0: card.play(target=game.players[idx].hero) elif target <= 7: card.play(target=game.players[idx].field[target - 1]) elif target <= 14: card.play(target=game.players[jdx].field[target - 8]) elif target == 15: card.play(target=game.players[jdx].hero) ## hero power elif action < self.getActionSize() - 1: _, target = self.extractHeroPowerAction(action) heropower = game.players[idx].hero.power if not heropower.requires_target(): game.players[idx].hero.power.use() elif target == 0: heropower.use(target=game.players[idx].hero) elif target <= 7: heropower.use(target=game.players[idx].field[target - 1]) elif target <= 14: heropower.use(target=game.players[jdx].field[target - 8]) elif target == 15: heropower.use(target=game.players[jdx].hero) elif action == self.getActionSize() - 1: game.end_turn() except GameOver: pass b = self.extractBoard(game) return (b, -player) def getValidMoves(self, board, player): validMoves = [0 for _ in range(self.getActionSize())] validMoves[-1] = 1 if board[pr(player)][self.playerTurnTrackerIndex] == 0: return validMoves game = self.injectBoard(board) enemyPlayer = game.players[pr(-player)] player = game.players[pr(player)] ## cards for i in range(len(player.hand)): card = player.hand[i] if card.is_playable(): if not card.requires_target(): cIdx = self.getCardActionIndex(i, self.passTarget) validMoves[cIdx] = 1 else: ## 0 = own face, 1-7 = own minions ## 8-14 = enemy minions, 15 = enemy face for target in card.play_targets: tIdx = -1 if target == player.hero: tIdx = 0 elif target == enemyPlayer.hero: tIdx = 15 elif target in player.field: tIdx = player.field.index(target) + 1 elif target in enemyPlayer.field: tIdx = enemyPlayer.field.index(target) + 1 + 7 if tIdx >= 0: validMoves[self.getCardActionIndex(i, tIdx)] = 1 ## attacks for i in range(len(player.field)): char = player.field[i] if char.can_attack(debug=False): for target in char.attack_targets: tIdx = -1 if target == enemyPlayer.hero: tIdx = self.faceTarget elif target in enemyPlayer.field: tIdx = enemyPlayer.field.index(target) if tIdx >= 0: validMoves[self.getMinionActionIndex(i, tIdx)] = 1 ## hero power if player.hero.power.is_usable(): if not player.hero.power.requires_target(): validMoves[self.getHeroPowerActionIndex(0)] = 1 else: for target in player.hero.power.targets: tIdx = -1 if target == player.hero: tIdx = 0 elif target == enemyPlayer.hero: tIdx = 15 elif target in player.field: tIdx = player.field.index(target) + 1 elif target in enemyPlayer.field: tIdx = enemyPlayer.field.index(target) + 1 + 7 if tIdx >= 0: validMoves[self.getHeroPowerActionIndex(tIdx)] = 1 return validMoves def getGameEnded(self, board, player): idx = pr(player) jdx = pr(-player) if board[idx][self.playerHealthIndex] <= 0: return -1 if board[jdx][self.playerHealthIndex] <= 0: return 1 return 0 def getCanonicalForm(self, board, player): if player == -1: canonicalBoard = np.zeros(self.getBoardSize()) canonicalBoard[0] = board[1] canonicalBoard[1] = board[0] return canonicalBoard return board def getSymmetries(self, board, pi): ##jptodo: probs want to sort minions at some point return [(board, pi)] def stringRepresentation(self, board): return board.tostring() def extractRow(self, player): _player_deck = self.decklists[1] if player.first_player else self.decklists[-1] handTracker = [0 for _ in range(len(_player_deck))] deckTracker = [0 for _ in range(len(_player_deck))] minions = [] for character in player.characters[1:]: minion_id = _player_deck.index(character.id) minion_data = [character.atk, character.health, int(character.can_attack()), minion_id, int(character.divine_shield)] minions += minion_data assert len(minion_data) == self.minionSize, "Minion data being added not of correct size." for _ in range(self.maxMinions - (len(player.characters)-1)): minions += [0 for _ in range(self.minionSize)] _flag = False for i in range(len(_player_deck)): card = _player_deck[i] next_card = _player_deck[i+1] if i+1 < self.deckSize else None if _flag: _flag = False continue elif card == next_card: _flag = True handTracker[i] = int( card in [i.id for i in player.hand] ) handTracker[i+1] = int( [i.id for i in player.hand].count(card) == 2 ) deckTracker[i+1] = int( card in [i.id for i in player.deck] ) deckTracker[i] = int( [i.id for i in player.deck].count(card) == 2 ) else: handTracker[i] = int( card in [i.id for i in player.hand] ) deckTracker[i] = int( card in [i.id for i in player.deck] ) last_card = card row = [0 for _ in range(self.getBoardSize()[1])] for i in range(self.minionSize * self.maxMinions): row[i] = minions[i] row[self.playerCardsInHandIndex] = len(player.hand) row[self.playerHealthIndex] = player.characters[0].health row[self.playerManaIndex] = player.mana row[self.playerMaxManaIndex] = player.max_mana row[self.playerTurnTrackerIndex] = int(player.current_player) row[self.playerCanHeroPowerIndex] = int(player.hero.power.is_usable()) row[self.playerArmorIndex] = player.hero.armor for i in self.handTrackerIndices: row[i] = handTracker[self.handTrackerIndices.index(i)] for i in self.deckTrackerIndices: row[i] = deckTracker[self.deckTrackerIndices.index(i)] return row def extractBoard(self, game): b = np.zeros(self.getBoardSize()) b[0] = self.extractRow(game.players[0]) b[1] = self.extractRow(game.players[1]) return b def syncBoard(self, board): return self.extractBoard(self.injectBoard(board)) def injectBoard(self, board): game = direwolf.setup_game() for idx in [0,1]: player = game.players[idx] row = board[idx] _player_deck = self.decklists[idx+1] mis = [i*self.minionSize for i in range(self.maxMinions)] mma = self.playerMaxManaIndex hti = [i for i in self.handTrackerIndices] dti = [i for i in self.deckTrackerIndices] if row[self.playerTurnTrackerIndex] == 1: game.current_player = player player.hand = [] player.deck = [] player.hero.damage = player.hero.max_health - row[self.playerHealthIndex] player.max_mana = int(row[mma]) player.used_mana = int(row[mma] - row[self.playerManaIndex]) player.hero.power.activations_this_turn = 0 if row[self.playerCanHeroPowerIndex] == 1 else 1 player.hero.armor = row[self.playerArmorIndex] for mi in mis: if row[mi] > 0: cardIdx = int(row[mi + self.minionIdIndex]) card = player.card(_player_deck[cardIdx]) card.turns_in_play = 1 if row[mi + self.minionCanAttackIndex] > 0 else 0 card.atk = row[mi + self.minionAttackIndex] try: card.damage = card.max_health - row[mi + self.minionHealthIndex] except Exception as e: print(player.field) print(row[mi], mi, cardIdx, _player_deck[cardIdx], card) raise e card.divine_shield = bool(row[mi + self.minionDivineShieldIndex]) card.zone = Zone.PLAY for i in hti: if row[i] == 1: card = player.card(_player_deck[self.handTrackerIndices.index(i)]) card.zone = Zone.HAND for i in dti: if row[i] == 1: card = player.card(_player_deck[self.deckTrackerIndices.index(i)]) card.zone = Zone.DECK return game def listValidMoves(board, player): h = HearthstoneGame() try: v = h.getValidMoves(board, player) except GameOver: return [] l = [i for i in range(len(v)) if v[i] == 1] return l def display(board): print(tostring(board)) def tostring(board): h = HearthstoneGame() board = np.copy(board) s= "~"*30 if board[0][h.playerTurnTrackerIndex] == 1 else "-"*30 s+= "Top To Play (1)" if board[0][h.playerTurnTrackerIndex] == 1 else "Bottom To Play (-1)" s+="\n" s+=(' '.join(["[{}:{} {} ({})]".format(h.extractAction(l)[0], h.extractAction(l)[1], h.extractAction(l)[2], l) for l in listValidMoves(board, 1)])) s+=("\n\n") j = 0 s+=str(int(board[j][h.playerHealthIndex])) + ("+{}".format(str(int(board[j][h.playerArmorIndex]))) if board[j][h.playerArmorIndex] > 0 else "") + " " + str(int(board[j][h.playerManaIndex])) + " " + ' '.join(["[{}]".format(h.decknames[j+1][h.handTrackerIndices.index(i)]) for i in h.handTrackerIndices if board[j][i] == 1]) s+="\n" s+=str(["{}/{}{}".format(int(board[j][i]),int(board[j][i+1]), "⁷" if board[j][i+2]==0 else "") for i in range(0, h.minionSize*h.maxMinions, h.minionSize) if board[j][i]>0]) s+="\n" s+=("\n") j = 1 s+=str(["{}/{}{}".format(int(board[j][i]),int(board[j][i+1]), "⁷" if board[j][i+2]==0 else "") for i in range(0, h.minionSize*h.maxMinions, h.minionSize) if board[j][i]>0]) s+="\n" s+=str(int(board[j][h.playerHealthIndex])) + " " + str(int(board[j][h.playerManaIndex])) + " " + ' '.join(["[{}]".format(h.decknames[j+1][h.handTrackerIndices.index(i)]) for i in h.handTrackerIndices if board[j][i] == 1]) s+=("\n\n") s+=(' '.join(["[{}:{} {} ({})]".format(h.extractAction(l)[0], h.extractAction(l)[1], h.extractAction(l)[2], l) for l in listValidMoves(board, -1)])) s+=("\n") return s def dfs_lethal_solver(board, player=1): h = HearthstoneGame() frontier = [board, ] explored = [] parents = {} goal_node = None jdx = 1 if player == 1 else 0 while True: if len(frontier) == 0: return [] current_node = frontier.pop() explored.append(str(current_node)) # Check if node is goal-node if current_node[jdx][h.playerHealthIndex] <= 0: goal_node = current_node break # get nodes we're connected to connected_nodes = [] validMoves = h.getValidMoves(current_node, player)[:-1] validMoves = [i for i in range(len(validMoves)) if validMoves[i] == 1] for v in validMoves: new_node, _ = h.getNextState(current_node, player, v) parents[str(new_node)] = (current_node, v) connected_nodes.append(new_node) # expanding nodes for node in connected_nodes: if str(node) not in explored: frontier.append(node) path = [] c_node = (goal_node, None) while str(c_node[0]) != str(board): c_node = parents[str(c_node[0])] path.append(c_node[1]) return path[::-1] ## -- tests -- ## h=HearthstoneGame() penguinId = h.player1_deck_names.index("Town Crier") def test_drawCardEndOfTurn(): b = h.getInitBoard() g = h.injectBoard(b) occ = b[0][h.playerCardsInHandIndex] turns = 3 for i in range(turns): b, _ = h.getNextState(b, 1, 239) b, _ = h.getNextState(b, -1, 239) display(b) assert(b[0][h.playerCardsInHandIndex] == occ + turns) def test_getHeroPowerAction(): idx = h.getHeroPowerActionIndex(0) _, ex = h.extractHeroPowerAction(idx) assert(ex == 0) assert(h.getHeroPowerActionIndex(h.passTarget)==231) def test_frostboltingEveryone(): b = h.getInitBoard() fsIdx = h.player1_deck_names.index("Shield Slam") for j in h.handTrackerIndices: b[0][j] = 0 b[0][h.handTrackerIndices[fsIdx]] = 1 b[0][h.playerManaIndex] = 10 for i in [j*h.minionSize for j in range(h.maxMinions)]: for k in range(h.minionSize): b[0][i+k] = 1 b[1][i+k] = 1 b[0][i+h.minionCanAttackIndex] = 0 b[0][i+h.minionIdIndex] = penguinId for target in range(1, h.totalTargets-1, 1): cIdx = h.getCardActionIndex(0, target) v = h.getValidMoves(b, 1) display(b) assert(v[cIdx] == 1) def test_extractFinalCardIndex(): action = h.getCardActionIndex(9, 15) assert(h.extractAction(action) == ("card", 9, 15)) assert(h.extractAction(167) == ("card", 6, 8)) def test_handleUntargetedSpell(): b = h.getInitBoard() fsIdx = h.player1_deck_names.index("Whirlwind") for j in h.handTrackerIndices: b[0][j] = 0 b[0][h.handTrackerIndices[fsIdx]] = 1 b[1][0] = 1 b[1][1] = 1 b[1][2] = 0 b[1][3] = penguinId b[0][h.playerManaIndex] = 10 b,p = h.getNextState(b,1,h.getCardActionIndex(0,h.passTarget)) for j in h.handTrackerIndices: b[0][j] = 0 b[0][h.handTrackerIndices[fsIdx]] = 1 b,p = h.getNextState(b,1,h.getCardActionIndex(0,h.passTarget)) display(b) assert(b[1][0] == 0) assert(b[1][1] == 0) def test_handleTargetedCardOnlyMinionTarget(): b = h.getInitBoard() exIdx = h.player1_deck_names.index("Shield Slam") cwIdx = h.player1_deck_names.index("Gluttonous Ooze") for j in h.handTrackerIndices: b[0][j] = 0 b[0][h.handTrackerIndices[exIdx]] = 1 b[0][0] = 4 b[0][1] = 5 b[0][2] = 0 b[0][3] = cwIdx b[0][h.playerManaIndex] = 10 b,p = h.getNextState(b, 1, h.getCardActionIndex(0,1)) assert(b[0][0] == 4) assert(b[0][1] == 5) def test_injectBoard_fatigueDeath(): board = h.getInitBoard() p=1 for i in range(100): board, p = h.getNextState(board, p, 239) def test_getNextState_canAttackForLethal(): board = h.getInitBoard() board[1][h.playerHealthIndex] = 3 board[0][0] = 5 board[0][1] = 1 board[0][2] = 1 board[0][3] = 2 display(board) p=1 board, p = h.getNextState(board, p, 7) def test_injectExtractMatch(): board = h.getInitBoard() game = h.injectBoard(board) nboard = h.extractBoard(game) for i in range(len(board[0])): assert(board[0][i] == nboard[0][i]) def test_injectBoard_cardsInHand_afterOneTurn(): board = h.getInitBoard() game = h.injectBoard(board) player = game.players[0] jplayer = game.players[1] game.end_turn() game.end_turn() assert(len(player.hand) == 4) assert(len(jplayer.hand) == 4) def test_injectBoard_cardsInHand_onInit(): board = h.getInitBoard() game = h.injectBoard(board) player = game.players[0] assert(len(game.players[0].hand) == 3) def test_initBoard_correctDeck(): board = h.getInitBoard() game = h.injectBoard(board) player = game.players[0] assert(len(player.deck) == len(h.player1_deck)-board[0][h.playerCardsInHandIndex]) def test_getGameEnded_player2Win(): board = h.getInitBoard() board[0][h.playerHealthIndex] = 0 assert(h.getGameEnded(board, 1) == -1) assert(h.getGameEnded(board, -1) == 1) def test_getGameEnded_player1Win(): board = h.getInitBoard() board[1][h.playerHealthIndex] = 0 assert(h.getGameEnded(board, 1) == 1) assert(h.getGameEnded(board, -1) == -1) def test_getNextState_endOfGame(): board = h.getInitBoard() board[0][h.playerHealthIndex] = 0 h.getNextState(board, 1, h.getActionSize()-1) assert(h.getGameEnded(board, 1) == -1) def test_getNextState_blankPass_player1(): board = h.getInitBoard() action = h.getActionSize() - 1 player = 1 nextBoard, nextPlayer = h.getNextState(board, player, action) assert(nextPlayer == -1) assert(nextBoard[0][h.playerTurnTrackerIndex] == 0) def test_getNextState_blankPass_player2(): board = h.getInitBoard() game = h.injectBoard(board) game.end_turn() board = h.extractBoard(game) action = h.getActionSize() - 1 player = -1 nextBoard, nextPlayer = h.getNextState(board, player, action) assert(nextPlayer == -player) assert(nextBoard[0][h.playerTurnTrackerIndex] == 1) def test_getNextState_minionGoesFace_player2(): board = h.getInitBoard() board[1][0] = 2 board[1][1] = 3 board[1][2] = 1 board[1][3] = 1 game = h.injectBoard(board) game.end_turn() board = h.extractBoard(game) action = h.getMinionActionIndex(0, h.faceTarget) player = -1 nextBoard, nextPlayer = h.getNextState(board, player, action) assert(nextBoard[0][h.playerHealthIndex] == h.startingHealth - 2) def test_getNextState_oneMinionAttacking_oneMinionDefending_player1(): board = h.getInitBoard() board[0][0] = 2 board[0][1] = 3 board[0][2] = 0 board[0][3] = penguinId board[1][0] = 2 board[1][1] = 3 board[1][2] = 0 board[1][3] = penguinId game = h.injectBoard(board) game.end_turn() game.end_turn() b = h.extractBoard(game) b, p = h.getNextState(b, 1, h.getMinionActionIndex(0, 0)) assert(p == -1) assert(b[0][1] == 1) assert(b[1][1] == 1) def test_getNextState_oneMinionAttacking_oneMinionDefending_player2(): board = h.getInitBoard() board[0][0] = 2 board[0][1] = 3 board[0][2] = 0 board[0][3] = penguinId board[1][0] = 2 board[1][1] = 3 board[1][2] = 0 board[1][3] = penguinId game = h.injectBoard(board) game.end_turn() b = h.extractBoard(game) b, p = h.getNextState(b, -1, h.getMinionActionIndex(0, 0)) assert(p == 1) assert(b[0][1] == 1) assert(b[1][1] == 1) def test_getValidMoves_onlyPass(): board = h.getInitBoard() validMoves = h.getValidMoves(board, 1) assert(validMoves[-1] == 1) def test_getValidMoves_oneSleepingMinion(): board = h.getInitBoard() board[0][0] = 1 board[0][1] = 0 board[0][2] = 0 board[0][3] = penguinId v = h.getValidMoves(board, 1) assert(v[h.getMinionActionIndex(0, 0)] == 0) assert(v[h.getMinionActionIndex(0, 2)] == 0) assert(v[h.getMinionActionIndex(0, h.faceTarget)] == 0) assert(v[h.getMinionActionIndex(0, h.passTarget)] == 0) def test_getValidMoves_oneMinionAttacking(): board = h.getInitBoard() board[0][0] = 2 board[0][1] = 3 board[0][2] = 0 board[0][3] = penguinId game = h.injectBoard(board) game.end_turn() game.end_turn() b = h.extractBoard(game) v = h.getValidMoves(b, 1) assert(v[h.getMinionActionIndex(0, 0)] == 0) assert(v[h.getMinionActionIndex(0, 2)] == 0) assert(v[h.getMinionActionIndex(0, h.faceTarget)] == 1) assert(v[h.getMinionActionIndex(0, h.passTarget)] == 0) def test_getValidMoves_oneMinionAttacking_oneMinionDefending_player1(): board = h.getInitBoard() board[0][0] = 2 board[0][1] = 3 board[0][2] = 0 board[0][3] = penguinId board[1][0] = 2 board[1][1] = 3 board[1][2] = 0 board[1][3] = penguinId game = h.injectBoard(board) game.end_turn() game.end_turn() b = h.extractBoard(game) v = h.getValidMoves(b, 1) assert(v[h.getMinionActionIndex(0, 0)] == 1) assert(v[h.getMinionActionIndex(0, 2)] == 0) assert(v[h.getMinionActionIndex(0, h.faceTarget)] == 0) assert(v[h.getMinionActionIndex(0, h.passTarget)] == 0) def test_getValidMoves_oneMinionAttacking_oneMinionDefending_player2(): board = h.getInitBoard() board[0][0] = 2 board[0][1] = 3 board[0][2] = 0 board[0][3] = penguinId board[1][0] = 2 board[1][1] = 3 board[1][2] = 0 board[1][3] = penguinId game = h.injectBoard(board) game.end_turn() b = h.extractBoard(game) v = h.getValidMoves(b, -1) assert(v[h.getMinionActionIndex(0, 0)] == 1) assert(v[h.getMinionActionIndex(0, 2)] == 0) assert(v[h.getMinionActionIndex(0, h.faceTarget)] == 1) assert(v[h.getMinionActionIndex(0, h.passTarget)] == 0) def test_injectAndExtract(): board = h.getInitBoard() board[0][0] = 1 board[0][1] = 0 board[0][2] = 0 board[0][3] = penguinId irow = board[0] game = h.injectBoard(board) prow = h.extractRow(game.players[0]) assert(len(irow) == len(prow)) assert([irow[i] == prow[i] for i in range(len(irow))]) def test_extractRow(): board = h.getInitBoard() board[0][0] = 2 board[0][1] = 3 board[0][2] = 0 board[0][3] = penguinId game = h.injectBoard(board) for i in [0,1]: row = h.extractRow(game.players[i]) assert(row[h.playerHealthIndex] == h.startingHealth) assert(row[h.playerManaIndex] == 0) assert(row[h.playerMaxManaIndex] == 0) row = h.extractRow(game.players[0]) assert(row[0] == 2) assert(row[1] == 3) assert(row[2] == 0) assert(row[3] == penguinId) def test_getBoardSize(): assert(h.getBoardSize() == (2, h.maxMinions * h.minionSize + h.playerSize)) def test_getInitBoard(): initBoard = h.getInitBoard() for idx in [0,1]: row = initBoard[idx] assert(row[h.playerHealthIndex] == h.startingHealth) assert(row[h.playerManaIndex] == 0) assert(row[h.playerCardsInHandIndex] == 3) def test_getActionSize(): assert(h.getActionSize() == 240) def test_getGameEnded_draw(): player = 1 board = h.getInitBoard() assert(h.getGameEnded(board,player) == 0) def test_getGameEnded(): player = 1 idx = pr(player) board = h.getInitBoard() board[idx][h.playerHealthIndex] = -1 assert(h.getGameEnded(board,-player) == 1) assert(h.getGameEnded(board,player) == -1) def test_getMinionActionIndex(): assert(h.getMinionActionIndex(0,0) == 0) assert(h.getMinionActionIndex(1,0) == h.enemyTargets) def test_getCardActionIndex(): assert(h.getCardActionIndex(0,0) == h.maxMinions * h.enemyTargets) assert(h.getCardActionIndex(1,0) == h.maxMinions * h.enemyTargets + h.totalTargets) def test_extractMinionAction(): idx = h.getMinionActionIndex(3, 4) assert(h.extractMinionAction(idx)[0] == 3) assert(h.extractMinionAction(idx)[1] == 4) def test_extractCardAction(): idx = h.getCardActionIndex(9, 11) assert(h.extractCardAction(idx)[0] == 9) assert(h.extractCardAction(idx)[1] == 11) def test_heroPowerTargeted(): b = h.getInitBoard() g = h.injectBoard(b) p = g.players[0] heropower = p.hero.power b[0][h.playerManaIndex] = 10 b[0][h.playerCanHeroPowerIndex] = 1 for i in [j*h.minionSize for j in range(h.maxMinions)]: for k in range(h.minionSize): b[0][i+k] = 1 b[1][i+k] = 1 b[0][i+h.minionCanAttackIndex] = 0 b[0][i+h.minionIdIndex] = penguinId v = h.getValidMoves(b, 1) for target in range(h.totalTargets): hIdx = h.getHeroPowerActionIndex(target) assert(v[hIdx] == 1 or not heropower.requires_target()) def test_heroPowerUntargeted(): b = h.getInitBoard() b[1][h.playerManaIndex] = 10 b[1][h.playerCanHeroPowerIndex] = 1 b[1][h.playerTurnTrackerIndex] = 1 v = h.getValidMoves(b, -1) display(b) assert(v[h.getHeroPowerActionIndex(0)] == 1) def test_canOnlyHeroPowerOnce(): b = h.getInitBoard() b[0][h.playerManaIndex] = 10 b[0][h.playerCanHeroPowerIndex] = 1 b[0][h.playerTurnTrackerIndex] = 1 b, _ = h.getNextState(b, 1, h.getHeroPowerActionIndex(0)) v = h.getValidMoves(b, 1) assert(v[h.getHeroPowerActionIndex(0)] == 0) def test_handleChargeMinion(): pass def test_turnTime(): import time b = h.getInitBoard() s = time.time() p = 1 display(b) o=0 r = 100 for i in range(r): v = h.getValidMoves(b, p) v = [i for i in range(len(v)) if v[i] == 1] if v[0] == 239: o+=1 b, p = h.getNextState(b, p, v[0]) if h.getGameEnded(b,p) != 0: b = h.getInitBoard() p = 1 t = (time.time()-s)/(r-o) assert(t <= 0.1) def test_RockPoolHunter(): b = h.getInitBoard() mrglIdx = h.player2_deck_names.index("<NAME>") rockpoolIdx = h.player2_deck_names.index("Rockpool Hunter") for j in h.handTrackerIndices: b[1][j] = 0 b[1][h.handTrackerIndices[rockpoolIdx]] = 1 b[1][0] = 1 b[1][1] = 2 b[1][2] = 0 b[1][3] = mrglIdx b,p = h.getNextState(b, 1, 239) b,p = h.getNextState(b, p, 239) b,p = h.getNextState(b, p, 239) b,p = h.getNextState(b, p, 239) b,p = h.getNextState(b, p, 239) b,p = h.getNextState(b, -1, h.getCardActionIndex(0, 1)) display(b) assert(b[1][0] == 3) assert(b[1][1] == 3) def test_CallToArms(): b = h.getInitBoard() c2aIdx = h.player2_deck_names.index("<NAME>") b[1][h.playerTurnTrackerIndex] = 1 for j in h.handTrackerIndices: b[1][j] = 0 b[1][h.handTrackerIndices[c2aIdx]] = 1 b[1][h.playerManaIndex] = 10 b,p = h.getNextState(b, -1, h.getCardActionIndex(0, h.passTarget)) b[1][h.playerManaIndex] = 10 c2aIdx = h.player2_deck_names.index("<NAME>") for j in h.handTrackerIndices: b[1][j] = 0 b[1][h.handTrackerIndices[c2aIdx]] = 1 b,p = h.getNextState(b, -1, h.getCardActionIndex(0, h.passTarget)) g = h.injectBoard(b) display(b) assert(len(g.player2.field) == 4) assert(b[1][0] == 3) assert(b[1][1] == 3)<file_sep>/z_jps/__init__.py from .jps import * <file_sep>/jcs.py from HearthstoneGame import HearthstoneGame, tostring, dfs_lethal_solver import direwolf as direwolf import multiprocessing from multiprocessing.pool import Pool import numpy as np from math import * import operator import random import time import sys class HearthState: """ A state of the game, i.e. the game board. These are the only functions which are absolutely necessary to implement UCT in any 2-player complete information deterministic zero-sum game, although they can be enhanced and made quicker, for example by using a GetRandomMove() function to generate a random move during rollout. By convention the players are numbered 1 and 2. """ def __init__(self): self.playerJustMoved = 1 self.h = HearthstoneGame() self.board = self.h.getInitBoard() def Clone(self): """ Create a deep clone of this game state. """ st = HearthState() st.board = np.copy(self.board) st.playerJustMoved = self.playerJustMoved return st def DoMove(self, move): """ Update a state by carrying out the given move. Must update playerJustMoved. """ self.board, _ = self.h.getNextState(self.board, self.playerJustMoved, move) self.playerJustMoved = -self.playerJustMoved def GetMoves(self): """ Get all possible moves from this state. """ if self.board[0][self.h.playerHealthIndex] <= 0 or self.board[1][self.h.playerHealthIndex] <= 0: return [] v = self.h.getValidMoves(self.board, self.playerJustMoved) v = [i for i in range(self.h.getActionSize()) if v[i] == 1] return v def GetRandomMove(self): v = self.GetMoves() return random.choice(v) def GetBestBoardControlMove(self): v = self.GetMoves() if len(v) == 1: return v[0] best_power_gap = 0 best_move = v[0] idx = 0 if self.playerJustMoved == 1 else 1 jdx = int(not(idx)) for a in v[:-1]: b, _ = self.h.getNextState(self.board, self.playerJustMoved, a) power_gap = 0 for i in range(self.h.minionSize * self.h.maxMinions): friendly_atk = b[idx][i + self.h.minionAttackIndex] friendly_health = b[idx][i + self.h.minionHealthIndex] enemy_atk = b[jdx][i + self.h.minionAttackIndex] enemy_health = b[jdx][i + self.h.minionHealthIndex] power_gap += friendly_atk + friendly_health power_gap -= enemy_atk + enemy_health if power_gap > best_power_gap: best_power_gap = power_gap best_move = a return best_move def GetBestFaceMove(self): v = self.GetMoves() most_damage = 0 best_move = v[0] idx = 0 if self.playerJustMoved == 1 else 1 jdx = int(not(idx)) starting_health = self.board[jdx][self.h.playerHealthIndex] for a in v: b, _ = self.h.getNextState(self.board, self.playerJustMoved, a) damage = starting_health - b[jdx][self.h.playerHealthIndex] if damage > most_damage: most_damage = damage best_move = a return best_move def GetResult(self, playerjm): """ Get the game result from the viewpoint of playerjm. """ idx = 0 if playerjm == -1 else 1 return 1 if self.board[idx][self.h.playerHealthIndex] > 0 else 0 def __repr__(self): return tostring(self.board) class Node: """ A node in the game tree. Note wins is always from the viewpoint of playerJustMoved. Crashes if state not specified. """ def __init__(self, move = None, parent = None, state = None): self.move = move # the move that got us to this node - "None" for the root node self.parentNode = parent # "None" for the root node self.childNodes = [] self.wins = 0 self.visits = 0 self.untriedMoves = state.GetMoves() # future child nodes self.playerJustMoved = state.playerJustMoved # the only part of the state that the Node needs later def UCTSelectChild(self): """ Use the UCB1 formula to select a child node. Often a constant UCTK is applied so we have lambda c: c.wins/c.visits + UCTK * sqrt(2*log(self.visits)/c.visits to vary the amount of exploration versus exploitation. """ s = sorted(self.childNodes, key = lambda c: c.wins/c.visits + sqrt(2*log(self.visits)/c.visits))[-1] return s def AddChild(self, m, s): """ Remove m from untriedMoves and add a new child node for this move. Return the added child node """ n = Node(move = m, parent = self, state = s) self.untriedMoves.remove(m) self.childNodes.append(n) return n def Update(self, result): """ Update this node - one additional visit and result additional wins. result must be from the viewpoint of playerJustmoved. """ self.visits += 1 self.wins += result def TreeToString(self, indent): s = self.IndentString(indent) + str(self) for c in self.childNodes: s += c.TreeToString(indent+1) return s def IndentString(self,indent): s = "\n" for i in range (1,indent+1): s += "| " return s def ChildrenToString(self): s = "" for c in self.childNodes: s += str(c) + "\n" return s def __repr__(self): return "[M:" + str(self.move) + " W/V:" + str(self.wins) + "/" + str(self.visits) + " U:" + str(self.untriedMoves) + "]" def __add__(self, other): mergedNode = Node(state=HearthState()) mergedNode.playerJustMoved = self.playerJustMoved mergedNode.wins = self.wins + other.wins mergedNode.visits = self.visits + other.visits for child_a in self.childNodes: for child_b in other.childNodes: if child_a.move == child_b.move: mergedNode.childNodes.append(child_a + child_b) return mergedNode """ Conduct a UCT search for itermax iterations starting from rootstate. Return the best move from the rootstate. Assumes 2 alternating players (player 1 starts), with game results in the range [0.0, 1.0]. """ def UCT(rootstate, itermax, verbose=False, parallel=False, bestNode=False, prebuiltNode=None): rootnode = Node(state = rootstate) if prebuiltNode is None else prebuiltNode for i in range(itermax): if verbose: print("[{}/{}]".format(i+1,itermax), end="\r") node = rootnode state = rootstate.Clone() # Select while node.untriedMoves == [] and node.childNodes != []: # node is fully expanded and non-terminal node = node.UCTSelectChild() state.DoMove(node.move) # Expand if node.untriedMoves != []: # if we can expand (i.e. state/node is non-terminal) m = random.choice(node.untriedMoves) state.DoMove(m) node = node.AddChild(m,state) # add child and descend tree # Rollout - this can often be made orders of magnitude quicker using a state.GetRandomMove() function while state.GetMoves() != []: r = random.random() if r < 0.5: state.DoMove(state.GetRandomMove()) elif r < 0.6: state.DoMove(state.GetBestFaceMove()) else: state.DoMove(state.GetBestBoardControlMove()) # Backpropagate while node != None: # backpropagate from the expanded node and work back to the root node node.Update(state.GetResult(node.playerJustMoved)) # state is terminal. Update node with result from POV of node.playerJustMoved node = node.parentNode # Output some information about the tree - can be omitted if verbose and not parallel: print(rootnode.TreeToString(0)) elif not parallel: print(rootnode.ChildrenToString()) if bestNode: return sorted(rootnode.childNodes, key = lambda c: c.visits)[-1] if parallel: return rootnode return sorted(rootnode.childNodes, key = lambda c: c.visits)[-1].move # return the move that was most visited """ Parallelism, Pervasive AF """ def mp_worker(data): rootstate, itermax, verbose = data return UCT(rootstate, itermax, verbose=verbose, parallel=True) def mp_UCT(rootstate, itermax, verbose=False): p_c = 4 p = multiprocessing.Pool(p_c) data = [] for i in range(p_c): rs = rootstate.Clone() data.append((rs, int(itermax/p_c), verbose)) results = p.map(mp_worker, data) visits = {} for rootnode in results: for child in rootnode.childNodes: m = child.move if m in visits: visits[m] += child.visits else: visits[m] = child.visits s = sorted(visits.items(), key=operator.itemgetter(1)) if (verbose): print(["{}->{}".format(a[0],a[1]) for a in s]) p.close() p.join() return s[-1][0] """ Play a sample game between two UCT players where each player gets a different number of UCT iterations (= simulations = tree nodes). """ def UCTPlayGame(player_1, player_2, verbose=True): h = HearthstoneGame() state = HearthState() while (state.GetMoves() != []): real_player = 1 if state.board[0][h.playerTurnTrackerIndex] == 1 else -1 if sum(h.getValidMoves(state.board, real_player)) == 1 or real_player != state.playerJustMoved: m = 239 state.DoMove(m) elif real_player == 1: if (verbose) : print(state) m = player_1(state) if (verbose) : print("Best Move: " + str(m) + "\n") try: state.DoMove(m) except: state.DoMove(239) elif real_player == -1: if (verbose) : print(state) m = player_2(state) if (verbose) : print("Best Move: " + str(m) + "\n") try: state.DoMove(m) except: state.DoMove(239) return -1 if state.board[0][h.playerHealthIndex] <= 0 else 1 if __name__ == '__main__': ## need to set up keeping the tree between runs direwolf.setup_game() print("\nAnd there, but for the grace of god, I go.\n") h = HearthstoneGame() s = HearthState() passBot = lambda b: 239 randBot = lambda b: random.choice(b.GetMoves()) humBot = lambda b: int(input(":: ")) uct10 = lambda b: UCT(rootstate=b, itermax=10, verbose=True) lelBot_010 = lambda b: mp_UCT(rootstate=b, itermax=12, verbose=False) lelBot_100 = lambda b: mp_UCT(rootstate=b, itermax=100, verbose=False) lelBot_800 = lambda b: mp_UCT(rootstate=b, itermax=800, verbose=False) lelBot_400 = lambda b: mp_UCT(rootstate=b, itermax=400, verbose=False) lelBot_1600 = lambda b: mp_UCT(rootstate=b, itermax=1600, verbose=False) lelBot_3200 = lambda b: mp_UCT(rootstate=b, itermax=3200, verbose=False) t9000 = lambda b: mp_UCT(rootstate=b, itermax=9000, verbose=False) valueBot = lambda b: b.GetBestBoardControlMove() faceBot = lambda b: b.GetBestFaceMove() wins = {1:0, -1:0} matches = int(sys.argv[1]) if len(sys.argv) > 1 else 3 player_1 = lelBot_400 player_2 = valueBot total_time = 0.0 time_per_game = 0.0 play_orders = {1: (player_1, player_2), -1: (player_2, player_1)} for m in range(matches): print() for i in play_orders.keys(): s = time.time() wins[i*UCTPlayGame(play_orders[i][0], play_orders[i][1], verbose=False or humBot in play_orders[i])] += 1 total_time += time.time() - s time_per_game = total_time / (wins[1] + wins[-1]) print("[ {}:{} - {} games remaining, {} per game ]".format(wins[1], wins[-1], matches*2 - (wins[1]+wins[-1]), time.strftime('%H:%M:%S', time.gmtime(time.time() - s)))) print() print("\n\n[ {}:{} ( {}% ) ]\n\n".format(wins[1], wins[-1], int((wins[1]/(wins[-1]+wins[1]))*100))) print()<file_sep>/HearthstonePlayers.py import numpy as np from .HearthstoneGame import display from DMCTS import MCTS from utils import * class PassBot(): def __init__(self, game): self.game = game def play(self, board): return self.game.getActionSize() - 1 class RandBot(): def __init__(self, game): self.game = game def play(self, board): a = np.random.randint(self.game.getActionSize()) valids = self.game.getValidMoves(board, 1) while valids[a]!=1: a = np.random.randint(self.game.getActionSize()) return a class HumBot(): def __init__(self, game): self.game = game def play(self, board): valid = self.game.getValidMoves(board, 1) if sum(valid) == 1: return 239 valid_indices = [] for i in range(len(valid)): if valid[i] == 1: valid_indices.append(i) while True: a = int(input(":: ")) if valid[a]==1: break else: print('Invalid') return a class FaceBot(): def __init__(self, game): self.game = game def play(self, board): valid = self.game.getValidMoves(board, 1) valid_indices = [i for i in range(len(valid)) if valid[i] == 1] return valid_indices[0] class ValueBot(): def __init__(self, game): self.game = game def play(self, board): valid = self.game.getValidMoves(board, 1) valid[63] = 0 valid_indices = [i for i in range(len(valid)) if valid[i] == 1] ## get current my minions/enemy minions/enemy my_mc = sum([board[0][i*4 + 1] for i in range(7)]) en_mc = sum([board[1][i*4 + 1] for i in range(7)]) for a in valid_indices: nb, _ = self.game.getNextState(board, 1, a) ## check if after move i have same minions, enemy has less new_mmc = sum([board[0][i*4 + 1] for i in range(7)]) new_emc = sum([board[1][i*4 + 1] for i in range(7)]) ## if so, do that move, otherwise check for any minion actions that go face if new_mmc == my_mc and new_emc < en_mc: return a return valid_indices[0] class MatchBot20(): def __init__(self, game, iterations): self.game = game self.args = dotdict({'numMCTSSims': iterations, 'cpuct':1.0}) self.mcts = MCTS(game, self.args) def play(self, board): return np.argmax(self.mcts.getActionProb(board, temp=0)) if sum(self.game.getValidMoves(board, 1)) > 1 else 239
41813be9edab16f9dbcd03b63950404ab7a1d565
[ "Python" ]
6
Python
jp-ganis/DireWolfAlpha
3bf1a76c341d353cdf6e9e43e0b7f7e1316b3af6
21e82812c1bb32ebfae4530ce1ba665eb0871dbf
refs/heads/master
<repo_name>tz1006/wxlog<file_sep>/README.md # wxlog WeChat Logging <file_sep>/filelog.py #!/usr/bin/python3 # -*- coding: UTF-8 -*- # filename: filelog.py # version: 0.0.1 # description: filelog # useage: from filelog import from prettytable import PrettyTable from datetime import datetime from pytz import timezone from concurrent.futures import ThreadPoolExecutor import os import queue class log(): def __init__(self, path): self.wechat = wechat self.path = path self.checkdir(path) self.queue = queue.Queue() self.start() def checkdir(self, path): dirfile = path.rsplit('/', 1) if len(dirfile) == 2: dir = dirfile[0] if os.path.exists(dir) == False: os.makedirs(dir) print('初始化 %s' % path) def write(self, message, level='INFO', show=0): time = datetime.now(timezone('Asia/Shanghai')).strftime("%Y-%m-%d %H:%M:%S") text = '{} [{}] - {}'.format(time, level, message) self.queue.put(text) if show != 0: print(text) def writer(self): while self.logging == True: text = self.queue.get() with open(self.path , 'a') as f: f.write(text + '\n') def start(self): self.queue.queue.clear() self.logging = True pool = ThreadPoolExecutor(max_workers=1) pool.submit(self.writer) def exit(self): self.logging = False self.write('Log 退出.') def read(path, line=15): table = PrettyTable(["TIME", "LEVEL", "MESSAGE"]) with open(path) as f: txt = f.readlines() if len(txt) < line: line = len(txt) for i in range(line): i = - (i + 1) text = txt[i].replace('\n', '') time = text.rsplit(' ',3)[0] level = text.split('[')[1].split(']')[0] message = text.rsplit(' ',1) table.add_row([time, level, message]) print(table) if __name__ == '__main__': import code code.interact(banner = "", local = locals()) # a = log('test.log') # a.exit() # a.write('This is the first log.')
75e5aaa233a590ec8472ca0594b56b17c8474772
[ "Markdown", "Python" ]
2
Markdown
tz1006/wxlog
a7d1b1991b70ea9b7fea155d0688f7569c509b30
6ae1635f31fd062e20ce57de3a004225e3e4f768
refs/heads/main
<file_sep>package vntu.fcsa.gonchar.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @ComponentScan("vntu.fcsa.gonchar") @PropertySource("classpath:cashRegister.properties") public class SpringConfig { } <file_sep>package vntu.fcsa.gonchar; import org.junit.Test; public class TestCashRegister { @Test public void test1() { } } <file_sep>Cash register Cash register это программное обеспечение, иммитирующее работу магазинных кассовых апаратов. Управление программой выполняеться с помощью специальных команд - ключей определённых опций. Все команды управления выводяться в консоль при запуске приложения. Функционал приложения: - Добавление новых товаров; - Удаление устарелых товаров; - Покупка товаров; - Просмотр всех товаров; - Заказ доставки товаров; - Автоматическое пополнение запасов товара, если его количество меньше минимально допустимого; - Логирование всех чеков в специально созданном файле checks-logs; - Сумма с покупки попадает в кассу, и там хранится (файл cass.txt); - Если сумма в кассе превышает установленное значенние, выполняется инкасация, и деньги переводятся на банковский счёт (файл bank.txt); - Все имеющиеся в продаже товары (их ID, имя, вес и цена) хранятся в файлах базы данных: milkProducts.txt - молочные продукты, meatProducts.txt - мясные продукты; - Стоимость доставки товара равна 75% от цены продажи этого товара, деньги списываются с банковского счёта; Приложение находится на стадии активной доработки и устранения багов. При разработке приложения использовались следущие технологии: - использование конфигурационного класса для управления средствами Spring Core; - использование аннотаций @Component для автоматического создания бинов; - использование аннотаций @Scope для изменения области видимости бинов; - использование аннотаций @Value для присвоения значений полям через файл .properties; - использование аннотаций @Autowired и @Qualifier для внедрения зависимостей; - использование бинов для создания объектов; - использование инверсии управления (IoC); - использование Init, Destroy и Factory методов; - обработка исключений. <file_sep>cashRegister.model=toshiba cashRegister.batteryCharge=100<file_sep>package vntu.fcsa.gonchar; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import vntu.fcsa.gonchar.config.SpringConfig; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Comparator; import java.util.Scanner; /** * VNTU-FCSA * 1-ICT-20(b) * <NAME> **/ @Component @Scope("prototype") public class MilkProduct extends Product { private MilkProduct() { } private MilkProduct(int id, String name, double weight, double cost) { this.id = id; this.name = name; this.weight = weight; this.cost = cost; } public static MilkProduct createMilkProduct() { AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(SpringConfig.class); return context.getBean("milkProduct", MilkProduct.class); } @Override public void readProducts() { try { Scanner scanner = new Scanner(new File(CashRegister.MILK_PRODUCTS_TXT), StandardCharsets.UTF_8); while (scanner.hasNextLine()) { Product product = createMilkProduct(); String[] strings = scanner.nextLine().split(";"); product.setId(Integer.parseInt(strings[0])); product.setName(strings[1]); product.setWeight(Double.parseDouble(strings[2])); product.setCost(Double.parseDouble(strings[3])); product.autoDelivery(); CashRegister.MILK_PRODUCTS_LIST.add(new MilkProduct(product.getId(), product.getName(), product.getWeight(), product.getCost())); } scanner.close(); } catch (IOException | ArrayIndexOutOfBoundsException ex) { System.out.println(ex.getMessage()); } CashRegister.MILK_PRODUCTS_LIST.sort(Comparator.comparing(IProducts::getId)); } }
c25605b523c31ebde845908768405902341fe9e7
[ "Java", "Text", "INI" ]
5
Java
Sergey-GG/CashRegister-v1.2
cfb6ff0e1da0721dc0664efe1c75c97817e3b5c6
e275260b23ec9b1598700572dd0c87e8270eb0bc
refs/heads/master
<repo_name>s2841458/SolarSystem<file_sep>/constants.js var STAGE_WIDTH = 1280, STAGE_HEIGHT = 720, TIME_PER_FRAME = 33, GAME_FONTS = "bold 20px sans-sarif", TEXT_PRELOADING_X = 10, TEXT_PRELOADING_Y = 10, TEXT_PRELOADING = "LOADING..."; var IMAGE_START_X = 0, IMAGE_START_Y = 0, CHAR_SPEED = 5, SHIP_WIDTH = 96, SHIP_HEIGHT = 48, SHIP_START_X = 0, SHIP_START_Y = 336, MAP_WIDTH = 1280, MAP_HEIGHT = 720; var PATH_SHIP = "img/ship.png", PATH_SUN = "img/sun.gif", PATH_MERCURY = "img/mercury.gif", PATH_VENUS = "img/venus.gif", PATH_EARTH = "img/earth.gif", PATH_MARS = "img/mars.gif", PATH_JUPITER = "img/jupiter.gif", PATH_SATURN = "img/saturn.gif", PATH_URANUS = "img/uranus.gif", PATH_NEPTUNE = "img/neptune.gif", PATH_PLUTO = "img/pluto.gif", PATH_KUIPER = "img/kuiper.gif";<file_sep>/index.html <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Solar System</title> </head> <body> <h1>The Solar System</h1> <canvas id="gameCanvas"> Please upgrade your browser to support HTML5. </canvas> <p>Press "W" to travel through space</p> <script type="text/javascript" src="constants.js"></script> <script type="text/javascript" src="game.js"></script> <hr> <form action="test.php"> <input type="submit" value="TAKE THE TEST"> </form> </body> </html><file_sep>/test.php <?php $score = 0; $result = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_POST["question1"] == "1") { $score = $score + 1; } if ($_POST["question2"] == "3") { $score = $score + 1; } if ($_POST["question3"] == "2") { $score = $score + 1; } if ($_POST["question4"] == "1") { $score = $score + 1; } if ($_POST["question5"] == "3") { $score = $score + 1; } if ($score == "0") { $result = "Maybe knowing about space isn't for you"; } else if ($score == "1") { $result = "You could be a NASA intern!"; } else if ($score == "2") { $result = "You could be a Physicist"; } else if ($score == "3") { $result = "You could be a space engineer"; } else if ($score == "4") { $result = "you could be an Astronaut!"; } else if ($score == "5") { $result = "you could be an Astronaut!"; } } ?> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Solar System</title> </head> <body> <h1>TEST</h1> <p><?php echo $result;?></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <fieldset> <h4>Question 1: How many planets are in the solar system?</h4> <label for="q1a1">9</label> <input name="question1" id="q1a1" value="1" checked type="radio"></br> <label for="q1a2">10</label> <input name="question1" id="q1a2" value="2" type="radio"></br> <label for="q1a3">4</label> <input name="question1" id="q1a3" value="3" type="radio"></br> <label for="q1a4">8</label> <input name="question1" id="q1a4" value="4" type="radio"> </fieldset> <fieldset> <h4>Question 2: How many stars are in the solar system?</h4> <label for="q2a1">0</label> <input name="question2" id="q2a1" value="1" checked type="radio"></br> <label for="q2a2">2</label> <input name="question2" id="q2a2" value="2" type="radio"></br> <label for="q2a3">1</label> <input name="question2" id="q2a3" value="3" type="radio"></br> <label for="q2a4">9</label> <input name="question2" id="q2a4" value="4" type="radio"> </fieldset> <fieldset> <h4>Question 3: Which planet has 62 moons in its orbit?</h4> <label for="q3a1">Earth.</label> <input name="question3" id="q3a1" value="1" checked type="radio"></br> <label for="q3a2">Saturn.</label> <input name="question3" id="q3a2" value="2" type="radio"></br> <label for="q3a3">Uranus.</label> <input name="question3" id="q3a3" value="3" type="radio"></br> <label for="q3a4">Pluto.</label> <input name="question3" id="q3a4" value="4" type="radio"> </fieldset> <fieldset> <h4>Question 4: Which planet is a jovian planet?</h4> <label for="q4a1">Jupiter.</label> <input name="question4" id="q4a1" value="1" checked="" type="radio"></br> <label for="q4a2">Mercury.</label> <input name="question4" id="q4a2" value="2" type="radio"></br> <label for="q4a3">Earth.</label> <input name="question4" id="q4a3" value="3" type="radio"></br> <label for="q4a4">Venus.</label> <input name="question4" id="q4a4" value="4" type="radio"> </fieldset> <fieldset> <h4>Question 5: What is the Kuiper belt?</h4> <label for="q5a1">Where <NAME> lives.</label> <input name="question5" id="q5a1" value="1" checked type="radio"></br> <label for="q5a2">The path of an asteroid named Kuiper.</label> <input name="question5" id="q5a2" value="2" type="radio"></br> <label for="q5a3">A series of Pluto-like dwarf planets.</label> <input name="question5" id="q5a3" value="3" type="radio"></br> <label for="q5a4">The name of Saturn's rings.</label> <input name="question5" id="q5a4" value="4" type="radio"> </fieldset> <input type="submit" value="Submit answers"> </form> </body> </html>
5c05c430f16219f3cfbdbfa7b8cca118803ba610
[ "JavaScript", "HTML", "PHP" ]
3
JavaScript
s2841458/SolarSystem
96b1e80a4f88c7abd10938f88a64cd0492ee5ab3
3f21bc0685fe0f34c078dea3b3ebcfb68937ac42
refs/heads/main
<file_sep>let colorInputColor = document.getElementById('colorInputColor') colorInputColor.addEventListener('input', e => { let background = document.getElementById('background') background.style.background = e.target.value }) let size; function incfont() { let d = document.getElementById('fontsize').value; let x = document.getElementById('background'); x.style.fontSize = d + "px" size = d document.getElementById("size").innerHTML = size; }
c67159869b251ff3643e2a577deb3e5f6af101c9
[ "JavaScript" ]
1
JavaScript
espnal/Roguin-P
3f0f52f1cd1b923228e0389b4f30b3080da0d246
6734aa63d3b46c7aff2751277462df0611a7b28a
refs/heads/master
<file_sep>import collections import csv import os from collections import defaultdict from os.path import isfile import matplotlib.pyplot as plt import numpy as np from tflearn.data_utils import load_csv del os.environ['TCL_LIBRARY'] class DataPreprocessor: def __init__(self): self.data_path = os.path.join(os.path.dirname(__file__), '..', 'data') self.txt_files = [f for f in os.listdir(self.data_path) if (isfile(os.path.join(self.data_path, f)) and not f.startswith('RUL'))] self.train_csv_files = [] self.test_csv_files = [] def get_data(self, dataset_index, skip_columns=None): """ Loads training set by index. There are 4 training documents :param dataset_index: [0-3] index of the document to load :param skip_columns: list of columns to be removed from the dataset :return: training a tens data and labels """ self._preprocess(force=False) if skip_columns is None: skip_columns = [] training_file, test_file = self._get_files_at_index(dataset_index) train_x, train_y = load_csv(training_file, categorical_labels=False) test_x, test_y = load_csv(test_file, categorical_labels=False) if skip_columns: for col in skip_columns: DataPreprocessor._skip_column(train_x, col) DataPreprocessor._skip_column(test_x, col) np_train_x = np.array(train_x, dtype=np.float32) np_train_y = np.array(train_y, dtype=np.float32) np_train_y = np_train_y[:, np.newaxis] # add one axis np_test_x = np.array(test_x, dtype=np.float32) np_test_y = np.array(test_y, dtype=np.float32) np_test_y = np_test_y[:, np.newaxis] # add one axis return DataPreprocessor._normalize_columns(np_train_x), \ DataPreprocessor._normalize_columns(np_train_y), \ DataPreprocessor._normalize_columns(np_test_x), \ DataPreprocessor._normalize_columns(np_test_y) def _preprocess(self, force=False): """ Generates a csv file for each file in the folder :param force: Force csv generation even if target folder is not empty """ # Generate only if force is True or the target directory already contains data if force or not self._already_generated(): for txt_file in self.txt_files: self._generate_csv(txt_file) self.train_csv_files = [self._get_processed_file_path(f) for f in self.txt_files if f.startswith('train')] self.test_csv_files = [self._get_processed_file_path(f) for f in self.txt_files if f.startswith('test')] def _get_files_at_index(self, index): return self.train_csv_files[index], self.test_csv_files[index] def _generate_csv(self, fname): """ Creates a csv file from txt file :param fname: source .txt file (i.e. train_FD002.txt) """ txt_path = os.path.join(self.data_path, fname) csv_path = self._get_processed_file_path(fname) engine_count = DataPreprocessor._get_time_series_for_each_engine(txt_path) os.makedirs(os.path.dirname(csv_path), exist_ok=True) with open(csv_path, 'w') as csv_file: filewriter = csv.writer(csv_file, delimiter=',') filewriter.writerow(['unit', 'time', 'settings1', 'settings2', 'settings3', 'sensor1', 'sensor2', 'sensor3', 'sensor4', 'sensor5', 'sensor6', 'sensor7', 'sensor8', 'sensor9', 'sensor10', 'sensor11', 'sensor12', 'sensor13', 'sensor14', 'sensor15', 'sensor16', 'sensor17', 'sensor18', 'sensor19', 'sensor20', 'sensor21', 'rul']) with open(txt_path, 'r') as txt_file: lines = txt_file.readlines() for line_index in range(len(lines)): columns = lines[line_index].strip().split(' ') unit = columns[0] engine_count[unit] -= 1 columns.append(engine_count[unit]) filewriter.writerow(columns) def _already_generated(self): # FIXME: Use a more robust approach flist = os.listdir(self._get_processed_files_dir()) return len(flist) == 8 def _get_processed_file_path(self, fname): return os.path.join(self._get_processed_files_dir(), fname.replace('.txt', '.csv')) def _get_processed_files_dir(self): return os.path.join(self.data_path, 'processed') @staticmethod def _normalize_columns(input_array): return input_array / input_array.max(axis=0) @staticmethod def _skip_column(data, col_index): """ Removes column at index from each row in data :param data: Input data from csv (side effect) :param col_index: index of the column to remove """ for row in data: del row[col_index] @staticmethod def _get_time_series_for_each_engine(fpath): with open(fpath) as input_file: lines = input_file.readlines() engine_count = defaultdict(int) for line_index in range(len(lines)): engine = lines[line_index].split(' ')[0] engine_count[engine] += 1 return collections.OrderedDict(sorted(engine_count.items())) class LstmDataProcessor: def __init__(self): pass @staticmethod def reshape_array(data, num_steps, input_len): """ Reshapes input array to be fed into lstm cell. It will then reshaped into [batch_size, num_steps, input_len]. To avoid exceptions during reshape last elements of the array are cutoff :param data: nparray of shape [n, input_len] :param num_steps: number of sequential inputs :param input_len: number of entries for each input :return: a reshaped nparray """ truncated = LstmDataProcessor._lstm_truncate_sequence(data, num_steps) shape_0 = int(len(truncated) / num_steps) shape_1 = num_steps shape_2 = input_len return truncated.reshape([shape_0, shape_1, shape_2]) @staticmethod def _lstm_truncate_sequence(data_, num_steps): new_size = int(len(data_) / num_steps) * num_steps return data_[0:new_size] class PlotUtils: def __init__(self): self.plot_index = 1 def make_plot(self, predicted_data, real_data, num_points, mode, save_fname): """ Makes a plot for the given input :param predicted_data: nparray for predicted data :param real_data: nparray for real data (same size of predicted) :param num_points: number of points to be showed, less or at most equal to len(predicted) :param mode: enum{'save', 'show'} :param save_fname: If provided the image will be saved to file. The file name for the image to save """ if num_points: predicted_data = predicted_data[0:num_points] real_data = real_data[0:num_points] x_axis = np.arange(0, len(predicted_data), 1) # Build plot plt.figure(self.plot_index) plt.plot(x_axis, predicted_data, marker='o', linestyle='--', label='predicted') plt.plot(x_axis, real_data, marker='x', label='real') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) self.plot_index += 1 if mode != 'save': plt.show() else: dest_dir = os.path.join(os.path.dirname(__file__), '../plots') dest_file = os.path.join(dest_dir, save_fname) os.makedirs(os.path.dirname(dest_file), exist_ok=True) plt.savefig(dest_file) <file_sep># -*- coding: utf-8 -*- from __future__ import print_function import tflearn from data_processing.preprocess import DataPreprocessor, PlotUtils class RUL: def __init__(self, data_processor): self.data_proc = data_processor @staticmethod def build_mlp_dnn(input_len): """ :param input_len: Number of columns for each row of data :return: """ net = tflearn.input_data(shape=[None, input_len]) net = tflearn.fully_connected(incoming=net, n_units=input_len, activation='sigmoid') net = tflearn.batch_normalization(net) net = tflearn.fully_connected(incoming=net, n_units=input_len, activation='sigmoid') net = tflearn.batch_normalization(net) net = tflearn.fully_connected(incoming=net, n_units=input_len, activation='sigmoid') net = tflearn.batch_normalization(net) net = tflearn.fully_connected(incoming=net, n_units=input_len, activation='sigmoid') net = tflearn.batch_normalization(net) net = tflearn.fully_connected(incoming=net, n_units=input_len, activation='sigmoid') net = tflearn.batch_normalization(net) net = tflearn.fully_connected(incoming=net, n_units=1, activation='sigmoid') net = tflearn.regression(net, optimizer='adam', loss='mean_square', metric='R2', learning_rate=0.001) return net # params BATCH_SIZE = 128 N_EPOCHS = 20 dp = DataPreprocessor() plt_util = PlotUtils() rul = RUL(data_processor=dp) data_train_x, data_train_y, test_x, test_y = dp.get_data(dataset_index=0, skip_columns=[0]) # Define model net = RUL.build_mlp_dnn(data_train_x.shape[1]) model = tflearn.DNN(net) # Start training epoch = 1 for epoch in range(N_EPOCHS + 1): model.fit(data_train_x, data_train_y, n_epoch=1, batch_size=BATCH_SIZE, show_metric=True) test_data_prediction = model.predict(test_x) plt_util.make_plot(predicted_data=test_data_prediction, real_data=test_y, num_points=2000, mode='save', save_fname='fit_test/epoch_%s' % epoch) train_data_prediction = model.predict(data_train_x) plt_util.make_plot(predicted_data=train_data_prediction, real_data=data_train_y, num_points=2000, mode='save', save_fname='fit_train/epoch_%s' % epoch) print("Optimization finished!") <file_sep>backports.weakref==1.0rc1 bleach==1.5.0 cycler==0.10.0 html5lib==0.9999999 Markdown==2.6.8 matplotlib==2.0.2 numpy==1.13.1 olefile==0.44 Pillow==4.2.1 protobuf==3.3.0 pyparsing==2.2.0 python-dateutil==2.6.1 pytz==2017.2 six==1.10.0 tensorflow==1.2.1 tflearn==0.3.2 Werkzeug==0.12.2 <file_sep>import unittest from data_loader.preprocess import DataPreprocessor from app import RUL """ ...----.... ..-:"'' ''"-.. .-' '-. .' . . '. .' . . . . .''. .' . . . . . . . ..:. .' . . . . . . .. . . ....::. .. . . . . . . .. . ....:IA. .: . . . . . . .. . .. .. ....:IA. .: . . .. . . . . .. . ... ....:.:VHA. '.. . .. . . . . .. . .. . .....:.::IHHB. .:. . . . . . . . . . . ...:.:... .......:HIHMM. .:.... . . ."::"'.. . . . .:.:.:II;,. .. ..:IHIMMA ':.:.. ..::IHHHHHI::. . . ...:.::::.,,,. . ....VIMMHM .:::I. .AHHHHHHHHHHAI::. .:...,:IIHHHHHHMMMHHL:. . VMMMM .:.:V.:IVHHHHHHHMHMHHH::..:" .:HIHHHHHHHHHHHHHMHHA. .VMMM. :..V.:IVHHHHHMMHHHHHHHB... . .:VPHHMHHHMMHHHHHHHHHAI.:VMMI ::V..:VIHHHHHHMMMHHHHHH. . .I":IIMHHMMHHHHHHHHHHHAPI:WMM ::". .:.HHHHHHHHMMHHHHHI. . .:..I:MHMMHHHHHHHHHMHV:':H:WM :: . :.::IIHHHHHHMMHHHHV .ABA.:.:IMHMHMMMHMHHHHV:'. .IHWW '. ..:..:.:IHHHHHMMHV" .AVMHMA.:.'VHMMMMHHHHHV:' . :IHWV :. .:...:".:.:TPP" .AVMMHMMA.:. "VMMHHHP.:... .. :IVAI .:. '... .:"' . ..HMMMHMMMA::. ."VHHI:::.... .:IHW' ... . . ..:IIPPIH: ..HMMMI.MMMV:I:. .:ILLH:.. ...:I:IM : . .'"' .:.V". .. . :HMMM:IMMMI::I. ..:HHIIPPHI::'.P:HM. :. . . .. ..:.. . :AMMM IMMMM..:...:IV":T::I::.".:IHIMA 'V:.. .. . .. . . . 'VMMV..VMMV :....:V:.:..:....::IHHHMH "IHH:.II:.. .:. . . . . " :HB"" . . ..PI:.::.:::..:IHHMMV" :IP""HHII:. . . . . .'V:. . . ..:IH:.:.::IHIHHMMMMM" :V:. VIMA:I.. . . . .. . . .:.I:I:..:IHHHHMMHHMMM :"VI:.VWMA::. .: . .. .:. ..:.I::.:IVHHHMMMHMMMMI :."VIIHHMMA:. . . .: .:.. . .:.II:I:AMMMMMMHMMMMMI :..VIHIHMMMI...::.,:.,:!"I:!"I!"I!"V:AI:VAMMMMMMHMMMMMM' ':.:HIHIMHHA:"!!"I.:AXXXVVXXXXXXXA:."HPHIMMMMHHMHMMMMMV V:H:I:MA:W'I :AXXXIXII:IIIISSSSSSXXA.I.VMMMHMHMMMMMM 'I::IVA ASSSSXSSSSBBSBMBSSSSSSBBMMMBS.VVMMHIMM'"' I:: VPAIMSSSSSSSSSBSSSMMBSSSBBMMMMXXI:MMHIMMI .I::. "H:XIIXBBMMMMMMMMMMMMMMMMMBXIXXMMPHIIMM' :::I. ':XSSXXIIIIXSSBMBSSXXXIIIXXSMMAMI:.IMM :::I:. .VSSSSSISISISSSBII:ISSSSBMMB:MI:..:MM ::.I:. ':"SSSSSSSISISSXIIXSSSSBMMB:AHI:..MMM. ::.I:. . ..:"BBSSSSSSSSSSSSBBBMMMB:AHHI::.HMMI :..::. . ..::":BBBBBSSBBBMMMB:MMMMHHII::IHHMI ':.I:... ....:IHHHHHMMMMMMMMMMMMMMMHHIIIIHMMV" "V:. ..:...:.IHHHMMMMMMMMMMMMMMMMHHHMHHMHP' ':. .:::.:.::III::IHHHHMMMMMHMHMMHHHHM" "::....::.:::..:..::IIIIIHHHHMMMHHMV" "::.::.. .. . ...:::IIHHMMMMHMV" "V::... . .I::IHHMMV"' '"VHVHHHAHHHHMMV:"' """ class TestPreprocessor(unittest.TestCase): def setUp(self): self.dp = DataPreprocessor() self.dp.preprocess() def test_loaded(self): train_files = self.dp.train_csv_files test_files = self.dp.test_csv_files whole_folder = self.dp.txt_files rul_files = [f for f in whole_folder if f.startswith('RUL')] self.assertTrue(len(train_files) == 4) self.assertTrue(len(test_files) == 4) self.assertTrue(len(whole_folder) == 8) self.assertTrue(len(rul_files) == 0) def test_get_batch_files(self): train_file, test_file = self.dp.get_files_at_index(0) self.assertTrue('train_FD001.csv' in train_file) self.assertTrue('test_FD001.csv' in test_file) <file_sep>import unittest from data_loader.preprocess import DataPreprocessor from app import RUL """ ...----.... ..-:"'' ''"-.. .-' '-. .' . . '. .' . . . . .''. .' . . . . . . . ..:. .' . . . . . . .. . . ....::. .. . . . . . . .. . ....:IA. .: . . . . . . .. . .. .. ....:IA. .: . . .. . . . . .. . ... ....:.:VHA. '.. . .. . . . . .. . .. . .....:.::IHHB. .:. . . . . . . . . . . ...:.:... .......:HIHMM. .:.... . . ."::"'.. . . . .:.:.:II;,. .. ..:IHIMMA ':.:.. ..::IHHHHHI::. . . ...:.::::.,,,. . ....VIMMHM .:::I. .AHHHHHHHHHHAI::. .:...,:IIHHHHHHMMMHHL:. . VMMMM .:.:V.:IVHHHHHHHMHMHHH::..:" .:HIHHHHHHHHHHHHHMHHA. .VMMM. :..V.:IVHHHHHMMHHHHHHHB... . .:VPHHMHHHMMHHHHHHHHHAI.:VMMI ::V..:VIHHHHHHMMMHHHHHH. . .I":IIMHHMMHHHHHHHHHHHAPI:WMM ::". .:.HHHHHHHHMMHHHHHI. . .:..I:MHMMHHHHHHHHHMHV:':H:WM :: . :.::IIHHHHHHMMHHHHV .ABA.:.:IMHMHMMMHMHHHHV:'. .IHWW '. ..:..:.:IHHHHHMMHV" .AVMHMA.:.'VHMMMMHHHHHV:' . :IHWV :. .:...:".:.:TPP" .AVMMHMMA.:. "VMMHHHP.:... .. :IVAI .:. '... .:"' . ..HMMMHMMMA::. ."VHHI:::.... .:IHW' ... . . ..:IIPPIH: ..HMMMI.MMMV:I:. .:ILLH:.. ...:I:IM : . .'"' .:.V". .. . :HMMM:IMMMI::I. ..:HHIIPPHI::'.P:HM. :. . . .. ..:.. . :AMMM IMMMM..:...:IV":T::I::.".:IHIMA 'V:.. .. . .. . . . 'VMMV..VMMV :....:V:.:..:....::IHHHMH "IHH:.II:.. .:. . . . . " :HB"" . . ..PI:.::.:::..:IHHMMV" :IP""HHII:. . . . . .'V:. . . ..:IH:.:.::IHIHHMMMMM" :V:. VIMA:I.. . . . .. . . .:.I:I:..:IHHHHMMHHMMM :"VI:.VWMA::. .: . .. .:. ..:.I::.:IVHHHMMMHMMMMI :."VIIHHMMA:. . . .: .:.. . .:.II:I:AMMMMMMHMMMMMI :..VIHIHMMMI...::.,:.,:!"I:!"I!"I!"V:AI:VAMMMMMMHMMMMMM' ':.:HIHIMHHA:"!!"I.:AXXXVVXXXXXXXA:."HPHIMMMMHHMHMMMMMV V:H:I:MA:W'I :AXXXIXII:IIIISSSSSSXXA.I.VMMMHMHMMMMMM 'I::IVA ASSSSXSSSSBBSBMBSSSSSSBBMMMBS.VVMMHIMM'"' I:: VPAIMSSSSSSSSSBSSSMMBSSSBBMMMMXXI:MMHIMMI .I::. "H:XIIXBBMMMMMMMMMMMMMMMMMBXIXXMMPHIIMM' :::I. ':XSSXXIIIIXSSBMBSSXXXIIIXXSMMAMI:.IMM :::I:. .VSSSSSISISISSSBII:ISSSSBMMB:MI:..:MM ::.I:. ':"SSSSSSSISISSXIIXSSSSBMMB:AHI:..MMM. ::.I:. . ..:"BBSSSSSSSSSSSSBBBMMMB:AHHI::.HMMI :..::. . ..::":BBBBBSSBBBMMMB:MMMMHHII::IHHMI ':.I:... ....:IHHHHHMMMMMMMMMMMMMMMHHIIIIHMMV" "V:. ..:...:.IHHHMMMMMMMMMMMMMMMMHHHMHHMHP' ':. .:::.:.::III::IHHHHMMMMMHMHMMHHHHM" "::....::.:::..:..::IIIIIHHHHMMMHHMV" "::.::.. .. . ...:::IIHHMMMMHMV" "V::... . .I::IHHMMV"' '"VHVHHHAHHHHMMV:"' """ class TestRUL(unittest.TestCase): def setUp(self): self.dp = DataPreprocessor() self.rul = RUL(data_processor=self.dp) self.rul.preprocess_data() def test_load_and_cleanup(self): data, labels = self.rul.load_data(0) self.assertTrue(data is not None, "Data not None") self.assertTrue(labels is not None, "Labels not None") self.assertTrue(len(labels) == len(data), "Data and labels have same length") # Before column remove self.assertTrue(len(data[0]) == 26) RUL._skip_column(data=data, col_index=0) self.assertTrue(len(data[0]) == 25)
d31113ce4a40fec54abb1e6c4c7471dbed39495f
[ "Python", "Text" ]
5
Python
insanediv/tensorflow-predictive-analisys
46fa83b093654dd058343603f2c85bbbe8454fbd
7122f0447a9223790ced78bb18cbc3574e03496b
refs/heads/master
<file_sep># SealMic-Android 本文档介绍了 SealMic 的整体框架设计和核心流程,为开发者了解 SealMic 的主要功能提供指导性说明。[体验 SealMic](https://www.rongcloud.cn/download/demo) 。 ## 背景介绍 SealMic 展示了如何通过融云 RTCLib SDK 实现音频社交功能。 * **RTCLib SDK:融云实时音视频 SDK** ## 主要功能介绍 SealMic 主要由两个页面构成:语音聊天室列表页和语音聊天室详情页面。 * **语音聊天室列表页** &emsp; 展示了当前所有创建的聊天室,可以选择加入某个聊天室或创建新聊天室。 * **语音聊天室详情页** &emsp; 展示了当前语音聊天室内的麦位及用户信息。 所有在语音聊天室内的用户可以发送文字进行聊天。 房主和在麦位上的用户可进行语音聊天。 房主可针对麦位进行控制,比如限制在麦位上的用户发言或限制用户进行上麦操作。 房主可更改聊天室的背景来使聊天室内所有的用户同时看见当前新的聊天室的背景。 ** 特别说明:为了重点演示 SealMic 核心功能,SealMic 中简化了部分逻辑:** * 没有用户管理体系,而是根据用户 id 的 hashcode 值取余后生成对应资源的 index. ## 语音聊天室的概念 在 SealMic 中有三个抽象概念的语音聊天室,虽然使用相同的 id 但功能范围各不同: * **业务层面的语音聊天室** &emsp;在用户创建聊天室时请求业务服务器,业务服务器创建聊天室,并返回给创者者当前聊天室的 id,同时其他用户可通过获取聊天室列表接口获取到此聊天室的 id。用户调根据此聊天室 id 加入 IM 聊天室和音频 RTC 房间。当前用户属于哪个聊天室,当前聊天室内有哪些用户是基于此聊天室。 * **IM 即时通讯层面的语音聊天室** &emsp;加入 IM 聊天室后,用户可以发送文本消息聊天。另外维护聊天室各种状态的信令消息也通过 IM 服务来收发。 * **RTC 音频层面的语音聊天室** &emsp; 加入 RTC 聊天室后,用户可以获得到当前语音聊天室内所有发布音频流的用户,并选择订阅音频流来收听目标用户的声音,也可以自己发布音频流让其他人听到自己的声音。 以下是用户加入语音聊天室并进行语音聊天过程的时序。 ![](./images/image01.png) 说明:为了防止用户在调用业务服务器加入聊天室与加入 IM 聊天室之间的消息丢失,需要先加入 IM 服务器,再调用业务服务器加入聊天室。 ## 语音聊天室中的角色 语音聊天室中一共有三个角色: * **听众** &emsp; 加入聊天室后用户的默认角色。可以进行文字交流,并收听聊天室内其他用户的发言。可以选择空麦位进行上麦操作;或者由 *房主* 以抱麦形式上麦,上麦后成为 *连麦者* 进行语音发言。 * **连麦者** &emsp; 可进行语音发言,也可以随意更更改到其他空的麦位上,即跳麦;也可以选择下麦变回 *听众*。 * **房主** &emsp; 即语音聊天室的创建者。 房主具有房间的控制能力。 房主可以更改聊天室中的麦位的状态。 房主可以选择房间内的某个 *听众* 上麦,使其成为连麦者。 房主可以使 *连麦者* 下麦变为 *听众* 或将 *连麦者* 踢出聊天室。 房主可以更改聊天室内的背景使聊天室内的其他用户同步更新此背景。 房主可以解散聊天室,当房主退出或者解散聊天室时聊天室内的其他用户会受到通知并退出聊天室。 ## 语音聊天室中的麦位 在 SealMic 聊天室中一共有8个麦位,只有房主和在麦位上的用户可以进行发言。房主可以对麦位进行控制,麦位一共有以下几个状态: * **空麦位** &emsp; 听众可以上麦,连麦者可进行跳麦到此麦位,房主可进行抱麦使听众上麦。 * **麦位被禁止发言** &emsp; 在禁止发言的麦位上,连麦者无法进行语音发言。 * **麦位被锁定** &emsp; 在被锁定的麦位上,听众无法进行上麦操作,连麦者无法进行跳麦操作。 ## 用户上麦流程 以下流程图简述了听众进行上麦操作时,用户与各个服务器的之间的交互。 ![](./images/image02.png) ## 房主抱麦流程 以下流程图简述了房主抱麦时,被抱麦的听众及其他用户与各个服务器之间的交互流程。 ![](./images/image03.png) ## 房主麦位管理和更换聊天室背景流程 以下流程图简述了房主进行麦位控制和更换聊天室背景时,其他用户与各个服务器之间的交互并完成同步更新的流程。 ![](./images/image04.png) ## 代码目录介绍 Android 端代码主要由 ui,task,net,im,rtc 五个包组成。 * **ui** &emsp;包含所有显示相关的组件。包含 聊天室界面 ChatRoomActivity,主界面和聊天室界面使用到一些控件。 * **task** &emsp;对于首页和聊天室内的业务处理。UI 层直接调用 task 包中的业务管理类进行业务操作,由这些管理类去调用 net,im,rtc 包中对应类的方法去实现相应操作并将结果反馈给 UI。主要业务由以下三个管理类实现: AuthManager 管理用户登录业务,RoomManager 管理聊天室相关业务,ThreadManager 管理线程。 * **net** &emsp;对于所有关于 SealMic 业务逻辑上的网络请求封装。网络部分使用 Retrofit 2.0 框架进行封装。 * **im** &emsp;对应 SealMic 中使用 融云 IMLib 对即时通讯部分的封装和自定义消息的实现。自定义消息包括聊天室麦位更改消息,聊天室背景改变消息。 * **rtc** &emsp;对应 SealMic 中使用 融云 RTCLib 对音频聊天相关的功能封装。 其他包由以下几个组成: * **constant** &emsp;定义了网络相关常量和业务错误代码。 * **model** &emsp;业务中使用的模型对象和枚举。 * **utils** &emsp;包括日志打印,Toast 提示等辅助工具,随机资源素材管理。 在根目录下有以下两个类: * **SealMicApp** &emsp;应用的 Application 类,在应用启动时初始化了 融云 IMLib 及其他组件。 * **MainActivity** &emsp;应用的主界面,展示了当前已创建的聊天室列表。 ## 运行环境 * Android Studio 3.2&ensp;以上版本 SealMic 适配了 Android X,所以需要 使用 3.2&ensp;以上版本的 Android Studio 才能保证可以正常编译和使用。 * 推荐使用真实 Android 设备 部分模拟器会存在功能缺失或运行环境不稳定等情况影响使用体验。 ## 文档链接 * 关于 Android IM 即时通讯 SDK 的 [开发指南](https://www.rongcloud.cn/docs/android.html) * 关于 Android 音视频通讯 SDK 的 [开发指南](https://www.rongcloud.cn/docs/android_rtclib.html) * SealMic Server 源码可以参考[这里](https://github.com/rongcloud/sealmic-server) ## 联系我们 * 如果发现了示例代码的 bug, 欢迎提交 [issue](https://github.com/rongcloud/sealmic-android/issues) * 如果有售前咨询问题, 可以拨打 13161856839 进行咨询。 <file_sep>package cn.rongcloud.sealmic.task; import java.util.List; import cn.rongcloud.sealmic.model.RoomMicPositionInfo; import cn.rongcloud.sealmic.task.role.Role; import io.rong.imlib.model.Message; /** * 聊天房间事件监听 */ public interface RoomEventListener { /** * 房间人数发生变化 * @param memberCount */ void onRoomMemberChange(int memberCount); /** * 麦位信息更新 * * @param micPositionInfoList */ void onMicUpdate(List<RoomMicPositionInfo> micPositionInfoList); /** * 当有房间内有人说话时,回调所有当前说话人的用户id * * @param speakUserIdList */ void onRoomMicSpeak(List<String> speakUserIdList); /** * 当有新的聊天消息 * * @param message */ void onMessageEvent(Message message); /** * 发送消息失败 * * @param message * @param errorCode */ void onSendMessageError(Message message, int errorCode); /** * 房间背景更新 * * @param bgId */ void onRoomBgChanged(int bgId); /** * 当前角色发生改变 * * @param role */ void onRoleChanged(Role role); /** * 被提出房间 */ void onKickOffRoom(); /** * 房间被销毁 */ void onRoomDestroy(); /** * 长时间网络异常时退出房间 */ void onErrorLeaveRoom(); /** * 当房间超出了最长存在时间 */ void onRoomExistOverTimeLimit(); } <file_sep>package cn.rongcloud.sealmic.ui; public class ChatRoomBgItem { int drawableId; boolean checked; public ChatRoomBgItem() { } public ChatRoomBgItem(int drawableId, boolean checked) { this.drawableId = drawableId; this.checked = checked; } public int getDrawableId() { return drawableId; } public void setDrawableId(int drawableId) { this.drawableId = drawableId; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } }<file_sep>package cn.rongcloud.sealmic.constant; public class IntentExtra { public final static String ROOM_ID = "roomId"; public final static String EXIT_ROOM = "exit_room"; } <file_sep>package cn.rongcloud.sealmic.utils.log; import android.content.Context; public class SLog { public static final String TAG_NET = "SealMicNet"; public static final String TAG_TASK = "SealMicTask"; public static final String TAG_IM = "SealMicIM"; public static final String TAG_RTC = "SealMicRTC"; public static void init(Context context) { SLogCreator.sInstance.init(context); } public static void i(String tag, String msg) { SLogCreator.sInstance.i(tag, msg); } public static void i(String tag, String msg, Throwable tr) { SLogCreator.sInstance.i(tag, msg, tr); } public static void v(String tag, String msg) { SLogCreator.sInstance.v(tag, msg); } public static void v(String tag, String msg, Throwable tr) { SLogCreator.sInstance.v(tag, msg, tr); } public static void d(String tag, String msg) { SLogCreator.sInstance.d(tag, msg); } public static void d(String tag, String msg, Throwable tr) { SLogCreator.sInstance.d(tag, msg, tr); } public static void w(String tag, String msg) { SLogCreator.sInstance.w(tag, msg); } public static void w(String tag, String msg, Throwable tr) { SLogCreator.sInstance.w(tag, msg, tr); } public static void e(String tag, String msg) { SLogCreator.sInstance.e(tag, msg); } public static void e(String tag, String msg, Throwable tr) { SLogCreator.sInstance.e(tag, msg, tr); } private static class SLogCreator { // 使用其他Log请替换此实现 public final static ISLog sInstance = new SimpleDebugSLog(); } } <file_sep>#!/bin/bash # Created by qixinbing on 2019/3/7. # Copyright (c) 2019 RongCloud. All rights reserved. #本脚本用于开发进行本地打包测试 #使用方式 :终端进入当前目录,执行 sh pre_build.sh #按需修改下面的参数 # app 版本号 export APP_Version="1.0.0" export Branch="dev" cd .. sh script/build.sh<file_sep>package cn.rongcloud.sealmic.net; import java.util.HashMap; import java.util.List; import cn.rongcloud.sealmic.model.UserInfo; import cn.rongcloud.sealmic.net.model.CreateRoomResult; import cn.rongcloud.sealmic.net.model.LoginResult; import cn.rongcloud.sealmic.model.DetailRoomInfo; import cn.rongcloud.sealmic.model.BaseRoomInfo; import cn.rongcloud.sealmic.net.retrofit.CallBackWrapper; import cn.rongcloud.sealmic.net.retrofit.RetrofitClient; import cn.rongcloud.sealmic.net.retrofit.RetrofitUtil; import okhttp3.RequestBody; /** * 使用 Retrofit 实现对用户信息的请求 */ public class SealMicRequest { private RetrofitClient mClient; private SealMicService mService; public SealMicRequest(RetrofitClient client) { mClient = client; mService = mClient.createService(SealMicService.class); } /** * 登录 * * @param deviceId * @param callBack */ public void login(String deviceId, RequestCallBack<LoginResult> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("deviceId", deviceId); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.login(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 创建房间 * * @param subject 房间主题 * @param type 房间类型 * @param callBack */ public void createRoom(String subject, int type, RequestCallBack<CreateRoomResult> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("subject", subject); paramsMap.put("type", String.valueOf(type)); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.createRoom(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 获取房间列表 * * @param callBack */ public void getChatRoomList(RequestCallBack<List<BaseRoomInfo>> callBack) { mService.getRoomList().enqueue(new CallBackWrapper<>(callBack)); } /** * 获取房间详情 */ public void getChatRoomDetail(String roomId, RequestCallBack<DetailRoomInfo> callBack) { mService.getRoomDetailInfo(roomId).enqueue(new CallBackWrapper<>(callBack)); } /** * 获取房间用户列表 * * @param roomId * @param callBack */ public void getChatRoomUserList(String roomId, RequestCallBack<List<UserInfo>> callBack) { mService.getRoomUserList(roomId).enqueue(new CallBackWrapper<>(callBack)); } /** * 销毁房间 * * @param roomId * @param callBack */ public void destroyRoom(String roomId, RequestCallBack<Boolean> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.destroyRoom(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 加入房间 * * @param roomId * @param callBack */ public void joinRoom(String roomId, RequestCallBack<DetailRoomInfo> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.joinChatRoom(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 离开房间 * * @param roomId * @param callBack */ public void leaveRoom(String roomId, RequestCallBack<Boolean> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.leaveChatRoom(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 当前用户(非房主)上麦 * * @param roomId * @param position * @param callBack */ public void joinMic(String roomId, int position, RequestCallBack<Boolean> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); paramsMap.put("targetPosition", String.valueOf(position)); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.joinChatMic(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 当前用户(非房主)下麦 * * @param roomId * @param position * @param callBack */ public void leaveMic(String roomId, int position, RequestCallBack<Boolean> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); paramsMap.put("targetPosition", String.valueOf(position)); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.leaveChatMic(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 当前用户更改麦位位置, 即跳麦 * * @param roomId 当前房间 id * @param fromPosition * @param toPosition * @param callBack */ public void changMicPosition(String roomId, int fromPosition, int toPosition, RequestCallBack<Boolean> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); paramsMap.put("fromPosition", String.valueOf(fromPosition)); paramsMap.put("toPosition", String.valueOf(toPosition)); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.changeChatMicPosition(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 房主更改麦位状态 * * @param roomId * @param position * @param userId * @param cmd * @param callBack */ public void controlMicPosition(String roomId, int position, String userId, int cmd, RequestCallBack<Boolean> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); paramsMap.put("targetPosition", String.valueOf(position)); paramsMap.put("targetUserId", userId); paramsMap.put("cmd", String.valueOf(cmd)); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.controlChatMic(body).enqueue(new CallBackWrapper<>(callBack)); } /** * 设置房间背景 * * @param roomId * @param backgroundIndex * @param callBack */ public void setRoomBackground(String roomId, int backgroundIndex, RequestCallBack<Boolean> callBack) { HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("roomId", roomId); paramsMap.put("bgId", String.valueOf(backgroundIndex)); RequestBody body = RetrofitUtil.createJsonRequest(paramsMap); mService.setRoomBackground(body).enqueue(new CallBackWrapper<>(callBack)); } } <file_sep>package cn.rongcloud.sealmic.ui.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import java.util.ArrayList; import java.util.List; import cn.rongcloud.sealmic.R; import cn.rongcloud.sealmic.utils.DisplayUtils; public class MicSeatRippleView extends View { private final static long DEFAULT_AUTO_STOP_RIPPLE_INTERVAL_TIME_MILLIS = 3000; private Context mContext; // 画笔 private Paint paint; // 控件宽 private float width; // 控件高 private float height; private float maxRadius; // 声波的圆圈集合 private List<Circle> rippleList; // 圆圈扩散的速度 private float speed; // 圆圈初始距离 private int startOffset; // 圆圈之间的间距 private int density; // 圆圈的颜色 private int color; // 圆圈是否为填充模式 private boolean isFill; // 圆圈是否为渐隐模式 private boolean isAlpha; // 是否启动动画 private boolean startRipple = false; // 自动取消动画时间 private long autoStopTimeIntervalMillis = DEFAULT_AUTO_STOP_RIPPLE_INTERVAL_TIME_MILLIS; // 开始动画的时间 private long startRippleTimeMillis; public MicSeatRippleView(Context context) { this(context, null); } public MicSeatRippleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MicSeatRippleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // 获取用户配置属性 TypedArray tya = context.obtainStyledAttributes(attrs, R.styleable.MicSeatRippleView); color = tya.getColor(R.styleable.MicSeatRippleView_color, Color.BLUE); speed = tya.getFloat(R.styleable.MicSeatRippleView_speed, 1); density = tya.getInt(R.styleable.MicSeatRippleView_density, 10); isFill = tya.getBoolean(R.styleable.MicSeatRippleView_isFill, false); isAlpha = tya.getBoolean(R.styleable.MicSeatRippleView_isAlpha, false); startOffset = (int) tya.getDimension(R.styleable.MicSeatRippleView_startOffset, 0); tya.recycle(); init(); } private void init() { mContext = getContext(); // 设置画笔样式 paint = new Paint(); paint.setColor(color); paint.setStrokeWidth(DisplayUtils.dp2px(mContext, 1)); if (isFill) { paint.setStyle(Paint.Style.FILL); } else { paint.setStyle(Paint.Style.STROKE); } paint.setStrokeCap(Paint.Cap.ROUND); paint.setAntiAlias(true); // 添加第一个圆圈 rippleList = new ArrayList<>(); density = DisplayUtils.dp2px(mContext, density); // 设置View的圆为半透明 setBackgroundColor(Color.TRANSPARENT); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); drawInCircle(canvas); } /** * 圆到宽度 * * @param canvas */ private void drawInCircle(Canvas canvas) { canvas.save(); // 处理每个圆的宽度和透明度 for (int i = 0; i < rippleList.size(); i++) { Circle c = rippleList.get(i); // 当半径超出View的宽度后移除 if (c.radius > maxRadius) { rippleList.remove(i); } else { paint.setAlpha(c.alpha); canvas.drawCircle(width / 2, height / 2, c.radius - paint.getStrokeWidth(), paint); // 计算不透明的数值 if (isAlpha) { double alpha = 255 - (c.radius - startOffset) / (maxRadius - startOffset) * 255; c.alpha = (int) alpha; } // 修改这个值控制速度 c.radius += speed; } } // 里面添加圆 if (startRipple) { addRipples(); } invalidate(); canvas.restore(); } private void addRipples() { long currentTimeMillis = System.currentTimeMillis(); if (autoStopTimeIntervalMillis > 0 && currentTimeMillis - startRippleTimeMillis > autoStopTimeIntervalMillis) { startRipple = false; return; } if (rippleList.size() > 0) { // 控制第二个圆出来的间距 if (rippleList.get(rippleList.size() - 1).radius - startOffset == density) { rippleList.add(new Circle(startOffset, 255)); } } else { rippleList.add(new Circle(startOffset, 255)); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = MeasureSpec.getSize(widthMeasureSpec); height = MeasureSpec.getSize(heightMeasureSpec); maxRadius = Math.min(width, height) / 2; // 设置该view的宽高 setMeasuredDimension((int) width, (int) height); } class Circle { Circle(int radius, int alpha) { this.radius = radius; this.alpha = alpha; } float radius; int alpha; } public void enableRipple(boolean enable) { startRipple = enable; if (autoStopTimeIntervalMillis > 0) { startRippleTimeMillis = System.currentTimeMillis(); } if (enable && rippleList.size() == 0) { rippleList.add(new Circle(startOffset, 255)); } } } <file_sep>package cn.rongcloud.sealmic.task; import cn.rongcloud.sealmic.model.LoginInfo; import cn.rongcloud.sealmic.model.UserInfo; import cn.rongcloud.sealmic.net.HttpClient; import cn.rongcloud.sealmic.net.SealMicRequest; import cn.rongcloud.sealmic.net.model.LoginResult; import cn.rongcloud.sealmic.task.callback.HandleRequestWrapper; /** * 用户相关业务处理 */ public class AuthManager { private static AuthManager instance; private SealMicRequest mRequest; private String currentUserId; public static AuthManager getInstance() { if (instance == null) { synchronized (AuthManager.class) { if (instance == null) { instance = new AuthManager(); } } } return instance; } private AuthManager() { mRequest = HttpClient.getInstance().getRequest(); } /** * 用户登录 * * @param deviceId * @param callBack */ public void login(String deviceId, ResultCallback<LoginInfo> callBack) { mRequest.login(deviceId, new HandleRequestWrapper<LoginInfo, LoginResult>(callBack) { @Override public LoginInfo handleRequestResult(LoginResult dataResult) { if (dataResult != null) { String auth = dataResult.getAuthorization(); AuthManager.this.currentUserId = dataResult.getUserId(); // 保存用户认证信息,用于请求其他api认证使用 if (auth != null) { HttpClient.getInstance().setAuthHeader(auth); } LoginInfo loginInfo = new LoginInfo(); UserInfo userInfo = new UserInfo(); userInfo.setUserId(currentUserId); loginInfo.setImToken(dataResult.getImToken()); loginInfo.setUserInfo(userInfo); return loginInfo; } return null; } }); } public String getCurrentUserId() { return currentUserId; } } <file_sep>package cn.rongcloud.sealmic.model; import cn.rongcloud.sealmic.utils.ResourceUtils; public class UserInfo { private String userId; private long joinDt; private String nickName; private int avatarResourceId; public long getJoinDt() { return joinDt; } public void setJoinDt(long joinDt) { this.joinDt = joinDt; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getNickName() { if (nickName == null) { nickName = ResourceUtils.getInstance().getUserName(userId); } return nickName; } public int getAvatarResourceId() { if (avatarResourceId == 0) { avatarResourceId = ResourceUtils.getInstance().getUserAvatarResourceId(userId); } return avatarResourceId; } } <file_sep>include ':sealmic', ':IMLib' <file_sep>package cn.rongcloud.sealmic.task.callback; import cn.rongcloud.sealmic.net.RequestCallBack; import cn.rongcloud.sealmic.task.ResultCallback; import cn.rongcloud.sealmic.task.ThreadManager; /** * 将网络请求的结果 RequestCallBack 转换为任务处理结果 RequestCallBack,并切换至主线程 * @param <RequestResult> */ public class RequestWrapper<RequestResult> implements RequestCallBack<RequestResult> { private ResultCallback<RequestResult> mCallBack; private ThreadManager mThreadManager; public RequestWrapper(ResultCallback<RequestResult> callBack) { mCallBack = callBack; mThreadManager = ThreadManager.getInstance(); } @Override public void onSuccess(final RequestResult result) { if (mCallBack == null) return; mThreadManager.runOnUIThread(new Runnable() { @Override public void run() { mCallBack.onSuccess(result); } }); } @Override public void onFail(final int errorCode) { if (mCallBack == null) return; mThreadManager.runOnUIThread(new Runnable() { @Override public void run() { mCallBack.onFail(errorCode); } }); } public ResultCallback<RequestResult> getCallBack() { return mCallBack; } public ThreadManager getTaskManager() { return mThreadManager; } } <file_sep>package cn.rongcloud.sealmic.ui.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import java.util.List; import cn.rongcloud.sealmic.R; import cn.rongcloud.sealmic.ui.ChatRoomBgItem; public class ChatRoomBGItemAdapter extends BaseAdapter { private List<ChatRoomBgItem> list; Context context; public ChatRoomBGItemAdapter(Context context, List<ChatRoomBgItem> list) { if (list.size() >= 31) { this.list = list.subList(0, 30); } else { this.list = list; } this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.chatroom_setting_bg_item, parent, false); } ImageView ivBG = convertView.findViewById(R.id.iv_bg); ImageView ivBGChecked = convertView.findViewById(R.id.iv_bg_checked); ivBG.setBackground(context.getResources().getDrawable(list.get(position).getDrawableId())); if (list.get(position).isChecked()) { ivBGChecked.setVisibility(View.VISIBLE); } else { ivBGChecked.setVisibility(View.GONE); } return convertView; } @Override public int getCount() { if (list != null) { return list.size(); } else { return 0; } } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } /** * 传入新的数据 刷新UI的方法 */ public void updateListView(List<ChatRoomBgItem> list) { this.list = list; notifyDataSetChanged(); } } <file_sep>package cn.rongcloud.sealmic.model; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; import org.json.JSONObject; public class RoomMicPositionInfo implements Parcelable { @SerializedName(value = "userId", alternate = {"uid"}) private String userId; // 当前麦位上的人员 id @SerializedName("rid") private String roomId; private int state; private int position; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getRoomId() { return roomId; } public void setRoomId(String roomId) { this.roomId = roomId; } public int getState() { return state; } public void setState(int state) { this.state = state; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.userId); dest.writeString(this.roomId); dest.writeInt(this.state); dest.writeInt(this.position); } public RoomMicPositionInfo() { } public static RoomMicPositionInfo parseJsonToMicPositionInfo(JSONObject jsonObject) { RoomMicPositionInfo micPositionInfo = new RoomMicPositionInfo(); micPositionInfo.setUserId(jsonObject.optString("uid")); micPositionInfo.setRoomId(jsonObject.optString("rid")); micPositionInfo.setState(jsonObject.optInt("state")); micPositionInfo.setPosition(jsonObject.optInt("position")); return micPositionInfo; } protected RoomMicPositionInfo(Parcel in) { this.userId = in.readString(); this.roomId = in.readString(); this.state = in.readInt(); this.position = in.readInt(); } public static final Creator<RoomMicPositionInfo> CREATOR = new Creator<RoomMicPositionInfo>() { @Override public RoomMicPositionInfo createFromParcel(Parcel source) { return new RoomMicPositionInfo(source); } @Override public RoomMicPositionInfo[] newArray(int size) { return new RoomMicPositionInfo[size]; } }; } <file_sep>package cn.rongcloud.sealmic.net.retrofit; import cn.rongcloud.sealmic.constant.ErrorCode; import cn.rongcloud.sealmic.constant.ServerErrorCode; import cn.rongcloud.sealmic.net.RequestCallBack; import cn.rongcloud.sealmic.net.model.Result; import cn.rongcloud.sealmic.utils.log.SLog; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CallBackWrapper<R> implements Callback<Result<R>> { private RequestCallBack<R> mCallBack; public CallBackWrapper(RequestCallBack<R> callBack) { mCallBack = callBack; } @Override public void onResponse(Call<Result<R>> call, Response<Result<R>> response) { Result<R> body = response.body(); if (body != null) { int errCode = body.getErrCode(); if (errCode == 0) { mCallBack.onSuccess(body.getDataResult()); } else { SLog.e(SLog.TAG_NET, "url:" + call.request().url().toString() + " ,errorMsg:" + body.getErrMsg() + ", errorDetail:" + body.getErrDetail()); // 将网络请求 errorCode 转换为ErrorCode对应错误枚举 ErrorCode errorCode; switch (errCode) { case ServerErrorCode.MIC_POSITION_HAS_BEEN_HOLD: // 跳麦,麦位上已有人 errorCode = ErrorCode.MIC_POSITION_HAS_BEEN_HOLD; break; case ServerErrorCode.ROOM_CREATE_ROOM_OVER_LIMIT: // 创建房间超过上限 errorCode = ErrorCode.ROOM_CREATE_ROOM_OVER_LIMIT; break; case ServerErrorCode.ROOM_JOIN_MEMBER_OVER_LIMIT: // 房间人数超过上限 errorCode = ErrorCode.ROOM_JOIN_MEMBER_OVER_LIMIT; break; case ServerErrorCode.USER_ALREADY_ON_MIC_POSITION: errorCode = ErrorCode.MIC_USER_ALREADY_ON_OTHER_POSITION; break; default: errorCode = ErrorCode.RESULT_FAILED; } mCallBack.onFail(errorCode.getCode()); } } else { SLog.e(SLog.TAG_NET, "url:" + call.request().url().toString() + ", no response body"); mCallBack.onFail(ErrorCode.RESULT_ERROR.getCode()); } } @Override public void onFailure(Call<Result<R>> call, Throwable t) { SLog.e(SLog.TAG_NET, call.request().url().toString() + " - " + (t != null ? t.getMessage() : "")); mCallBack.onFail(ErrorCode.NETWORK_ERROR.getCode()); } } <file_sep>package cn.rongcloud.sealmic.rtc; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import cn.rongcloud.rtc.RTCErrorCode; import cn.rongcloud.rtc.RongRTCEngine; import cn.rongcloud.rtc.callback.JoinRoomUICallBack; import cn.rongcloud.rtc.callback.RongRTCResultUICallBack; import cn.rongcloud.rtc.events.RongRTCEventsListener; import cn.rongcloud.rtc.room.RongRTCRoom; import cn.rongcloud.rtc.stream.MediaType; import cn.rongcloud.rtc.stream.ResourceState; import cn.rongcloud.rtc.stream.local.RongRTCAVOutputStream; import cn.rongcloud.rtc.stream.local.RongRTCCapture; import cn.rongcloud.rtc.stream.remote.RongRTCAVInputStream; import cn.rongcloud.rtc.user.RongRTCLocalUser; import cn.rongcloud.rtc.user.RongRTCRemoteUser; import cn.rongcloud.sealmic.constant.ErrorCode; import cn.rongcloud.sealmic.task.ResultCallback; import cn.rongcloud.sealmic.task.ThreadManager; import cn.rongcloud.sealmic.utils.log.SLog; /** * Rong RTC 语音业务封装 */ public class RtcClient { private static RtcClient instance; private RtcClient() { } public static RtcClient getInstance() { if (instance == null) { synchronized (RtcClient.class) { if (instance == null) { instance = new RtcClient(); } } } return instance; } /** * 加入语音聊天房间 * * @param roomId * @param callBack */ public void joinRtcRoom(final String roomId, final RongRTCEventsListener rtcEventsListener, final ResultCallback<RongRTCRoom> callBack) { RongRTCEngine.getInstance().joinRoom(roomId, new JoinRoomUICallBack() { @Override protected void onUiSuccess(RongRTCRoom rtcRoom) { rtcRoom.registerEventsListener(rtcEventsListener); if (callBack != null) { callBack.onSuccess(rtcRoom); } } @Override protected void onUiFailed(RTCErrorCode rtcErrorCode) { SLog.e(SLog.TAG_RTC, "joinRtcRoom failed - " + rtcErrorCode.gerReason()); if (callBack != null) { callBack.onFail(ErrorCode.RTC_ERROR.getCode()); } } }); } /** * 离开语音聊天室 * * @param roomId * @param callBack */ public void quitRtcRoom(final String roomId, final ResultCallback<Boolean> callBack) { RongRTCEngine.getInstance().quitRoom(roomId, new RongRTCResultUICallBack() { @Override public void onUiSuccess() { if (callBack != null) { callBack.onSuccess(true); } } @Override public void onUiFailed(RTCErrorCode rtcErrorCode) { SLog.e(SLog.TAG_RTC, "quitRtcRoom error - " + rtcErrorCode.gerReason()); if (callBack != null) { callBack.onFail(ErrorCode.RTC_ERROR.getCode()); } } }); } /** * 开启语音聊天 * * @param rtcRoom * @param callBack */ public void startVoiceChat(RongRTCRoom rtcRoom, final ResultCallback<Boolean> callBack) { RongRTCLocalUser localUser = rtcRoom.getLocalUser(); List<RongRTCAVOutputStream> localAvStreams = localUser.getLocalAvStreams(); if (localAvStreams != null) { for (RongRTCAVOutputStream outputStream : localAvStreams) { MediaType mediaType = outputStream.getMediaType(); // 禁用视频 if (mediaType == MediaType.VIDEO) { outputStream.setResourceState(ResourceState.DISABLED); } } } localUser.publishDefaultAVStream(new RongRTCResultUICallBack() { @Override public void onUiSuccess() { if (callBack != null) { callBack.onSuccess(true); } } @Override public void onUiFailed(RTCErrorCode rtcErrorCode) { SLog.e(SLog.TAG_RTC, "startVoiceChat error - " + rtcErrorCode.gerReason()); if (callBack != null) { callBack.onFail(ErrorCode.RTC_ERROR.getCode()); } } }); } /** * 停止语音聊天 * * @param rtcRoom * @param callBack */ public void stopVoiceChat(RongRTCRoom rtcRoom, final ResultCallback<Boolean> callBack) { RongRTCLocalUser localUser = rtcRoom.getLocalUser(); localUser.unPublishDefaultAVStream(new RongRTCResultUICallBack() { @Override public void onUiSuccess() { if (callBack != null) { callBack.onSuccess(true); } } @Override public void onUiFailed(RTCErrorCode rtcErrorCode) { SLog.e(SLog.TAG_RTC, "stopVoiceChat error - " + rtcErrorCode.gerReason()); if (callBack != null) { callBack.onFail(ErrorCode.RTC_ERROR.getCode()); } } }); } /** * 设置麦克风是否可用 * * @param enable */ public void setLocalMicEnable(boolean enable) { RongRTCCapture.getInstance().muteMicrophone(!enable); } /** * 接受房间语音 * * @param rtcRoom * @param userList 要接受语音的用户列表 * @param callBack */ public void receiveRoomVoice(RongRTCRoom rtcRoom, List<String> userList, final ResultCallback<Boolean> callBack) { Map<String, RongRTCRemoteUser> remoteUsers = rtcRoom.getRemoteUsers(); List<RongRTCAVInputStream> receiveVoiceSteamList = new ArrayList<>(); for (String userId : userList) { RongRTCRemoteUser rongRTCRemoteUser = remoteUsers.get(userId); if (rongRTCRemoteUser != null) { List<RongRTCAVInputStream> remoteAVStreams = rongRTCRemoteUser.getRemoteAVStreams(); if (remoteAVStreams != null && remoteAVStreams.size() > 0) { receiveVoiceSteamList.addAll(remoteAVStreams); } } } if (receiveVoiceSteamList.size() > 0) { rtcRoom.subscribeAvStream(receiveVoiceSteamList, new RongRTCResultUICallBack() { @Override public void onUiSuccess() { if (callBack != null) { callBack.onSuccess(true); } } @Override public void onUiFailed(RTCErrorCode rtcErrorCode) { SLog.e(SLog.TAG_RTC, "receiveRoomVoice error - " + rtcErrorCode.gerReason()); if (callBack != null) { callBack.onFail(ErrorCode.RTC_ERROR.getCode()); } } }); }else{ ThreadManager.getInstance().runOnUIThread(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onSuccess(true); } } }); } } /** * 房间静音 * * @param rtcRoom * @param callBack */ public void muteRoomVoice(RongRTCRoom rtcRoom, final ResultCallback<Boolean> callBack) { Map<String, RongRTCRemoteUser> remoteUserMap = rtcRoom.getRemoteUsers(); List<RongRTCAVInputStream> receiveVoiceSteamList = new ArrayList<>(); Collection<RongRTCRemoteUser> remoteUsers = remoteUserMap.values(); for (RongRTCRemoteUser remoteUser : remoteUsers) { receiveVoiceSteamList.addAll(remoteUser.getRemoteAVStreams()); } if (receiveVoiceSteamList.size() > 0) { rtcRoom.unSubscribeAVStream(receiveVoiceSteamList, new RongRTCResultUICallBack() { @Override public void onUiSuccess() { if (callBack != null) { callBack.onSuccess(true); } } @Override public void onUiFailed(RTCErrorCode rtcErrorCode) { SLog.e(SLog.TAG_RTC, "muteRoomVoice error - " + rtcErrorCode.gerReason()); if (callBack != null) { callBack.onFail(ErrorCode.RTC_ERROR.getCode()); } } }); }else{ ThreadManager.getInstance().runOnUIThread(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onSuccess(true); } } }); } } } <file_sep>package cn.rongcloud.sealmic.constant; /** * 服务器返回错误码 */ public class ServerErrorCode { /** * 当前麦位已有用户 */ public static final int MIC_POSITION_HAS_BEEN_HOLD = 24; /** * 当前房间数量已达到上限 */ public static final int ROOM_CREATE_ROOM_OVER_LIMIT = 26; /** * 当前房间内人数已达到上限 */ public static final int ROOM_JOIN_MEMBER_OVER_LIMIT = 27; /** * 用户已在麦位上 */ public static final int USER_ALREADY_ON_MIC_POSITION = 28; } <file_sep>package cn.rongcloud.sealmic.net; import android.content.Context; import android.content.SharedPreferences; import cn.rongcloud.sealmic.constant.NetConstant; import cn.rongcloud.sealmic.net.retrofit.RetrofitClient; import static android.content.Context.MODE_PRIVATE; public class HttpClient { private static final String TAG = "HttpClient"; private static HttpClient sInstance; private Context mContext; private RetrofitClient mClient; private SealMicRequest mRequest; private HttpClient() { } public void init(Context context) { mContext = context; mClient = new RetrofitClient(context, SealMicUrls.DOMAIN); mRequest = new SealMicRequest(mClient); } public static HttpClient getInstance() { if (sInstance == null) { synchronized (HttpClient.class) { if (sInstance == null) { sInstance = new HttpClient(); } } } return sInstance; } public SealMicRequest getRequest() { return mRequest; } /** * 设置用户登录认证 * * @param auth */ public void setAuthHeader(String auth) { SharedPreferences.Editor config = mContext.getSharedPreferences(NetConstant.SP_NAME_NET, MODE_PRIVATE) .edit(); config.putString(NetConstant.SP_KEY_NET_HEADER_AUTH, auth); config.commit(); } /** * 清除包括cookie和登录认证 */ public void clearRequestCache() { SharedPreferences.Editor config = mContext.getSharedPreferences(NetConstant.SP_NAME_NET, MODE_PRIVATE) .edit(); config.remove(NetConstant.SP_KEY_NET_HEADER_AUTH); config.remove(NetConstant.SP_KEY_NET_COOKIE_SET); config.commit(); } } <file_sep>package cn.rongcloud.sealmic.im.message; import android.os.Parcel; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import io.rong.imlib.MessageTag; import io.rong.imlib.model.MessageContent; /** * 房间背景变动消息 */ @MessageTag(value = "SM:RBgNtfyMsg", flag = MessageTag.NONE) public class RoomBgChangeMessage extends MessageContent { private final static String TAG = RoomBgChangeMessage.class.getSimpleName(); private int bgId; public RoomBgChangeMessage(byte[] data) { String jsonStr = null; try { jsonStr = new String(data, "UTF-8"); JSONObject jsonObj = new JSONObject(jsonStr); setBgId(jsonObj.optInt("bgId")); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public int getBgId() { return bgId; } public void setBgId(int bgId) { this.bgId = bgId; } @Override public byte[] encode() { return new byte[0]; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.bgId); } protected RoomBgChangeMessage(Parcel in) { this.bgId = in.readInt(); } public static final Creator<RoomBgChangeMessage> CREATOR = new Creator<RoomBgChangeMessage>() { @Override public RoomBgChangeMessage createFromParcel(Parcel source) { return new RoomBgChangeMessage(source); } @Override public RoomBgChangeMessage[] newArray(int size) { return new RoomBgChangeMessage[0]; } }; } <file_sep>package cn.rongcloud.sealmic.im.message; import android.os.Parcel; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import cn.rongcloud.sealmic.utils.log.SLog; import io.rong.imlib.MessageTag; import io.rong.imlib.model.MessageContent; /** * 房间成员变动消息 */ @MessageTag(value = "SM:RMChangeMsg", flag = MessageTag.NONE) public class RoomMemberChangedMessage extends MessageContent { private final String TAG = RoomMemberChangedMessage.class.getSimpleName(); private int cmd; //1 join, 2 leave, 3 kick, private String targetUserId; private int targetPosition = -1; //-1 无效,>=0 有效的麦位 public RoomMemberChangedMessage(byte[] data) { String jsonStr = null; try { jsonStr = new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { SLog.e(TAG, "UnsupportedEncodingException ", e); } try { JSONObject jsonObj = new JSONObject(jsonStr); setCmd(jsonObj.optInt("cmd")); setTargetUserId(jsonObj.optString("targetUserId")); setTargetPosition(jsonObj.optInt("targetPosition")); } catch (JSONException e) { e.printStackTrace(); } } public RoomMemberAction getRoomMemberAction() { return RoomMemberAction.valueOf(cmd); } public void setCmd(int cmd) { this.cmd = cmd; } public String getTargetUserId() { return targetUserId; } public void setTargetUserId(String targetUserId) { this.targetUserId = targetUserId; } public int getTargetPosition() { return targetPosition; } public void setTargetPosition(int targetPosition) { this.targetPosition = targetPosition; } @Override public byte[] encode() { return new byte[0]; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.cmd); dest.writeString(this.targetUserId); dest.writeInt(this.targetPosition); } public RoomMemberChangedMessage() { } protected RoomMemberChangedMessage(Parcel in) { this.cmd = in.readInt(); this.targetUserId = in.readString(); this.targetPosition = in.readInt(); } public static final Creator<RoomMemberChangedMessage> CREATOR = new Creator<RoomMemberChangedMessage>() { @Override public RoomMemberChangedMessage createFromParcel(Parcel source) { return new RoomMemberChangedMessage(source); } @Override public RoomMemberChangedMessage[] newArray(int size) { return new RoomMemberChangedMessage[size]; } }; public enum RoomMemberAction { UNKNOWN, JOIN, LEAVE, KICK; public static RoomMemberAction valueOf(int value) { for (RoomMemberAction action : RoomMemberAction.values()) { if (action.ordinal() == value) { return action; } } return UNKNOWN; } } } <file_sep>package cn.rongcloud.sealmic.task; import android.text.TextUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import cn.rongcloud.rtc.RTCErrorCode; import cn.rongcloud.rtc.callback.RongRTCResultUICallBack; import cn.rongcloud.rtc.engine.report.StatusReport; import cn.rongcloud.rtc.events.RongRTCEventsListener; import cn.rongcloud.rtc.events.RongRTCStatusReportListener; import cn.rongcloud.rtc.room.RongRTCRoom; import cn.rongcloud.rtc.stream.remote.RongRTCAVInputStream; import cn.rongcloud.rtc.user.RongRTCRemoteUser; import cn.rongcloud.sealmic.constant.ErrorCode; import cn.rongcloud.sealmic.im.IMClient; import cn.rongcloud.sealmic.im.message.MicPositionChangeMessage; import cn.rongcloud.sealmic.im.message.MicPositionControlMessage; import cn.rongcloud.sealmic.im.message.RoomBgChangeMessage; import cn.rongcloud.sealmic.im.message.RoomDestroyNotifyMessage; import cn.rongcloud.sealmic.im.message.RoomIsActiveMessage; import cn.rongcloud.sealmic.im.message.RoomMemberChangedMessage; import cn.rongcloud.sealmic.model.BaseRoomInfo; import cn.rongcloud.sealmic.model.DetailRoomInfo; import cn.rongcloud.sealmic.model.MicBehaviorType; import cn.rongcloud.sealmic.model.MicState; import cn.rongcloud.sealmic.model.RoomMicPositionInfo; import cn.rongcloud.sealmic.model.UserInfo; import cn.rongcloud.sealmic.net.HttpClient; import cn.rongcloud.sealmic.net.SealMicRequest; import cn.rongcloud.sealmic.net.model.CreateRoomResult; import cn.rongcloud.sealmic.rtc.RtcClient; import cn.rongcloud.sealmic.task.callback.HandleRequestWrapper; import cn.rongcloud.sealmic.task.callback.RequestWrapper; import cn.rongcloud.sealmic.task.role.Linker; import cn.rongcloud.sealmic.task.role.Listener; import cn.rongcloud.sealmic.task.role.Owner; import cn.rongcloud.sealmic.task.role.Role; import cn.rongcloud.sealmic.utils.log.SLog; import io.rong.imlib.IRongCallback; import io.rong.imlib.RongIMClient; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.Message; import io.rong.message.TextMessage; public class RoomManager { /** * 房主发送房间保活消息间隔时间 */ private static final long ROOM_SEND_ACTIVE_INTERVAL_TIME_MILLIS = 10 * 60 * 1000; private static RoomManager sInstance; private ThreadManager threadManager; private SealMicRequest request; private IMClient imClient; private RtcClient rtcClient; private RoomMessageListener messageListener; private RoomRtcEventListener rtcListener; private final Object roomLock = new Object(); // 用户所在当前房间的详细信息 private DetailRoomInfo currentRoom; // 用户所在当前房间的音频房间实体 private RongRTCRoom currentRTCRoom; // 用户所在当前房间的角色 private Role currentRole; // 用户所在当前房间声音是否开启 private boolean currentRoomAudioEnable; // 用户所在当前房间的事件回调 private RoomEventListener currentRoomEventListener; // 房主用于发送房间正在活动的消息线程 private RoomActiveMsgSenderThread currentRoomActiveThread; public static RoomManager getInstance() { if (sInstance == null) { synchronized (RoomManager.class) { if (sInstance == null) { sInstance = new RoomManager(); } } } return sInstance; } private RoomManager() { threadManager = ThreadManager.getInstance(); request = HttpClient.getInstance().getRequest(); rtcClient = RtcClient.getInstance(); imClient = IMClient.getInstance(); messageListener = new RoomMessageListener(); imClient.addMessageReceiveListener(messageListener); } /** * 获取聊天室房间列表 */ public void getChatRoomList(ResultCallback<List<BaseRoomInfo>> callBack) { request.getChatRoomList(new RequestWrapper<>(callBack)); } /** * 创建房间 * * @param subject 主题内容 * @param type 类型 * @param callBack */ public void createRoom(String subject, int type, ResultCallback<CreateRoomResult> callBack) { request.createRoom(subject, type, new RequestWrapper<>(callBack)); } /** * 销毁房间,此操作仅房主可使用 * * @param callBack */ public void destroyRoom(final String roomId, ResultCallback<Boolean> callBack) { request.destroyRoom(roomId, new HandleRequestWrapper<Boolean, Boolean>(callBack) { @Override public Boolean handleRequestResult(Boolean requestResult) { if (requestResult) { clearRoomInfo(roomId); } return requestResult; } }); imClient.quitChatRoom(roomId, null); rtcClient.quitRtcRoom(roomId, null); } /** * 加入聊天室 * * @param roomId * @param callBack */ public void joinRoom(final String roomId, final ResultCallback<DetailRoomInfo> callBack) { /* * 加入房间前进行初始化房间保证可以监听到对应房间的消息,再加入 IM 的聊天室,最后进行API服务器服加入聊天室请求 * 防止API服务器请求延迟丢失对应聊天室的消息 */ initRoomInfo(roomId); imClient.joinChatRoom(roomId, new ResultCallback<String>() { @Override public void onSuccess(final String roomId) { request.joinRoom(roomId, new HandleRequestWrapper<DetailRoomInfo, DetailRoomInfo>(callBack) { @Override public DetailRoomInfo handleRequestResult(DetailRoomInfo dataResult) { if (dataResult != null) { synchronized (roomLock) { //补偿在加入聊天室时收到的消息 if (currentRoom != null) { dataResult.setMessageList(currentRoom.getMessageList()); //如果加入房间前收到了麦位变动消息则以消息为准,防止请求延迟造成麦位改变状态没有及时更新 if (currentRoom.getMicPositions().size() > 0) { dataResult.setMicPositions(currentRoom.getMicPositions()); } } currentRoom = dataResult; currentRole = initCurrentRole(); // 当为房主时,每隔一定时间发送房间正在活动消息以保证 IM 聊天室 不会因长时间没有人发消息而销毁 if (currentRole instanceof Owner) { currentRoomActiveThread = new RoomActiveMsgSenderThread(roomId); currentRoomActiveThread.start(); } return currentRoom; } } return null; } @Override public void onFail(int errorCode) { super.onFail(errorCode); /* * 请求服务器加入聊天室失败时退出聊天室 */ imClient.quitChatRoom(roomId, null); clearRoomInfo(roomId); } }); } @Override public void onFail(int errorCode) { callBack.onFail(errorCode); clearRoomInfo(roomId); } }); } /** * 获得当前聊天室 * * @return */ public DetailRoomInfo getCurrentRoomInfo() { return currentRoom; } /** * 退出聊天室 * * @param callBack */ public void leaveRoom(final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRoom != null) { final String roomId = currentRoom.getRoomId(); request.leaveRoom(currentRoom.getRoomId(), new HandleRequestWrapper<Boolean, Boolean>(callBack) { @Override public Boolean handleRequestResult(Boolean requestResult) { if (requestResult != null) { clearRoomInfo(roomId); } return requestResult; } }); imClient.quitChatRoom(roomId, null); rtcClient.quitRtcRoom(roomId, null); } else { notInJoinToRoomCallBack(callBack); } } } /** * 获取房间详细 * * @param roomId * @param callBack */ public void getRoomDetailInfo(final String roomId, final ResultCallback<DetailRoomInfo> callBack) { request.getChatRoomDetail(roomId, new HandleRequestWrapper<DetailRoomInfo, DetailRoomInfo>(callBack) { @Override public DetailRoomInfo handleRequestResult(DetailRoomInfo dataResult) { synchronized (roomLock) { /* * 当现在已加入房间且与获取的房间 id 相同时更新房间人数和房间人员 */ if (currentRoom != null && dataResult != null) { if (currentRoom.getRoomId().equals(dataResult.getRoomId())) { currentRoom.setMemCount(dataResult.getMemCount()); currentRoom.setAudiences(dataResult.getAudiences()); currentRoom.setMicPositions(dataResult.getMicPositions()); //检测角色是否发生了改变 final Role newRole = initCurrentRole(); if (newRole != null && !newRole.isSameRole(currentRole)) { // 角色发生改变时回调角色改变监听 currentRole = newRole; final RoomEventListener roomEventlistener = currentRoomEventListener; if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onRoleChanged(newRole); } }); } } else if (!newRole.equals(currentRole)) { // 角色没有改版但是角色信息改变时仅更新信息 currentRole = newRole; } } } return dataResult; } } }); } /** * 获取房间用户列表 * * @param roomId * @param callBack */ public void getRoomUserList(final String roomId, final ResultCallback<List<UserInfo>> callBack) { request.getChatRoomUserList(roomId, new RequestWrapper<>(callBack)); } /** * 加入麦位 * * @param position * @param callBack */ public void joinMic(final int position, final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRoom != null) { final String roomId = currentRoom.getRoomId(); request.joinMic(roomId, position, new RequestWrapper<>(callBack)); } else { notInJoinToRoomCallBack(callBack); } } } /** * 离开麦位 * * @param position * @param callBack */ public void leaveMic(final int position, final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRoom != null) { final String roomId = currentRoom.getRoomId(); request.leaveMic(roomId, position, new RequestWrapper<>(callBack)); } else { notInJoinToRoomCallBack(callBack); } } } /** * 跳转麦位 */ public void changeMicPosition(final int fromPosition, final int targetPosition, final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRoom != null) { final String roomId = currentRoom.getRoomId(); request.changMicPosition(roomId, fromPosition, targetPosition, new RequestWrapper<>(callBack)); } else { notInJoinToRoomCallBack(callBack); } } } /** * 控制麦位状态 * * @param position * @param targetUserId * @param cmd * @param callBack */ public void controlMicPosition(final int position, String targetUserId, int cmd, final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRoom != null) { final String roomId = currentRoom.getRoomId(); request.controlMicPosition(roomId, position, targetUserId, cmd, new RequestWrapper<>(callBack)); } else { notInJoinToRoomCallBack(callBack); } } } /** * 在当前所在聊天室发送消息 * * @param message */ public void sendChatRoomMessage(String message) { synchronized (roomLock) { if (currentRoom == null) { return; } TextMessage textMessage = TextMessage.obtain(message); RongIMClient.getInstance().sendMessage(Conversation.ConversationType.CHATROOM, currentRoom.getRoomId(), textMessage, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { synchronized (roomLock) { currentRoom.getMessageList().add(message); if (currentRoomEventListener != null) { currentRoomEventListener.onMessageEvent(message); } } } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { synchronized (roomLock) { if (currentRoomEventListener != null) { // 当不在聊天室时回调与房间断开连接 if (errorCode == RongIMClient.ErrorCode.NOT_IN_CHATROOM) { currentRoomEventListener.onErrorLeaveRoom(); } else { currentRoomEventListener.onSendMessageError(message, ErrorCode.ROOM_SEND_MSG_ERROR.getCode()); } } } } }); } } /** * 设置当前房间的事件监听 * * @param currentRoomEventListener */ public void setCurrentRoomEventListener(RoomEventListener currentRoomEventListener) { this.currentRoomEventListener = currentRoomEventListener; } /** * 开始加入接受音频 * * @param callBack */ public void initRoomVoice(final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRoom == null) { notInJoinToRoomCallBack(callBack); return; } final String roomId = currentRoom.getRoomId(); rtcListener = new RoomRtcEventListener(roomId); // 加入rtc房间 rtcClient.joinRtcRoom(roomId, rtcListener, new ResultCallback<RongRTCRoom>() { @Override public void onSuccess(RongRTCRoom rongRTCRoom) { synchronized (roomLock) { String rtcRoomId = rongRTCRoom.getRoomId(); // 若当前已不再房间则不进行处理 if (currentRoom == null || !currentRoom.getRoomId().equals(rtcRoomId)) { rtcClient.quitRtcRoom(rtcRoomId, null); callBack.onFail(ErrorCode.RTC_JOIN_ROOM_ERROR.getCode()); return; } currentRTCRoom = rongRTCRoom; // 加入当前房间发言监听 currentRTCRoom.registerStatusReportListener(rtcListener); callBack.onSuccess(true); } } @Override public void onFail(int errorCode) { callBack.onFail(errorCode); } }); } } /** * 开始语音聊天 * * @param callBack */ public void startVoiceChat(ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRTCRoom != null) { rtcClient.startVoiceChat(currentRTCRoom, callBack); } else { notInJoinToRoomCallBack(callBack); } } } /** * 关闭语音聊天 * * @param callBack */ public void stopVoiceChat(ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRTCRoom != null) { rtcClient.stopVoiceChat(currentRTCRoom, callBack); } else { notInJoinToRoomCallBack(callBack); } } } /** * 设置是否开启房间聊天声音 * * @param callBack */ public void enableRoomChatVoice(final boolean enable, final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRTCRoom != null) { if (enable) { List<String> enableVoiceChatUserList = getEnableVoiceChatUserList(); rtcClient.receiveRoomVoice(currentRTCRoom, enableVoiceChatUserList, new ResultCallback<Boolean>() { @Override public void onSuccess(Boolean aBoolean) { currentRoomAudioEnable = true; callBack.onSuccess(aBoolean); } @Override public void onFail(int errorCode) { callBack.onFail(errorCode); } }); } else { rtcClient.muteRoomVoice(currentRTCRoom, new ResultCallback<Boolean>() { @Override public void onSuccess(Boolean aBoolean) { currentRoomAudioEnable = false; callBack.onSuccess(aBoolean); } @Override public void onFail(int errorCode) { callBack.onFail(errorCode); } }); } } else { notInJoinToRoomCallBack(callBack); } } } /** * 开启或关闭自己的麦克风 */ public void enableMic(boolean enableMic) { rtcClient.setLocalMicEnable(enableMic); } /** * 返回当前可进行语音聊天的用户 * 可进行语音聊天的用户包括房主及在麦位上未被禁麦的用户 */ public List<String> getEnableVoiceChatUserList() { synchronized (roomLock) { List<String> userList = new ArrayList<>(); if (currentRoom == null) return userList; // 加入房主 userList.add(currentRoom.getCreatorUserId()); List<RoomMicPositionInfo> micPositions = currentRoom.getMicPositions(); if (micPositions != null) { // 加入麦位上可发言的用户 for (RoomMicPositionInfo micInfo : micPositions) { int state = micInfo.getState(); if (MicState.isState(state, MicState.Hold) && !MicState.isState(state, MicState.Forbidden)) { userList.add(micInfo.getUserId()); } } } return userList; } } /** * 返回当前在麦位上的用户 */ public List<String> getOnMicPositionUserList() { synchronized (roomLock) { List<String> userList = new ArrayList<>(); if (currentRoom == null) return userList; // 加入房主 userList.add(currentRoom.getCreatorUserId()); List<RoomMicPositionInfo> micPositions = currentRoom.getMicPositions(); if (micPositions != null) { // 加入麦位上的用户 for (RoomMicPositionInfo micInfo : micPositions) { int state = micInfo.getState(); if (MicState.isState(state, MicState.Hold)) { userList.add(micInfo.getUserId()); } } } return userList; } } /** * 获取当前角色 * * @return */ public Role getCurrentRole() { return currentRole; } /** * 根据当前房间信息初始化当前角色 * * @return */ private Role initCurrentRole() { String currentUserId = AuthManager.getInstance().getCurrentUserId(); if (TextUtils.isEmpty(currentUserId) || currentRoom == null) { return null; } String creatorUserId = currentRoom.getCreatorUserId(); // 在调用进入 IM 房间后,在调用 API服务器 进入房间成功前创建房间用户 id 为空,此时无法判断角色 if (creatorUserId == null) { return null; } // 本人为创建房间用户时,自己即为房主 if (currentUserId.equals(creatorUserId)) { return new Owner(); } // 判断当前用户是否在麦位上,如果在麦位上则为连麦者 List<RoomMicPositionInfo> micPositions = currentRoom.getMicPositions(); if (micPositions != null) { for (RoomMicPositionInfo micInfo : micPositions) { String micUser = micInfo.getUserId(); if (currentUserId.equals(micUser)) { Linker linker = new Linker(); linker.setMicPositionInfo(micInfo); return linker; } } } // 房间存在则当前用户为听众 return new Listener(); } /** * 获取当前房间声音是否开启 * * @return */ public boolean isCurrentRoomVoiceEnable() { return currentRoomAudioEnable; } /** * 当没有加入房间时回调错误 * * @param callBack */ private void notInJoinToRoomCallBack(final ResultCallback callBack) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onFail(ErrorCode.ROOM_NOT_JOIN_TO_ROOM.getCode()); } } }); } /** * 初始化房间信息 * * @param roomId */ private void initRoomInfo(String roomId) { synchronized (roomLock) { currentRoom = new DetailRoomInfo(); currentRoom.setRoomId(roomId); currentRoomAudioEnable = true; } } /** * 清除房间信息 */ private void clearRoomInfo(String roomId) { synchronized (roomLock) { if (currentRoom != null && currentRoom.getRoomId().equals(roomId)) { currentRoom = null; if (currentRTCRoom != null) { currentRTCRoom.unRegisterEventsListener(rtcListener); currentRTCRoom.unRegisterStatusReportListener(rtcListener); currentRTCRoom.release(); currentRTCRoom = null; } currentRoomEventListener = null; currentRole = null; currentRoomAudioEnable = false; if (currentRoomActiveThread != null) { // 如果线程正在睡眠则打断睡眠,加速线程退出 currentRoomActiveThread.interrupt(); currentRoomActiveThread = null; } } } } /** * 设置房间背景 * * @param backgroundIndex * @param callBack */ public void setRoomBackground(final int backgroundIndex, final ResultCallback<Boolean> callBack) { synchronized (roomLock) { if (currentRoom == null) { notInJoinToRoomCallBack(callBack); return; } final String roomId = currentRoom.getRoomId(); request.setRoomBackground(roomId, backgroundIndex, new HandleRequestWrapper<Boolean, Boolean>(callBack) { @Override public Boolean handleRequestResult(Boolean aBoolean) { synchronized (roomLock) { if (currentRoom != null && currentRoom.getRoomId().equals(roomId) && aBoolean) { currentRoom.setBgId(backgroundIndex); } } return aBoolean; } }); } } /** * 聊天室相关信息拦截处理 */ private class RoomMessageListener implements RongIMClient.OnReceiveMessageListener { @Override public boolean onReceived(final Message message, int i) { synchronized (roomLock) { Conversation.ConversationType conversationType = message.getConversationType(); if (conversationType == Conversation.ConversationType.CHATROOM) { if (currentRoom == null) return false; //判断chatRoomID String targetId = message.getTargetId(); if (!currentRoom.getRoomId().equals(targetId)) return false; final RoomEventListener roomEventlistener = currentRoomEventListener; // 当为文本消息 if (message.getContent() instanceof TextMessage) { //文本消息显示在聊天列表中 currentRoom.getMessageList().add(message); if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onMessageEvent(message); } }); } //房间成员变动消息 } else if (message.getContent() instanceof RoomMemberChangedMessage) { RoomMemberChangedMessage memberChangedMessage = (RoomMemberChangedMessage) message.getContent(); //房间成员变动消息显示在聊天列表中 currentRoom.getMessageList().add(message); if (memberChangedMessage.getRoomMemberAction() == RoomMemberChangedMessage.RoomMemberAction.JOIN) { currentRoom.setMemCount(currentRoom.getMemCount() + 1); } else if (memberChangedMessage.getRoomMemberAction() == RoomMemberChangedMessage.RoomMemberAction.LEAVE || memberChangedMessage.getRoomMemberAction() == RoomMemberChangedMessage.RoomMemberAction.KICK) { currentRoom.setMemCount(currentRoom.getMemCount() - 1); } final int memCount = currentRoom.getMemCount(); if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onMessageEvent(message); roomEventlistener.onRoomMemberChange(memCount); } }); } String currentUserId = AuthManager.getInstance().getCurrentUserId(); String targetUserId = memberChangedMessage.getTargetUserId(); String creatorUserId = currentRoom.getCreatorUserId(); //房主退出房间时通知所有人退出,当自己为房主时不做重复通知 if (creatorUserId != null && memberChangedMessage.getRoomMemberAction() == RoomMemberChangedMessage.RoomMemberAction.LEAVE && creatorUserId.equals(targetUserId) && !currentUserId.equals(creatorUserId)) { if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onRoomDestroy(); } }); } } //麦位变动消息更新麦位信息 } else if (message.getContent() instanceof MicPositionChangeMessage) { MicPositionChangeMessage positionChangeMessage = (MicPositionChangeMessage) message.getContent(); final List<RoomMicPositionInfo> micPositions = positionChangeMessage.getMicPositions(); if (micPositions != null) { currentRoom.setMicPositions(micPositions); } else { currentRoom.clearMicPositions(); } if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onMicUpdate(micPositions); } }); } //麦位控制消息更新麦位信息 } else if (message.getContent() instanceof MicPositionControlMessage) { MicPositionControlMessage positionChangeMessage = (MicPositionControlMessage) message.getContent(); final List<RoomMicPositionInfo> micPositions = positionChangeMessage.getMicPositions(); if (micPositions != null) { currentRoom.setMicPositions(micPositions); } else { currentRoom.clearMicPositions(); } if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { synchronized (roomLock) { roomEventlistener.onMicUpdate(micPositions); } } }); } // 当前如果麦位控制信息针对当前用户,则进行麦克风开启和关闭事件 String currentUserId = AuthManager.getInstance().getCurrentUserId(); String targetUserId = positionChangeMessage.getTargetUserId(); if (currentUserId.equals(targetUserId)) { final Role newRole = initCurrentRole(); currentRole = newRole; MicBehaviorType behaviorType = positionChangeMessage.getBehaviorType(); switch (behaviorType) { case PickupMic: case JumpOnMic: case UnForbidMic: if (roomEventlistener != null && newRole != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onRoleChanged(newRole); } }); } break; case JumpDownMic: case ForbidMic: if (roomEventlistener != null && newRole != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onRoleChanged(newRole); } }); } break; case KickOffMic: currentRole = new Linker(); if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onKickOffRoom(); } }); } break; } } // 房间背景更新消息 } else if (message.getContent() instanceof RoomBgChangeMessage) { final RoomBgChangeMessage bgChangeMessage = (RoomBgChangeMessage) message.getContent(); if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onRoomBgChanged(bgChangeMessage.getBgId()); } }); } } else if (message.getContent() instanceof RoomDestroyNotifyMessage) { if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onRoomExistOverTimeLimit(); } }); } } return true; } return false; } } } private class RoomRtcEventListener implements RongRTCEventsListener, RongRTCStatusReportListener { private String listenRoomId; RoomRtcEventListener(String roomId) { listenRoomId = roomId; } /** * 判断是否在房间内 * * @return */ private boolean isInRoom() { synchronized (roomLock) { if (currentRTCRoom != null) { return currentRTCRoom.getRoomId().equals(listenRoomId); } } return false; } /** * 当有用户发布音视频流时回调,通过此回调可以订阅其他用户发布的的 * * @param rongRTCRemoteUser * @param list */ @Override public void onRemoteUserPublishResource(RongRTCRemoteUser rongRTCRemoteUser, List<RongRTCAVInputStream> list) { /* * 当前不在房间内或当前不开启房间内音频时不进行订阅音频 */ if (!isInRoom() || !currentRoomAudioEnable) return; /* * 判断当前用户是否已在可进行语音聊天用户列表中, * 仅接受在该列表中的用户音频声音 */ List<String> enableVoiceChatUserList = getEnableVoiceChatUserList(); if (enableVoiceChatUserList.contains(rongRTCRemoteUser.getUserId())) { rongRTCRemoteUser.subscribeAvStream(rongRTCRemoteUser.getRemoteAVStreams(), new RongRTCResultUICallBack() { @Override public void onUiSuccess() { SLog.d(SLog.TAG_RTC, "subscribeAvStream - success"); } @Override public void onUiFailed(RTCErrorCode rtcErrorCode) { SLog.e(SLog.TAG_RTC, "subscribeAvStream - failed:" + rtcErrorCode.gerReason()); } }); } } @Override public void onRemoteUserAudioStreamMute(RongRTCRemoteUser rongRTCRemoteUser, RongRTCAVInputStream rongRTCAVInputStream, boolean b) { } @Override public void onRemoteUserVideoStreamEnabled(RongRTCRemoteUser rongRTCRemoteUser, RongRTCAVInputStream rongRTCAVInputStream, boolean b) { } @Override public void onRemoteUserUnPublishResource(RongRTCRemoteUser rongRTCRemoteUser, List<RongRTCAVInputStream> list) { } @Override public void onUserJoined(RongRTCRemoteUser rongRTCRemoteUser) { } @Override public void onUserLeft(RongRTCRemoteUser rongRTCRemoteUser) { } @Override public void onUserOffline(RongRTCRemoteUser rongRTCRemoteUser) { } @Override public void onVideoTrackAdd(String s, String s1) { } @Override public void onFirstFrameDraw(String s, String s1) { } /** * 由于异常退出房间 */ @Override public void onLeaveRoom() { SLog.e(SLog.TAG_RTC, "Room id:" + (currentRoom != null ? currentRoom.getRoomId() : "") + ",onErrorLeaveRoom"); final RoomEventListener roomEventlistener = currentRoomEventListener; if (roomEventlistener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { roomEventlistener.onErrorLeaveRoom(); } }); } } @Override public void onReceiveMessage(Message message) { } /** * 接受音频音频回调,通过该回调接口可以知道当前哪个用户在发言 * * @param hashMap 用户id 与 代表当前音频声音大小的等级,注意此处的用户id会有后缀tag * 如果非用户自定义的音频流则以 _RongCloudRTC 为后缀 */ @Override public void onAudioReceivedLevel(HashMap<String, String> hashMap) { if (hashMap == null || hashMap.size() == 0) return; final List<String> enableVoiceChatUserList = getEnableVoiceChatUserList(); final List<String> speakUserList = new ArrayList<>(); Set<String> userAudioSet = hashMap.keySet(); for (String userAudioId : userAudioSet) { /* * 此处的userId包含固定的后缀_RongCloudRTC,需要截取 */ String userId = userAudioId; if (userId != null && userId.endsWith("_RongCloudRTC")) { userId = userAudioId.substring(0, userAudioId.lastIndexOf("_RongCloudRTC")); } // 判断该音频是否在可发言用户列表中 if (enableVoiceChatUserList.contains(userId)) { // 获取音频声音等级,大于0则代表正在发言 String audioLevel = hashMap.get(userAudioId); int levelValue = 0; try { levelValue = Integer.parseInt(audioLevel); } catch (Exception e) { } if (levelValue > 0) { speakUserList.add(userId); } } } final RoomEventListener eventListener = currentRoomEventListener; if (eventListener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { eventListener.onRoomMicSpeak(speakUserList); } }); } } /** * 当前发言者音频回调,通过该回调接口可以知道当前自己是否在发言 * * @param audioLevel 声音大小等级,0代表没有声音 */ @Override public void onAudioInputLevel(String audioLevel) { final List<String> enableVoiceChatUserList = getEnableVoiceChatUserList(); String currentUserId = AuthManager.getInstance().getCurrentUserId(); if (enableVoiceChatUserList.contains(currentUserId)) { final List<String> speakUserList = new ArrayList<>(); // 获取音频声音等级,大于0则代表正在发言 int levelValue = 0; try { levelValue = Integer.parseInt(audioLevel); } catch (Exception e) { } if (levelValue > 0) { speakUserList.add(currentUserId); } final RoomEventListener eventListener = currentRoomEventListener; if (eventListener != null) { threadManager.runOnUIThread(new Runnable() { @Override public void run() { eventListener.onRoomMicSpeak(speakUserList); } }); } } } @Override public void onConnectionStats(StatusReport statusReport) { } } /** * 用于房主定时发送房间正在活动消息的线程 * 保证聊天室不会因长时间没有人发消息而销毁 */ private class RoomActiveMsgSenderThread extends Thread { private String roomId; public RoomActiveMsgSenderThread(String roomId) { this.roomId = roomId; } /** * 判断当前所在房间是否为启动该线程时的房间 * * @return */ private boolean isInRoom() { synchronized (roomLock) { if (currentRoom != null) { String currentRoomRoomId = currentRoom.getRoomId(); if (this.roomId != null && this.roomId.equals(currentRoomRoomId)) { return true; } } } return false; } @Override public void run() { // 当房主在房间时,每隔一定时间就发送房间正在活动消息 while (isInRoom()) { RoomIsActiveMessage roomIsActiveMessage = new RoomIsActiveMessage(); Message message = Message.obtain(roomId, Conversation.ConversationType.CHATROOM, roomIsActiveMessage); RongIMClient.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { } }); try { Thread.sleep(ROOM_SEND_ACTIVE_INTERVAL_TIME_MILLIS); } catch (InterruptedException e) { } } } } }<file_sep>package cn.rongcloud.sealmic.ui.widget; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.view.animation.DecelerateInterpolator; import java.util.ArrayList; import java.util.List; import cn.rongcloud.sealmic.R; public class RoomManagerRippleView extends View { private final static long DEFAULT_AUTO_STOP_RIPPLE_INTERVAL_TIME_MILLIS = 3000; private Context context; // 圆圈集合 private List<Circle> circleList; // 圆圈初始半径 private int startRadius; // 圆圈最大半径 private int maxRadius; // 第一个圆圈的颜色 private int firstColor; // 第二个圆圈的颜色 private int secondColor; // View宽 private float mWidth; // View高 private float mHeight; private long autoStopTimeIntervalMillis = DEFAULT_AUTO_STOP_RIPPLE_INTERVAL_TIME_MILLIS; private long startRippleTimeMillis; private AnimatorSet animatorSet; private boolean startAnimator = true; private long duration; public RoomManagerRippleView(Context context) { this(context, null); } public RoomManagerRippleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RoomManagerRippleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray tya = context.obtainStyledAttributes(attrs, R.styleable.RoomManagerRippleView); firstColor = tya.getColor(R.styleable.RoomManagerRippleView_firstColor, Color.BLUE); secondColor = tya.getColor(R.styleable.RoomManagerRippleView_secondColor, Color.argb(60, 0, 0, 255)); duration = (long) tya.getInt(R.styleable.RoomManagerRippleView_duration, 1000); startRadius = (int) tya.getDimension(R.styleable.RoomManagerRippleView_startRadius, 0); maxRadius = (int) tya.getDimension(R.styleable.RoomManagerRippleView_maxRadius, 0); tya.recycle(); init(); } private void init() { context = getContext(); circleList = new ArrayList<>(); // 第两个圆的半径 int firstCircleMaxRadius = (maxRadius - startRadius) / 2 + startRadius; // 添加第一个圆圈 Paint paint = new Paint(); paint.setColor(firstColor); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); Circle firstCircle = new Circle(startRadius, firstCircleMaxRadius, paint); circleList.add(firstCircle); // 添加第二个圆圈 paint = new Paint(); paint.setColor(secondColor); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); Circle secondCircle = new Circle(startRadius, maxRadius, paint); circleList.add(secondCircle); // 设置透明背景 setBackgroundColor(Color.TRANSPARENT); // 动画 ObjectAnimator firstAnimator = ObjectAnimator.ofInt(firstCircle, "radius", firstCircle.startRadius, firstCircle.maxRadius); firstAnimator.setInterpolator(new DecelerateInterpolator(6)); firstAnimator.setDuration((int) (duration * 0.75)); firstAnimator.setRepeatCount(1); firstAnimator.setRepeatMode(ValueAnimator.REVERSE); ObjectAnimator secondAnimator = ObjectAnimator.ofInt(secondCircle, "radius", secondCircle.startRadius, secondCircle.maxRadius); secondAnimator.setInterpolator(new DecelerateInterpolator(1)); secondAnimator.setDuration(duration); secondAnimator.setRepeatCount(1); secondAnimator.setRepeatMode(ValueAnimator.REVERSE); animatorSet = new AnimatorSet(); animatorSet.playTogether(firstAnimator, secondAnimator); animatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { long currentTimeMillis = System.currentTimeMillis(); if (autoStopTimeIntervalMillis > 0 && currentTimeMillis - startRippleTimeMillis > autoStopTimeIntervalMillis) { startAnimator = false; return; } if (startAnimator) { animatorSet.start(); } } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); drawCircle(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mWidth = MeasureSpec.getSize(widthMeasureSpec); mHeight = MeasureSpec.getSize(heightMeasureSpec); // 设置该view的宽高 setMeasuredDimension((int) mWidth, (int) mHeight); } /** * 圆到宽度 * * @param canvas */ private void drawCircle(Canvas canvas) { canvas.save(); // 处理每个圆的宽度和透明度 for (int i = 0; i < circleList.size(); i++) { Circle c = circleList.get(i); canvas.drawCircle(mWidth / 2, mHeight / 2, c.radius, c.paint); } invalidate(); canvas.restore(); } class Circle { int radius; int startRadius; int maxRadius; Paint paint; Circle(int startRadius, int maxRadius, Paint paint) { this.startRadius = startRadius; this.maxRadius = maxRadius; this.radius = startRadius; this.paint = paint; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } } public void enableRipple(boolean enable) { startAnimator = enable; if (autoStopTimeIntervalMillis > 0) { startRippleTimeMillis = System.currentTimeMillis(); } if (enable && !animatorSet.isRunning()) { animatorSet.start(); } } } <file_sep>package cn.rongcloud.sealmic.task.role; import android.text.TextUtils; import java.util.ArrayList; import java.util.List; import androidx.annotation.Nullable; import cn.rongcloud.sealmic.constant.ErrorCode; import cn.rongcloud.sealmic.model.DetailRoomInfo; import cn.rongcloud.sealmic.model.MicBehaviorType; import cn.rongcloud.sealmic.model.MicState; import cn.rongcloud.sealmic.model.RoomMicPositionInfo; import cn.rongcloud.sealmic.task.ResultCallback; import cn.rongcloud.sealmic.task.RoomManager; public class Owner extends Role { public Owner() { } @Override public List<MicBehaviorType> getBehaviorList(int micPosition) { RoomMicPositionInfo micPositionInfo = getMicInfoByPosition(micPosition); List<MicBehaviorType> behaviorList = new ArrayList<>(); String userId = micPositionInfo.getUserId(); if (micPositionInfo != null) { // 根据麦位状态添加可操作的行为 int micState = micPositionInfo.getState(); // 判断麦位是否有人来进行抱麦和下麦操作 if (TextUtils.isEmpty(userId) && !MicState.isState(micState, MicState.Locked)) { behaviorList.add(MicBehaviorType.PickupMic); //抱麦 } else if (!TextUtils.isEmpty(userId)) { behaviorList.add(MicBehaviorType.KickOffMic); //踢麦 behaviorList.add(MicBehaviorType.JumpDownMic); //下麦 } // 判断锁麦状态 if (MicState.isState(micState, MicState.Locked)) { behaviorList.add(MicBehaviorType.UnlockMic); //解锁麦 } else { behaviorList.add(MicBehaviorType.LockMic); //锁麦 } // 判断麦位禁麦状态 if (MicState.isState(micState, MicState.Forbidden)) { behaviorList.add(MicBehaviorType.UnForbidMic); //解禁麦 } else { behaviorList.add(MicBehaviorType.ForbidMic); //禁麦 } } return behaviorList; } @Override public void perform(MicBehaviorType micBehaviorType, int targetPosition, String targetUserId, ResultCallback<Boolean> callback) { RoomManager.getInstance().controlMicPosition(targetPosition, targetUserId, micBehaviorType.ordinal(), callback); } @Override public void leaveRoom(final ResultCallback<Boolean> callBack) { final RoomManager roomManager = RoomManager.getInstance(); DetailRoomInfo currentRoomInfo = roomManager.getCurrentRoomInfo(); if (currentRoomInfo == null || TextUtils.isEmpty(currentRoomInfo.getRoomId())) { if (callBack != null) { callBack.onFail(ErrorCode.ROOM_NOT_JOIN_TO_ROOM.getCode()); } return; } final String roomId = currentRoomInfo.getRoomId(); roomManager.leaveRoom(new ResultCallback<Boolean>() { @Override public void onSuccess(Boolean aBoolean) { roomManager.destroyRoom(roomId, callBack); } @Override public void onFail(int errorCode) { if (callBack != null) { callBack.onFail(errorCode); } } }); } @Override public boolean hasVoiceChatPermission() { return true; } @Override public boolean hasRoomSettingPermission() { return true; } @Override public boolean isSameRole(Role role) { return role instanceof Owner; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof Owner) { return true; } return super.equals(obj); } } <file_sep>#!/bin/bash # RTC Build # # Created by qixinbing on 19/3/6. # Copyright (c) 2019 RongCloud. All rights reserved. # 该脚本原则上由 Jenkins 编译触发,如果想本地编译,请通过 pre_build.sh 触发本脚本 #sh scripts/build.sh trap exit ERR BUILD_PATH=`pwd` OUTPUT_PATH="${BUILD_PATH}/output" BRANCH=${Branch} CUR_TIME=$(date "+%Y%m%d%H%M") APP_VERSION=${APP_Version} echo "Build Path:"$BUILD_PATH #拉取源码,参数 1 为 git 仓库目录,2 为 git 分支 function pull_sourcecode() { path=$1 branch=$2 cd ${path} git fetch git reset --hard git checkout ${branch} git pull origin ${branch} } ##复制 SDK 或者源码到指定目录并压缩,参数1:原始目录,参数2:目标目录,参数3:压缩包名称 #function copy_sdk(){ # src_path=$1 # target_path=$2 # zip_file_name=$3 # # mkdir $target_path # cp -af $src_path/* $target_path # zip -r $OUTPUT_PATH/${zip_file_name}.zip $target_path # rm -rf $target_path #} # # #pull_sourcecode ./ $RTC_BRANCH # #sed -i -e 's/3612cc23a8/3b03bae451/g' app/src/main/java/cn/rongcloud/rtc/RongRTCApplication.java chmod +x gradlew ./gradlew clean -i ./gradlew sealmic:assemble rm -rf $OUTPUT_PATH mkdir -p $OUTPUT_PATH cp -r sealmic/build/outputs/apk/debug/sealmic-debug.apk ${OUTPUT_PATH}/SealMic_v${APP_VERSION}_${CUR_TIME}.apk cp -r sealmic/build/outputs/apk/release/sealmic-release.apk ${OUTPUT_PATH}/SealMic_v${APP_VERSION}_${CUR_TIME}_release.apk <file_sep>package cn.rongcloud.sealmic; import android.app.Dialog; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Random; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import cn.rongcloud.sealmic.model.BaseRoomInfo; import cn.rongcloud.sealmic.model.DetailRoomInfo; import cn.rongcloud.sealmic.model.LoginInfo; import cn.rongcloud.sealmic.net.model.CreateRoomResult; import cn.rongcloud.sealmic.task.AuthManager; import cn.rongcloud.sealmic.task.ResultCallback; import cn.rongcloud.sealmic.task.RoomManager; import cn.rongcloud.sealmic.ui.BaseActivity; import cn.rongcloud.sealmic.ui.ChatRoomActivity; import cn.rongcloud.sealmic.ui.adapter.ChatRoomRefreshAdapter; import cn.rongcloud.sealmic.utils.ResourceUtils; import cn.rongcloud.sealmic.utils.ToastUtils; import cn.rongcloud.sealmic.utils.log.SLog; import io.rong.imlib.RongIMClient; import static cn.rongcloud.rtc.core.voiceengine.BuildInfo.MANDATORY_PERMISSIONS; public class MainActivity extends BaseActivity implements View.OnClickListener { public static final String TAG = "MainActivity"; /** * 退出应用时两次点击后退键的时间间隔 */ private static final long DOUBLE_BACK_KEY_TO_EXIT_INTERVAL_MILLIS = 2000; private ImageView imageViewCreate; private Dialog bottomDialog; private int selectedId = -1; private ChatRoomRefreshAdapter chatRoomRefreshAdapter; private RecyclerView recyclerView = null; private EditText editText; private SwipeRefreshLayout mRefreshLayout; private Handler handler; private View emptyView; private volatile boolean isJoiningRoom = false; // 是否正有加入房间操作 private long lastPressBackKeyMillis; // 最近一次点击后退键的时间 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seal_mic_main); handler = new Handler(); loginToServer(); initView(); checkPermissions(); } /** * 加载聊天室数据 */ private void loadData() { RoomManager.getInstance().getChatRoomList(new ResultCallback<List<BaseRoomInfo>>() { public void onSuccess(List<BaseRoomInfo> baseRoomInfoList) { if(baseRoomInfoList == null || baseRoomInfoList.size() == 0){ emptyView.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); }else { emptyView.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } chatRoomRefreshAdapter.setLoadDataList(baseRoomInfoList); mRefreshLayout.setRefreshing(false); } @Override public void onFail(int errorCode) { ToastUtils.showErrorToast(errorCode); } }); } /** * 初始化view */ private void initView() { imageViewCreate = findViewById(R.id.rc_seal_mic_create_iv); imageViewCreate.setOnClickListener(this); chatRoomRefreshAdapter = new ChatRoomRefreshAdapter(this); setAdapterItemClickListener(); recyclerView = findViewById(R.id.rc_seal_mic_rv); final GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2); recyclerView.setLayoutManager(gridLayoutManager); recyclerView.setAdapter(chatRoomRefreshAdapter); imageViewCreate = findViewById(R.id.rc_seal_mic_create_iv); imageViewCreate.setOnClickListener(this); mRefreshLayout = findViewById(R.id.srl_refresh); // 初始画面,使用 SwipeRefreshLayout 做 Loading mRefreshLayout.setRefreshing(true); // 自定义 SwipeRefreshLayout 颜色 mRefreshLayout.setColorSchemeResources( android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light, android.R.color.holo_blue_light, android.R.color.holo_purple ); // 设定下拉圆圈的背景色 mRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white); // 下拉刷新 mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //防止第一次登录失败,加入补充登录的时机 loginToServer(); loadData(); } }); // 列表空图标 emptyView = findViewById(R.id.rc_seal_mic_empty_view); } @Override protected void onResume() { super.onResume(); /* * 加入延时能改善刚退出房间时,房间没有完全销毁导致刷新的列表中存在即将销毁的房间 * 点击时因房间已不存在而报错 */ handler.postDelayed(new Runnable() { @Override public void run() { loadData(); } }, 1000); /* * 当成功加入房间后,再次回到主界面时才可以再加入其他房间 * 防止多次加入房间问题 */ isJoiningRoom = false; } private void loginToServer() { if (!TextUtils.isEmpty(AuthManager.getInstance().getCurrentUserId())) return; // 生成唯一随机id String deviceId = String.valueOf(new Random().nextLong()); // 请求服务器获取登录 IM 所使用的 token AuthManager.getInstance().login(deviceId, new ResultCallback<LoginInfo>() { @Override public void onSuccess(LoginInfo loginInfo) { if (loginInfo != null) { loginToIM(loginInfo.getImToken()); } } @Override public void onFail(int errorCode) { ToastUtils.showToast(R.string.toast_error_login_failed); } }); } private void loginToIM(String token) { RongIMClient.connect(token, new RongIMClient.ConnectCallback() { @Override public void onTokenIncorrect() { SLog.e(TAG, "RongIMClient onTokenIncorrect"); } @Override public void onSuccess(String s) { SLog.d(TAG, "RongIMClient connect success"); //ToastUtils.showToast(R.string.toast_login_success); } @Override public void onError(RongIMClient.ErrorCode errorCode) { SLog.e(TAG, "RongIMClient connect onError:" + errorCode.getValue() + "-" + errorCode.getMessage()); } }); } private void joinChatRoom(final String roomId, final boolean isCreate) { if (!isCreate) { //ToastUtils.showToast(R.string.toast_joining_room); } RoomManager.getInstance().joinRoom(roomId, new ResultCallback<DetailRoomInfo>() { @Override public void onSuccess(DetailRoomInfo detailRoomInfo) { if (isCreate) { //ToastUtils.showToast(R.string.toast_create_room_success); } else { //ToastUtils.showToast(R.string.toast_join_room_success); } Intent intent = new Intent(MainActivity.this, ChatRoomActivity.class); startActivity(intent); } @Override public void onFail(int errorCode) { isJoiningRoom = false; ToastUtils.showErrorToast(errorCode); // 可能存在加入的房间已不存在而导致保存,此时刷新下房间列表 loadData(); } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.rc_seal_mic_create_iv: if (isJoiningRoom) return; showBottomDialog(); break; default: break; } } /** * 弹出底部对话框 */ private void showBottomDialog() { bottomDialog = new Dialog(this, R.style.BottomDialog); View contentView = LayoutInflater.from(this).inflate(R.layout.rc_seal_mic_dialog, null); editText = contentView.findViewById(R.id.room_edit_text); // 默认选择一条随机话题 String randomRoomTopic = ResourceUtils.getInstance().getRandomRoomTopic(); editText.setText(randomRoomTopic); editText.setSelection(randomRoomTopic.length()); bottomDialog.setContentView(contentView); bottomDialogCloseClick(contentView); // 初始化点击事件 int[] arrayClicker = {R.id.random, R.id.topics_1, R.id.topics_2, R.id.topics_3, R.id.topics_4, R.id.topics_5, R.id.room_create}; for (int clickId : arrayClicker) { itemClick(contentView, clickId); } //默认选中第一项类型 TextView topic1Tv = contentView.findViewById(R.id.topics_1); topic1Tv.setSelected(true); selectedId = R.id.topics_1; ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams(); layoutParams.width = getResources().getDisplayMetrics().widthPixels; layoutParams.height = (int) getResources().getDimension(R.dimen.bottom_dialog_height); contentView.setLayoutParams(layoutParams); bottomDialog.getWindow().setGravity(Gravity.BOTTOM); bottomDialog.show(); } /** * 点击底部弹出框中聊天室类型Textiew处理 * * @param contentView * @param clickId */ private void itemClick(final View contentView, final int clickId) { final TextView clickItem = contentView.findViewById(clickId); clickItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.random: // 设置随机房间名称 String randomRoomTopic = ResourceUtils.getInstance().getRandomRoomTopic(); editText.setText(randomRoomTopic); editText.setSelection(randomRoomTopic.length()); break; case R.id.topics_1: case R.id.topics_2: case R.id.topics_3: case R.id.topics_4: case R.id.topics_5: // 刷新点击状态 TextView selectedItem = contentView.findViewById(selectedId); if (selectedItem != null && !selectedItem.equals(clickItem)) { selectedItem.setSelected(false); } clickItem.setSelected(true); selectedId = v.getId(); break; case R.id.room_create: if (TextUtils.isEmpty(editText.getText())) { ToastUtils.showToast(R.string.toast_error_invalid_room_title); return; } String subjectStr = editText.getText().toString(); int type = formatType(selectedId); // 判断是否有手机运行权限进行语音聊天 if (!checkPermissions()) return; // 标记正在进入房间 isJoiningRoom = true; //ToastUtils.showToast(R.string.toast_creating_room); RoomManager.getInstance().createRoom(subjectStr, type, new ResultCallback<CreateRoomResult>() { @Override public void onSuccess(CreateRoomResult createRoomResult) { bottomDialog.dismiss(); joinChatRoom(createRoomResult.getRoomId(), true); } @Override public void onFail(int errorCode) { isJoiningRoom = false; ToastUtils.showErrorToast(errorCode); loadData(); } }); break; default: break; } } }); } /** * 将选中的id转成对应的type * * @param selectedId * @return */ private int formatType(int selectedId) { switch (selectedId) { case R.id.topics_1: return 1; case R.id.topics_2: return 2; case R.id.topics_3: return 3; case R.id.topics_4: return 4; case R.id.topics_5: return 5; default: return 0; } } /** * 点击关闭底部弹出框 * * @param contentView */ private void bottomDialogCloseClick(View contentView) { ImageView bottomDialogClose = contentView.findViewById(R.id.bottom_dialog_close); bottomDialogClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (bottomDialog != null && bottomDialog.isShowing()) { bottomDialog.dismiss(); } } }); } @Override protected void onDestroy() { if (bottomDialog != null && bottomDialog.isShowing()) { bottomDialog.dismiss(); bottomDialog = null; } super.onDestroy(); } private void setAdapterItemClickListener() { chatRoomRefreshAdapter.setOnItemClickListener(new ChatRoomRefreshAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { if (!checkPermissions()) return; BaseRoomInfo roomInfo = chatRoomRefreshAdapter.getItem(position); if (roomInfo != null && !TextUtils.isEmpty(roomInfo.getRoomId())) { // 判断是否正在进入房间,房子多次进入房间 if (isJoiningRoom) return; isJoiningRoom = true; joinChatRoom(roomInfo.getRoomId(), false); } else { ToastUtils.showToast(R.string.chatroom_info_error); } } }); } private boolean checkPermissions() { List<String> unGrantedPermissions = new ArrayList(); for (String permission : MANDATORY_PERMISSIONS) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { unGrantedPermissions.add(permission); } } if (unGrantedPermissions.size() == 0) {//已经获得了所有权限 return true; } else {//部分权限未获得,重新请求获取权限 String[] array = new String[unGrantedPermissions.size()]; ActivityCompat.requestPermissions(this, unGrantedPermissions.toArray(array), 0); ToastUtils.showToast(R.string.toast_error_need_app_permission); return false; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public void onBackPressed() { long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis - lastPressBackKeyMillis < DOUBLE_BACK_KEY_TO_EXIT_INTERVAL_MILLIS) { finish(); } else { lastPressBackKeyMillis = currentTimeMillis; ToastUtils.showToast(R.string.toast_press_back_one_more_to_exit); } } }
d0b90d9136ff86368f24d23b3bf1491ee751479a
[ "Markdown", "Java", "Shell", "Gradle" ]
25
Markdown
luohan013/sealmic-android
59219503a92b861a2297a379026bdbbde9e827b0
7d6b4eb9e213424812a9b46b589474d971e87df3
refs/heads/master
<file_sep>#include<mpi.h> #include <stdio.h> #include<stdlib.h> // we need a special format of matrix for our algorithm , let's call it formal "S" // the first matrix would be in column major format and the second one in a row major format //so we make two functions to change a column major to row major and vice versa //this makes sure that we can work on any format of the input //after processing the input with those two functions , our multipliaction algorithm requires us to have those in format "S" void createMatrix(float *A,int n , float a ) // generate n elements for a matrix { int i; for(i=0;i<n;i++) {A[i]= (float)rand()/(float)(RAND_MAX/a);} // floats wil be all less than a } void rtoC(float* A , float* B , int m , int n){ //converts row major A into column major B , size is m*n for (int i=0;i< m ;i++){ for (int j=0; j< n; j++){ B[j*m + i] = A[i*n + j] ; } } } void ctor(float* A , float* B , int m , int n){ //converts column major A into row major B , size is m*n for (int i=0;i< m ;i++){ for (int j=0; j< n; j++){ B[i*n + j] =A[j*m + i] ; } } } void matrix_Multiply(float *A, float *B, float *C, int m, int n, int p){ // A is column major and B is row major // Output c is row major //A is m*n and B is n*p int i, j, k; for (i = 0; i < m; i++){ for (j = 0; j < p; j++){ C[i*p + j] = 0; for (k = 0; k < n; k++) C[i*p + j] += A[ k*m + i] * B[k*p + j]; } } } //checks if two matrices are equal int matrixEqual (float *A , float *B , int p ){ // returns 0 for equal or 1 for unequal // p is total number of elements in them int i; for (i = 0; i < p; i++){ if (A[i] == B[i]){} else {return 1;} } return 0; } int main (int argc, char**argv){ int rank,size,n ,count; n=4; // size of matrix //count = atoi(argv[2]); // number of cores MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&size); MPI_Comm_rank(MPI_COMM_WORLD,&rank); count = size; int partSize = 32/count ; float *partMatrix1 =(float*)malloc((partSize*n)*sizeof(float)); // space to store and mutilply partial matrices float *partMatrix2 =(float*)malloc((partSize*n)*sizeof(float)); float *partProduct=(float*)malloc((n*n)*sizeof(float)); float *wholeMatrix1; float *wholeMatrix2 ; float *wholeProduct1 ; float *wholeProduct2; double startTime ; double endTime ; double timeSerial; double *elapsed ; double *timeParallel; printf("The rank is %d\n\n",rank); if(rank ==0) { wholeMatrix1=(float*)malloc((n*32)*sizeof(float)); wholeMatrix2=(float*)malloc((n*32)*sizeof(float)); wholeProduct1=(float*)malloc((n*n)*sizeof(float)); for(int i=0;i<(n*n);i++){ wholeProduct1[i] = 0.000;} wholeProduct2=(float*)malloc((n*n)*sizeof(float)); for(int i=0;i<(n*n);i++){ wholeProduct2[i] = 0.000;} createMatrix(wholeMatrix1 ,(n*32),10000.00); createMatrix(wholeMatrix2 ,(n*32),10000.00); startTime = MPI_Wtime(); matrix_Multiply(wholeMatrix1 , wholeMatrix2 ,wholeProduct2, n , partSize , n); endTime = MPI_Wtime(); timeSerial = endTime - startTime; for(int q=0; q<(n*n);q++){ printf("The integer is: %f\n", wholeProduct2[q]);} } MPI_Barrier(MPI_COMM_WORLD); startTime = MPI_Wtime(); MPI_Scatter(wholeMatrix1,(partSize*n),MPI_FLOAT,partMatrix1,(partSize*n),MPI_FLOAT,0,MPI_COMM_WORLD); MPI_Scatter(wholeMatrix2,(partSize*n),MPI_FLOAT,partMatrix2,(partSize*n),MPI_FLOAT,0,MPI_COMM_WORLD); matrix_Multiply(partMatrix1 , partMatrix2 ,partProduct, n , partSize , n); MPI_Reduce(partProduct,wholeProduct1,(n*n),MPI_FLOAT,MPI_SUM,0,MPI_COMM_WORLD); endTime = MPI_Wtime(); elapsed[0] = endTime - startTime; MPI_Reduce(elapsed,timeParallel,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD); if(rank==0){ for(int q=0; q<(n*n);q++){ printf("The integer is: %f\n", wholeProduct1[q]); } printf("Hello C Language"); for(int q=0; q<(n*n);q++){ printf("The integer is: %f\n", wholeProduct2[q]); } int p = matrixEqual(wholeProduct1 , wholeProduct2 , (n*n)); printf("The integer is: %d\n", p); printf("Serial time collective: %f\n", timeSerial); printf("Parallel time collective: %f\n", timeParallel[0]); } MPI_Finalize(); return 0; } <file_sep># MPIcol380 Multiplying two matrices through parallel processes using MPI
d569b9b6c141c73c5b366ccf867af0415a3f915d
[ "Markdown", "C" ]
2
C
AdarshaAman/MPIcol380
3aa59acc2c68257a30cb3b0cc28bcb8be6da3163
8d815951b711efd5134649377328f1ac270066b3
refs/heads/master
<file_sep><!doctype html> <html> <head> <meta charset="utf-8"> <title>Police Emergency Service System</title> <link rel="stylesheet" type="text/css" href="hongyang_pess.css"> </head> <body> <script> function meaningful() { var x=document.forms["formLogCall"]["callName"].value; if (x==null || x=="") { alert("Please Enter Caller Name!"); return false; } } function meaningful() { var x = document.forms["formLogCall"]['contactNo'].value; if(x == "" || x=="") { alert("Contact Number Must Be In!"); return false; } } function meaningful() { var x = document.forms["formLogCall"]['description'].value; if(x == "") { alert("Description Must Be Filled Out!"); return false; } } </script> <div class="container"> <?php require_once 'nav.php';?> <?php require_once 'db_config.php'; $mysqli = mysqli_connect("localhost", "root", "", "hongyang_pessdb"); if ($mysqli->connect_error) { die("Failed to connect to MySQL: ".$mysqli->connect_errno); } $sql = "SELECT * FROM incidenttype"; if (!($stmt = $mysqli->prepare($sql))) { die("Unable to prepare: ".$mysqli->errno); } if (!$stmt->execute()) { die("Cannot be executed: ".$stmt->errno); } if (!($resultset = $stmt->get_result())) { die("Result set malfunction: ".$stmt->errno); } $incidentType; while ($row = $resultset->fetch_assoc()) { $incidentType[$row['incidentTypeId']] = $row['incidentTypeDesc']; } $stmt->close(); $resultset->close(); $mysqli->close(); ?> <form name="formLogCall" method="post" action="dispatch.php" onSubmit="return meaningful();"> <fieldset> <legend>Log Call</legend> <table width="53%" border="4" align="center" cellpadding="6" cellspacing="6"> <tr> <td width="60%">Caller Name : </td> <td width="50%"><input type="text" name="callName" id="callName"></td> </tr> <tr> <td width="50%">Contact No : </td> <td width="50%"><input type="text" name="contactNo" id="contactNo"></td> </tr> <tr> <td width="50%">Incident Type : </td> <td width="50%"> <select name="incidentType" id="incidentType"> <?php foreach($incidentType as $key=> $value) {?> <option value="<?php echo $key ?> " > <?php echo $value ?> </option> <?php } ?> </td> </tr> <tr> <td width="50%">Location : </td> <td width="50%"><input type="text" name="location" id="location"></td> </tr> <tr> <td width="50%">Description : </td> <td width="50%"><textarea name="description" id="description" cols="65" rows="10"></textarea></td> </tr> <tr> <td><input type="reset" name="Cancel" id="cancel" value="Clear"</td> <td><input type="submit" name="Submit" id="Submit" value="Proceed"</td> </tr> <marquee behaviour="alternate" direction="down" scrollamount="3"><li><mark>[Server Update 20/4]</li></mark></marquee> <marquee behaviour="alternate" direction="down" scrollamount="3"><li>[Database Checked 5/4]</li></marquee> </table> </div> <style> .footer { position:inherit; left: 0; bottom: 0; width: 100%; background-color: black; color: white; text-align: center; } </style> <div class="footer"> <p>Copyright © 2020 <NAME>. All Rights Reserved.</p> </div> </fieldset> </form> </body> </html> <file_sep><!doctype html> <html> <head> <meta charset="utf-8"> <title>Police Emergency Service System</title> <link rel="stylesheet" type="text/css" href="hongyang_pess.css"> </head> <body> <div class="container"> <!-- display the incident information passed from logcall.php --> <form name="form1" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?> "> <table width="50%" border="2" align="center" cellpadding"5" cellspacing="5"> <?php require_once 'nav.php';?> <?php if (isset($_POST["btnDispatch"])) { require_once 'db_config.php'; //create database connection $mysqli = mysqli_connect("localhost", "root", "", "hongyang_pessdb"); // Check connection if ($mysqli->connect_errno) { die("Failed to connect to MySQL: ".$mysqli->connect_errno); } $patrolcarDispatched = $_POST["chkPatrolcar"]; $numofPatrolcarDispatched = count($patrolcarDispatched); // insert new incident $incidentStatus; if ($numofPatrolcarDispatched > 0) { $incidentStatus='2'; } else { $incidentStatus='1'; } $sql = "INSERT INTO incident (callerName, phoneNumber, incidentTypeId, incidentLocation, incidentDesc, incidentStatusId) VALUES (?, ?, ?, ?, ?, ?)"; if (!($stmt = $mysqli->prepare($sql))) { die("Prepare failed: ".$mysqli->errno); } if (!$stmt->bind_param('ssssss', $_POST['callName'], $_POST['contactNo'], $_POST['incidentType'], $_POST['location'], $_POST['description'], $incidentStatus)) { die("Binding parameters failed: ".$stmt->errno); } if (!$stmt->execute()) { die("Insert incident table failed: ".$stmt->errno); } // retrieve incident_id for the newly inserted incident $incidentId=mysqli_insert_id($mysqli); // update patrolcar status table and add into dispatch table for($i=0; $i < $numofPatrolcarDispatched; $i++) { // update patrol car status $sql = "UPDATE patrolcar SET patrolcarStatusId = '1' WHERE patrolcarId = ?"; if (!($stmt = $mysqli->prepare($sql))) { die("Prepare failed: ".$mysqli->errno); } if (!$stmt->bind_param('s', $patrolcarDispatched[$i])){ die("Binding parameters failed: ".$stmt->errno); } if (!$stmt->execute()) { die("Update patrolcar_status table failed: ".$stmt->errno); } // insert dispatch data $sql = "INSERT into dispatch (incidentId, patrolcarId, timeDispatched) VALUES (?, ?, NOW())"; if (!($stmt = $mysqli->prepare($sql))) { die ("Prepare failed: ".$mysqli->errno); } if (!$stmt->bind_param('ss', $incidentId, $patrolcarDispatched[$i])){ die("Binding parameters failed: ".$stmt->errno); } if (!$stmt->execute()) { die("Insert dispatch table failed: ".$stmt->errno); } } $stmt->close(); $mysqli->close(); } ?> <tr> <td colspan="10">Incident Detail</td> </tr> <tr> <td width="50%">Caller's Name : </td> <td><input type="text" name="callName" id="callName" value="<?php echo $_POST['callName'] ?>" readonly> </td> </tr> <tr> <td width="50%">Contact No : </td> <td><input type="text" name="contactNo" id="contactNo" value="<?php echo $_POST ['contactNo']?>" readonly> </td> </tr> <tr> <td width="50%">Location : </td> <td><input type="text" name="location" id="location" value="<?php echo $_POST ['location']?>" readonly> </td> </tr> <tr> <td width="40%">Incident Type : </td> <td><input type="text" name="incidentType" id="incidentType" value="<?php echo $_POST ['incidentType']?>" readonly> </td> </tr> <tr> <td width="50%">Description : </td> <td><textarea name="description" cols="50" rows="6" readonly id="description" readonly><?php echo $_POST['description'] ?></textarea> </td> </tr> </table> <?php // connect to a database require_once 'db_config.php'; // create database connection $mysqli = mysqli_connect("localhost", "root", "", "hongyang_pessdb"); // check connection if ($mysqli->connect_errno) { die("Failed to connect to MySQL: ".$mysqli->connect_errno); } //retrieve from patrolcar table those patrol cars that are 2:Patrol Car 3: Free $sql = "SELECT patrolcarId, statusDesc FROM patrolcar JOIN patrolcar_status ON patrolcar.patrolcarStatusId=patrolcar_status.StatusId WHERE patrolcar.patrolcarStatusId='2' OR patrolcar.patrolcarStatusId='3'"; if (!($stmt = $mysqli->prepare($sql))) { die("Prepare Failed: ".$mysqli->errno); } if (!$stmt->execute()) { die("Execute Failed: ".$stmt->errno); } if (!($resultset = $stmt->get_result())) { die("Gtting result set failed: ".$stmt->errno); } $patrolcarArray; while ($row = $resultset->fetch_assoc()) { $patrolcarArray[$row['patrolcarId']] = $row['statusDesc']; } $stmt->close(); $resultset->close(); $mysqli->close(); ?> <!-- populate table with patrol car data --> <br><br><table border="1" align="center"> <tr> <td colspan="3">Dispatch Patrolcar Panel</td> </tr> <?php foreach($patrolcarArray as $key=>$value){ ?> <tr> <td><input type="checkbox" name="chkPatrolcar[]" value="<?php echo $key?>"></td> <td><?php echo $key ?></td> <td><?php echo $value ?></td> </tr> <?php } ?> <tr> <td><input type="reset" name="btnCancel" id="btnCancel" value="Reset"></td> <td colspan="2" align="center" width="80%"><input type="submit" name="btnDispatch" id="btnDispatch" value="Dispatch"> </td> </tr> </div> </table> <style> .footer { position:inherit; left: 0; bottom: 0; width: 100%; background-color: black; color: white; text-align: center; } </style> <div class="footer"> <p>Copyright © 2020 <NAME>. All Rights Reserved.</p> </div> </form> </body> </html>
4ad86a6233eadcf1d93faf516fbbafaa5fb5b1d4
[ "PHP" ]
2
PHP
HongYang27/PoliceEmergencyServiceSystem
c9163746e360febb0af2a2e009e8a78b87e662c8
9ef2d3b595b680aecf3fd3540627915195bbcac1
refs/heads/master
<repo_name>wjw0970/ConsoleCode<file_sep>/tests/helpers/helper.js /** * Created by lakhdeep on 7/9/15. */ var exp = { googleLogin: require('./googleLogin'), //googleLogOut: require('./googleLogin'), openWHpage: require('./openWHpage') } module.exports = exp; <file_sep>/tests/helpers/openWHpage.js "use strict"; var bootstrap = require('../bootstrap'), alphaRedMart = bootstrap.alphaRedMart, desired = bootstrap.desired, wd = bootstrap.wd; module.exports = { openWHpage: function(browser) { return browser .waitForElementByCss('.menu-title.ng-scope span[tooltip="Warehouse"]', wd.asserters.isDisplayed, 20000) .click() .sleep(3000) .waitForElementByCss('.page-header.ng-scope', wd.asserters.isDisplayed, 20000) .text() .should.eventually.include('Active Pickings'); } }; <file_sep>/tests/bootstrap.js /** * Bootstrap test settings */ var _, chai, chaiAsPromised, chance, wd, desired, alphaRedMart, seleniumServerUrl, browser, unix = Math.round(+new Date() / 1000).toString().substring(0, 9); require('colors'); _ = require('lodash'); chai = require('chai'); chaiAsPromised = require('chai-as-promised'); chance = new (require('chance'))(); wd = require('wd'); mongodb = require('mongodb'); // setup bdd chai.use(chaiAsPromised); chai.should(); chaiAsPromised.transferPromiseness = wd.transferPromiseness; // http configuration, not needed for simple runs wd.configureHttp({ timeout: 60000, retryDelay: 100, retries: 3 }); // building desired capability alphaRedMart = 'https://www.google.com/intl/en/mail/help/about.html'; seleniumServerUrl = 'http://selenium.alpha.redmart.com:4444/wd/hub'; seleniumServerUrl = process.env.LOCAL ? void 0 : seleniumServerUrl; desired = JSON.parse(process.env.DESIRED || '{browserName: "firefox"}'); desired.name = ''; desired.tags = ['']; if (process.env.CI) { desired['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; desired['build'] = process.env.TRAVIS_BUILD_NUMBER; } var exp = { // libs _: _, chai: chai, chaiAsPromised: chaiAsPromised, chance: chance, wd: wd, // vars desired: desired, alphaRedMart: alphaRedMart, existingUser: { email: '',//'<EMAIL>', password: '<PASSWORD>', firstName: 'John', lastName: 'Smith', contact: '91234567', userId: ''//117656 }, products: [ { id: 10868, name: 'Bake King Rose Essence', url: 'http://alpha.redmart.com/food-cupboard/home-baking/baking-needs' }, { id: 8125, name: '<NAME>', url: 'http://alpha.redmart.com/food-cupboard/condiments-dressings/chilli-sauce' } ], //generate random email address random_email: function () { console.log("generate random email address for registration"); var emailID = chance.first().toLowerCase().substring(0, 4) + "_" + chance.last().toLowerCase().substring(0, 4) + "_" + unix; if (exp.existingUser.email == '') { exp.existingUser.email = emailID + "@qatester.com"; } return emailID + "@qatester.com"; }, //generate random mobile number //random_number: function() { // console.log("generate random mobile number for registration"); // var number = 0; // for (i = 0; i < 8; i++) { // number += Math.floor(Math.random() * Math.pow(10, i)) // } // console.log(number) // if (exp.existingUser.contact == '') { // exp.existingUser.contact = "9" + number; // } // return "9" + number; //}, // helpers getBrowserFromWD: function () { console.log("in function: getBrowserFromWD"); browser = process.env.CI ? wd.promiseChainRemote('localhost', 4444) : wd.promiseChainRemote(seleniumServerUrl); // optional extra logging browser.on('status', function (info) { console.log(info.cyan); }); browser.on('command', function (eventType, command, response) { console.log(' > ' + eventType.cyan, command, (response || '').grey); }); browser.on('http', function (meth, path, data) { console.log(' > ' + meth.magenta, path, (data || '').grey); }); return browser; }, //insert QTY to db updateQtyForMarketPlace: function (itemId) { var MongoClient = mongodb.MongoClient; var mongoUrl = 'mongodb://mongo1.alpha.redmart.com:27017/redmart'; MongoClient.connect(mongoUrl, function (err, db) { console.log('---------------updateQtyForMarketPlace-----------------' + itemId); if (err) { console.log('Unable to connect to the mongoDB server. Error:', err); } else { console.log('Connection established to', mongoUrl); var collection = db.collection('inventory'); collection.update({id: itemId}, { $set: { "atp_lots.0.qty_in_stock": 50, "atp_lots.0.stock_status": 1, "atp_lots.0.qty_in_carts": 0, "atp_lots.0.from_date": new Date(new Date().setDate(new Date().getDate() + 2)), "atp_lots.0.to_date": new Date(new Date().setDate(new Date().getDate() + 365)) } }, function (err, numUpdated) { if (err) { console.log(err); } else if (numUpdated) { console.log('Updated Successfully: ' + numUpdated); } else { console.log('No document found with defined "find" criteria!'); } db.close(); }); } }); }, updateQty: function (itemId) { var MongoClient = mongodb.MongoClient; var mongoUrl = 'mongodb://mongo1.alpha.redmart.com:27017/redmart'; MongoClient.connect(mongoUrl, function (err, db) { console.log('---------------updateQty-----------------' + itemId); if (err) { console.log('Unable to connect to the mongoDB server. Error:', err); } else { console.log('Connection established to', mongoUrl); var collection = db.collection('inventory'); collection.update({id: itemId}, { $set: {qty_in_stock: 50, stock_status: 1, qty_in_carts: 0} }, function (err, numUpdated) { if (err) { console.log(err); } else if (numUpdated) { console.log('Updated Successfully: ' + numUpdated); } else { console.log('No document found with defined "find" criteria!'); } db.close(); }); } }); }, removeNumber: function () { var MongoClient = mongodb.MongoClient; var mongoUrl = 'mongodb://mongo1.alpha.redmart.com:27017/redmart'; MongoClient.connect(mongoUrl, function (err, db) { console.log('---------------removeNumber-----------------'); if (err) { console.log('Unable to connect to the mongoDB server. Error:', err); } else { console.log('Connection established to', mongoUrl); var collection = db.collection('unique_phone_numbers'); collection.update({"phone_number.local_number": "91234567"}, { $set: {member_ids: []} }, function (err, numUpdated) { if (err) { console.log(err); } else if (numUpdated) { console.log('Removed Successfully: ' + numUpdated); } else { console.log('No document found with defined "find" criteria!'); } db.close(); }); } }); }, removeAddress: function () { var MongoClient = mongodb.MongoClient; var mongoUrl = 'mongodb://mongo1.alpha.redmart.com:27017/redmart'; MongoClient.connect(mongoUrl, function (err, db) { console.log('---------------removeAddress-----------------'); if (err) { console.log('Unable to connect to the mongoDB server. Error:', err); } else { console.log('Connection established to', mongoUrl); var collection = db.collection('unique_address'); collection.remove({"zip": "688727"}, function (err, numUpdated) { if (err) { console.log(err); } else if (numUpdated) { console.log('Removed Successfully: ' + numUpdated); } else { console.log('No document found with defined "find" criteria!'); } db.close(); }); } }); }, emptyCart: function (userId) { if(userId == ''){ userId = exp.getUserId(exp.existingUser.email); } var MongoClient = mongodb.MongoClient; var mongoUrl = 'mongodb://mongo1.alpha.redmart.com:27017/redmart'; MongoClient.connect(mongoUrl, function (err, db) { console.log('---------------emptyCart-----------------' + userId); if (err) { console.log('Unable to connect to the mongoDB server. Error:', err); } else { console.log('Connection established to', mongoUrl); var collection = db.collection('cart'); collection.update({member_id: userId, state: {$gt: 1, $lt: 8}}, { $set: { items: [], "total.sub_total": 0.0000000000000000, "total.grand_total": 0.0000000000000000, "total.dollars_to_free_delivery": 49.0000000000000000, "total.delivery_fee_waived": 0, "total.shipping": 0.0000000000000000, "total.discount": 0.0000000000000000, "total.discount_code": "", "total.discount_type": 0, "total.discount_description": "", "total.incentive": 0.0000000000000000, "total.edo_incentive": 0.0000000000000000, "total.used_credit": 0.0000000000000000 } }, function (err, numUpdated) { if (err) { console.log(err); } else if (numUpdated) { console.log('Emptied Successfully: ' + numUpdated); } else { console.log('No document found with defined "find" criteria!'); } db.close(); }); } }); }, getUserId: function (email) { var MongoClient = mongodb.MongoClient; var mongoUrl = 'mongodb://mongo1.alpha.redmart.com:27017/redmart'; MongoClient.connect(mongoUrl, function (err, db) { console.log('---------------getUserId-----------------' + email); if (err) { console.log('Unable to connect to the mongoDB server. Error:', err); } else { console.log('Connection established to', mongoUrl); var collection = db.collection('members'); var data = collection.findOne({"email":email},{id:1}, function (err, item) { if (err) { console.log(err); } else if (item) { console.log('Retrieved Successfully: ' + item.id); //exp.existingUser.userId = item.id; return item.id; } else { console.log('No document found with defined "find" criteria!'); } db.close(); }); } }); } }; module.exports = exp; <file_sep>/tests/functional/PickDeviceSearch/existing.func.js "use strict"; var bootstrap = require('../../bootstrap'), alphaRedMart = bootstrap.alphaRedMart, helper = require('../../helpers/helper'), //mongodb = require('mongodb'), chance = bootstrap.chance, googleLogin = helper.googleLogin, openWHpage = helper.openWHpage, desired = bootstrap.desired, wd = bootstrap.wd; desired.name = 'Test with ' + desired.browserName; ///// Test suite ///// describe('Auth Existing', function () { this.timeout(200000); var browser, url = alphaRedMart, // special keys altKey = wd.SPECIAL_KEYS.Alt, nullKey = wd.SPECIAL_KEYS.NULL, returnKey = wd.SPECIAL_KEYS.Return, enterKey = wd.SPECIAL_KEYS.Enter; before(function () { browser = bootstrap.getBrowserFromWD(); return browser .init(desired) .setWindowSize(1440, 900) .get(url); }); after(function () { return browser.quit(); }); /////////////////////// ///// TESTS START ///// /////////////////////// describe('01 Sign in', function () { it('should sign in existing user', function () { return googleLogin.googleLogin(browser); }); }); describe('02 click the ware house', function () { it('should open the ware house page', function () { return openWHpage.openWHpage(browser); }); }); describe('03 click Pick Device Search', function () { it('should open Pick Device Search page', function () { return browser .waitForElementByCss('.inner-text-list.ng-scope li', wd.asserters.isDisplayed, 20000) .elementByXPath('//*[contains(text(), "Pick Device Search")]') .click() .sleep(3000) .waitForElementByCss('.page-header.ng-scope h1', wd.asserters.isDisplayed, 20000) .text() .should.eventually.include('Search Pick Device Usage History') }); }); describe('04 Search Device via IMEI', function() { it('should list device event records', function() { return browser .waitForElementByCss('.small.full.ng-pristine.ng-valid', wd.asserters.isDisplayed, 20000) .type('357294062423841') .waitForElementByCss('.col-md-2 button', wd.asserters.isDisplayed, 20000) .click() .sleep(3000) .elementByXPath('//*[contains(text(), "SG0638")]') .text() .should.eventually.include('SG0638') }) }) describe('05 click logout', function () { it('should logout the current user', function() { return googleLogin.googleLogout(browser); }) }); ///////////////////// ///// TESTS END ///// ///////////////////// }); <file_sep>/tests/desireds.js module.exports = { chrome: { browserName: 'chrome' }, explorer: { browserName: 'internet explorer' }, firefox: { browserName: 'firefox' }, safari: { browserName: 'safari', platform: 'OS X 10.10' } }; <file_sep>/Gruntfile.js var _ = require('lodash'), desireds = require('./tests/desireds'), gruntConfig = { test: 'tests', env: { // dynamically filled }, concurrent: { 'browsers-tests': [] // dynamically filled }, mochaTest: { options: { reporter: 'tap' }, functional: { src: ['<%= test %>/functional/order/normal.register.func.js','<%= test %>/functional/**/*.func.js'] }, test: { //src: ['<%= test %>/functional/Rejections/existing.func.js'] //src: ['<%= test %>/functional/PickRateSearch/existing.func.js'] //src: ['<%= test %>/functional/CheckInDashboard/existing.func.js'] //src: ['<%= test %>/functional/CheckInSearch/existing.func.js'] //src: ['<%= test %>/functional/PickDeviceSearch/existing.func.js'] //src: ['<%= test %>/functional/Pickers/existing.func.js'] //src: ['<%= test %>/functional/SearchRejections/existing.func.js'] //src: ['<%= test %>/functional/SkippedPicks/existing.func.js'] //src: ['<%= test %>/functional/WaveStatus/existing.func.js'] //PickDeviceSearch src: ['<%= test %>/functional/**/*.func.js'] }, firefox: { src: ['<%= test %>/firefox/order/normal.register.func.js', '<%= test %>/firefox/order/*.func.js'] } } }; // dynamically fill `env` and `concurrent:browsers-tests` // in `gruntConfig` _.each(desireds, function(desired, key) { gruntConfig.env[key] = { DESIRED: JSON.stringify(desired) }; gruntConfig.concurrent['browsers-tests'].push('test:' + key); }); // console.log(gruntConfig); module.exports = function(grunt) { // Project configuration. grunt.initConfig(gruntConfig); // load all grunt tasks matching the `grunt-*` pattern require('load-grunt-tasks')(grunt); // test tasks _.each(desireds, function(desired, key) { // all tests if(key = "chrome"){ grunt.registerTask('test:' + key, ['env:' + key, 'mochaTest:functional']); } if(key = "firefox"){ grunt.registerTask('test:' + key, ['env:' + key, 'mochaTest:firefox']); } // tests by functionality, add as needed grunt.registerTask('test:Rejections:' + key, ['env:' + key, 'mochaTest:authTests']); grunt.registerTask('test:Rejections:existing:' + key, ['env:' + key, 'mochaTest:existingAuthTests']); grunt.registerTask('test:Rejections:new:' + key, ['env:' + key, 'mochaTest:newAuthTests']); grunt.registerTask('test:order:' + key, ['env:' + key, 'mochaTest:orderTests']); grunt.registerTask('test:order:existing:' + key, ['env:' + key, 'mochaTest:existingOrderTests']); grunt.registerTask('test:order:new:' + key, ['env:' + key, 'mochaTest:newOrderTests']); }); grunt.registerTask('test', ['test:' + _.chain(desireds).keys().first()]); grunt.registerTask('test:parallel', ['concurrent:browsers-tests']); // default task grunt.registerTask('default', ['test']); }; <file_sep>/README.md #Warehouse Console QA Documentation *** *Author(s):* <NAME> *Version:* v1.0.0 *** Houses the functional tests for Golden Grocer. Runs functional tests against Alpha. ##Table of Contents 1. Testing Structure 2. Test Suites 3. JavaScript Files 4. Processes ##1. Testing Structure The testing structure for Golden Grocer is as follows: * tests/ * functional/ * CheckInDashboard/ * CheckInSearch/ * [... future test folders ...] * bootstrap.js * desireds.js * Gruntfile.js * README.md (This documentation) ##2. Test Suites Test suites are grouped by functionality, as can be seen by the folder structure. They are further broken down by commonalities of the test cases. This is so that test cases or suites can be skipped if needed. It also minimises test failures when running huge tests. Test framework used is Mocha, with Promise, and driven by WebDriver library, WD.js ####Creating new test suite file You can duplicate any of the existing test suite files as a starting point. The existing files are commented to guide you in where to begin. Limit the use of selector methods to `.elementByCss()` so that the test suite code base is easier to maintain. For a comprehensive list of available methods to use, please take a look at the WD.js [api doc](https://github.com/admc/wd/blob/master/doc/api.md). ##3. JavaScript Files ####CheckInDashboard/existing.func.js Authentication test suite for checkin dashboard. ####CheckInSearch/register.func.js Authentication test suite for checkin search ##4. Processes Any new test suites to be introduced to this repository has to go through the Github pull-request review process. Check the `REVIEWERS` file for repository members. 1. Create a new feature branch via Git Flow, or with the `feature/` prefix 2. Commit and test often 3. Create pull request to `develop` for code review 4. Stable test suites will be merged into `master`
d314fa37ee8a6780fbe7a09b34419fca0a762ac8
[ "JavaScript", "Markdown" ]
7
JavaScript
wjw0970/ConsoleCode
03d56adb12c9fb7a12f684f1caa9486eb952b321
6d1e8b054f9b61d1c60bd67888e4b905cd9db41f
refs/heads/master
<repo_name>MrHidee/Pwjs<file_sep>/problem005.js function strangeSum(a, b) { if (!((typeof a === 'number' ) && (a/parseInt(a)===1)&&(typeof b === 'number' ) && (b/parseInt(b)===1))) { return null; } if (a===b) { return 3*(a+b); } else { return a+b; } }<file_sep>/problem001.js function triangleArea(a, b, c) { if (a+b < c || a+c < b || b+c < a){ return -1; } var ret = Math.round(Math.sqrt(((a+b+c)/2)*(((a+b+c)/2)-a)*(((a+b+c)/2)-b)*(((a+b+c)/2)-c)) * 100) / 100; if ( ret > 0 ) { return ret; } else { return -1; } }
b98021624eb1fde310f2e8b5ffd64bbbcd853647
[ "JavaScript" ]
2
JavaScript
MrHidee/Pwjs
f1ecb3e43aaad936bc6fa6997393cbafbca72f40
aad98bea4726aea7bb2b1bc388e87e6c7a8c5912
refs/heads/master
<repo_name>Zaman3027/Stepuserdetail<file_sep>/src/components/UserForm.js import React, { Component } from 'react' import FormUserDetail from './FormUserDetail' import FormPersonalDetail from './FormPersonalDetail' import Confirm from './Confirm' export class UserForm extends Component { state={ step:1, firstName:'', lastname:'', email:'', occupation:'', city:'', bio:'', } //proceed to next step nextStep = ()=>{ const {step} = this.state; this.setState({ step:step+1, }) } //prev step prevStep = () => { const { step } = this.state; this.setState({ step: step - 1 }); }; //handel Field change handleChange = input => e =>{ this.setState({[input]:e.target.value}) } render() { const {step} = this.state; const {firstName,lastname,email,occupation,city,bio} = this.state; const values = {firstName,lastname,email,occupation,city,bio} switch(step){ case 1: return( <FormUserDetail nextStep = {this.nextStep} handleChange = {this.handleChange} values = {values} /> ) case 2: return ( <FormPersonalDetail nextStep = {this.nextStep} handleChange = {this.handleChange} values = {values} prevStep = {this.prevStep} /> ) case 3: return ( <Confirm values = {values} nextStep = {this.nextStep} prevStep = {this.prevStep} /> ) case 4: return <h1>Sucess Done</h1> default: return(<div/>) } } } export default UserForm
404703f1eb0e72239abe6dbf8c71f734ca697ca8
[ "JavaScript" ]
1
JavaScript
Zaman3027/Stepuserdetail
b497a9bb4e1a0aabff933fea97c3643ad4563aad
1cc8f3856a36857fd82f68d4dfcd896fd77268cd
refs/heads/master
<repo_name>Duckson29/MoviaAdminSite<file_sep>/src/app/generated/MoviaMobilEndPiontGrpc_pb_service.d.ts // package: BusGrpcProto // file: src/app/protos/MoviaMobilEndPiontGrpc.proto import * as src_app_protos_MoviaMobilEndPiontGrpc_pb from "../../../src/app/generated/MoviaMobilEndPiontGrpc_pb"; import {grpc} from "@improbable-eng/grpc-web"; type BusGrpcServiceCreateBus = { readonly methodName: string; readonly service: typeof BusGrpcService; readonly requestStream: false; readonly responseStream: false; readonly requestType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus; readonly responseType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged; }; type BusGrpcServiceGetBusInfo = { readonly methodName: string; readonly service: typeof BusGrpcService; readonly requestStream: false; readonly responseStream: false; readonly requestType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest; readonly responseType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus; }; type BusGrpcServiceUpdateBusInfo = { readonly methodName: string; readonly service: typeof BusGrpcService; readonly requestStream: false; readonly responseStream: false; readonly requestType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus; readonly responseType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged; }; type BusGrpcServiceDeleteBus = { readonly methodName: string; readonly service: typeof BusGrpcService; readonly requestStream: false; readonly responseStream: false; readonly requestType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus; readonly responseType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged; }; type BusGrpcServiceGetAllBuss = { readonly methodName: string; readonly service: typeof BusGrpcService; readonly requestStream: false; readonly responseStream: false; readonly requestType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest; readonly responseType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.BusList; }; type BusGrpcServiceUpdaeBusPoscition = { readonly methodName: string; readonly service: typeof BusGrpcService; readonly requestStream: false; readonly responseStream: false; readonly requestType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus; readonly responseType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged; }; type BusGrpcServiceUpdatePassagseCount = { readonly methodName: string; readonly service: typeof BusGrpcService; readonly requestStream: false; readonly responseStream: false; readonly requestType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus; readonly responseType: typeof src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged; }; export class BusGrpcService { static readonly serviceName: string; static readonly CreateBus: BusGrpcServiceCreateBus; static readonly GetBusInfo: BusGrpcServiceGetBusInfo; static readonly UpdateBusInfo: BusGrpcServiceUpdateBusInfo; static readonly DeleteBus: BusGrpcServiceDeleteBus; static readonly GetAllBuss: BusGrpcServiceGetAllBuss; static readonly UpdaeBusPoscition: BusGrpcServiceUpdaeBusPoscition; static readonly UpdatePassagseCount: BusGrpcServiceUpdatePassagseCount; } export type ServiceError = { message: string, code: number; metadata: grpc.Metadata } export type Status = { details: string, code: number; metadata: grpc.Metadata } interface UnaryResponse { cancel(): void; } interface ResponseStream<T> { cancel(): void; on(type: 'data', handler: (message: T) => void): ResponseStream<T>; on(type: 'end', handler: (status?: Status) => void): ResponseStream<T>; on(type: 'status', handler: (status: Status) => void): ResponseStream<T>; } interface RequestStream<T> { write(message: T): RequestStream<T>; end(): void; cancel(): void; on(type: 'end', handler: (status?: Status) => void): RequestStream<T>; on(type: 'status', handler: (status: Status) => void): RequestStream<T>; } interface BidirectionalStream<ReqT, ResT> { write(message: ReqT): BidirectionalStream<ReqT, ResT>; end(): void; cancel(): void; on(type: 'data', handler: (message: ResT) => void): BidirectionalStream<ReqT, ResT>; on(type: 'end', handler: (status?: Status) => void): BidirectionalStream<ReqT, ResT>; on(type: 'status', handler: (status: Status) => void): BidirectionalStream<ReqT, ResT>; } export class BusGrpcServiceClient { readonly serviceHost: string; constructor(serviceHost: string, options?: grpc.RpcOptions); createBus( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, metadata: grpc.Metadata, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; createBus( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; getBusInfo( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest, metadata: grpc.Metadata, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus|null) => void ): UnaryResponse; getBusInfo( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus|null) => void ): UnaryResponse; updateBusInfo( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, metadata: grpc.Metadata, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; updateBusInfo( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; deleteBus( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, metadata: grpc.Metadata, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; deleteBus( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; getAllBuss( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest, metadata: grpc.Metadata, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusList|null) => void ): UnaryResponse; getAllBuss( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusList|null) => void ): UnaryResponse; updaeBusPoscition( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, metadata: grpc.Metadata, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; updaeBusPoscition( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; updatePassagseCount( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, metadata: grpc.Metadata, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; updatePassagseCount( requestMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, callback: (error: ServiceError|null, responseMessage: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged|null) => void ): UnaryResponse; } <file_sep>/src/app/generated/MoviaMobilEndPiontGrpc_pb_service.js // package: BusGrpcProto // file: src/app/protos/MoviaMobilEndPiontGrpc.proto var src_app_protos_MoviaMobilEndPiontGrpc_pb = require("../../../src/app/generated/MoviaMobilEndPiontGrpc_pb"); var grpc = require("@improbable-eng/grpc-web").grpc; var BusGrpcService = (function () { function BusGrpcService() {} BusGrpcService.serviceName = "BusGrpcProto.BusGrpcService"; return BusGrpcService; }()); BusGrpcService.CreateBus = { methodName: "CreateBus", service: BusGrpcService, requestStream: false, responseStream: false, requestType: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, responseType: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged }; BusGrpcService.GetBusInfo = { methodName: "GetBusInfo", service: BusGrpcService, requestStream: false, responseStream: false, requestType: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest, responseType: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus }; BusGrpcService.UpdateBusInfo = { methodName: "UpdateBusInfo", service: BusGrpcService, requestStream: false, responseStream: false, requestType: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, responseType: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged }; BusGrpcService.DeleteBus = { methodName: "DeleteBus", service: BusGrpcService, requestStream: false, responseStream: false, requestType: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, responseType: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged }; BusGrpcService.GetAllBuss = { methodName: "GetAllBuss", service: BusGrpcService, requestStream: false, responseStream: false, requestType: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusRequest, responseType: src_app_protos_MoviaMobilEndPiontGrpc_pb.BusList }; BusGrpcService.UpdaeBusPoscition = { methodName: "UpdaeBusPoscition", service: BusGrpcService, requestStream: false, responseStream: false, requestType: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, responseType: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged }; BusGrpcService.UpdatePassagseCount = { methodName: "UpdatePassagseCount", service: BusGrpcService, requestStream: false, responseStream: false, requestType: src_app_protos_MoviaMobilEndPiontGrpc_pb.Bus, responseType: src_app_protos_MoviaMobilEndPiontGrpc_pb.DatabaseChaged }; exports.BusGrpcService = BusGrpcService; function BusGrpcServiceClient(serviceHost, options) { this.serviceHost = serviceHost; this.options = options || {}; } BusGrpcServiceClient.prototype.createBus = function createBus(requestMessage, metadata, callback) { if (arguments.length === 2) { callback = arguments[1]; } var client = grpc.unary(BusGrpcService.CreateBus, { request: requestMessage, host: this.serviceHost, metadata: metadata, transport: this.options.transport, debug: this.options.debug, onEnd: function (response) { if (callback) { if (response.status !== grpc.Code.OK) { var err = new Error(response.statusMessage); err.code = response.status; err.metadata = response.trailers; callback(err, null); } else { callback(null, response.message); } } } }); return { cancel: function () { callback = null; client.close(); } }; }; BusGrpcServiceClient.prototype.getBusInfo = function getBusInfo(requestMessage, metadata, callback) { if (arguments.length === 2) { callback = arguments[1]; } var client = grpc.unary(BusGrpcService.GetBusInfo, { request: requestMessage, host: this.serviceHost, metadata: metadata, transport: this.options.transport, debug: this.options.debug, onEnd: function (response) { if (callback) { if (response.status !== grpc.Code.OK) { var err = new Error(response.statusMessage); err.code = response.status; err.metadata = response.trailers; callback(err, null); } else { callback(null, response.message); } } } }); return { cancel: function () { callback = null; client.close(); } }; }; BusGrpcServiceClient.prototype.updateBusInfo = function updateBusInfo(requestMessage, metadata, callback) { if (arguments.length === 2) { callback = arguments[1]; } var client = grpc.unary(BusGrpcService.UpdateBusInfo, { request: requestMessage, host: this.serviceHost, metadata: metadata, transport: this.options.transport, debug: this.options.debug, onEnd: function (response) { if (callback) { if (response.status !== grpc.Code.OK) { var err = new Error(response.statusMessage); err.code = response.status; err.metadata = response.trailers; callback(err, null); } else { callback(null, response.message); } } } }); return { cancel: function () { callback = null; client.close(); } }; }; BusGrpcServiceClient.prototype.deleteBus = function deleteBus(requestMessage, metadata, callback) { if (arguments.length === 2) { callback = arguments[1]; } var client = grpc.unary(BusGrpcService.DeleteBus, { request: requestMessage, host: this.serviceHost, metadata: metadata, transport: this.options.transport, debug: this.options.debug, onEnd: function (response) { if (callback) { if (response.status !== grpc.Code.OK) { var err = new Error(response.statusMessage); err.code = response.status; err.metadata = response.trailers; callback(err, null); } else { callback(null, response.message); } } } }); return { cancel: function () { callback = null; client.close(); } }; }; BusGrpcServiceClient.prototype.getAllBuss = function getAllBuss(requestMessage, metadata, callback) { if (arguments.length === 2) { callback = arguments[1]; } var client = grpc.unary(BusGrpcService.GetAllBuss, { request: requestMessage, host: this.serviceHost, metadata: metadata, transport: this.options.transport, debug: this.options.debug, onEnd: function (response) { if (callback) { if (response.status !== grpc.Code.OK) { var err = new Error(response.statusMessage); err.code = response.status; err.metadata = response.trailers; callback(err, null); } else { callback(null, response.message); } } } }); return { cancel: function () { callback = null; client.close(); } }; }; BusGrpcServiceClient.prototype.updaeBusPoscition = function updaeBusPoscition(requestMessage, metadata, callback) { if (arguments.length === 2) { callback = arguments[1]; } var client = grpc.unary(BusGrpcService.UpdaeBusPoscition, { request: requestMessage, host: this.serviceHost, metadata: metadata, transport: this.options.transport, debug: this.options.debug, onEnd: function (response) { if (callback) { if (response.status !== grpc.Code.OK) { var err = new Error(response.statusMessage); err.code = response.status; err.metadata = response.trailers; callback(err, null); } else { callback(null, response.message); } } } }); return { cancel: function () { callback = null; client.close(); } }; }; BusGrpcServiceClient.prototype.updatePassagseCount = function updatePassagseCount(requestMessage, metadata, callback) { if (arguments.length === 2) { callback = arguments[1]; } var client = grpc.unary(BusGrpcService.UpdatePassagseCount, { request: requestMessage, host: this.serviceHost, metadata: metadata, transport: this.options.transport, debug: this.options.debug, onEnd: function (response) { if (callback) { if (response.status !== grpc.Code.OK) { var err = new Error(response.statusMessage); err.code = response.status; err.metadata = response.trailers; callback(err, null); } else { callback(null, response.message); } } } }); return { cancel: function () { callback = null; client.close(); } }; }; exports.BusGrpcServiceClient = BusGrpcServiceClient; <file_sep>/src/app/generated/MoviaMobilEndPiontGrpc_pb.d.ts // package: BusGrpcProto // file: src/app/protos/MoviaMobilEndPiontGrpc.proto import * as jspb from "google-protobuf"; export class Bus extends jspb.Message { getId(): number; setId(value: number): void; getName(): string; setName(value: string): void; getMake(): string; setMake(value: string): void; getDriver(): string; setDriver(value: string): void; getRouteid(): number; setRouteid(value: number): void; getTotaltbuscap(): number; setTotaltbuscap(value: number): void; getCurrentpaxcont(): number; setCurrentpaxcont(value: number): void; getLat(): string; setLat(value: string): void; getLon(): string; setLon(value: string): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): Bus.AsObject; static toObject(includeInstance: boolean, msg: Bus): Bus.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: Bus, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): Bus; static deserializeBinaryFromReader(message: Bus, reader: jspb.BinaryReader): Bus; } export namespace Bus { export type AsObject = { id: number, name: string, make: string, driver: string, routeid: number, totaltbuscap: number, currentpaxcont: number, lat: string, lon: string, } } export class BusList extends jspb.Message { clearBuslistList(): void; getBuslistList(): Array<Bus>; setBuslistList(value: Array<Bus>): void; addBuslist(value?: Bus, index?: number): Bus; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): BusList.AsObject; static toObject(includeInstance: boolean, msg: BusList): BusList.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: BusList, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): BusList; static deserializeBinaryFromReader(message: BusList, reader: jspb.BinaryReader): BusList; } export namespace BusList { export type AsObject = { buslistList: Array<Bus.AsObject>, } } export class DatabaseChaged extends jspb.Message { getHaschanbged(): boolean; setHaschanbged(value: boolean): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): DatabaseChaged.AsObject; static toObject(includeInstance: boolean, msg: DatabaseChaged): DatabaseChaged.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: DatabaseChaged, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): DatabaseChaged; static deserializeBinaryFromReader(message: DatabaseChaged, reader: jspb.BinaryReader): DatabaseChaged; } export namespace DatabaseChaged { export type AsObject = { haschanbged: boolean, } } export class BusRequest extends jspb.Message { getId(): string; setId(value: string): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): BusRequest.AsObject; static toObject(includeInstance: boolean, msg: BusRequest): BusRequest.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: BusRequest, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): BusRequest; static deserializeBinaryFromReader(message: BusRequest, reader: jspb.BinaryReader): BusRequest; } export namespace BusRequest { export type AsObject = { id: string, } } <file_sep>/src/app/archive/archive.component.ts import { animate, state, style, transition, trigger } from '@angular/animations'; import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild, ViewChildren } from '@angular/core'; import { MatPaginator, PageEvent } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTable, MatTableDataSource } from '@angular/material/table'; import { MoviaServiceService } from '../services/movia-service.service'; import { Bus, BusRequest } from '../generated/MoviaMobilEndPiontGrpc_pb'; import { isTemplateExpression } from 'typescript'; /** * @title Table with expandable rows */ @Component({ selector: 'app-archive', templateUrl: './archive.component.html', styleUrls: ['./archive.component.css'], animations: [ trigger('detailExpand', [ state('collapsed, void', style({ height: '0px', minHeight: '0' })), state('expanded', style({ height: '*' })), transition('expanded <=> collapsed, void => expanded', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')), ]), ], }) export class ArchiveComponent implements OnInit, OnDestroy, AfterViewInit { length = 100; pageSize = 10; pageSizeOptions: number[] = [5, 10, 25, 100]; pageEvent: PageEvent = new PageEvent(); /*--------------ViewChilds--------------*/ @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild("mattable", { read: MatSort }) sort!: MatSort; @ViewChild("tableDone", { read: MatSort }) sortDone!: MatSort; @ViewChild("tableDone") tabledone!: MatTable<Bus>; @ViewChild("paginatorDone") paginatorDone!: MatPaginator; /*--------------SimpleDataObjects--------------*/ public dataSource: Array<Bus> = new Array<Bus>(); /*--------------DataTable Values--------------*/ displayedColumns = ["id", "name", "make", "driver", "routeid", "totaltbuscap", "currentpaxcont", "lat", "lon"]; matdatasource = new MatTableDataSource<Bus>(this.dataSource); dataSourceBuss: Array<Bus> = new Array<Bus>(); matdatasourceBuss = new MatTableDataSource<Bus>(this.dataSourceBuss); expandingelement: Bus = new Bus(); isExpansionDetailRow = (id: number, row: any | Bus) => this.isExpansionDetailRows(id, row); constructor(private dataserve: MoviaServiceService) { this.dataserve.GetBusInfo("", new BusRequest()); this.dataserve.BusInfomation$.subscribe(x => { this.matdatasource.data = []; this.matdatasourceBuss.data = []; if (x.getName().length !< 0) { this.matdatasourceBuss.data.push((x as Bus)) this.matdatasourceBuss._updateChangeSubscription(); } }); } ngAfterViewInit(): void { this.matdatasource.paginator = this.paginator; this.matdatasource.sort = this.sort; this.onsortChange(); this.matdatasourceBuss.sort = this.sortDone; this.matdatasourceBuss.paginator = this.paginatorDone; this.onSortDoneChange(); } ngOnDestroy(): void { this.dataserve.BusInfomation$.unsubscribe(); } ngOnInit() { } /** * This apply a filter to the matdatatable. */ applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.matdatasource.filter = filterValue.trim().toLowerCase(); } applyFilterDone(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.matdatasourceBuss.filter = filterValue.trim().toLowerCase(); } /** * This sets up the sorting logic for the table. * displayedColumns = ["id", "name", "make", "driver", "routeid", "totaltbuscap", "currentpaxcont", "lat", "lon"]; */ onsortChange() { this.matdatasource.sortingDataAccessor = (item, property) => { let switchValue = "" switch (property) { case 'id': switchValue = item.getName(); break; case 'name': switchValue = item.getId().toString(); break; case 'make': switchValue = item.getMake(); break; case 'driver': switchValue = item.getDriver(); break; } return switchValue; }; } onSortDoneChange() { this.matdatasourceBuss.sortingDataAccessor = (item, property) => { let switchValue = "" switch (property) { case 'id': switchValue = item.getName(); break; case 'name': switchValue = item.getId().toString(); break; case 'make': switchValue = item.getMake(); break; case 'driver': switchValue = item.getDriver(); break; } return switchValue; }; } /** * This is a control cheack to control wheter or not any giving row at any giving time can/allowed to be render. * @param i the row id number * @param row the row * @returns boolean indication wheter or not the row can be expandede/rednder. */ isExpansionDetailRows(i: number, row: Bus): boolean { // console.log("Cheaking if row can be expanded"); return true; } } <file_sep>/src/app/services/movia-service.service.ts import { Injectable } from '@angular/core'; import { grpc } from '@improbable-eng/grpc-web'; import { Bus, BusRequest } from '../generated/MoviaMobilEndPiontGrpc_pb'; import { BusGrpcServiceClient, BusGrpcService } from '../generated/MoviaMobilEndPiontGrpc_pb_service'; import { BehaviorSubject, Observable, of, Subject, zip } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MoviaServiceService { hostAddress = "0.0.0.0"; BusInfomation$: BehaviorSubject<Bus> = new BehaviorSubject<Bus>(new Bus()); constructor() { } GetBusInfo(busId: string, busToGet: BusRequest) { grpc.invoke(BusGrpcService.GetBusInfo, { request: busToGet, host: this.hostAddress, onMessage: (Message: Bus) => { console.log('entris change: ' + Message.getName()); this.BusInfomation$.next(Message); }, onEnd: (res) => { console.log() }, }); } }
7ce1be85a43225995154f31297441463ca7c5ded
[ "JavaScript", "TypeScript" ]
5
TypeScript
Duckson29/MoviaAdminSite
cd08d5a818adfec1cc77300ae0af036333fc9e7a
0d59217d6bd25a0dc0c7740bfdeeb0607d04d557
refs/heads/main
<repo_name>Asiberus/Freelance-Template<file_sep>/src/js/tools/Utils.js const get = url => { return new Promise((resolve, reject) => { const options = { method: 'GET', headers: new Headers([ ['Content-Type', 'application/json; charset=UTF-8'] ]) }; fetch(url, options) .then(response => response.text()) .then(resolve) .catch(reject); }); }; const appendZeroPrefixToDate = value => { if (value.toString().length < 2) { value = `0${value}`; } return value; } export { get, appendZeroPrefixToDate }; <file_sep>/src/js/tools/Notification.js import '../../scss/tools/notification.scss'; class Notification { /** @summary Create an instance of a notification handler * @author <NAME> * @since June 2018 * @description Build the notification singleton handler that will handle all incoming Notifications * @param {object} [options] - The notification handler global options * @param {string} [options.position=top-right] - <i>top-left; top-right; bottom-left; bottom-right;</i> * @param {string} [options.thickBorder=top] - <i>top; bottom; left; right; none;</i> * @param {number} [options.duration=3000] - Notification life cycle duration (in ms) in range N* * @param {number} [options.transition=100] - Notification fade animation transition timing (in ms) in range N* * @param {number} [options.maxActive=5] - Maximum of simultaneously opened notification in range N* */ constructor(options) { if (!!Notification.instance) { // GoF Singleton return Notification.instance; } Notification.instance = this; // Attributes declaration /** @private * @member {boolean} - Dismiss all operation in progress flag */ this._dismissAllLock = false; /** @private * @member {object} - Notification handler container node */ this._dom = {}; /** @private * @member {object} - Active notifications object : retrieve a notification using its ID (this._active[ID]) */ this._active = {}; /** @private * @member {object} - Queue notifications when max active has been reached */ this._queue = {}; /** @private * @member {object} - Notification handler default values */ this._default = {}; /** @private * @member {string} - The handler position in viewport - <i>top-left; top-right; bottom-left; bottom-right;</i> */ this._position = ''; /** @private * @member {string} - The thick border position in the Notification - <i>top; bottom; left; right; none;</i> */ this._thickBorder = ''; /** @private * @member {number} - The Notification on screen duration in ms */ this._duration = 0; /** @private * @member {number} - The fade transition time in ms */ this._transition = 0; /** @private * @member {number} - The maximum amount of active Notification */ this._maxActive = 0; /** @public * @member {number} - The component version */ this.version = '1.1.0'; // Build singleton and attach this._init(options); // Return singleton return this; } /** @method * @name destroy * @public * @memberof Notification * @author <NAME> * @since March 2019 * @description Destroy the singleton and detach it from the DOM */ destroy() { document.body.removeChild(this._dom); // Delete object attributes Object.keys(this).forEach(key => { delete this[key]; }); // Clear singleton instance Notification.instance = null; } /* --------------------------------------------------------------------------------------------------------------- */ /* ------------------------------ NOTIFICATION JS HANDLER CONSTRUCTION METHODS -------------------------------- */ /* */ /* The following methods only concerns the singleton creation. It handle all arguments and will fallback on */ /* default values if any argument doesn't meet its expected value or type. */ /* --------------------------------------------------------------------------------------------------------------- */ /** @method * @name _init * @private * @memberof Notification * @author <NAME> * @since July 2018 * @description Create the handler DOM element, set default values, test given options and properly add CSS class to the handler * @param {object} [options] - The notification handler global options * @param {string} [options.position=top-right] - <i>top-left; top-right; bottom-left; bottom-right;</i> * @param {string} [options.thickBorder=top] - <i>top; bottom; left; right; none;</i> * @param {number} [options.duration=3000] - Notification life cycle duration (in ms) in range N* * @param {number} [options.transition=100] - Notification fade animation transition timing (in ms) in range N* * @param {number} [options.maxActive=5] - Maximum of simultaneously opened notification in range N* */ _init(options) { // Declare options as object if empty if (options === undefined) { options = {}; } // Create notification main container this._dom = document.createElement('DIV'); // Notification handler DOM container this._dom.classList.add('notification-container'); // Set proper CSS class // Notification.js default values this._default = { handler: { position: 'top-right', thickBorder: 'top', duration: 5000, transition: 200, maxActive: 10 }, notification: { type: 'info', message: '', title: '', iconless: false, closable: true, sticky: false, renderTo: this._dom, CBtitle: '', callback: null, isDimmed: false }, color: { success: 'rgb(76, 175, 80)', info: 'rgb(3, 169, 244)', warning: 'rgb(255, 152, 0)', error: 'rgb(244, 67, 54)' }, svgPath: { success: 'M12.5 0C5.602 0 0 5.602 0 12.5S5.602 25 12.5 25 25 19.398 25 12.5 19.398 0 12.5 0zm-2.3 18.898l-5.5-5.5 1.8-1.796 3.7 3.699L18.5 7l1.8 1.8zm0 0', info: 'M12.504.035a12.468 12.468 0 100 24.937 12.468 12.468 0 000-24.937zM15.1 19.359c-.643.25-1.153.445-1.537.576-.384.134-.825.199-1.333.199-.775 0-1.381-.192-1.813-.57a1.832 1.832 0 01-.642-1.442c0-.227.015-.459.047-.693.03-.24.083-.504.154-.806l.802-2.835c.069-.272.132-.527.182-.77.048-.244.069-.467.069-.668 0-.36-.075-.615-.223-.756-.153-.144-.437-.213-.857-.213-.207 0-.422.036-.639.095a9.914 9.914 0 00-.56.184l.213-.874a19.777 19.777 0 011.51-.549 4.48 4.48 0 011.361-.23c.77 0 1.368.19 1.784.56a1.857 1.857 0 01.626 1.452c0 .122-.012.341-.04.652a4.44 4.44 0 01-.162.856l-.798 2.831a8.133 8.133 0 00-.176.775c-.05.288-.075.51-.075.66 0 .374.082.633.251.771.165.134.458.202.875.202.192 0 .412-.037.66-.1.243-.073.42-.127.531-.18zm-.144-11.483a1.901 1.901 0 01-1.343.518 1.93 1.93 0 01-1.352-.518 1.65 1.65 0 01-.562-1.258 1.688 1.688 0 01.562-1.266 1.914 1.914 0 011.35-.522c.524 0 .975.173 1.345.523a1.673 1.673 0 01.56 1.266 1.65 1.65 0 01-.56 1.257z', warning: 'M24.585 21.17L13.774 3.24a1.51 1.51 0 00-2.586 0L.376 21.17a1.51 1.51 0 001.293 2.29h21.623a1.51 1.51 0 001.292-2.29zM12.49 8.714c.621 0 1.146.35 1.146.97 0 1.895-.223 4.618-.223 6.513 0 .494-.541.7-.923.7-.51 0-.94-.208-.94-.701 0-1.894-.223-4.617-.223-6.511 0-.62.51-.971 1.163-.971zm.015 11.734a1.225 1.225 0 01-1.225-1.226c0-.669.525-1.227 1.225-1.227.652 0 1.21.558 1.21 1.227 0 .652-.557 1.225-1.21 1.225z', error: 'M12.469.027c-3.332 0-6.465 1.301-8.824 3.653-4.86 4.86-4.86 12.777 0 17.636a12.392 12.392 0 008.824 3.653c3.336 0 6.465-1.301 8.824-3.653 4.863-4.859 4.863-12.777 0-17.636A12.417 12.417 0 0012.469.027zm5.61 18.086a1.137 1.137 0 01-.802.332c-.285 0-.582-.113-.8-.332l-4.008-4.008-4.008 4.008a1.137 1.137 0 01-.8.332c-.286 0-.583-.113-.802-.332a1.132 1.132 0 010-1.605l4.008-4.004L6.86 8.496a1.132 1.132 0 010-1.605 1.127 1.127 0 011.602 0l4.008 4.007 4.008-4.007a1.127 1.127 0 011.601 0c.45.449.45 1.164 0 1.605l-4.004 4.008 4.004 4.004c.45.449.45 1.164 0 1.605zm0 0' } }; // Build singleton from options and sanitize them this._setOptionsDefault(options); this._position = options.position; this._thickBorder = options.thickBorder; this._duration = options.duration; this._transition = options.transition; this._maxActive = options.maxActive; this._setAttributesDefault(); // Add position CSS class only after this._position is sure to be a valid value this._dom.classList.add(this._position); this._attach(); } /** @method * @name _setOptionsDefault * @private * @memberof Notification * @summary Set singleton options * @author <NAME> * @since March 2019 * @description Build the notification singleton according to the user options * @param {object} options - The singleton options to set */ _setOptionsDefault(options) { if (options.position === undefined) { options.position = this._default.handler.position; } if (options.thickBorder === undefined) { options.thickBorder = this._default.handler.thickBorder; } if (options.duration === undefined) { options.duration = this._default.handler.duration; } if (options.transition === undefined) { options.transition = this._default.handler.transition; } if (options.maxActive === undefined) { options.maxActive = this._default.handler.maxActive; } } /** @method * @name _setAttributesDefault * @private * @memberof Notification * @summary Check the notification singleton options validity * @author <NAME> * @since March 2019 * @description Fallback on default attributes value if the notification singleton options are invalid */ _setAttributesDefault() { if (this._position !== 'top-left' && /* Illegal value for position */ this._position !== 'top-right' && this._position !== 'bottom-left' && this._position !== 'bottom-right') { this._position = this._default.handler.position; // Default value } if (this._thickBorder !== 'top' && /* Illegal value for thick border */ this._thickBorder !== 'bottom' && this._thickBorder !== 'left' && this._thickBorder !== 'right' && this._thickBorder !== 'none') { this._thickBorder = this._default.handler.thickBorder; // Default value } if (typeof this._duration !== 'number' || this._duration <= 0) { // Illegal value for duration this._duration = this._default.handler.duration; // Default value } if (typeof this._transition !== 'number' || this._duration < (this._transition * 2) || this._transition <= 0) { // Transition over (duration / 2) this._transition = this._default.handler.transition; // Default value for _maxActive } if (typeof this._maxActive !== 'number' || this._maxActive <= 0) { // Illegal value for maxActive this._maxActive = this._default.handler.maxActive; // Default value for _maxActive } } /** @method * @name _attach * @private * @memberof Notification * @author <NAME> * @since July 2018 * @description Attach the notification handler to the dom using a fragment */ _attach() { const fragment = document.createDocumentFragment(); fragment.appendChild(this._dom); document.body.appendChild(fragment); } /* --------------------------------------------------------------------------------------------------------------- */ /* ------------------------------------- NOTIFICATION SPECIFIC METHODS ---------------------------------------- */ /* */ /* The following methods implements notification features. It handle its events, lifecycle depending on its */ /* parameters, its DOM structure, and its animations. The Notification singleton will handle the notification */ /* stacking the in user interface. */ /* --------------------------------------------------------------------------------------------------------------- */ /** @method * @name _events * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Handle mouse events for the given notification * @param {{id: number}} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {object} notification.dom - Notifiction DOM element * @param {number} notification.requestCount - Notification inner call counter * @param {number} notification.timeoutID - Notification own setTimeout ID * @param {boolean} notification.sticky - Notification sticky behvaior * @param {boolean} notification.closable - Make notification closable flag */ _events(notification) { let closeFired = false; // Close fired flag // Inner callback functions const _unDim = () => { // Undim notification if (notification.isDimmed) { this._unDim(notification); } }; const _close = () => { // Close notification if (this._active[notification.id] === undefined) { return; } // Update counter DOM element if (notification.requestCount > 1) { this._decrementRequestCounter(notification, true); } // Remove notification element from the DOM tree else if (!closeFired) { closeFired = true; window.clearTimeout(notification.timeoutID); // Clear life cycle timeout notification.dom.close.removeEventListener('click', _close); // Avoid error when spam clicking the close button this._close(notification); } }; const _resetTimeout = () => { // Reset life cycle timeout if (this._active[notification.id] === undefined) { return; } if (!closeFired && !notification.isDimmed) { // Only reset timeout if no close event has been fired this._resetTimeout(notification); } }; // Mouse event listeners if (notification.sticky) { notification.dom.addEventListener('mouseenter', _unDim.bind(this)); notification.dom.addEventListener('mouseout', _unDim.bind(this)); } if (notification.closable) { notification.dom.addEventListener('click', _close.bind(this)); notification.dom.close.addEventListener('click', _close.bind(this)); } notification.dom.addEventListener('mouseover', _resetTimeout.bind(this)); } /** @method * @name _buildUI * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Builds the DOM element that contains and that adapts to all given options * @param {object} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {string} notification.type - Error, Warning, Info, Success * @param {string} notification.title - Notification title * @param {string} notification.message - Notification message * @param {boolean} notification.iconless - No icon flag * @param {string} notification.thickBorder - Notification border side (override handler side value) * @param {boolean} notification.closable - Make notification closable flag * @param {boolean} notification.sticky - Make notification sticky flag * @param {string} notification.CBtitle - Notification callback title * @param {function} notification.callback - Notification callback button * @returns {object} Enhanced and ready notification object */ _buildUI(notification) { notification.requestCount = 1; notification.totalRequestCount = 1; this._buildUIDom(notification); this._buildNotificationType(notification); if (notification.iconless) { notification.dom.message.classList.add('iconless-width'); } notification.dom.text.appendChild(notification.dom.maintitle); notification.dom.text.appendChild(notification.dom.message); // Add callback button and listener if needed if (notification.callback) { const callbackButton = document.createElement('BUTTON'); callbackButton.innerHTML = notification.CBtitle; notification.dom.text.appendChild(callbackButton); callbackButton.addEventListener('click', () => { this._close(notification); notification.callback(); }); } // Fill notification DOM element if (!notification.iconless) { notification.dom.appendChild(notification.dom.icon); } notification.dom.appendChild(notification.dom.text); // Append close button if needed if (notification.closable) { notification.dom.appendChild(notification.dom.close); } // Return final notification return notification; } /** @method * @name _buildUIDom * @private * @memberof Notification * @summary Create the Notification DOM tree * @author <NAME> * @since March 2019 * @description Build all the Notification internal structure * @param {object} notification - The notification to create */ _buildUIDom(notification) { // Create notification DOM elements notification.dom = document.createElement('DIV'); notification.dom.icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); notification.dom.iconPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); notification.dom.text = document.createElement('DIV'); notification.dom.close = document.createElement('DIV'); notification.dom.maintitle = document.createElement('H6'); notification.dom.message = document.createElement('P'); // Class assignation notification.dom.classList.add('notification'); notification.dom.icon.classList.add('vector-container'); notification.dom.text.classList.add('text-container'); notification.dom.close.classList.add('close'); // Changing border side if (notification.thickBorder === 'top') { notification.dom.classList.add('top-border'); } else if (notification.thickBorder === 'bottom') { notification.dom.classList.add('bottom-border'); } else if (notification.thickBorder === 'left') { notification.dom.classList.add('left-border'); } else if (notification.thickBorder === 'right') { notification.dom.classList.add('right-border'); } // Text modification notification.dom.maintitle.innerHTML = notification.title || ''; notification.dom.message.innerHTML = notification.message || ''; notification.dom.close.innerHTML = '&#x2716;'; // Image vector notification.dom.icon.setAttribute('viewBox', '0 0 25 25'); notification.dom.icon.setAttribute('width', '25'); notification.dom.icon.setAttribute('height', '25'); notification.dom.icon.appendChild(notification.dom.iconPath); } /** @method * @name _buildNotificationType * @private * @memberof Notification * @summary Attach proper assets and css * @author <NAME> * @since March 2019 * @description Fills the Notification icon and class according to its inner type * @param {object} notification - The notification to fill */ _buildNotificationType(notification) { // Type specification (title, icon, color) if (['success', 'warning', 'error', 'info'].indexOf(notification.type) !== -1){ notification.dom.classList.add(notification.type); if (!notification.iconless) { notification.dom.iconPath.setAttribute('fill', this._default.color[notification.type]); notification.dom.iconPath.setAttribute('d', this._default.svgPath[notification.type]); } } else { notification.dom.classList.add('info'); if (!notification.iconless) { notification.dom.iconPath.setAttribute('fill', this._default.color.info); notification.dom.iconPath.setAttribute('d', this._default.svgPath.info); } } } /** @method * @name _start * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Call this method to add the new notification to the DOM container, and launch its life cycle * @param {object} notification - The notification object * @param {number} notification.id - Notification own ID */ _start(notification) { if (Object.keys(this._active).length >= this._maxActive) { this._queue[notification.id] = notification; } else { this._active[notification.id] = notification; // Append the new notification to the _active object this._events(notification); // Listen to mouse events on the newly created notification this._open(notification); // Open the new notification notification.timeoutID = window.setTimeout(() => { this._checkCounter(notification); // Check notification request count to act accordingly }, notification.duration); // Use Notification master duration } } /** @method * @name _open * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Open and add the notification to the container * @param {{id: number}} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {object} notification.dom - Notifiction DOM element */ _open(notification) { // Reverse insertion when notifications are on bottom if (this._position === 'bottom-right' || this._position === 'bottom-left') { notification.renderTo.insertBefore(notification.dom, notification.renderTo.firstChild); } else { notification.renderTo.appendChild(notification.dom); } notification.opened = Date.now(); window.setTimeout(() => { notification.dom.style.opacity = 1; }, 10); } /** @method * @name _close * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Close and remove the notification from the container * @param {{id: number}|{id: number, dom: Object, requestCount: number, timeoutID: number, sticky: boolean, closable: boolean}} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {boolean} notification.isClosing - Already closing flag * @param {object} notification.dom - Notifiction DOM element * @param {object} notification.renderTo - DOM object to render the notification in */ _close(notification) { if (notification.isClosing) { // Avoid double close on a notification (in case dismiss/dismissAll is triggerred when notification is already closing) return; } notification.isClosing = true; // Lock notification to one fadeOut animation notification.closed = Date.now(); notification.effectiveDuration = notification.closed - notification.opened; notification.dom.style.opacity = 0; window.setTimeout(() => { notification.renderTo.removeChild(notification.dom); // Remove this notification from the DOM tree delete this._active[notification.id]; if (Object.keys(this._queue).length > 0) { // Notification queue is not empty this._start(this._queue[Object.keys(this._queue)[0]]); // Start first queued notification delete this._queue[Object.keys(this._queue)[0]]; // Shift queue object } else if (Object.keys(this._active).length === 0) { // Check this._active emptyness this._dismissAllLock = false; // Unlock dismissAllLock } }, 1000); // Transition value set in _notification.scss } /** @method * @name _incrementRequestCounter * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description This method is called when a notification is requested another time * @param {object} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {number} notification.requestCount - Notification inner call counter * @param {object} notification.dom - Notifiction DOM element * @param {boolean} notification.sticky - Notification sticky behvaior * @param {boolean} notification.isDimmed - Notification dimmed status (only useful if notification.sticky is true) */ _incrementRequestCounter(notification) { ++notification.requestCount; // Increment notification.requestCount if (notification.totalRequestCount < notification.requestCount) { notification.totalRequestCount = notification.requestCount; } // Update counter DOM element if (notification.requestCount > 1) { let valueToDisplay = '∞'; if (notification.requestCount < 100) { valueToDisplay = notification.requestCount; } if (notification.dom.counter) { // Update existing counter notification.dom.counter.innerHTML = valueToDisplay; } else { // Create counter DOM element notification.dom.counter = document.createElement('DIV'); notification.dom.counter.classList.add('counter'); notification.dom.counter.innerHTML = valueToDisplay; notification.dom.appendChild(notification.dom.counter); } } // Undim notification if it is a sticky/dimmed one if (notification.sticky && notification.isDimmed) { this._unDim(notification); } } /** @method * @name _decrementRequestCounter * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description This method is called each notification cycle end to update its inner counter * @param {{id: number, dom: Object, requestCount: number, timeoutID: number, sticky: boolean, closable: boolean}} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {boolean} notification.sticky - Notification sticky behvaior * @param {boolean} notification.isDimmed - Notification dimmed status (only useful if notification.sticky is true) * @param {number} notification.requestCount - Notification inner call counter * @param {object} notification.dom - Notification DOM element * @param {boolean} force - To force the notification.requestCount decrementation */ _decrementRequestCounter(notification, force) { if (notification.sticky && !force) { if (!notification.isDimmed) { this._dim(notification); } return; } this._resetTimeout(notification); --notification.requestCount; // Decrement notification.requestCount // Update counter DOM element if (notification.requestCount > 1) { let valueToDisplay = '∞'; if (notification.requestCount < 100) { valueToDisplay = notification.requestCount; } notification.dom.counter.innerHTML = valueToDisplay; } else { // Remove counter element from the DOM tree notification.dom.removeChild(notification.dom.counter); delete notification.dom.counter; } } /** @method * @name _checkCounter * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description This method will reset the fadeout/dim timeout or close/dim the notification depending on its requestCount * @param {{id: number}} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {number} notification.requestCount - Notification inner call counter * @param {object} notification.dom - Notifiction DOM element * @param {number} notification.timeoutID - Notification own setTimeout ID * @param {boolean} notification.sticky - Notification sticky behvaior */ _checkCounter(notification) { // This notification as still more than one cycle to live if (notification.requestCount > 1) { this._decrementRequestCounter(notification); } else { // This notification reached the end of its life cycle if (notification.renderTo.contains(notification.dom)) { window.clearTimeout(notification.timeoutID); if (notification.sticky) { // FadeOut/Dim depending on sticky behavior this._dim(notification); } else { this._close(notification); } } } } /** @method * @name _clearRequestCount * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Method that clear every pending request * @param {object} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {object} notification.dom - Notifiction DOM element */ _clearRequestCount(notification) { notification.requestCount = 1; notification.dom.removeChild(notification.dom.counter); delete notification.dom.counter; } /** @method * @name _resetTimeout * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Use this to reset a notification life cycle, and delay its close event * @param {{id: number}|{id: number, dom: Object, requestCount: number, timeoutID: number, sticky: boolean, closable: boolean}} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {number} notification.timeoutID - Notification own setTimeout ID */ _resetTimeout(notification) { window.clearTimeout(notification.timeoutID); // Clear previous life cycle notification.timeoutID = window.setTimeout(() => { this._checkCounter(notification); // Check notification request count to act accordingly }, notification.duration); // Use Notification master duration } /** @method * @name _dim * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Only useful for sticky notification that dim instead of close at the end of its life cycle * @param {{id: number, requestCount: number, dom: Object, timeoutID: number, sticky: boolean}} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {object} notification.dom - Notifiction DOM element * @param {boolean} notification.sticky - Notification sticky behvaior * @param {boolean} notification.isDimmed - Notification dimmed status (only useful if notification.sticky is true) */ _dim(notification) { const that = this; let i = 100; (function halfFadeOut() { // Start animation immediatly if (i >= 0) { notification.dom.style.opacity = i / 100; --i; if (i === 50 && notification.sticky) { // Opacity has reached 0.51 notification.dom.style.opacity = 0.5; // Set half transparency on notification notification.isDimmed = true; // Update notification dim status return; // End function } } window.setTimeout(halfFadeOut, that._transition / 100); // Split animation transition into 100 iterations (50 for real here) })(); } /** @method * @name _unDim * @private * @memberof Notification * @author <NAME> * @since June 2018 * @description Call this method when a notification is not inactive anymore * @param {object} notification - The notification object * @param {number} notification.id - Notification personnal ID * @param {object} notification.dom - Notifiction DOM element * @param {boolean} notification.isDimmed - Notification dimmed status (only useful if notification.sticky is true) */ _unDim(notification) { const that = this; let i = 50; (function halfFadeIn() { if (i < 100) { notification.dom.style.opacity = i / 100; ++i; } else if (i === 100) { notification.dom.style.opacity = 1; // Set full visibility on notification notification.isDimmed = false; // Update notification dim status that._resetTimeout(notification); // Reset life cycle timeout return; // End function } window.setTimeout(halfFadeIn, that._transition / 100); // Split animation transition into 100 iterations (50 for real here) })(); } /* --------------------------------------------------------------------------------------------------------------- */ /* ----------------------------- SINGLE NOTIFICATION CONSTRUCTION UTILS METHODS ------------------------------- */ /* */ /* The following methods only concerns a new notification request. It will test the options validity, default to */ /* fallback value if necessary and give the notification a pseudo unique identifier. */ /* --------------------------------------------------------------------------------------------------------------- */ /** @method * @name _checkNotificationOptionsValidity * @private * @memberof Notification * @summary Check the Notification options validity * @author <NAME> * @since March 2019 * @description Check a Notification options object against the required parameters. * @param {object} options - The notification options to check validity */ _checkNotificationOptionsValidity(options) { // Check for mandatory arguments existence if (options === undefined || (options.type === undefined || options.message === undefined)) { return false; } // Check existing message if (typeof options.message !== 'string' || options.message.length === 0) { return false; } // Check for unclosable at all notification if (options.sticky && options.closable === false) { return false; } // Test Notification inner variables validity if (options.type !== 'info' && options.type !== 'success' && options.type !== 'warning' && options.type !== 'error') { options.type = this._default.notification.type; } // Unlock dismissAllLock if (this._dismissAllLock) { this._dismissAllLock = false; } return true; } /** @method * @name _setOptionsFallback * @private * @memberof Notification * @summary Set Notification fallback options * @author <NAME> * @since March 2019 * @description Check a Notification options object and fill it with default value in case they are empty. * @param {object} options - The notification options to fill with default value if empty */ _setOptionsFallback(options) { if (options.title === undefined) { options.title = this._default.notification.title; } if (options.duration === undefined) { options.duration = this._duration; } if (options.iconless === undefined) { options.iconless = this._default.notification.iconless; } if (options.thickBorder === undefined) { options.thickBorder = this._thickBorder; } if (options.closable === undefined) { options.closable = this._default.notification.closable; } if (options.sticky === undefined) { options.sticky= this._default.notification.sticky; } if (options.renderTo === undefined) { options.renderTo = this._default.notification.renderTo; } if (options.CBtitle === undefined) { options.CBtitle = this._default.notification.CBtitle; } if (options.callback === undefined) { options.callback = this._default.notification.callback; } if (options.isDimmed === undefined) { options.isDimmed = this._default.notification.isDimmed; } } /** @method * @name _idGenerator * @private * @memberof Notification * @summary Generate an ID * @author <NAME> * @since June 2018 * @description Hash the seed to generate an ID * @param {string} seed - The seed string to hash * @param {number} length - The length of the returned ID */ _idGenerator(seed, length) { /* Original code from: * http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/ * Tweaked to fit Notification class needs */ let hash = 0; let character = ''; if (seed.length === 0 || length > 12) { return undefined; } for (let i = 0; i < seed.length; ++i) { character = seed.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash |= 0; // Convert to 32bit integer } return (Math.abs(hash).toString(36) + '' + Math.abs(hash / 2).toString(36).split('').reverse().join('')).substring(0, length).toUpperCase(); // Here is the twekead line } /* --------------------------------------------------------------------------------------------------------------- */ /* -------------------------------------- NOTIFICATION PUBLIC METHODS ----------------------------------------- */ /* */ /* The following methods are the exposed API of the Notification component. It allow to raise standard or custom */ /* notification without bothering their lifecycle, position or other JavaScript expensive implementation. */ /* --------------------------------------------------------------------------------------------------------------- */ /** @method * @name new * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Build a notification according to the given options, then append it to notification container. * @param {object} options - The notification options object * @param {string} options.type - <i>Error; Warning; Info; Success;</i> * @param {string} [options.title=options.type] - Notification title * @param {string} options.message - Notification message * @param {number} [options.duration=handler] - Notification duration (override handler duration value) * @param {boolean} [options.iconless=false] - No icon flag * @param {string} [options.thickBorder=handler] - Notification border side (override handler side value) * @param {boolean} [options.closable=true] - Make notification closable flag * @param {boolean} [options.sticky=false] - Make notification sticky flag * @param {object} [options.renderTo=handler] - Dom object to render the notification in * @param {string} [options.CBtitle=Callback] - Notification callback title * @param {function} [options.callback=undefined] - Notification callback button * @returns {number} The newly created notification ID */ new(options) { if (this._checkNotificationOptionsValidity(options) === false) { console.error('Notification.js : new() options argument object is invalid.'); return -1; } this._setOptionsFallback(options); // Build notification DOM element according to the given options let notification = this._buildUI({ id: this._idGenerator(`${options.type}${options.message}`, 5), // Generating an ID of 5 characters long from notification mandatory fields type: options.type, message: options.message, title: options.title, duration: options.duration, iconless: options.iconless, thickBorder: options.thickBorder, closable: options.closable, sticky: options.sticky, renderTo: options.renderTo, CBtitle: options.CBtitle, callback: options.callback, isDimmed: options.isDimmed // Only useful if sticky is set to true }); // Create a new notification in the container: No notification with the same ID is already open if (!this._active[notification.id]) { this._start(notification); } else { // Use existing notification: increment request count and reset timeout this._resetTimeout(this._active[notification.id]); this._incrementRequestCounter(this._active[notification.id]); notification = this._active[notification.id]; // Clear local new notification since it already exists in this._active } return notification.id; } /** @method * @name info * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Build an info notification * @param {object} options - The notification options object (see new() arguments since this is an abstraction of new()) * @returns {number} The newly created notification ID */ info(options) { if (options) { options.type = 'info'; return this.new(options); } else { console.error('Notification.js : No arguments provided for info() method.'); } } /** @method * @name success * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Build a success notification * @param {object} options - The notification options object (see new() arguments since this is an abstraction of new()) * @returns {number} The newly created notification ID */ success(options) { if (options) { options.type = 'success'; return this.new(options); } else { console.error('Notification.js : No arguments provided for success() method.'); } } /** @method * @name warning * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Build a warning notification * @param {object} options - The notification options object (see new() arguments since this is an abstraction of new()) * @returns {number} The newly created notification ID */ warning(options) { if (options) { options.type = 'warning'; return this.new(options); } else { console.error('Notification.js : No arguments provided for warning() method.'); } } /** @method * @name error * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Build an error notification * @param {object} options - The notification options object (see new() arguments since this is an abstraction of new()) * @returns {number} The newly created notification ID */ error(options) { if (options) { options.type = 'error'; return this.new(options); } else { console.error('Notification.js : No arguments provided for error() method.'); } } /** @method * @name dismiss * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Dismiss a specific notification via its ID * @param {string} id - The notification ID to dismiss */ dismiss(id) { window.clearTimeout(this._active[id].timeoutID); // Clear notification timeout if (this._active[id].requestCount > 1) { // Several request are pending this._clearRequestCount(this._active[id]); // Clear all pending request } this._close(this._active[id]); // Close notification } /** @method * @name dismissAll * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Clear the notification handler from all its active notifications */ dismissAll() { if (!this._dismissAllLock && Object.keys(this._active).length !== 0) { // Check that _dimissAllLock is disable and that there is still notification displayed this._dismissAllLock = true; // dismissAllLock will be unlocked at the last _close() method call this._queue = {}; // Clear queue object for (const id in this._active) { // Iterate over notifications this.dismiss(id); } } } /** @method * @name dismissType * @public * @memberof Notification * @author <NAME> * @since June 2018 * @description Dismiss all notifications from a given type * @param {string} type - <i>succes; info; warning; error;</i> */ dismissType(type) { if (Object.keys(this._active).length !== 0) { // Check that _dismissAllLock is disable and that there is still notification displayed for (const id in this._active) { // Iterate over notifications if (this._active[id].type === type) { this.dismiss(id); } } } } } export default Notification; <file_sep>/README.md # Freelance-Template Bunch of templates usefull for every freelancer <file_sep>/src/js/pages/Quotation.js import { get, appendZeroPrefixToDate } from '../tools/Utils'; import QuotationModal from "../modal/QuotationModal"; import { jsPDF } from '../../../assets/lib/jspdf.umd.min'; /* New quotation methods */ const newQuotation = freelancerInfo => { new QuotationModal({ url: 'assets/html/QuotationModal.html', callback: modalInfoRetrieved.bind(this, freelancerInfo) }); }; const modalInfoRetrieved = (freelancerInfo, customerInfo) => { const date = new Date(); let quotationNumber = `${date.getFullYear()}-101`; const quotation = JSON.parse(window.FT.ls.getItem('quotations')); if (quotation) { quotationNumber = `${quotation.lastNumber.split('-')[0]}-${parseInt(quotation.lastNumber.split('-')[1]) + 1}`; } const quotationInfo = { number: quotationNumber, // TODO, increment according to existing quotations emission: `${appendZeroPrefixToDate(date.getDate())}/${appendZeroPrefixToDate(date.getMonth() + 1)}/${date.getFullYear()}`, ending: `${appendZeroPrefixToDate(date.getDate())}/${appendZeroPrefixToDate(date.getMonth() + 2)}/${date.getFullYear()}`, htPrice: '0 €', globalDiscount: '0 %', totalPrice: '0 €' }; window.FT.clearView(); buildQuotation(freelancerInfo, customerInfo, quotationInfo); }; const buildQuotation = (freelancerInfo, customerInfo, quotationInfo) => { get('assets/html/QuotationTemplate.html').then(template => { // Parse template and append it to the section container const parser = new DOMParser(); const dom = parser.parseFromString(template, 'text/html'); const wrapper = dom.body.firstChild; document.querySelector('#section-content').appendChild(wrapper); // Template filling with custom info wrapper.querySelector('#quotation-number').innerHTML = quotationInfo.number; wrapper.querySelector('#date-emission').innerHTML = quotationInfo.emission; wrapper.querySelector('#date-ending').innerHTML = quotationInfo.ending; wrapper.querySelector('#freelancer-name').innerHTML = `${freelancerInfo.genre} ${freelancerInfo.surname} ${freelancerInfo.name}`; wrapper.querySelector('#freelancer-address').innerHTML = `${freelancerInfo.address}<br>${freelancerInfo.zipcode} – ${freelancerInfo.town}`; wrapper.querySelector('#freelancer-phone').innerHTML = `${freelancerInfo.phone}`; wrapper.querySelector('#freelancer-mail').innerHTML = `${freelancerInfo.mail}`; wrapper.querySelector('#customer-company-name').innerHTML = `${customerInfo.society}`; wrapper.querySelector('#customer-company-type').innerHTML = `${customerInfo.type}`; wrapper.querySelector('#customer-address').innerHTML = `${customerInfo.address}<br>${customerInfo.zipcode} – ${customerInfo.town}`; wrapper.querySelector('#customer-siret').innerHTML = `${customerInfo.siret}`; wrapper.querySelector('#quotation-object').innerHTML = `${customerInfo.object}`; wrapper.querySelector('#freelancer-siret').innerHTML = `${freelancerInfo.siret}`; wrapper.querySelector('#freelancer-ape').innerHTML = `${freelancerInfo.ape}`; wrapper.querySelector('#freelancer-tva').innerHTML = `${freelancerInfo.tva}`; wrapper.querySelector('#freelancer-bank').innerHTML = `${freelancerInfo.bank}`; wrapper.querySelector('#freelancer-iban').innerHTML = `${freelancerInfo.iban}`; wrapper.querySelector('#freelancer-bic').innerHTML = `${freelancerInfo.bic}`; // Quotation interactivity const dlImg = document.createElement('IMG'); dlImg.src = 'assets/img/download.svg'; document.querySelector('#view-controls').appendChild(dlImg); dlImg.addEventListener('click', downloadQuotation.bind(dlImg, wrapper.children[0], quotationInfo.number)); const saveImg = document.createElement('IMG'); saveImg.src = 'assets/img/save.svg'; document.querySelector('#view-controls').appendChild(saveImg); saveImg.addEventListener('click', saveQuotation.bind(saveImg, freelancerInfo, customerInfo, quotationInfo)); }); }; const downloadQuotation = (wrapper, number) => { // Hacking modal overlay to display a loading screen const overlay = document.createElement('DIV'); overlay.className = 'loading-overlay'; document.body.appendChild(overlay); // Remove border shadow for document for proper printing wrapper.classList.add('printing'); html2canvas(wrapper, { scale: 5 }).then(canvas => { const imgData = canvas.toDataURL('image/png'); console.log(imgData) const file = new jsPDF('p', 'mm', 'a4', true); file.addImage(imgData, 'PNG', 0, 0, 210, 297, '', 'FAST'); file.save(`Devis - ${number}.pdf`); wrapper.classList.remove('printing'); document.body.removeChild(overlay); }); }; const saveQuotation = (freelancerInfo, customerInfo, quotationInfo) => { let quotation = JSON.parse(window.FT.ls.getItem('quotations')); if (!quotation) { quotation = { lastNumber: quotationInfo.number, saved: [] }; } // Try to find already saved quotation for (let i = 0; i < quotation.saved.length; ++i) { // Found the saved quotation, update it then return if (quotation.saved[i].quotationInfo.number === quotationInfo.number) { quotation.saved[i] = { freelancerInfo: freelancerInfo, customerInfo: customerInfo, quotationInfo: quotationInfo }; window.FT.ls.setItem('quotations', JSON.stringify(quotation)); window.FT.Notification.success({ title: 'Devis mis a jour', message: `Le devis ${quotationInfo.number} à été mis à jour. Vous pourrez le retrouver dans la liste de vos devis.` }); return; } } // No saved quotation found, update last number, save current one quotation.lastNumber = quotationInfo.number; quotation.saved.push({ freelancerInfo: freelancerInfo, customerInfo: customerInfo, quotationInfo: quotationInfo }); document.querySelector('#quotation-count').innerHTML = quotation.saved.length; window.FT.ls.setItem('quotations', JSON.stringify(quotation)); window.FT.Notification.success({ title: 'Devis sauvegardé', message: `Le devis ${quotationInfo.number} à été sauvegardé. Vous pourrez le retrouver dans la liste de vos devis.` }); }; /* Listing quotation front page */ const listQuotation = quotations => { window.FT.clearView(); const container = document.createElement('DIV'); container.classList.add('quotations-list'); for (let i = 0; i < quotations.saved.length; ++i) { const quotation = document.createElement('DIV'); const number = document.createElement('H5'); const date = document.createElement('P'); const customer = document.createElement('P'); const object = document.createElement('P'); const price = document.createElement('P'); quotation.classList.add('quotation-preview'); number.innerHTML = `Devis ${quotations.saved[i].quotationInfo.number}`; date.innerHTML = `<i>${quotations.saved[i].quotationInfo.emission}</i>`; customer.innerHTML = `${quotations.saved[i].customerInfo.society}`; object.innerHTML = `${quotations.saved[i].customerInfo.object}`; price.innerHTML = `<b>${quotations.saved[i].quotationInfo.totalPrice}</b>`; const group1 = document.createElement('DIV'); const group2 = document.createElement('DIV'); const group3 = document.createElement('DIV'); group1.appendChild(number); group1.appendChild(date); group1.appendChild(customer); group2.appendChild(object); group3.appendChild(price); quotation.appendChild(group1); quotation.appendChild(group2); quotation.appendChild(group3); container.appendChild(quotation); quotation.addEventListener('click', () => { window.FT.clearView(); buildQuotation(quotations.saved[i].freelancerInfo, quotations.saved[i].customerInfo, quotations.saved[i].quotationInfo); }); } document.querySelector('#section-content').appendChild(container); }; export { newQuotation, listQuotation }; <file_sep>/src/tools/webpack.common.js const path = require('path'); const webpack = require('webpack'); const loaders = require('./loaders'); const plugins = require('./plugins'); module.exports = { entry: { freelancetemplate: './src/js/FreelanceTemplate.js', }, module: { rules: [ loaders.JSLoader, loaders.CSSLoader ] }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, '../../assets/dist'), library: 'FreelanceTemplate', // We set a library name to bundle the export default of the class libraryTarget: 'window', // Make it globally available libraryExport: 'default' // Make FreelanceTemplate.default become FreelanceTemplate }, plugins: [ new webpack.ProgressPlugin(), plugins.CleanWebpackPlugin, plugins.ESLintPlugin, plugins.StyleLintPlugin, plugins.MiniCssExtractPlugin ] }; <file_sep>/src/js/modal/Modal.js import { get } from '../tools/Utils'; class Modal { constructor(options) { this._url = options.url; this._rootElement = null; this._modalOverlay = null; this._closeButton = null; this.close = this.close.bind(this); this._loadTemplate(); } destroy() { this._modalOverlay.removeEventListener('click', this.close); this._closeButton.removeEventListener('click', this.close); // Must be overridden in child class to clean extension properties and events delete this._url; delete this._rootElement; delete this._modalOverlay; delete this._closeButton; } _loadTemplate() { get(this._url).then(template => { this._rootElement = this._parseHTMLFragment(template); // Create overlay modal container this._modalOverlay = document.createElement('DIV'); this._modalOverlay.className = 'loading-overlay'; this._modalOverlay.appendChild(this._rootElement); // Get close button from template this._closeButton = this._rootElement.querySelector('#modal-close'); this.open(); this._fillAttributes(); }); } _fillAttributes() { // Must be overridden in child class to build modal with HTML template attributes } _parseHTMLFragment(htmlString) { const parser = new DOMParser(); const dom = parser.parseFromString(htmlString, 'text/html'); return dom.body.firstChild; } open() { document.body.appendChild(this._modalOverlay); this._modalOverlay.addEventListener('click', this.close); this._closeButton.addEventListener('click', this.close); } close(event) { // Must be overridden in child class to properly clean extension properties and events if (!event || (event && (event.target === this._modalOverlay || event.target === this._closeButton || event.target === this._footerCloseButton))) { // Remove the overlay from the body document.body.removeChild(this._modalOverlay); // Use the child class destroy this.destroy(); } } } export default Modal; <file_sep>/src/js/modal/QuotationModal.js import Modal from './Modal.js'; class QuotationModal extends Modal { constructor(options) { super(options); this._cb = options.callback; this._generateButton = null; this.generate = this.generate.bind(this); } destroy() { super.destroy(); this._generateButton.removeEventListener('click', this.generate); } _fillAttributes() { this._generateButton = this._rootElement.querySelector('#modal-footer-generate'); this._events(); } _events() { this._generateButton.addEventListener('click', this.generate); } generate() { this._cb({ society: this._rootElement.querySelector('#society').value, type: this._rootElement.querySelector('#type').value, address: this._rootElement.querySelector('#address').value, zipcode: this._rootElement.querySelector('#zipcode').value, town: this._rootElement.querySelector('#town').value, siret: this._rootElement.querySelector('#siret').value, object: this._rootElement.querySelector('#object').value }); this.close(); } } export default QuotationModal; <file_sep>/src/js/modal/NewContractModal.js import Modal from './Modal.js'; class NewContactModal extends Modal { constructor(options) { super(options); this._cb = options.callback; this._generateButton = null; this.generate = this.generate.bind(this); } destroy() { super.destroy(); this._generateButton.removeEventListener('click', this.generate); } _fillAttributes() { this._generateButton = this._rootElement.querySelector('#modal-footer-generate'); this._events(); } _events() { this._generateButton.addEventListener('click', this.generate); } generate() { this._cb({ type: this._rootElement.querySelector('#type').value }); this.close(); } } export default NewContactModal; <file_sep>/src/js/modal/InitModal.js import Modal from './Modal.js'; class InitModal extends Modal { constructor(options) { super(options); this._cb = options.callback; this._data = options.data; this._saveButton = null; this.save = this.save.bind(this); } destroy() { super.destroy(); this._saveButton.removeEventListener('click', this.save); } _fillAttributes() { this._saveButton = this._rootElement.querySelector('#modal-footer-save'); if (this._data) { this._rootElement.querySelector('#civility').value = this._data.genre; this._rootElement.querySelector('#surname').value = this._data.surname; this._rootElement.querySelector('#name').value = this._data.name; this._rootElement.querySelector('#address').value = this._data.address; this._rootElement.querySelector('#zipcode').value = this._data.zipcode; this._rootElement.querySelector('#town').value = this._data.town; this._rootElement.querySelector('#phone').value = this._data.phone; this._rootElement.querySelector('#mail').value = this._data.mail; this._rootElement.querySelector('#siret').value = this._data.siret; this._rootElement.querySelector('#ape').value = this._data.ape; this._rootElement.querySelector('#tva').value = this._data.tva; this._rootElement.querySelector('#bank').value = this._data.bank; this._rootElement.querySelector('#iban').value = this._data.iban; this._rootElement.querySelector('#bic').value = this._data.bic; } this._events(); } _events() { this._saveButton.addEventListener('click', this.save); } save() { this._cb({ genre: this._rootElement.querySelector('#civility').value, surname: this._rootElement.querySelector('#surname').value, name: this._rootElement.querySelector('#name').value, address: this._rootElement.querySelector('#address').value, zipcode: this._rootElement.querySelector('#zipcode').value, town: this._rootElement.querySelector('#town').value, phone: this._rootElement.querySelector('#phone').value, mail: this._rootElement.querySelector('#mail').value, siret: this._rootElement.querySelector('#siret').value, ape: this._rootElement.querySelector('#ape').value, tva: this._rootElement.querySelector('#tva').value, bank: this._rootElement.querySelector('#bank').value, iban: this._rootElement.querySelector('#iban').value, bic: this._rootElement.querySelector('#bic').value }); this.close(); } } export default InitModal; <file_sep>/src/js/FreelanceTemplate.js import '../scss/freelancetemplate.scss'; import Notification from "./tools/Notification"; import InitModal from "./modal/InitModal"; import { newQuotation, listQuotation } from './pages/Quotation'; import { newContract } from './pages/Contract'; class FreelanceTemplate { constructor() { this._ls = window.localStorage; this.Notification = new Notification(); } init() { if (!this._ls.getItem('freelancer-info')) { new InitModal({ url: 'assets/html/InitModal.html', callback: this._init.bind(this) }); } else { this._init(); } } _init(info) { if (!info) { info = JSON.parse(this._ls.getItem('freelancer-info')); } else { this._ls.setItem('freelancer-info', JSON.stringify(info)); } const quotation = JSON.parse(this._ls.getItem('quotations')); if (quotation) { document.querySelector('#quotation-count').innerHTML = quotation.saved.length; } document.querySelector('#hello-freelancer').innerHTML = `Bonjour ${info.surname}!`; document.querySelector('#edit-freelancer').addEventListener('click', this._editFreelancer.bind(this)); document.querySelector('#new-quotation').addEventListener('click', this._newQuotation.bind(this)); document.querySelector('#quotation-count').addEventListener('click', this._listQuotation.bind(this)); document.querySelector('#new-contract').addEventListener('click', this._newContract.bind(this)); } _editFreelancer() { new InitModal({ url: 'assets/html/InitModal.html', data: JSON.parse(this._ls.getItem('freelancer-info')), callback: info => { this._ls.setItem('freelancer-info', JSON.stringify(info)); } }); } _newQuotation() { newQuotation(JSON.parse(this._ls.getItem('freelancer-info'))); } _listQuotation() { const quotations = JSON.parse(this._ls.getItem('quotations')); if (quotations) { listQuotation(quotations); } } _newContract() { newContract(JSON.parse(this._ls.getItem('freelancer-info'))); } clearView() { document.querySelector('#view-controls').innerHTML = ''; document.querySelector('#section-content').innerHTML = ''; } get ls() { return this._ls; } } export default FreelanceTemplate;
150a9e127f8cd4603b2d365a6291b957d2dc042c
[ "JavaScript", "Markdown" ]
10
JavaScript
Asiberus/Freelance-Template
a1cd43db0233f0b98e6d0bb2b5582186c78154f2
50e17388a9d213d44c3caff5f6dd296741372580
refs/heads/master
<repo_name>john-mai-2605/language-difficulty-prediction<file_sep>/single_model.py import pandas as pd import re import numpy as np import cmudict from sklearn import * import matplotlib.pyplot as plt from sklearn.preprocessing import RobustScaler, OrdinalEncoder, OneHotEncoder from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectFromModel unigrams_df = pd.read_csv('unigram_freq.csv', index_col = 'word') class Dataset: def __init__(self, path): self.data = pd.read_csv(path) self.X = self.data[[ 'length', 'aveLength', 'maxLength', 'minLength', 'aveFreq', 'maxFreq', 'minFreq', 'aveDepth', 'maxDepth', 'minDepth', 'aveDensity', 'minDensity', 'maxDensity', 'aveAmbiguity', 'minAmbiguity', 'maxAmbiguity', 'wpm', 'elapse_time', 'speed', 'noun', 'verb', 'adj', 'adv', 'action', 'adventure', 'american', 'animal', 'animation', 'australian', 'british', 'comedy', 'cooking', 'documentary', 'drama', 'education', 'english', 'fantasy', 'food', 'foreign accent', 'interview', 'monologue', 'movie', 'news', 'review', 'romance', 'sciencefiction', 'sitcom', 'song', 'speech', 'superhero', 'tvseries', 'talkshow', 'technology', 'thriller', 'trailer']] self.y = self.data['error_rate'] self.scaler = RobustScaler() self.imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean') self.enc_oh = OneHotEncoder() self.enc_ord = OrdinalEncoder() def split(self, test_ratio): return model_selection.train_test_split(self.X, self.y, test_size = test_ratio, random_state=42) def encode(self): pass # self.X['tag'] = self.enc_ord.fit_transform(self.X['tag'].to_numpy().reshape(-1, 1)) # self.X['genreTag'] = self.enc_ord.fit_transform(self.X['genreTag'].to_numpy().reshape(-1, 1)) def normalize(self, X_train, X_test): self.imputer.fit(X_train) X_train = self.imputer.transform(X_train) X_test = self.imputer.transform(X_test) self.scaler.fit(X_train) return self.scaler.transform(X_train), self.scaler.transform(X_test) class Regressor: def __init__(self, reg): self.reg = reg def fit(self, X, y, **kwargs): return self.reg.fit(X, y, **kwargs) def predict(self, X_test): return self.reg.predict(X_test) def evaluate(self, y_test, y_pred): mse = metrics.mean_squared_error(y_test, y_pred) r2 = metrics.r2_score(y_test, y_pred) print(np.sqrt(mse), r2) clf_test = [map_to_class(y) for y in y_test] clf_pred = [map_to_class(y) for y in y_pred] print(metrics.confusion_matrix(clf_test, clf_pred)) print(metrics.classification_report(clf_test, clf_pred)) def run(self, X, y, X_test, y_test, **kwargs): self.fit(X, y, **kwargs) y_pred = self.predict(X_test) self.evaluate(y_test, y_pred) def select(self, X_train, X_test): self.selector = SelectFromModel(self.reg, prefit = True, threshold = -np.inf, max_features = 15) return self.selector.transform(X_train), self.selector.transform(X_test) class Classifier: def __init__(self, clf): self.clf = clf def fit(self, X, y, **kwargs): return self.clf.fit(X, y, **kwargs) def predict(self, X_test): return self.clf.predict(X_test) def evaluate(self, y_test, y_pred): print(metrics.confusion_matrix(y_test, y_pred)) print(metrics.classification_report(y_test, y_pred)) def run(self, X, y, X_test, y_test, **kwargs): self.fit(X, y, **kwargs) y_pred = self.predict(X_test) self.evaluate(y_test, y_pred) def select(self, X_train, X_test): self.selector = SelectFromModel(self.clf, prefit = True) return self.selector.transform(X_train), self.selector.transform(X_test) def map_to_class(score, s1 = 2/3, s2 = 1/3): if score > s1: return 2 if score > s2: return 1 return 0 data = Dataset('../processed_data.csv') # data.encode() # data.selection() X_train, X_test, y_train, y_test = data.split(0.2) X_train, X_test = data.normalize(X_train, X_test) y_train_clf = [map_to_class(y) for y in y_train] y_test_clf = [map_to_class(y) for y in y_test] print("---------Regressor---------") # Boosted tree print("XGB Tree") import xgboost as xgb param = { 'n_estimators': 10000, 'learning_rate': 0.1, 'objective': 'reg:squarederror', 'verbosity' : 0} fit_param = { 'eval_set':[(X_train, y_train), (X_test, y_test)], 'early_stopping_rounds': 200, 'verbose' : False} BT = Regressor(xgb.XGBModel(**param)) BT.run(X_train, y_train, X_test, y_test, **fit_param) X_train_new, X_test_new = BT.select(X_train, X_test) fit_param = { 'eval_set':[(X_train_new, y_train), (X_test_new, y_test)], 'early_stopping_rounds': 100, 'verbose' : False} # BT.run(X_train_new, y_train, X_test_new, y_test, **fit_param) xgb.plot_importance(BT.reg) plt.show() # RF print("Random Forest") RF = Regressor(ensemble.RandomForestRegressor(random_state=42)) RF.run(X_train, y_train, X_test, y_test) # X_train_new, X_test_new = RF.select(X_train, X_test) # RF.run(X_train_new, y_train, X_test_new, y_test) print("--------Classifier----------") # Boosted tree print("XGB Tree") param = { 'learning_rate': 0.05, 'objective': 'multi:softmax', 'verbosity' : 0, 'eval_metric' : 'mlogloss', 'n_estimators': 5000} fit_param = { 'eval_set':[(X_train, y_train_clf), (X_test, y_test_clf)], 'early_stopping_rounds': 100, 'verbose' : False} BT = Classifier(xgb.XGBClassifier(**param)) BT.run(X_train, y_train_clf, X_test, y_test_clf, **fit_param) X_train_new, X_test_new = BT.select(X_train, X_test) fit_param = { 'eval_set':[(X_train_new, y_train_clf), (X_test_new, y_test_clf)], 'early_stopping_rounds': 100, 'verbose' : False} #BT.run(X_train_new, y_train_clf, X_test_new, y_test_clf, **fit_param) # plt.show() #RF print("Random Forest") RF = Classifier(ensemble.RandomForestClassifier(random_state=42)) RF.run(X_train, y_train_clf, X_test, y_test_clf) # X_train_new, X_test_new = RF.select(X_train, X_test) # RF.run(X_train_new, y_train_clf, X_test_new, y_test_clf)<file_sep>/tree_aware.py import pandas as pd import re import numpy as np import cmudict from sklearn import * import matplotlib.pyplot as plt from collections import Counter import pickle from reg_resampler import resampler from imblearn.over_sampling import SMOTE from sklearn.preprocessing import RobustScaler, OrdinalEncoder, OneHotEncoder, MinMaxScaler from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectFromModel from sklearn.cluster import KMeans from base_models import Regressor print("Load data...") with open('data.pkl', 'rb') as f: data = pickle.load(f) print("Load pretrained regressor...") with open ('regs.pkl', 'rb') as f: regs = pickle.load(f) X_train, y_train_clf, y_train = data['train'].values() X_test, y_test_clf, y_test = data['test'].values() tree_model = regs[0] base_model = regs[2] X_lr_train = tree_model.reg.apply(X_train) X_lr_test = tree_model.reg.apply(X_test) X_train = np.append(X_train, X_lr_train, axis=1) X_test = np.append(X_test, X_lr_test, axis=1) X_train = X_lr_train X_test = X_lr_test print("Train tree-aware model") base_model.run(X_lr_train, y_train, X_lr_test, y_test)<file_sep>/preprocessing.py import pandas as pd import re import numpy as np import cmudict import textdistance import sklearn import pickle import nltk # Load vocab # file = open('vocab', 'rb') # vocab = pickle.load(file) unigrams_df = pd.read_csv('unigram_freq.csv', index_col = 'word') pron_dict = cmudict.dict() # The class for Word class Word: # Constructor def __init__(self, token): self.token = re.sub(r'\W+', '', str(token)).lower() # Basic features def length(self): if not self.token: return 0 return len(self.token) def frequency(self): try: return np.log(unigrams_df.loc[self.token]['count']) except: return 0 def orthogonal_depth(self): try: phoneme = pron_dict[self.token] return self.length()/len(phoneme[0]) except: return 1 def phonetic_density(self): cons = [0 if char in {'u', 'e', 'o', 'a', 'i'} else 1 for char in self.token] num_cons = sum(cons) if sum(cons) == 0: return 1 return self.length()/num_cons - 1 # class Vocab: # # Constructor # def __init__(self, token): # Test basic features # word = Word("this, ") # print(word.length()) # print(word.frequency()) # print(word.orthogonal_depth()) # print(word.phonetic_density()) # The class for Text (text fragments) class Text: # Constructor def __init__(self, text): self.text = text self.words = [Word(token) for token in text.strip().split(' ')] self.tokens = [Word(token).token for token in text.strip().split(' ')] self.pos_tags = [tag[:2] for (word, tag) in nltk.pos_tag(nltk.word_tokenize(text))] self.noun = 0 self.verb = 0 self.adj = 0 self.adv = 0 for pos in self.pos_tags: if pos == 'NN': self.noun += 1 if pos == 'VB': self.verb += 1 if pos == 'JJ': self.adj += 1 if pos == 'RB': self.adv += 1 self.length = np.asarray([word.length() for word in self.words]) self.frequency = np.asarray([word.frequency() for word in self.words]) self.orthogonal_depth = np.asarray([word.orthogonal_depth() for word in self.words]) self.phonetic_density = np.asarray([word.phonetic_density() for word in self.words]) self.pron_ambiguity = np.asarray([self.distance(word) for word in self.words]) def distance(self, word): return np.max([0 if word.token == another_word.token else textdistance.levenshtein.normalized_similarity(word.token, another_word.token) for another_word in self.words]) def extract_features(self): features = [len(self.words), self.noun/len(self.words), self.verb/len(self.words), self.adj/len(self.words), self.adv/len(self.words)] for prop in [self.length, self.frequency, self.orthogonal_depth, self.phonetic_density, self.pron_ambiguity]: features.append(np.average(prop)) features.append(np.max(prop)) features.append(np.min(prop)) return np.asarray(features) # Test text # text = Text(" I don't know where a headset ties into patriot") # print(text.orthogonal_depth) # print(text.extract_features()) # Class Dataset class Preprocess: def __init__(self, path): self.data = pd.read_csv(path) self.X = np.asarray([Text(text) for text in self.data['text']]) def transform(self): features = [Text(text).extract_features() for text in self.data['text']] self.data[[ 'length', 'noun', 'verb', 'adj', 'adv', 'aveLength', 'maxLength', 'minLength', 'aveFreq', 'maxFreq', 'minFreq', 'aveDepth', 'maxDepth', 'minDepth', 'aveDensity', 'minDensity', 'maxDensity', 'aveAmbiguity', 'minAmbiguity', 'maxAmbiguity' ]] = features self.data['speed'] = np.divide(self.data['length'], self.data['elapse_time']) self.data.to_csv('../processed_data.csv') data = Preprocess('../big_data.csv') data.transform() print("Finish pre-processing data") <file_sep>/README.md # Language difficulty Prediction Predict text difficulty for ESL learners <file_sep>/generate_dataset.py import pandas as pd import re import numpy as np import cmudict from sklearn import * import matplotlib.pyplot as plt from collections import Counter import pickle from imblearn.over_sampling import SMOTE from sklearn.preprocessing import RobustScaler, OrdinalEncoder, OneHotEncoder, MinMaxScaler from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectFromModel from sklearn.model_selection import GridSearchCV from sklearn.cluster import KMeans from sklearn.linear_model import ElasticNet, Lasso, BayesianRidge, LassoLarsIC from sklearn.linear_model import LinearRegression, SGDRegressor, PassiveAggressiveRegressor, HuberRegressor from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor from sklearn.kernel_ridge import KernelRidge import xgboost as xgb import lightgbm as lgb # clustering n_clusters = 35 tag_cluster_error_rate = 'tag_cluster_error_rate' tag_clustering_features = [ 'action', 'adventure', 'american', 'animal', 'animation', 'australian', 'british', 'comedy', 'cooking', 'documentary', 'drama', 'education', 'english', 'fantasy', 'food', 'foreign accent', 'interview', 'monologue', 'movie', 'news', 'review', 'romance', 'sciencefiction', 'sitcom', 'song', 'speech', 'superhero', 'tvseries', 'talkshow', 'technology', 'thriller', 'trailer', ] tag_cluster = 'tag_cluster' corr_cluster_error_rate = 'corr_cluster_error_rate' corr_clustering_features = ['elapse_time', 'speed', 'wpm', 'aveAmbiguity'] corr_cluster = 'corr_cluster' feature_columns = ['length', 'aveLength', 'maxLength', 'minLength', 'aveFreq', 'maxFreq', 'minFreq', 'aveDepth', 'maxDepth', 'minDepth', 'aveDensity', 'minDensity', 'maxDensity', 'aveAmbiguity', 'minAmbiguity', 'maxAmbiguity', 'wpm', 'elapse_time', 'speed', 'noun', 'verb', 'adj', 'adv', 'det', 'prep', 'norm', 'action', 'adventure', 'american', 'animal', 'animation', 'australian', 'british', 'comedy', 'cooking', 'documentary', 'drama', 'education', 'english', 'fantasy', 'food', 'foreign accent', 'interview', 'monologue', 'movie', 'news', 'review', 'romance', 'sciencefiction', 'sitcom', 'song', 'speech', 'superhero', 'tvseries', 'talkshow', 'technology', 'thriller', 'trailer', tag_cluster_error_rate, corr_cluster_error_rate, ] class Dataset: def __init__(self, path): self.data = pd.read_csv(path) # self.X = self.data[schema] self.y = self.data['error_rate'] self.scaler = RobustScaler() self.imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean') self.enc_oh = OneHotEncoder() self.enc_ord = OrdinalEncoder() self.kmeans = KMeans(n_clusters=n_clusters, random_state=123) def split(self, test_ratio): return model_selection.train_test_split(self.data, self.y, test_size = test_ratio, random_state=42) def encode(self): pass # self.X['tag'] = self.enc_ord.fit_transform(self.X['tag'].to_numpy().reshape(-1, 1)) # self.X['genreTag'] = self.enc_ord.fit_transform(self.X['genreTag'].to_numpy().reshape(-1, 1)) def normalize(self, X_train, X_test): self.imputer.fit(X_train) X_train = self.imputer.transform(X_train) X_test = self.imputer.transform(X_test) self.scaler.fit(X_train) return self.scaler.transform(X_train), self.scaler.transform(X_test) def select(self, X_train, y_train, X_test, k = 20): self.selector = SelectKBest(chi2, k) self.selector.fit(X_train, y_train) return self.selector.transform(X_train), self.selector.transform(X_test) def add_clustering_features(self, train, test, clustering_features, cluster_feature_name, normalize=False): clustering_X_train = train[clustering_features] clustering_X_test = test[clustering_features] if (normalize == True): scaler = MinMaxScaler() scaler.fit(clustering_X_train) train_for_clustering = scaler.transform(clustering_X_train) test_for_clustering = scaler.transform(clustering_X_test) # duplicate code to impute before clustering self.imputer.fit(clustering_X_train) clustering_X_train = self.imputer.transform(clustering_X_train) clustering_X_test = self.imputer.transform(clustering_X_test) ##### self.kmeans.fit(clustering_X_train) train_labels = self.kmeans.predict(clustering_X_train) test_labels = self.kmeans.predict(clustering_X_test) train['cluster'] = train_labels test['cluster'] = test_labels cluster_to_median = {} for i in range(n_clusters): cluster_to_median[i] = train['error_rate'].loc[train['cluster'] == i].median() train[cluster_feature_name] = train['cluster'].apply(lambda c:cluster_to_median[c]) test[cluster_feature_name] = test['cluster'].apply(lambda c:cluster_to_median[c]) return [train, test] def map_to_class(score, s1 = 2/3, s2 = 1/3): if score > s1: return 2 if score > s2: return 1 return 0 data = Dataset('../processed_data.csv') # data.encode() # data.selection() train, test, y_train, y_test = data.split(0.2) # add tag clustering feature train, test = data.add_clustering_features(train, test, tag_clustering_features, tag_cluster_error_rate) # add correlation based clustering feature train, test = data.add_clustering_features(train, test, corr_clustering_features, corr_cluster_error_rate, normalize = True) X_train = train[feature_columns] X_test = test[feature_columns] print(X_train[tag_cluster_error_rate].describe()) print(X_train[corr_cluster_error_rate].describe()) print(X_test[tag_cluster_error_rate].describe()) print(X_test[corr_cluster_error_rate].describe()) print('features', feature_columns) print('train size', X_train.shape) print('test size', X_test.shape) X_train, X_test = data.normalize(X_train, X_test) y_train_clf = [map_to_class(y) for y in y_train] y_test_clf = [map_to_class(y) for y in y_test] #X_train, X_test = data.select(X_train, y_train, X_test, 20) X = np.insert(X_train, 0, y_train, axis=1) smote = SMOTE(random_state=27) y_train_clf = [map_to_class(y) for y in y_train] X_new, _ = smote.fit_resample(X, y_train_clf) X_train, y_train = X_new[:, 1:], X_new[:,[0]].flatten() y_train_clf = [map_to_class(y) for y in y_train] y_test_clf = [map_to_class(y) for y in y_test] print(sorted(Counter(y_train_clf).items())) data = {'train': {'X': X_train, 'y_clf': y_train_clf, 'y_reg': y_train}, 'test': {'X': X_test, 'y_clf': y_test_clf, 'y_reg': y_test}} with open('data.pkl', 'wb') as f: pickle.dump(data, f)<file_sep>/base_models.py import pandas as pd import re import numpy as np import cmudict from sklearn import * import matplotlib.pyplot as plt from collections import Counter import pickle from imblearn.over_sampling import SMOTE from sklearn.preprocessing import RobustScaler, OrdinalEncoder, OneHotEncoder, MinMaxScaler from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectFromModel from sklearn.model_selection import GridSearchCV from sklearn.cluster import KMeans from sklearn.linear_model import ElasticNet, Lasso, BayesianRidge, LassoLarsIC from sklearn.linear_model import LinearRegression, SGDRegressor, PassiveAggressiveRegressor, HuberRegressor from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor from sklearn.kernel_ridge import KernelRidge import xgboost as xgb import lightgbm as lgb print("Load data...") with open('data.pkl', 'rb') as f: data = pickle.load(f) X_train, y_train_clf, y_train = data['train'].values() X_test, y_test_clf, y_test = data['test'].values() class Regressor: def __init__(self, reg): self.reg = reg def fit(self, X, y, **kwargs): return self.reg.fit(X, y, **kwargs) def predict(self, X_test): return self.reg.predict(X_test) def evaluate(self, y_test, y_pred): mse = metrics.mean_squared_error(y_test, y_pred) r2 = metrics.r2_score(y_test, y_pred) print(np.sqrt(mse), r2) clf_test = [map_to_class(y) for y in y_test] clf_pred = [map_to_class(y) for y in y_pred] print(metrics.confusion_matrix(clf_test, clf_pred)) print(metrics.classification_report(clf_test, clf_pred)) def tune(self, X_train, Y_train, param_grid, n_folds = 10, result_filename = 'reg_tuning_results.csv'): grid_cv = GridSearchCV(estimator = self.reg, param_grid = param_grid, cv = n_folds, scoring = 'neg_mean_squared_error', verbose = 0, n_jobs = -1 ) grid_cv.fit(X_train, Y_train) # save results tuning_results = pd.DataFrame(grid_cv.cv_results_) tuning_results.to_csv(result_filename) # set best params best_params = grid_cv.best_params_ self.reg.set_params(**best_params) def run(self, X, y, X_test, y_test, **kwargs): fitted_model = self.fit(X, y, **kwargs) y_pred = self.predict(X_test) self.evaluate(y_test, y_pred) try: importance = list(zip(fitted_model.feature_importances_, feature_columns)) importance.sort(reverse=True) print(importance) except: pass return y_pred def select(self, X_train, X_test, k = 50): self.selector = SelectFromModel(self.reg, prefit = True, threshold = -np.inf, max_features = k) return self.selector.transform(X_train), self.selector.transform(X_test) def map_to_class(score, s1 = 2/3, s2 = 1/3): if score > s1: return 2 if score > s2: return 1 return 0 if __name__ == '__main__': print("---------Regressor---------") models = [ElasticNet(), Lasso(), GradientBoostingRegressor(), BayesianRidge(), LassoLarsIC(), RandomForestRegressor(), xgb.XGBRegressor(), lgb.LGBMRegressor(), svm.SVR(), neural_network.MLPRegressor(), LinearRegression(), SGDRegressor(), PassiveAggressiveRegressor(), HuberRegressor()] EN_param_grid = {'alpha': [0.001, 0.01, 0.0001], 'copy_X': [True], 'l1_ratio': [0.6, 0.7], 'fit_intercept': [True], 'normalize': [False], 'precompute': [False], 'max_iter': [300, 3000], 'tol': [0.001], 'selection': ['random', 'cyclic'], 'random_state': [None]} LASS_param_grid = {'alpha': [0.001, 0.0001, 0.00001, 0.000001], 'copy_X': [True], 'fit_intercept': [True, False], 'normalize': [False], 'precompute': [False], 'max_iter': [300, 1000, 3000], 'tol': [0.1, 0.01, 0.001], 'selection': ['random'], 'random_state': [42]} GB_param_grid = {'loss': ['huber'], 'learning_rate': [0.1, 0.01, 0.001], 'n_estimators': [3000], 'max_depth': [3, 10], 'min_samples_split': [0.0025], 'min_samples_leaf': [5]} BR_param_grid = {'n_iter': [200], 'tol': [0.00001], 'alpha_1': [0.00000001], 'alpha_2': [0.000005], 'lambda_1': [0.000005], 'lambda_2': [0.00000001], 'copy_X': [True]} LL_param_grid = {'criterion': ['aic'], 'normalize': [True], 'max_iter': [100, 1000], 'copy_X': [True], 'precompute': ['auto'], 'eps': [0.000001, 0.00001, 0.0001]} RFR_param_grid = {'n_estimators': [50, 500], 'max_features': ['auto'], 'max_depth': [None], 'min_samples_split': [5], 'min_samples_leaf': [2]} XGB_param_grid = {'max_depth': [3, 10], 'learning_rate': [0.1, 0.05, 0.5], 'n_estimators': [000], 'booster': ['gbtree'], 'gamma': [0], 'reg_alpha': [0.1, 0.01], 'reg_lambda': [0.7], 'max_delta_step': [0], 'min_child_weight': [1], 'colsample_bytree': [0.5], 'colsample_bylevel': [0.2], 'scale_pos_weight': [1]} LGB_param_grid = {'objective': ['regression'], 'learning_rate': [0.05, 0.1, 0.5], 'n_estimators': [300, 3000]} SVR_param_grid = {'kernel': ['linear', 'poly', 'rbf', 'sigmoid']} MLP_param_grid = {'hidden_layer_sizes': [(100,), (100, 10)], 'random_state': [42], 'max_iter': [100, 1000], 'alpha': [0.01, 0.001, 0.0001]} LR_param_grid = {} GDR_param_grid = { 'loss': ['squared_loss', 'huber', 'squared_epsilon_insensitive', 'epsilon_insensitive'], 'penalty': ['l2', 'elasticnet', 'l1'], 'l1_ratio': [0.7, 0.8, 0.2, 0.5, 0.03], 'learning_rate': ['invscaling', 'constant', 'optimal'], 'alpha': [1e-01, 1e-2, 1e-03, 1e-4, 1e-05], 'epsilon': [1e-01, 1e-2, 1e-03, 1e-4, 1e-05], 'tol': [0.001, 0.003], 'eta0': [0.01, 1e-1, 1e-03, 1e-4, 1e-05], 'power_t': [0.5]} PAR_param_grid = {'loss': ['squared_epsilon_insensitive', 'epsilon_insensitive'], 'C': [0.001, 0.005, 0.003], 'max_iter': [1000], 'epsilon': [0.00001, 0.00005], 'tol': [1e-03, 1e-05,1e-02, 1e-01, 1e-04, 1e-06]} HR_param_grid = {'max_iter': [2000], 'alpha': [0.0001, 5e-05, 0.01, 0.00005, 0.0005, 0.5, 0.001], 'epsilon': [1.005, 1.05, 1.01, 1.001], 'tol': [1e-01, 1e-02]} params_grids = [EN_param_grid, LASS_param_grid, GB_param_grid, BR_param_grid, LL_param_grid, RFR_param_grid, XGB_param_grid, LGB_param_grid, SVR_param_grid, MLP_param_grid, LR_param_grid, GDR_param_grid, PAR_param_grid, HR_param_grid] regs = [] params = [] for model, param_grid in zip(models, params_grids): print(model.__class__.__name__) regressor = Regressor(model) print('Start tuning') regressor.tune(X_train, y_train, param_grid, result_filename = model.__class__.__name__ + ' hyperparameters.csv') print('Finish tuning') params.append(regressor.reg.get_params()) y = regressor.run(X_train, y_train, X_test, y_test) regs.append(regressor) with open('regs.pkl', 'wb') as f: pickle.dump(regs, f) with open('params.pkl', 'wb') as f: pickle.dump(params, f)<file_sep>/stacking.py import pandas as pd import re import numpy as np import cmudict from sklearn import * import matplotlib.pyplot as plt from sklearn.preprocessing import RobustScaler, OrdinalEncoder, OneHotEncoder from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectFromModel from sklearn.pipeline import make_pipeline from sklearn.ensemble import StackingRegressor, StackingClassifier, GradientBoostingRegressor from sklearn.linear_model import LinearRegression, LogisticRegression unigrams_df = pd.read_csv('unigram_freq.csv', index_col = 'word') class Dataset: def __init__(self, path): self.data = pd.read_csv(path) self.X = self.data[[ 'length', 'aveLength', 'maxLength', 'minLength', 'aveFreq', 'maxFreq', 'minFreq', 'aveDepth', 'maxDepth', 'minDepth', 'aveDensity', 'minDensity', 'maxDensity', 'aveAmbiguity', 'minAmbiguity', 'maxAmbiguity', 'wpm', 'elapse_time', 'speed', 'noun', 'verb', 'adj', 'adv', 'action', 'adventure', 'american', 'animal', 'animation', 'australian', 'british', 'comedy', 'cooking', 'documentary', 'drama', 'education', 'english', 'fantasy', 'food', 'foreign accent', 'interview', 'monologue', 'movie', 'news', 'review', 'romance', 'sciencefiction', 'sitcom', 'song', 'speech', 'superhero', 'tvseries', 'talkshow', 'technology', 'thriller', 'trailer']] self.y = self.data['error_rate'] self.scaler = RobustScaler() self.imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean') self.enc_oh = OneHotEncoder() self.enc_ord = OrdinalEncoder() def split(self, test_ratio): return model_selection.train_test_split(self.X, self.y, test_size = test_ratio, random_state=42) def encode(self): self.X['tag'] = self.enc_ord.fit_transform(self.X['tag'].to_numpy().reshape(-1, 1)) # self.X['genreTag'] = self.enc_ord.fit_transform(self.X['genreTag'].to_numpy().reshape(-1, 1)) def normalize(self, X_train, X_test): self.imputer.fit(X_train) X_train = self.imputer.transform(X_train) X_test = self.imputer.transform(X_test) self.scaler.fit(X_train) return self.scaler.transform(X_train), self.scaler.transform(X_test) class Regressor: def __init__(self, reg): self.reg = reg def fit(self, X, y, **kwargs): return self.reg.fit(X, y, **kwargs) def predict(self, X_test): return self.reg.predict(X_test) def evaluate(self, y_test, y_pred): mse = metrics.mean_squared_error(y_test, y_pred) r2 = metrics.r2_score(y_test, y_pred) print(np.sqrt(mse), r2) clf_test = [map_to_class(y) for y in y_test] clf_pred = [map_to_class(y) for y in y_pred] print(metrics.confusion_matrix(clf_test, clf_pred)) print(metrics.classification_report(clf_test, clf_pred)) def run(self, X, y, X_test, y_test, **kwargs): self.fit(X, y, **kwargs) y_pred = self.predict(X_test) self.evaluate(y_test, y_pred) def select(self, X_train, X_test): self.selector = SelectFromModel(self.reg, prefit = True, threshold = -np.inf, max_features = 15) return self.selector.transform(X_train), self.selector.transform(X_test) class Classifier: def __init__(self, clf): self.clf = clf def fit(self, X, y, **kwargs): return self.clf.fit(X, y, **kwargs) def predict(self, X_test): return self.clf.predict(X_test) def evaluate(self, y_test, y_pred): print(metrics.confusion_matrix(y_test, y_pred)) print(metrics.classification_report(y_test, y_pred)) def run(self, X, y, X_test, y_test, **kwargs): self.fit(X, y, **kwargs) y_pred = self.predict(X_test) self.evaluate(y_test, y_pred) def select(self, X_train, X_test): self.selector = SelectFromModel(self.clf, prefit = True) return self.selector.transform(X_train), self.selector.transform(X_test) def map_to_class(score, s1 = 2/3, s2 = 1/3): if score > s1: return 2 if score > s2: return 1 return 0 data = Dataset('../processed_data.csv') # data.encode() # data.selection() X_train, X_test, y_train, y_test = data.split(0.2) X_train, X_test = data.normalize(X_train, X_test) y_train_clf = [map_to_class(y) for y in y_train] y_test_clf = [map_to_class(y) for y in y_test] import lightgbm as lgb LGB = lgb.LGBMRegressor(objective='regression', learning_rate=0.1, n_estimators=5000) GBoost = GradientBoostingRegressor(n_estimators=5000, learning_rate=0.05, max_depth=4, max_features='sqrt', min_samples_leaf=15, min_samples_split=10, loss='huber', random_state =5) DT = tree.DecisionTreeRegressor() import xgboost as xgb param = { 'n_estimators': 10000, 'learning_rate': 0.1, 'objective': 'reg:squarederror', 'verbosity' : 0, 'n_jobs' : -1} fit_param = { 'eval_set':[(X_train, y_train), (X_test, y_test)], 'early_stopping_rounds': 200, 'verbose' : False} BT = xgb.XGBRegressor(**param) SVM = svm.SVR() RF = ensemble.RandomForestRegressor(random_state=42) NN = neural_network.MLPRegressor(hidden_layer_sizes = (100,), random_state=1, max_iter=100, alpha = 0.001) estimators = [('dt', DT), ('bt', BT), ('lgb', LGB), ('rf', RF), ('gb', GBoost)] reg = StackingRegressor(estimators=estimators, final_estimator=LinearRegression(), n_jobs = -1) stack = Regressor(reg) y_pred = stack.run(X_train, y_train, X_test, y_test) DT = tree.DecisionTreeClassifier() import xgboost as xgb param = { 'n_estimators': 10000, 'learning_rate': 0.1, 'objective': 'reg:squarederror', 'verbosity' : 0, 'n_jobs': -1} fit_param = { 'eval_set':[(X_train, y_train), (X_test, y_test)], 'early_stopping_rounds': 200, 'verbose' : False} BT = xgb.XGBClassifier(**param) # Stacking estimators = [('bt', BT.reg), ('lgb', lg.reg), ('gb', gb.reg)] reg = ensemble.StackingRegressor(estimators=estimators, final_estimator=rf.reg, n_jobs = -1, passthrough = True) stack = Regressor(reg) y = stack.run(X_train, y_train, X_test, y_test) # with open ('y_pred_regs.pkl', 'rb') as f: # y_preds = pickle.load(f) with open ('regs.pkl', 'rb') as f: regs = pickle.load(f) y_preds.append(y) regs.append(y) val = input("Enter to save, Ctrl+C to stop") # with open ('y_pred_regs.pkl', 'wb') as f: # pickle.dump(y_preds, f) with open ('regs.pkl', 'wb') as f: pickle.dump(regs, f) <file_sep>/blending.py import pandas as pd import re import numpy as np import cmudict from sklearn import * import matplotlib.pyplot as plt from collections import Counter import pickle from reg_resampler import resampler from imblearn.over_sampling import SMOTE from sklearn.preprocessing import RobustScaler, OrdinalEncoder, OneHotEncoder, MinMaxScaler from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectFromModel from sklearn.cluster import KMeans from base_models import Regressor, map_to_class print("Load data...") with open('data.pkl', 'rb') as f: data = pickle.load(f) print("Load pretrained regressor...") with open ('regs.pkl', 'rb') as f: regs = pickle.load(f) X_train, y_train_clf, y_train = data['train'].values() X_test, y_test_clf, y_test = data['test'].values() X_val, X_test, y_val, y_test = model_selection.train_test_split(X_test, y_test, test_size = 0.75, random_state=42) y_train_clf = [map_to_class(y) for y in y_train] y_test_clf = [map_to_class(y) for y in y_test] y_val_clf = [map_to_class(y) for y in y_val] print(sorted(Counter(y_train_clf).items())) print("---------Averaging Blending Regressor---------") y_pred_vals = [reg.predict(X_val) for reg in regs] weights = [0.5, 0, 0, 0, 0.5, 0] y_pred_val = sum(x*y for x, y in zip(weights, y_pred_vals)) clf_val = [map_to_class(y) for y in y_pred_val] print(metrics.confusion_matrix(y_val_clf, clf_val)) print(metrics.classification_report(y_val_clf, clf_val)) y_pred_tests = [reg.predict(X_test) for reg in regs] weights = [0.5, 0, 0, 0, 0.5, 0] y_pred_test = sum(x*y for x, y in zip(weights, y_pred_tests)) clf_test = [map_to_class(y) for y in y_pred_test] print(metrics.confusion_matrix(y_test_clf, clf_test)) print(metrics.classification_report(y_test_clf, clf_test)) print("---------Blending Regressor---------") X_val = np.append(X_val, np.asarray(y_pred_vals).T, axis = 1) X_test = np.append(X_test, np.asarray(y_pred_tests).T, axis = 1) model = Regressor(linear_model.LinearRegression()) model.run(X_val, y_val, X_test, y_test)<file_sep>/best_model.py import pandas as pd import re import numpy as np import cmudict from sklearn import * import matplotlib.pyplot as plt from collections import Counter import pickle from reg_resampler import resampler from imblearn.over_sampling import SMOTE from sklearn.preprocessing import RobustScaler, OrdinalEncoder, OneHotEncoder, MinMaxScaler from sklearn.impute import SimpleImputer from sklearn.feature_selection import SelectFromModel from sklearn.cluster import KMeans from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor import xgboost as xgb from base_models import Regressor, map_to_class print("Load data...") with open('data.pkl', 'rb') as f: data = pickle.load(f) print("Load pretrained regressor...") with open ('regs.pkl', 'rb') as f: regs = pickle.load(f) X_train, y_train_clf, y_train = data['train'].values() X_test, y_test_clf, y_test = data['test'].values() X_val, X_test, y_val, y_test = model_selection.train_test_split(X_test, y_test, test_size = 0.75, random_state=42) y_train_clf = [map_to_class(y) for y in y_train] y_test_clf = [map_to_class(y) for y in y_test] y_val_clf = [map_to_class(y) for y in y_val] print(sorted(Counter(y_train_clf).items())) print("---------Averaging Blending Regressor---------") param = { 'n_estimators': 3000, 'learning_rate': 0.1, 'objective': 'reg:squarederror', 'verbosity' : 0} XGB = Regressor(xgb.XGBRegressor(**param)) XGB_pred = XGB.run(X_train, y_train, X_val, y_val) param = {'loss': 'huber', 'learning_rate': 0.1, 'n_estimators': 3000} GB = Regressor(GradientBoostingRegressor(**param)) GB_pred = GB.run(X_train, y_train, X_val, y_val) regs = [XGB, GB] y_pred_vals = [XGB_pred, GB_pred] weights = [0.5, 0.5] y_pred_val = sum(x*y for x, y in zip(weights, y_pred_vals)) clf_val = [map_to_class(y) for y in y_pred_val] print(metrics.confusion_matrix(y_val_clf, clf_val)) print(metrics.classification_report(y_val_clf, clf_val)) y_pred_tests = [reg.predict(X_test) for reg in regs] weights = [0.5, 0.5] y_pred_test = sum(x*y for x, y in zip(weights, y_pred_tests)) clf_test = [map_to_class(y) for y in y_pred_test] print(metrics.confusion_matrix(y_test_clf, clf_test)) print(metrics.classification_report(y_test_clf, clf_test))
53057d50ce4f4cbb9703809c4d4237b578a57f20
[ "Markdown", "Python" ]
9
Python
john-mai-2605/language-difficulty-prediction
b5caee679bed29bf177a5777bc1d317e69ba4def
cf2aaac5e11a1420513a9dd751d2a29afc96823f
refs/heads/master
<file_sep>#ifndef CHICKEN_HPP #define CHICKEN_HPP #include "bird.hpp" class Chicken : public Bird { public: Chicken(const std::string name, const std::string favoriteFood, double wingSpan, bool isBroiler, const std::vector<AnimalID>& friends = std::vector<AnimalID>()) : Bird(name, favoriteFood, wingSpan, friends), _isBroiler(isBroiler) { } void printProperties(void); private: bool _isBroiler; }; #endif // CHICKEN_HPP <file_sep>#include "dog.hpp" void Dog::printProperties(void) { printf("%s, favorite food %s, %zu friends, type %s\n", _name.c_str(), _favoriteFood.c_str(), _friends.size(), _dogType.c_str()); }<file_sep>#include "zoo.hpp" #include <stdio.h> #include <algorithm> // for_each void Zoo::printAnimals(void) { std::for_each(_animalMap.begin(), _animalMap.end(), [&](std::pair<AnimalID, Animal*> elem) { elem.second->printProperties(); elem.second->printFriends(_animalMap); }); } void Zoo::liveDay(void) { std::for_each(_animalMap.begin(), _animalMap.end(), [&](std::pair<AnimalID, Animal*> animalData) { // Copies are fine since it's just some ID we're not going to change // and it's some ptr we're not going to change (however, contents are modified...) AnimalID animalID = animalData.first; Animal* animal = animalData.second; tryRemoveRandomFriend(animalID, animal); tryAddRandomFriend(animalID, animal); }); } void Zoo::addAnimal(Animal* animal) { _animalMap[_runningID] = animal; _animalIDs.push_back(_runningID); ++_runningID; } void Zoo::tryAddRandomFriend(AnimalID animalID, Animal* animal) { if (animal->nFriends() >= _animalMap.size() - 1) { // Already friend of everyone(expect oneself) return; } // Loop until found an animal that // (1) is not self // (2) is not yet a friend bool foundNewFriend = false; while (!foundNewFriend) { // Take random number from 0 to nFriends int64_t randIndex = rand() % _animalIDs.size(); AnimalID newFriendCandidateID = _animalIDs[randIndex]; // Check that it's not self // Check if it's a new friend if ((newFriendCandidateID != animalID) && !animal->isFriendWith(newFriendCandidateID)) { animal->setFriendship(newFriendCandidateID, true); // set also the other way around... _animalMap[newFriendCandidateID]->setFriendship(animalID, true); printf("%s has establised friendship with %s\n", _animalMap.at(animalID)->name().c_str(), _animalMap.at(newFriendCandidateID)->name().c_str()); foundNewFriend = true; } } } void Zoo::tryRemoveRandomFriend(AnimalID animalID, Animal* animal) { if (animal->nFriends() > 0) { AnimalID lostFriend = animal->loseOneRandomFriend(); _animalMap[lostFriend]->setFriendship(animalID, false); printf("%s has lost friendship with %s\n", _animalMap.at(animalID)->name().c_str(), _animalMap.at(lostFriend)->name().c_str()); } }<file_sep>#ifndef ZOO_HPP #define ZOO_HPP #include "animal.hpp" class Zoo { public: Zoo(void) : _runningID(0L) { }; // Print all animals, their properties and friends void printAnimals(void); // Update the friends of all animals; print changes void liveDay(void); void addAnimal(Animal* animal); void tryAddRandomFriend(AnimalID animalID, Animal* animal); void tryRemoveRandomFriend(AnimalID animalID, Animal* animal); private: std::unordered_map<AnimalID, Animal*> _animalMap; std::vector<AnimalID> _animalIDs; AnimalID _runningID; }; #endif // ZOO_HPP <file_sep>#include "chicken.hpp" void Chicken::printProperties(void) { const std::string broilerStr = (_isBroiler) ? "is broiler" : "is not broiler"; printf("%s, favorite food %s, %zu friends, wingspan %.2f, %s\n", _name.c_str(), _favoriteFood.c_str(), _friends.size(), _wingSpan, broilerStr.c_str()); }<file_sep>#ifndef DOG_HPP #define DOG_HPP #include "animal.hpp" class Dog : public Animal { public: Dog(const std::string name, const std::string favoriteFood, const std::string dogType, const std::vector<AnimalID>& friends = std::vector<AnimalID>()) : Animal(name, favoriteFood, friends), _dogType(dogType) {} void printProperties(void); private: const std::string _dogType; }; #endif // DOG_HPP <file_sep>#ifndef PARROT_HPP #define PARROT_HPP #include "bird.hpp" class Parrot : public Bird { public: Parrot(const std::string name, const std::string favoriteFood, double wingSpan, bool canSpeak, const std::vector<AnimalID>& friends = std::vector<AnimalID>()) : Bird(name, favoriteFood, wingSpan, friends), _canSpeak(canSpeak) { } void printProperties(void); private: bool _canSpeak; }; #endif // PARROT_HPP <file_sep>#ifndef ANIMAL_HPP #define ANIMAL_HPP #include <inttypes.h> #include <vector> #include <string> #include <unordered_map> #include <random> typedef int64_t AnimalID; class Animal { public: Animal(const std::string name, const std::string favoriteFood, const std::vector<AnimalID>& friends = std::vector<AnimalID>()) : _name(name), _favoriteFood(favoriteFood), _friends(friends) { } virtual void printProperties(void) = 0; void printFriends(const std::unordered_map<AnimalID, Animal*>& animalMap); bool isFriendWith(AnimalID animal); void setFriendship(AnimalID animal, bool status); AnimalID loseOneRandomFriend(void); size_t nFriends(void); const std::string name(void) const; protected: const std::string _name; const std::string _favoriteFood; std::vector<AnimalID> _friends; }; #endif // ANIMAL_HPP<file_sep>#include "parrot.hpp" void Parrot::printProperties(void) { const std::string canSpeakStr = (_canSpeak) ? "can speak" : "cannot speak"; printf("%s, favorite food %s, %zu friends, wingspan %.2f, %s\n", _name.c_str(), _favoriteFood.c_str(), _friends.size(), _wingSpan, canSpeakStr.c_str()); }<file_sep>#include "animal.hpp" #include <algorithm> bool Animal::isFriendWith(AnimalID animal) { for (auto& friendID : _friends) { if (friendID == animal) { return true; } } return false; } void Animal::setFriendship(AnimalID animal, bool status) { bool isFriendCurrently = isFriendWith(animal); if (!isFriendCurrently && status) { // add as friend _friends.push_back(animal); } else if (isFriendCurrently && !status) { // remove from friends _friends.erase(std::remove(_friends.begin(), _friends.end(), animal), _friends.end()); } } AnimalID Animal::loseOneRandomFriend(void) { // Take random number from 0 to nFriends int64_t randIndex = rand() % _friends.size(); AnimalID lostFriendID = _friends[randIndex]; // Lose the random friend setFriendship(lostFriendID, false); return lostFriendID; } size_t Animal::nFriends(void) { return _friends.size(); } void Animal::printFriends(const std::unordered_map<AnimalID, Animal*>& animalMap) { printf("Friends of %s are:\n", _name.c_str()); for (auto& friendID : _friends) { auto animalPtr = animalMap.at(friendID); printf("%s\n", animalPtr->name().c_str()); } printf("\n"); } const std::string Animal::name(void) const { return _name; }<file_sep>#ifndef BIRD_HPP #define BIRD_HPP #include "animal.hpp" class Bird : public Animal { public: Bird(const std::string name, const std::string favoriteFood, double wingSpan, const std::vector<AnimalID>& friends = std::vector<AnimalID>()) : Animal(name, favoriteFood, friends), _wingSpan(wingSpan) { } void printProperties(void) = 0; protected: double _wingSpan; }; #endif // BIRD_HPP <file_sep># Zoo ## Problem The task is to create an application that - Holds a database of a zoo with different kinds of animals - Edits relationships (friendship) between animals according to rules - Prints relevant data to the console - Allows user input via console ## Design ### Challenges Several challenges were faced solving this puzzle. The following paragraph discusses what choices has been done and why. - There are different kinds of animals with different kinds of properties. One must be able to conveniently add them to the database and print their properties. The correct properties must be printed: dog doesn't have wingspan, for instance. It seems that all animals have name, favorite food and friends. Each dog has dog type property. Each bird has a wingspan. Parrots can or can not speak. Chickens have a property to be broiler. This sense of hierarchy suggests that using inheritance is *possible*. It makes sense as we assume that all animals belong to one and only one base class. Thus, we should not face the multiple inheritance problem or any other inherent problem ("feature") of inheritance. The goal is to be able to initialize each animal with appropriate arguments according to their type but still be able to store them into the same data structure for being able to traverse them easily (list of animals). How to let the class "know" its type (Dog, Parrot,...) and thus print the correct properties? There are many options: - Templated function overloads - Let class own a number of generic properties and each property is able to return itself as a string for printing - Use virtual functions to make custom behavior for each animal (if one uses inheritance, this is the way to go) - There must be some data structure that contains the information of the friends of the animal. The structure must be convenient to read and write One could model the friends of all animals as a graph: one node for each animal, connections between nodes represent friendship. Then, interactions that change friendship change the connections. A way to implement this is to set up a `n x n` matrix where each cell represents whether there is a friendship between two animals. For instance, `friends[i][j]` is `1` if animal `i` and `j` are friends. The matrix would be symmetrical along the diagonal so there would also be obsolete information in the data structure. In a considerably big zoo, the data structure could be flattened into 1D vector for faster search. This seemed overkill (and especially *boring*) at first so in the end the friendship was modeled with simply having list of animal IDs in a vector and editing that accordingly upon friendship updates. ### Details As inheritance is used, let `Animal` be the base class which is inherited by `Dog` and `Bird`. Moreover, `Bird` is inherited by `Chicked` and `Parrot`. As we want to have a way to pick a specific animal regardless of its derived class, we have an unordered map where the key is `AnimalID` and the value is pointer to the `Animal` instance. `AnimalID`s are unique for each animal and they may be accessed in various data structures using this. It is cleaner to use the ID than passing around the pointer to the data in every interface. ### Program flow The animal data resides inside the scope of `main`. It could be inside `Zoo` but I didn't find that necessary in the context of this assignment. Doing it this way is safe: it ensures that the lifetime of the data is at least the lifetime of everyone using it. After setting up the zoo, the program polls for user input until it gets exit. It is ensured that the user does not input anything else than the desired commands. `printAnimals` will traverse the animal map and print the properties of the animals using the implementation of the appropriate derived class. After that, it will use a common function to print the friends as every animal holds the list of friends. `liveDay` will traverse the animal map and first try to remove a random friend from the list of friends of the animal, if any. If it removes a friend, also the occurrence of this animal is removed from the list of its friend. Then, similarly, random friend is tried to be added to the animal if it is not already friend of all animals. If friend is added, it is done for both animals: the friend lists for both animals are updated as friendship is commutative. ### Discussion on this solution One could have used [CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) instead One could have used [ECS](https://en.wikipedia.org/wiki/Entity_component_system) like [this one](https://github.com/Lehdari/TemplateECS) I tried to avoid overkill solutions for this (seemingly) simple task. However, I don't think I ended up with an **elegant** solution after all. The zoo in this task is 7 animals, so I didn't even bother to think the time complexity of searches in the data structures. If there would have been a note on scalability in the problem poster, I would have done this probably differently and benchmarked different options. ### Known limitations/"features" - In a day, animal may lose a friend and get the same friend back instantly ## Installation (Ubuntu) ### Requirements - Git - CMake (3.10 was used in testing, probably older will do) - C++ 14 -compatible compiler (g++ 7.4.0 was used in testing) ```bash git clone https://github.com/Hyrtsi/Zoo.git cd Zoo mkdir build cd build cmake .. make ``` ## Usage After build, ```bash ./Zoo ``` Instructions are printed to console. Press keys 1-3 to use the program. ## Tests Last but not least. How this program was verified. As it is dealing with functions that have side effects by nature (printing to console) and randomness, I didn't think unit tests make sense for many functions. Things that may be tested automatically - `animal.hpp`: Create instance of an animal with known list of friends instead of empty list OR use `setFriendship`. Check with `isFriendWith` and `nFriends` that the results are according to what was set - `zoo.hpp`: Amount of friends for a given animal should change after `tryAddRandomFriend` and `tryRemoveRandomFriend` unless the animal had 0/max friends. `liveDay` should increase amount of friends Manual tests - Feeding valid and invalid inputs to the program - Iterating many many days and checking if the amount of friends goes out of bounds or something else in prints seems out of place - Checking if the number of friends changes according the prints after a day - Checking that properties are correct for each animal <file_sep>#include "animal.hpp" #include "zoo.hpp" #include "dog.hpp" #include "chicken.hpp" #include "parrot.hpp" #include <time.h> #include <iostream> #include <cctype> bool pollCommands(Zoo& zoo); int main(int argc, char *argv[]) { // Initialize the random seed only once per program run srand(time(NULL)); // Initialize zoo Zoo zoo; Dog dog1("Dog one", "Meat", "Hunting dog"); Dog dog2("Dog two", "Fresh meat", "Assistance dog"); Dog dog3("Dog three", "Pedigree", "Racing dog"); Chicken chicken1("Chicken one", "Corn", 0.75, true); Chicken chicken2("Chicken two", "Corn", 0.75, false); Parrot parrot1("Parrot one", "Grain", 0.25, false); Parrot parrot2("Parrot two", "Corn", 0.50, true); zoo.addAnimal(&dog1); zoo.addAnimal(&dog2); zoo.addAnimal(&dog3); zoo.addAnimal(&chicken1); zoo.addAnimal(&chicken2); zoo.addAnimal(&parrot1); zoo.addAnimal(&parrot2); // Poll for user input bool gotExit = false; while (!gotExit) { gotExit = pollCommands(zoo); } printf("Exiting program\n"); return 0; } bool pollCommands(Zoo& zoo) { printf("\nPlease enter the next command.\n" "1 = List all animals, properties and friends\n" "2 = Live one day and update friendships\n" "3 = Exit\n"); std::string commandStr; std::cin >> commandStr; if (!std::cin) { return false; } bool gotExit = false; int32_t command = std::atoi(commandStr.c_str()); if (command == 1) { // List all animals printf("\n"); zoo.printAnimals(); } else if (command == 2) { // Live one day printf("\n"); zoo.liveDay(); } else if (command == 3) { // Exit gotExit = true; } else { // Invalid input printf("Please enter a valid input (integer, 1,2 or 3)!\n"); } return gotExit; } <file_sep>cmake_minimum_required(VERSION 3.10) project(Zoo) set (CMAKE_CXX_STANDARD 11) include_directories(include) file(GLOB SOURCES "src/*.cpp") add_executable(Zoo ${SOURCES})
4763ceb548db4e8b9d1c28ed280eb6c0084a9c64
[ "Markdown", "CMake", "C++" ]
14
C++
Hyrtsi/Zoo
e76be6df957e830a979ec69ca01b102cb0e27e09
ba27647582c5e50e15f62f30db428903ac277ce6
refs/heads/master
<file_sep>/* * <NAME> * 1 turn of the lead screw = 0.050" travel * 20 turns = 1" travel * 1 ipm travel speed = 20 RPM * 12 ipm = 1200 RPM */ #include "myStepper.h" #include "debugprint.h" // Pin Definitions #define BUZZER_PIN 10 #define LED_PIN 13 #define SPEED_PIN A9 #define FWD_PIN A0 #define REV_PIN A1 #define START_PIN A2 // Constants #define SLEEP_TIME 1000 #define SAMPLE_TIMER 500 #define DEBOUNCE_TIME 250 #define AVG_LIST_LEN 5 #define RPM_MIN 20 #define RPM_MAX 260 bool wasPressed = false; bool moveEnabled = false; int moveDir = MC_DIR_FWD; int speedKnob = 0; int oldSpeed = 0; uint32_t waitTime = 0; uint32_t debounceTimer = 0; uint32_t speedSampleTimer = 0; int avgList[AVG_LIST_LEN]; void setup() { Serial.begin(115200); // Allow everybody to wake up... //delay(2000); while ( ! Serial ) delay(10); debugprint(DEBUG_TRACE, "Mill Drive 0.1.0"); // Set up pins pinMode(LED_PIN, OUTPUT); pinMode(SPEED_PIN, INPUT); pinMode(BUZZER_PIN, OUTPUT); pinMode(FWD_PIN, INPUT_PULLUP); pinMode(REV_PIN, INPUT_PULLUP); pinMode(START_PIN, INPUT_PULLUP); // I'm awake, I'm awake!!! beep(100); // Set up the motor... theMotor.begin(); theMotor.setStepType(MC_STEP_FULL); // All done! beep(100); // Speed debugging cruft... //theMotor.moveNow(); } void beep(int duration) { // Set up pins... pinMode(BUZZER_PIN, OUTPUT); pinMode(LED_PIN, OUTPUT); // Turn on LED and enable buzzer... digitalWrite(LED_PIN, HIGH); analogWrite(BUZZER_PIN, 127); // Wait for the specified time... delay(duration); // Turn off the LED and buzzer... digitalWrite(LED_PIN, LOW); analogWrite(BUZZER_PIN, 0); } void complain() { beep(50); delay(50); beep(50); delay(50); beep(50); } int speedAverage(int speedReading) { return (speedReading / 100 * 100) + 1; // Rotate the list for ( int i = 0; i < AVG_LIST_LEN - 1; i++ ) { //debugprint(DEBUG_TRACE, "avgList[%d] = %d", i, avgList[i]); avgList[i + 1] = avgList[i]; } // Save the new value avgList[0] = speedReading; // Add them up int total = 0; for ( int i = 0; i < AVG_LIST_LEN; i++ ) { total += avgList[i]; } return total / AVG_LIST_LEN; } void handleControls() { // Check the speed pot... speedKnob = speedAverage(analogRead(SPEED_PIN)); // Check the direction switch... if ( ! digitalRead(FWD_PIN) ) { moveDir = MC_DIR_FWD; } else if ( ! digitalRead(REV_PIN) ) { moveDir = MC_DIR_REV; } // Check the start button... if ( digitalRead(START_PIN) == LOW ) { if ( ! wasPressed ) { beep(50); if ( moveEnabled ) { moveEnabled = false; } else { moveEnabled = true; } wasPressed = true; debounceTimer = millis() + DEBOUNCE_TIME; } } else { if ( millis() > debounceTimer ) { wasPressed = false; } } } void handleMotor () { if ( moveEnabled ) { // Set the motor speed if ( oldSpeed != speedKnob ) { theMotor.setSpeed(map(speedKnob, 1, 1023, RPM_MIN, RPM_MAX)); oldSpeed = speedKnob; } if ( ! theMotor.getCanMove() ) { //theMotor.setSpeed(map(speedKnob, 1, 1023, RPM_MIN, RPM_MAX)); // Set the motor direction switch ( moveDir ) { case MC_DIR_FWD: theMotor.setReverse(false); break; case MC_DIR_REV: theMotor.setReverse(true); break; default: debugprint(DEBUG_ERROR, "Invalid direction: %d", moveDir); break; } // Start the motor moving theMotor.moveNow(); } } else { if ( theMotor.getIsMoving() ) theMotor.stopNow(); } } void debugOutput() { if ( millis() > waitTime ) { debugprint(DEBUG_TRACE, "\n\n*** Current Status %ld ***", millis()); debugprint(DEBUG_TRACE, "Speed = %d", speedKnob); debugprint(DEBUG_TRACE, "Move is %s", moveEnabled?"enbaled":"disabled"); switch ( moveDir ) { case MC_DIR_FWD: debugprint(DEBUG_TRACE, "Forward"); break; case MC_DIR_REV: debugprint(DEBUG_TRACE, "Reverse"); break; default: debugprint(DEBUG_ERROR, "Invalid direction: %d", moveDir); break; } theMotor.dumpDebug(); waitTime = millis() + SLEEP_TIME; } } uint32_t theSpeed = RPM_MIN; void loop() { /* Speed debugging cruft... theMotor.setSpeed(theSpeed++); if ( theSpeed > RPM_MAX ) { theSpeed = RPM_MIN; } delay(250); */ handleControls(); debugOutput(); handleMotor(); } <file_sep> #ifndef _myStepper_h_ #define _myStepper_h_ #include <Arduino.h> #define STEP_PULSE(steps, microsteps, rpm) (60*1000000L/steps/microsteps/rpm) #define DEBUG_COILS 0x0010 // Motor Controller Pins #define MC_PIN_DIR 2 #define MC_PIN_STEP 3 #define MC_PIN_SLEEP 4 #define MC_PIN_RESET 5 #define MC_PIN_MS3 6 #define MC_PIN_MS2 7 #define MC_PIN_MS1 8 #define MC_PIN_ENABLE 9 // Motor Step Types #define NUM_STEPTYPES 5 // min step interval #define MC_STEP_FULL 0 // 1600 #define MC_STEP_HALF 1 // 800 #define MC_STEP_QUARTER 2 // 400 #define MC_STEP_EIGHTH 3 // 200 #define MC_STEP_SIXTEENTH 4 // 100 // Step Interval constraints #define MC_MIN_STEP_INTERVAL 2 // 2 uS ( 1200 rpm ) #define MC_MAX_STEP_INTERVAL 300000 // 300 mS ( 1 rpm ) // Motor Directions #define NUM_DIRS 2 #define MC_DIR_REV 0 #define MC_DIR_FWD 1 // Text debugging aids extern int stepTypes[NUM_STEPTYPES]; extern const char * stepTypeNames[NUM_STEPTYPES]; extern int stepTypeNickNames[NUM_STEPTYPES]; extern const char * dirNames[NUM_DIRS]; // // myStepper Class // class myStepper { public: void begin(); void setSpeed(int); void moveNow(); void stopNow(); void dumpDebug(); // Accessors int getStepType(); void setStepType(int); int getStepInterval(); void setStepInterval(int); int getRevSteps(); void setRevSteps(int); boolean getIsMoving(); void setIsMoving(boolean); boolean getCanMove(); void setCanMove(boolean); boolean getCoilPwr(); void setCoilPwr(boolean); boolean getReverse(); void setReverse(boolean); private: int m_stepType = MC_STEP_FULL; int m_stepInterval = MC_MAX_STEP_INTERVAL; int m_revSteps = 200; boolean m_isMoving = false; boolean m_canMove = false; boolean m_coilHold = false; boolean m_reverse = false; IntervalTimer myTimer; void coilsOn(); void coilsOff(); void stepOnce(); static void doInterrupt(); }; // Global motor object extern myStepper theMotor; #endif <file_sep>#include "myStepper.h" #include "debugprint.h" int stepTypes[NUM_STEPTYPES] = { MC_STEP_FULL, MC_STEP_HALF, MC_STEP_QUARTER, MC_STEP_EIGHTH, MC_STEP_SIXTEENTH, }; const char * stepTypeNames[NUM_STEPTYPES] = { "FULL", "HALF", "QUARTER", "EIGHTH", "SIXTEENTH", }; int stepTypeNickNames[NUM_STEPTYPES] = { 1, 2, 4, 8, 16 }; const char * dirNames[NUM_DIRS] = { "MC_DIR_REV", "MC_DIR_FWD", }; myStepper theMotor; // Set up the motor driver void myStepper::begin() { // Set the pin modes, and set them all to default values... pinMode(MC_PIN_DIR, OUTPUT); digitalWrite(MC_PIN_DIR, MC_DIR_FWD); pinMode(MC_PIN_STEP, OUTPUT); digitalWrite(MC_PIN_STEP, LOW); pinMode(MC_PIN_MS1, OUTPUT); digitalWrite(MC_PIN_MS1, LOW); pinMode(MC_PIN_MS2, OUTPUT); digitalWrite(MC_PIN_MS2, LOW); pinMode(MC_PIN_MS3, OUTPUT); digitalWrite(MC_PIN_MS3, LOW); pinMode(MC_PIN_SLEEP, OUTPUT); digitalWrite(MC_PIN_SLEEP, HIGH); pinMode(MC_PIN_RESET, OUTPUT); digitalWrite(MC_PIN_RESET, HIGH); pinMode(MC_PIN_ENABLE, OUTPUT); digitalWrite(MC_PIN_ENABLE, HIGH); // Set up the interrupt... myTimer.begin(doInterrupt, m_stepInterval); } void myStepper::dumpDebug() { debugprint(DEBUG_TRACE, "\nmyStepper status:"); debugprint(DEBUG_TRACE, "stepType = %s", stepTypeNames[m_stepType]); debugprint(DEBUG_TRACE, "stepInterval = %d", m_stepInterval); debugprint(DEBUG_TRACE, "Speed: %d RPM", 60000000 / m_revSteps / m_stepInterval ); debugprint(DEBUG_TRACE, "canMove = %s", m_canMove?"TRUE":"FALSE"); debugprint(DEBUG_TRACE, "isMoving = %s", m_isMoving?"TRUE":"FALSE"); debugprint(DEBUG_TRACE, "coilPwr = %s", m_coilHold?"TRUE":"FALSE"); debugprint(DEBUG_TRACE, "reverse = %s", m_reverse?"TRUE":"FALSE"); } // Accessors int myStepper::getStepType() { return m_stepType; } void myStepper::setStepType(int newType) { debugprint(DEBUG_TRACE, "Setting stepType to %s", stepTypeNames[newType]); m_stepType = newType >= 0 && newType < NUM_STEPTYPES ? newType : m_stepType; switch ( newType ) { case MC_STEP_FULL: digitalWrite(MC_PIN_MS1, LOW); digitalWrite(MC_PIN_MS2, LOW); digitalWrite(MC_PIN_MS3, LOW); break; case MC_STEP_HALF: digitalWrite(MC_PIN_MS1, HIGH); digitalWrite(MC_PIN_MS2, LOW); digitalWrite(MC_PIN_MS3, LOW); break; case MC_STEP_QUARTER: digitalWrite(MC_PIN_MS1, LOW); digitalWrite(MC_PIN_MS2, HIGH); digitalWrite(MC_PIN_MS3, LOW); break; case MC_STEP_EIGHTH: digitalWrite(MC_PIN_MS1, HIGH); digitalWrite(MC_PIN_MS2, HIGH); digitalWrite(MC_PIN_MS3, LOW); break; case MC_STEP_SIXTEENTH: digitalWrite(MC_PIN_MS1, HIGH); digitalWrite(MC_PIN_MS2, HIGH); digitalWrite(MC_PIN_MS3, HIGH); break; default: debugprint(DEBUG_ERROR, "*** EROR *** Invalid stepType requested: %d", newType); break; } } int myStepper::getStepInterval() { return m_stepInterval; } void myStepper::setStepInterval(int newInterval) { debugprint(DEBUG_TRACE, "Setting stepInterval to %d", newInterval); if ( newInterval >= MC_MIN_STEP_INTERVAL && newInterval <= MC_MAX_STEP_INTERVAL ) { m_stepInterval = newInterval; } else { debugprint(DEBUG_ERROR, "Invalid stepInterval: %d", newInterval); } } int myStepper::getRevSteps() { return m_revSteps; } void myStepper::setRevSteps(int newSteps) { debugprint(DEBUG_TRACE, "Setting revSteps to %d", newSteps); m_revSteps = newSteps >= MC_MIN_STEP_INTERVAL && newSteps <= MC_MAX_STEP_INTERVAL ? newSteps : m_revSteps; } boolean myStepper::getIsMoving() { return m_isMoving; } void myStepper::setIsMoving(boolean flag) { m_isMoving = flag; } boolean myStepper::getCanMove() { return m_canMove; } void myStepper::setCanMove(boolean flag) { m_canMove = flag; } boolean myStepper::getCoilPwr() { return m_coilHold; } void myStepper::setCoilPwr(boolean flag) { m_coilHold = flag; } boolean myStepper::getReverse() { return m_reverse; } void myStepper::setReverse(boolean flag ) { m_reverse = flag; } // // myStepper Implementation // // Turn on the coil power... void myStepper::coilsOn() { digitalWrite(MC_PIN_ENABLE, LOW); debugprint(DEBUG_TRACE, "coilsOn()"); } // Turn off the coil power... void myStepper::coilsOff() { digitalWrite(MC_PIN_ENABLE, HIGH); debugprint(DEBUG_TRACE, "coilsOff()"); } /* void myStepper::runUntil(bool * flag) { m_isMoving = true; while ( *flag ) { digitalWrite(MC_PIN_DIR, m_reverse); // Step the motor... digitalWrite(MC_PIN_STEP, HIGH); // assert STEP delayMicroseconds(2); // wait two microseconds digitalWrite(MC_PIN_STEP, LOW); // clear STEP } } */ void myStepper::stepOnce() { //Serial.print("."); // Are we allowed to move? if ( ! m_canMove ) return; m_isMoving = true; // Set the direction... digitalWrite(MC_PIN_DIR, m_reverse); // Step the motor... digitalWrite(MC_PIN_STEP, HIGH); // assert STEP delayMicroseconds(4); // wait two microseconds digitalWrite(MC_PIN_STEP, LOW); // clear STEP } // Handle the timer interrupt... void myStepper::doInterrupt() { // Hold that thought... noInterrupts(); // Step the motor... theMotor.stepOnce(); // You were saying...? interrupts(); } void myStepper::moveNow() { debugprint(DEBUG_TRACE, "Moving..."); m_canMove = true; coilsOn(); } // Stop the motor immediately... void myStepper::stopNow() { debugprint(DEBUG_TRACE, "Stopping..."); m_isMoving = false; m_canMove = false; if ( ! m_coilHold ) coilsOff(); } // Set the motor speed... void myStepper::setSpeed( int newRPM ) { // TODO: based on stepType. debugprint(DEBUG_TRACE, "Setting speed to %d", newRPM); // Calculate the new step interval... setStepInterval(60000000 / (newRPM * m_revSteps)); // Start another with the new stepInterval... myTimer.begin(doInterrupt, m_stepInterval); } <file_sep># MillDrive A Teensy-based stepper drive for a mill axis
0b05bba5593e96134abee65efcc7154bfaa35c3f
[ "Markdown", "C++" ]
4
C++
TimTheTerrible/MillDrive
e2c91e8d96c431bafa83b061105365862621b140
66728470afc243b7378c62b1cf9ed459d25bebda
refs/heads/master
<repo_name>ffrankies/Quarto<file_sep>/public/scripts/users.js /****************************************************************************** * Performs tasks related to user authentication. * Author: <NAME> * Date: 01/02/2016 *****************************************************************************/ "use strict"; var loggedIn = false; /** * Shorter form of getElementById */ function selectId(id) { var object = document.getElementById(id); return object; }; /** * Shorter form of document.querySelector. */ function query(cssQuery) { return document.querySelector(cssQuery); }; /** * Shorter form of getElementsByClassName */ function selectClass(classtext) { var objects = document.getElementsByClassName(classtext); return objects; }; /** * Selects the first element with a given class name that is a child of a * given parent object. */ function selectOne(parent, classtext) { var objects = parent.getElementsByClassName(classtext); return objects[0]; }; /** * Sets up an Ajax request, returns the ajax request object if successful, * null if not. */ function setUpAjax() { var ajax = null; try { // For modern browsers ajax = new XMLHttpRequest(); } catch (error) { // Older browsers console.log(error); try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (error) { console.log(error); try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (error) { console.log(error); return null; } } } return ajax; }; /** * Gets user info if user is logged in. */ function checkLogIn() { var ajax = setUpAjax(); if (ajax == null) { console.log("Incompatible browser."); return; } ajax.open("GET", "/users/verify"); ajax.setRequestHeader("Content-type", "application/json"); ajax.onreadystatechange = function () { if (ajax.readyState == 4) { var response = ajax.responseText; console.log(response); response = JSON.parse(response); if (response.success) { selectId("username").innerHTML = window.localStorage.getItem("username"); selectId("log-in").innerHTML = "Log Out"; } else { if (window.localStorage.getItem("username")) { window.localStorage.removeItem("username"); } selectId("username").innerHTML = ""; selectId("log-in").innerHTML = "Log In"; } } }; ajax.send(); }; /** * Logs user in/out. */ function logIn(uname, pwd) { var ajax = setUpAjax(); if (ajax == null) { console.log("Incompatible browser."); return; } if (loggedIn) { ajax.open("POST", "/users/logout"); ajax.setRequestHeader("Content-type", "application/json"); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { var response = ajax.responseText; console.log(response); response = JSON.parse(response); if (response.success) { loggedIn = false; selectId("username").innerHTML = ""; selectId("log-in").innerHTML = "Log In"; if (window.localStorage.getItem("username")) { window.localStorage.removeItem("username"); } } else { alert("An error occured when trying to log you out: " + response.message); } } }; ajax.send(); } else { ajax.open("POST", "/users/login"); ajax.setRequestHeader("Content-type", "application/json"); ajax.onreadystatechange = function () { if (ajax.readyState == 4) { var response = ajax.responseText; console.log(response); response = JSON.parse(response); if (response.success) { loggedIn = true; selectId("logInDiv").className = "notVisible"; selectId("username").innerHTML = uname; selectId("log-in").innerHTML = "Log Out"; window.localStorage.setItem("username", uname); } else { selectId("logInError").innerHTML = response.message; } } }; ajax.send(JSON.stringify( { username: uname, password: pwd } )); } }; /** * Signs up a user, and logs the user in. */ function signUp(uname, pwd) { var ajax = setUpAjax(); if (ajax == null) { console.log("Incompatible browser."); return; } ajax.open("POST", "/users/signup"); ajax.setRequestHeader("Content-type", "application/json"); ajax.onreadystatechange = function () { if (ajax.readyState == 4) { var response = ajax.responseText; console.log(response); response = JSON.parse(response); if (response.success) { selectId("signUpDiv").className = "notVisible"; logIn(uname, pwd); } else { selectId("signUpError").innerHTML = response.message; } } }; ajax.send(JSON.stringify( { username: uname, password: pwd } )); }; /** * Validates sing up and log in input. * For sign up, use "signUp" option, for log in, use "logIn" option */ function validate(option) { var uname = query("input[name='" + option + "Uname']").value; var pwd = query("input[name='" + option + "Pwd']").value; var error = selectId(option + "Error"); if (uname.length < 3 || uname.length > 16) { error.innerHTML = "Username must be between 3 and 16 characters long"; return; } if (pwd.length < 6 || pwd.length > 16) { error.innerHTML = "Password must be between 6 and 16 characters long"; return; } var notValid = "<>();[]{}"; for (var i = 0; i < notValid.length; ++i) { if (uname.includes(notValid[i]) || pwd.includes(notValid[i])) { error.innerHTML = "Username and Password cannot contain these " + "characters: " + notValid; return; } } if (uname[0] == ' ' || uname[uname.length - 1] == ' ') { error.innerHTML = "Username cannot start or end with a space."; return; } // Sends ajax request to sign up if (option == "signUp") { signUp(uname, pwd); } else if (option == "logIn") { logIn(uname, pwd); } }; function initUsers() { checkLogIn(); selectId("signUpDone").onclick = function() { validate("signUp"); }; selectId("logInDone").onclick = function() { validate("logIn"); }; }; document.addEventListener("readystatechange", function() { if (document.readyState === "interactive") { initUsers(); } }); <file_sep>/routes/dboperations.js var mongoose = require("mongoose"); var User = require("../models/users"); var Player = require("../models/players"); var db = mongoose.connection; /** * Adds an entry for a single player to the Player collection */ exports.addPlayer = function(req, res) { var name = req.body.username; Player.create( { username: name }, function(err) { if (err) { console.log(err); return res.status(500).json( { success: false, message: err.message, error: err } ); } else { return res.status(200).json( { success: true, message: "Registered a new user" } ); // end return } }); }; <file_sep>/public/scripts/player.js /****************************************************************************** * Class that Holds Player information. * Author: <NAME> * Date: 12/29/2016 *****************************************************************************/ "use strict"; var Player = (function() { // Converts player ranks to text representations. const RANKS = { 0: "Human", 1: "Beginner", 2: "Amateur", 3: "Pro", 4: "Expert", 5: "Champ" }; // Board constructor var init = function(name, rank) { // The name of this player var name = name; // Shows whether this player is an AI or Human player var ai; if (rank == 0) { ai = false; } else { ai = rank; } // The player's rank var rank = rank; return { name: name, ai: ai, rank: rank }; }; return { init: init, RANKS: RANKS }; })(); <file_sep>/routes/userRouter.js var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/users'); var dboper = require('./dboperations'); var Verify = require("./verify"); /* GET users listing. */ router.get('/', function(req, res, next) { res.send('respond with a resource'); }); /** * Allow new users to register. Once a user is registered, create an entry * in the Players collection for the user. */ router.post('/signup', function(req, res, next) { User.register(new User( { username: req.body.username, password: <PASSWORD> } ), req.body.password, function(err, user) { if (err) { console.log(err); return res.status(500).json( { success: false, message: err.message, error: err } ); } passport.authenticate('local', dboper.addPlayer(req, res))( req, res, next); }); // end of register }); /** * Logs a user in, sending a passport token if successful. */ router.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { console.log(err); return res.status(500).json( { success: false, message: "Login failure - authentication error", error: err } ); } if (!user) { console.log(info); return res.status(401).json( { success: false, message: "Login failure - could not find user", error: info } ); } req.logIn(user, function(err) { if (err) { console.log(err); return res.status(500).json( { success: false, message: "Login failure - could not login", error: err } ); } var token = Verify.getToken(user); res.cookie("quartotoken", token, { signed: true, httpOnly: true }); res.status(200).json( { success: true, message: "Successfully logged in"// , // token: token } ); }); })(req, res, next); }); /** * Logs a user out. */ router.get('/logout', function(req, res) { req.logout(); res.clearCookie('quartotoken'); return res.status(200).json( { success: true, message: "Successully logged out" } ); }); /** * Checks if a user is logged in. */ router.get('/verify', Verify.verifyUser, function(req, res, next) { // Do nothing }); module.exports = router; <file_sep>/app.js var express = require("express"); var bodyParser = require("body-parser"); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var mongoose = require('mongoose'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var User = require("./models/users"); // var Player = require("./models/players"); var userRouter = require("./routes/userRouter"); mongoose.connect(process.env.DBURL); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { console.log("Connected correctly to MongoLab DB server."); }); var app = express(); /** Sepecify middleware */ app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser(process.env.SECRETKEY)); app.use(passport.initialize()); passport.use(new LocalStrategy(User.authenticate())); passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser()); app.use(express.static(__dirname + "/public")); app.use("/users", userRouter); var server = app.listen(process.env.PORT || 8080, function() { var port = server.address().port; console.log("Server running on port: " + port); }); <file_sep>/models/players.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Player = new Schema( { username: { type: String, required: true, minlength: 3, maxlength: 16, index: { unique: true, dropDups: true } }, played: { type: Number, default: 0 }, wins: { type: Number, default: 0 }, losses: { type: Number, default: 0 }, rank: { type: Number, min: 1, max: 5, default: 1 }, pos: { type: Number, min: 0, default: 0 }, points: { type: Number, min: 0, default: 0 } }, { timestamps: true } ); module.exports = mongoose.model('Player', Player);
3644bb5b2cd51870009c04874836e2bbf1ad5630
[ "JavaScript" ]
6
JavaScript
ffrankies/Quarto
93f0f961f6a1165649e2a078edb3865b290c63f0
006b39be54574da0be6a05d70808694caa10955f
refs/heads/master
<file_sep>package PeterPan; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; import PeterPan.Trie; public class TextAnalyzer { private String text; private List<String> chapters; private String delimiter = "[,.\";?!-():\\[\\]]"; private class Word { private String text; private int wordCount; public Word(String text, int wordCount) { this.text = text; this.wordCount = wordCount; } public int getWordCount() { return this.wordCount; } public String getText() { return this.text; } } public TextAnalyzer(File file) { try { this.text = new String(Files.readAllBytes(file.toPath())); this.chapters = Arrays.asList(this.text.split("Chapter [0-9]+ .*")).subList(1, this.text.split("Chapter [0-9]+ .*").length); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public List<String> getChapters() { return this.chapters; } public void readFileAndParseChapters(File file) throws IOException { this.text = new String(Files.readAllBytes(file.toPath())); } public String getText() { return this.text; } public int getTotalNumberOfWords(File file) { int wordCount = 0; try { Scanner input = new Scanner(file); while(input.hasNextLine()) { wordCount += processString(input.nextLine()).length; } input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } return wordCount; } public int getTotalUniqueWords(File file) { HashSet<String> uniqueWords = new HashSet<>(); try { Scanner input = new Scanner(file); while(input.hasNextLine()) { String[] words = processString(input.nextLine()); for(String word : words) { uniqueWords.add(word.toLowerCase()); } } input.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return uniqueWords.size(); } // boolean maxQueue is used to specify the sorting. True for max heap. False for min heap. public PriorityQueue<Word> createWordFrequncyQueue(File file, boolean maxQueue) { HashMap<String, Integer> individualWordCount = new HashMap<>(); PriorityQueue<Word> queue = maxQueue ? new PriorityQueue<Word>((word1, word2) -> word2.getWordCount() - word1.getWordCount()) : new PriorityQueue<Word>((word1, word2) -> word1.getWordCount() - word2.getWordCount()); try { Scanner input = new Scanner(file); while(input.hasNextLine()) { String[] words = processString(input.nextLine()); for(String word : words) { individualWordCount.put(word, individualWordCount.getOrDefault(word, 0) + 1); } } for(String key : individualWordCount.keySet()) { Word word = new Word(key, individualWordCount.get(key)); queue.offer(word); } input.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return queue; } public List<String[]> get20MostFrequentWords(File file) { PriorityQueue<Word> queue = this.createWordFrequncyQueue(file, true); ArrayList<String[]> results = new ArrayList<>(); for(int i = 0; i < 20; i++) { Word word = queue.poll(); results.add(new String[] {word.getText(), String.valueOf(word.getWordCount())}); } return results; } public List<String[]> get20MostInterestingFrequentWords(File file) { PriorityQueue<Word> queue = this.createWordFrequncyQueue(file, true); HashSet<String> commonWords = new HashSet<>(); String[] words = new String[] { "the", "of", "to", "and", "a", "in", "is", "it", "you", "that", "he", "was", "for", "on", "are", "with", "as", "I", "his", "they", "be", "at", "one", "have", "this", "from", "or", "had", "by", "not", "word", "but", "what", "some", "we", "can", "out", "other", "were", "all", "there", "when", "up", "use", "your", "how", "said", "an", "each", "she", "which", "do", "their", "time", "if", "will", "way", "about", "many", "then", "them", "write", "would", "like", "so", "these", "her", "long", "make", "thing", "see", "him", "two", "has", "look", "more", "day", "could", "go", "come", "did", "number", "sound", "no", "most", "people", "my", "over", "know", "water", "than", "call", "first", "who", "may", "down", "side", "been", "now", "ind" }; for(String word : words) { commonWords.add(word); } ArrayList<String[]> results = new ArrayList<>(); while(results.size() < 20) { Word word = queue.poll(); if(!commonWords.contains(word.getText().toLowerCase())) { results.add(new String[] {word.getText(), String.valueOf(word.getWordCount())}); } } return results; } public List<String[]> get20LeastFrequentWords(File file) { PriorityQueue<Word> queue = this.createWordFrequncyQueue(file, false); ArrayList<String[]> results = new ArrayList<>(); for(int i = 0; i < 20; i++) { Word word = queue.poll(); results.add(new String[] {word.getText(), String.valueOf(word.getWordCount())}); } return results; } public List<Integer> getFrequencyOfWord(String word) { ArrayList<Integer> frequencyOfWord = new ArrayList<>(); for(String chapter : this.getChapters()) { String[] words = processChapter(chapter); int count = 0; for(String wd : words) { if(wd.equals(word)) { count++; } } frequencyOfWord.add(count); } return frequencyOfWord; } public int getChapterQuoteAppears(String quote) { for(int i = 0; i < chapters.size(); i++) { if(chapters.get(i).contains(quote)) { return i + 1; } } return -1; } public String generateSentence() { StringBuilder sb = new StringBuilder("The "); ArrayList<String> wordsAfterThe = new ArrayList<>(); for(String chapter : this.getChapters()) { String[] words = processChapter(chapter); for(int j = 0; j < words.length - 1; j++) { if(words[j].equals("the") || words[j].equals("The")) { wordsAfterThe.add(words[j + 1]); } } } for(int i = 0; i < 20; i++) { sb.append(wordsAfterThe.get((int)(Math.random() * wordsAfterThe.size()))); sb.append(i == 19 ? "." : " "); } return sb.toString(); } public List<String> getAutocompleteSentence(String startOfSentence) { Trie trie = new Trie(); for(String chapter : this.getChapters()) { String[] words = processChapter(chapter); for(String word : words) { trie.insert(word); } } return trie.getSuggestedList(startOfSentence); } public String[] processChapter(String chapter) { chapter = chapter.replaceAll(this.delimiter, " "); return chapter.split("\\s"); } public static String[] processString(String line) { line = line.replaceAll("[,.\";?!-():\\[\\]]", " "); ArrayList<String> filters = new ArrayList<>(); for(String word : line.split("\\s")) { if(word.length() != 0) { filters.add(word); } } return filters.toArray(new String[filters.size()]); } } <file_sep># ProjectGutenberg This project is a text analysis tool that supports the following operations: 1. getTotalNumberOfWords() 2. getTotalUniqueWords() 3. get20MostFrequentWords() 4. get20MostInterestingFrequentWords() 5. get20LeastFrequentWords() 6. getFrequencyOfWord() 7. getChapterQuoteAppears() 8. generateSentence() 9. getAutocompleteSentence() <file_sep>package PeterPan; import java.util.ArrayList; import java.util.List; public class Trie { class TrieNode { private TrieNode[] children; private boolean isEnd; public TrieNode() { this.children = new TrieNode[26]; } } private TrieNode root; public Trie() { this.root = new TrieNode(); } public void insert(String word) { word = word.toLowerCase(); TrieNode cursor = this.root; for(int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if(index < 26 && index >= 0) { if(cursor.children[index] == null) { cursor.children[index] = new TrieNode(); } cursor = cursor.children[index]; } } cursor.isEnd = true; } public boolean search(String word) { word = word.toLowerCase(); TrieNode cursor = this.root; for(int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if(cursor.children[index] == null) { return false; } cursor = cursor.children[index]; } return cursor.isEnd; } public List<String> getSuggestedList(String prefix) { ArrayList<String> results = new ArrayList<>(); StringBuilder sb = new StringBuilder(); prefix = prefix.toLowerCase(); TrieNode cursor = this.root; for(int i = 0; i < prefix.length(); i++) { int index = prefix.charAt(i) - 'a'; if(cursor.children[index] == null) { return results; } cursor = cursor.children[index]; } findAllSuggestions(cursor, results, sb); for(int i = 0; i < results.size(); i++) { results.set(i, prefix + results.get(i)); } return results; } private void findAllSuggestions(TrieNode node, ArrayList<String> suggestions, StringBuilder sb) { if(node.isEnd) { suggestions.add(sb.toString()); } for(int i = 0; i < node.children.length; i++) { if(node.children[i] != null) { sb.append((char) (i + 'a')); findAllSuggestions(node.children[i], suggestions, sb); sb.setLength(sb.length() - 1); } } } }
5523bd5fcd5e9f287739ae80a81371e3a70cfda8
[ "Markdown", "Java" ]
3
Java
Jian-Chen-SBU/ProjectGutenberg
1409dd0dbf3f5c1fff390bb61b8876b8da2f6f76
f8ed6c4de9f9d632d4ec9695359d12d40909e1a7
refs/heads/main
<file_sep>package com.example.demo.Bean; import java.util.Date; public class BrrowBook { private String date1; private String bookname; private String date2; private Integer day; public String getDate1() { return date1; } public void setDate1(String date1) { this.date1 = date1; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname; } public String getDate2() { return date2; } public void setDate2(String date2) { this.date2 = date2; } public Integer getDay() { return day; } public void setDay(Integer day) { this.day = day; } } <file_sep>import Vue from 'vue' import Router from 'vue-router' //import HelloWorld from '@/components/HelloWorld' import home from "../components/home" import HelloWorld from "../components/HelloWorld" import ElementTest from "../components/index" import lunobo from "../components/lunobo" import History from "../components/IBMProject/History"; import singin from "../components/singin"; import checkbook from "../components/checkbook"; import Issue from "../components/IBMProject/Issue"; import BrrowAndCheck from "../components/IBMProject/BrrowAndCheck"; import Bookrepository from "../components/IBMProject/Bookrepository"; import AdminIndex from "../components/AdminIndex"; import MyInfo from "../components/MyInfo"; import UserModify from "../components/UserModify"; import BorrowHistory from "../components/BorrowHistory"; import UserIndex from "../components/UserIndex"; import NoticeManage from "../components/NoticeManage"; import All from "../components/All"; import test from "../components/IBMProject/test"; import MybrrowBook from "../components/MybrrowBook"; import FormCheck from "../components/Test/FormCheck"; import father from "../components/Test/father"; import signup from "../components/signup"; import upfile from "../components/Test/upfile"; Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'ElementTest', meta:{ title:'五邑大学图书馆' }, component: ElementTest }, { path: '/h', name: 'Home', component: home }, { path: '/lun', name: 'lun', component: lunobo }, { path: '/signin', name: 'signin', component: singin }, { path: '/history', name: 'History', component: History }, { path: '/toin', name: 'Home', component: home }, { path: '/checkbook', name: 'checkbook', component: checkbook }, { path: '/issue', name: 'issue', component: Issue }, { path: '/BandC', name: 'BC', component:BrrowAndCheck }, { path: '/BR', name: 'BR', component: Bookrepository }, { // 管理员 path:'/adminindex', name:'AdminIndex', component:AdminIndex }, { // 我的信息 path:'/myinfo', name:'MyInfo', component:MyInfo }, { // 信息修改 path:'/usermodify', name:'UserModify', component:UserModify }, { // 借阅历史 path:'/borrowhistory', name:'BorrowHistory', component:BorrowHistory }, { // 用户 path:'/userindex', name:'UserIndex', component:UserIndex }, //公告 { path:'/noticemanage', name:'NoticeManage', component: NoticeManage }, { path: '/all', name: 'all', component: All }, { path: '/test', name: 'test', component: test }, { path: '/shell', name: 'MybookBook', component: MybrrowBook }, { path: '/tv', name: 'FormCheck', component: FormCheck }, { path: '/fa', name: 'father', component: father }, { path: '/signup', name: 'signup', component:signup }, { path:'/upfile', name:'upfile', components: upfile } ] }) <file_sep>// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' // import axios from 'axios' // axios.defaults.baseURL='/api' // axios.defaults.headers['Context-Type']='application/json' import http from "./util/http"; import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import qs from 'qs' import singin from "./components/singin"; Vue.prototype.$qs = qs Vue.config.productionTip = false Vue.prototype.axios= http Vue.config.devtools = true Vue.prototype.LOGNAME=global Vue.use(ElementUI) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>', data(){ return{ user_name:this.LOGNAME.User.user_name } } })
1bb35720bb333d9468dbef38695222681bea58fe
[ "JavaScript", "Java" ]
3
Java
DBSBoy/VueLibrary
a719acf18c0465c5a5f8699efd6ef6bcba23b7d6
84c2d1e6a06c19bbd16a0ee23ad6360fd95f8977
refs/heads/master
<repo_name>Krealll/Ext4-Formatting-Utility<file_sep>/FormatManager.cpp #include <FormatManager.h> void FormatManager::setFileSystem(FileSystem &value) { fileSystem = value; } bool FormatManager::getFlagFormat() const { return flagFormat; } void FormatManager::setFlagFormat(bool value) { flagFormat = value; } bool FormatManager::initialiseData() //initializinf file system and allocating { //and marking it super_dirty in order to write it on device at the end fileSystem.sb.s_feature_incompat |= EXT4_FEATURE_INCOMPAT_INLINE_DATA; fileSystem.error = ext2fs_initialize( fileSystem.path, EXT2_FLAG_PRINT_PROGRESS, &fileSystem.sb, unix_io_manager, &fileSystem.fs); if(this->fileSystem.error){ return false; } ext2fs_mark_super_dirty(fileSystem.fs); return true; } bool FormatManager::manageTables() //allocating space for inode table and bitmaps { blk64_t blk; dgrp_t i; int num; fileSystem.error = ext2fs_allocate_tables(fileSystem.fs); if(this->fileSystem.error){ return false; } for (i = 0; i < fileSystem.fs->group_desc_count; i++) { blk = ext2fs_inode_table_loc(fileSystem.fs, i); // solution for overflow error num = ext2fs_div_ceil((fileSystem.fs->super->s_inodes_per_group - ext2fs_bg_itable_unused(fileSystem.fs, i)) * EXT2_INODE_SIZE(fileSystem.fs->super), EXT2_BLOCK_SIZE(fileSystem.fs->super)); ext2fs_bg_flags_set(fileSystem.fs, i, EXT2_BG_INODE_ZEROED); ext2fs_zero_blocks2(fileSystem.fs, blk, num, &blk, &num); } // in case when fs has cmus feature // it's necessary to write zeroed inodes if (ext2fs_has_feature_metadata_csum(fileSystem.fs->super)) { ext2_ino_t ino; ext2_inode *inode; fileSystem.error = ext2fs_get_memzero(EXT2_INODE_SIZE(fileSystem.fs->super), &inode); if(this->fileSystem.error){ return false; } for (ino = 1; ino < EXT2_FIRST_INO(fileSystem.fs->super); ino++) { fileSystem.error = ext2fs_write_inode_full(fileSystem.fs, ino, inode, EXT2_INODE_SIZE(fileSystem.fs->super)); } ext2fs_free_mem(&inode); } return true; } bool FormatManager::createDirectories() //creating root and lost+found directories { ext2_inode inode; ext2_ino_t ino; const char *name = "lost+found"; unsigned int lpf_size = 0; fileSystem.error = ext2fs_mkdir(fileSystem.fs, EXT2_ROOT_INO, EXT2_ROOT_INO, 0); if(this->fileSystem.error){ return false; } if (getuid()) { fileSystem.error = ext2fs_read_inode(fileSystem.fs, EXT2_ROOT_INO, &inode); if(this->fileSystem.error){ return false; } inode.i_uid = getuid(); if (inode.i_uid) inode.i_gid = getgid(); } //Lost+found creation fileSystem.fs->umask = 077; // setting dir permissions fileSystem.error = ext2fs_mkdir(fileSystem.fs, EXT2_ROOT_INO, 0, name); if(this->fileSystem.error){ return false; } fileSystem.error = ext2fs_lookup(fileSystem.fs, EXT2_ROOT_INO, name, strlen(name), 0, &ino); if(this->fileSystem.error){ return false; } for (int i=1; i < EXT2_NDIR_BLOCKS; i++) { if ((lpf_size += fileSystem.fs->blocksize) >= 16*1024 && lpf_size >= 2 * fileSystem.fs->blocksize) break; fileSystem.error = ext2fs_expand_dir(fileSystem.fs, ino); if(this->fileSystem.error){ return false; } } return true; } bool FormatManager::writeReservedInodes() { ext2_ino_t inodeR; for (inodeR = EXT2_ROOT_INO + 1; inodeR < EXT2_FIRST_INODE(fileSystem.fs->super); inodeR++) ext2fs_inode_alloc_stats2(fileSystem.fs, inodeR, +1, 0); ext2fs_mark_ib_dirty(fileSystem.fs); return true; } bool FormatManager::endFormatting() // fflushing filesystem information { //to the device and closing filesystem ext2fs_flush(fileSystem.fs); ext2fs_close_free(&fileSystem.fs); return true; } <file_sep>/FormattingThread.h #ifndef FORMATTINGTHREAD_H #define FORMATTINGTHREAD_H #include "FormatManager.h" #include <QObject> #include<QThread> class FormattingThread : public QThread //custom thread class that manages formatting { Q_OBJECT public: FormatManager threadFormatManager; explicit FormattingThread(QThread *parent = nullptr); void setThreadFormatManager(FormatManager &value); bool flagCreated=0; // flag that indicates that thread was created //and doesn't need to connect slots again protected: QString infoString; // string for sending info into main thread void run(); bool formatDevice(); //main method of program signals: void send(QString); // method that will send info about formatting process signals: }; #endif // FORMATTINGTHREAD_H <file_sep>/FileSystem.h #pragma once #include <iostream> #include<ext2fs/ext2fs.h> #include<ext2fs/ext2_err.h> #include<QString> class FileSystem{ private: QString path; long currentSize=0; //Size of file system QString information; //String for file system information public: ext2_filsys fs; // stucture that represent file system ext2_super_block sb; // stucture that represent superblock of file system errcode_t error; FileSystem(){ path=""; this->sb.s_log_block_size=0; } ~FileSystem(){} void setBlockSize(int size); void setBlockCount(int count); QString getPath() const; void setPath(QString pathToFs); long getCurrentSize() const; void setCurrentSize(long value); QString getInformation() const; void setInformation(const QString &value); bool openFs(); // method opens that file system void processSize(); // setting block size and block count bool initializeFs(); //setting size of current file system QString info(); // method that show program info }; <file_sep>/FileSystem.cpp #include "FileSystem.h" QString FileSystem::getPath() const { return path; } void FileSystem::setPath(QString pathToFs) { path = pathToFs; } long FileSystem::getCurrentSize() const { return currentSize; } void FileSystem::setCurrentSize(long value) { currentSize = value; } QString FileSystem::getInformation() const { return information; } void FileSystem::setInformation(const QString &value) { information = value; } void FileSystem::setBlockSize(int size) { this->sb.s_log_block_size=size; } void FileSystem::setBlockCount(int count) { this->sb.s_blocks_count=count; } bool FileSystem::openFs() // method opens that file system { initialize_ext2_error_table(); error = ext2fs_open(this->path.toStdString().c_str(),EXT2_FLAG_RW, 0,4096,unix_io_manager,&fs); if(error){ if(error==EXT2_ET_UNEXPECTED_BLOCK_SIZE){ error = ext2fs_open(this->path.toStdString().c_str(),EXT2_FLAG_RW, 0,2048,unix_io_manager,&fs); if(error){ if(error==EXT2_ET_UNEXPECTED_BLOCK_SIZE){ error = ext2fs_open(this->path.toStdString().c_str(),EXT2_FLAG_RW, 0,1024,unix_io_manager,&fs); if(error){ return false; } } else{ return false; } } } else { return false; } } return true; } void FileSystem::processSize() // setting block size and block count { int tempSize, tempCount; tempSize =1024<<this->sb.s_log_block_size; tempCount=this->currentSize/tempSize; memset(&this->sb,0,sizeof (this->sb)); setBlockCount(tempCount); setBlockSize(tempSize>>11); } QString FileSystem::info() // method that show program info { if(this->currentSize==0){ // first time case information="Input proper device path to get information"; return information; } if(!openFs()){ information="Error: path not found or device is not supported"; return information; } information=""; information.append("Device name: "); information.append(this->fs->device_name); information.append("\n"); information.append("Block size: "); information.append(QString().number(this->fs->blocksize)); information.append("\n"); information.append("Block count: "); information.append(QString().number(this->fs->super->s_blocks_count)); information.append("\n"); information.append("First data blok: "); information.append(QString().number(this->fs->super->s_first_data_block)); information.append("\n"); information.append("Free blocks count: "); information.append(QString().number(this->fs->super->s_free_blocks_count)); information.append("\n"); ext2fs_free(fs); return information; } bool FileSystem::initializeFs() //setting size of current file system { if(openFs()){ this->sb.s_log_block_size=0; currentSize=this->fs->super->s_blocks_count; currentSize*=this->fs->blocksize; ext2fs_close(fs); return true; } else{ return false; } } <file_sep>/widget.cpp #include "widget.h" #include "ui_widget.h" #include"FileSystem.h" #include <QMessageBox> #include "FormattingThread.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); ui->textEdit->hide(); ui->progressBar->hide(); } Widget::~Widget() { delete ui; } void Widget::on_pushButton_clicked() // slot that manages file system info { if(fs->getPath()==""){ fs->info(); } QMessageBox::information(this,"File system information",this->fs->getInformation()); } void Widget::on_pushButton_2_clicked() // slot that manages formatting button { switch(QMessageBox::question(this,"WARNING","Be sure to unmount your device before fromatting",QMessageBox::Cancel|QMessageBox::Ok)) { case QMessageBox::Cancel: fs->info(); return; case QMessageBox::Ok: if(this->fs->getPath()==""){ QMessageBox::information(this,"Warning","Input proper device path"); return; } // If user confirmed, that device is unmounted ui->textEdit->show(); // formatting thread starts and connects ui->progressBar->show(); // to info recieving slot: update this->setFixedHeight(300); this->fs->processSize(); this->fm->setFileSystem(*fs); this->fm->setFlagFormat(true); ui->comboBox->setDisabled(true); ui->pushButton_2->setDisabled(true); ui->lineEdit->setDisabled(true); ui->textEdit->clear(); ui->textEdit->setDisabled(true); ui->progressBar->setValue(0); fThread.setThreadFormatManager(*this->fm); fThread.start(); if(fThread.flagCreated==0){ connect(&fThread,SIGNAL(send(QString)),this,SLOT(update(QString))); fThread.flagCreated=1; } default: return; } } void Widget::on_lineEdit_editingFinished() // slot that manages path to device { this->fs->setPath(ui->lineEdit->displayText().toStdString().c_str()); if(!this->fs->initializeFs()){ this->fs->setCurrentSize(0); this->fs->setPath(""); fs->info(); return; } fs->info(); } void Widget::on_comboBox_currentIndexChanged(int index) // slot that manages block size choice { this->fs->setBlockSize(index); } void Widget::on_pushButton_3_clicked() // slot that manages program info { QMessageBox::information(this,"Program information" , "Ext 4 formatting utility\nVersion 1.0" "\nSupport: https://github.com/Krealll"); } void Widget::closeEvent(QCloseEvent* event) // slot that disable closing the program while formatting { if(!fm->getFlagFormat()||fThread.threadFormatManager.getFlagFormat()==0){ event->accept(); return; } event->ignore(); } void Widget::update(QString info) // slot that recieves string from formatting thread { ui->textEdit->append(info); ui->progressBar->setValue(ui->progressBar->value()+12); if(info=="-Formatting ended"){ ui->progressBar->setValue(ui->progressBar->value()+10); usleep(500000); ui->progressBar->setValue(ui->progressBar->value()+10); usleep(300000); ui->progressBar->setValue(ui->progressBar->value()+10); usleep(100000); ui->progressBar->setValue(ui->progressBar->value()+10); ui->lineEdit->setDisabled(false); ui->comboBox->setDisabled(false); ui->pushButton_2->setDisabled(false); } } <file_sep>/FormattingThread.cpp #include "FormattingThread.h" FormattingThread::FormattingThread(QThread *parent) : QThread(parent){} void FormattingThread::setThreadFormatManager(FormatManager &value) { threadFormatManager = value; } void FormattingThread::run() { if(!formatDevice()){ emit send(infoString); return; } this->threadFormatManager.setFlagFormat(false); this->quit(); } bool FormattingThread::formatDevice() { if(threadFormatManager.initialiseData()) { emit send("-Initialized new file system"); sleep(1); if(threadFormatManager.manageTables()) { emit send("-Writed inode tables"); sleep(1); if(threadFormatManager.createDirectories()) { emit send("-Created root and lost+found direcories"); sleep(1); if(threadFormatManager.writeReservedInodes()) { emit send("-Writed reserved Inodes"); sleep(1); if(threadFormatManager.endFormatting()){ emit send("-Formatting ended"); return true; } else{ infoString="ERROR: while initialising file system"; } }else{ infoString="ERROR: while writing tables"; } }else{ infoString="ERROR: while creating directories"; } }else{ infoString="ERROR: while writing reserved inodes"; } }else{ infoString="ERROR: while closing file system"; } return false; } <file_sep>/FormatManager.h #pragma once #include <iostream> #include<unistd.h> #include<ext2fs/ext2fs.h> #include "FileSystem.h" class FormatManager { FileSystem fileSystem; bool flagFormat =0; //flag that indicates beginning of formatting public: FormatManager(){} ~FormatManager(){} bool initialiseData(); //initializinf file system and allocating //and marking it super_dirty in order to write it on device at the end bool manageTables(); //allocating space for inode table and bitmaps bool createDirectories(); //creating root and lost+found directories bool writeReservedInodes(); bool endFormatting(); // fflushing filesystem information to the device and closing filesystem void setFileSystem(FileSystem &value); bool getFlagFormat() const; void setFlagFormat(bool value); }; <file_sep>/widget.h #pragma once #include "FormatManager.h" #include "FileSystem.h" #include "FormattingThread.h" #include<ext2fs/ext2fs.h> #include<ext2fs/ext2_err.h> #include <QWidget> #include <QCloseEvent> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private slots: void on_pushButton_clicked(); // slot that manages file system info void on_pushButton_2_clicked(); // slot that manages formatting button void on_lineEdit_editingFinished(); // slot that manages path to device // slot that manages block size choice void on_comboBox_currentIndexChanged(int index); void on_pushButton_3_clicked(); // slot that manages program info void closeEvent(QCloseEvent*); // slot that disable closing the program while formatting void update(QString info); // slot that recieves string from formatting thread private: Ui::Widget *ui; FormatManager* fm = new FormatManager(); FileSystem* fs = new FileSystem(); FormattingThread fThread; };
f039dbe0f4a1173acb658bd0e936b3ce9b376976
[ "C++" ]
8
C++
Krealll/Ext4-Formatting-Utility
5d79430c58cced26929c178a3c66eb9621e80dfb
0ad3e2b953a131a4a9c45cffb2b4899a7c19de4f
refs/heads/main
<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Üye Ol</title> </head> <body> <div class="modal fade" id="uyelik" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header "> <h5 class="modal-title text-center" id="exampleModalLongTitle">ÜYE OL</h5> </div> <br> <div class="card-body"> <form method="post" name="dsadasda" id="uyelik_form"> <div class="form-label-group"> <label for="adsoyad">Ad Soyad</label> <input type="text" name="ad_soyad" class="form-control" id="ad_soyad" placeholder="Ad Soyad" required autofocus> </div> <br> <div class="form-label-group"> <label for="inputEmail">E-Posta</label> <input type="text" name="eposta" class="form-control" id="eposta" placeholder="E-Posta" required autofocus> </div> <br> <div class="form-label-group"> <label for="tcno">TC Kimlik Numarası</label> <input type="text" name="tc_no" class="form-control" id="tc_no" placeholder="TC Kimlik Numarası" required autofocus> </div> <br> <div class="form-label-group"> <label for="cinsiyet">Cinsiyet</label> <br> <label for="erkek">Erkek</label> <input type="radio" id="cinsiyet" name="cinsiyet" value="E"> <br> <label for="kadin">Kadın</label> <input type="radio" id="cinsiyet" name="cinsiyet" value="K"> </div> <br> <div class="form-label-group"> <label for="tcno">Telefon Numarası</label> <input type="text" name="tel_no" class="form-control" id="tel_no" placeholder="Telefon Numarası" required autofocus> </div> <br> <div class="form-label-group"> <label for="inputPassword">Şifre</label> <input type="password" name="sifre" class="form-control" id="sifre" placeholder="Şifre"> </div> <br> <input type="submit" class="btn btn-lg btn-primary btn-block text-uppercase" id="uye_btn" value="Üye Ol"> </form> </div> </div> </div> </div> <?php require_once("baglan.php"); if(isset($_POST['ad_soyad'])) { $ad_soyad=$_POST['ad_soyad']; $eposta = $_POST['eposta']; $cinsiyet=$_POST['cinsiyet']; $tc_no=$_POST['tc_no']; $tel_no=$_POST['tel_no']; $sifre=$_POST['sifre']; if( !$eposta|| !$sifre || !$ad_soyad || !$cinsiyet || !$tc_no || !$tel_no) { echo "<script>alert('Boş Geçilemez');</script>"; } else { $sorgu = $db->prepare("INSERT INTO kullanici(ad_soyad,eposta,cinsiyet,tc_no,tel_no,sifre) VALUES(?,?,?,?,?,?)"); $sorgu->bindParam(1, $ad_soyad, PDO::PARAM_STR); $sorgu->bindParam(2, $eposta, PDO::PARAM_STR); $sorgu->bindParam(3, $cinsiyet, PDO::PARAM_STR); $sorgu->bindParam(4, $tc_no, PDO::PARAM_STR); $sorgu->bindParam(5, $tel_no, PDO::PARAM_STR); $sorgu->bindParam(6, $sifre, PDO::PARAM_STR); //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu->execute()) { echo "<script>alert('Kaydınız Başarılı!');</script>"; //header("Location: index.php"); header("Refresh: 3; url=index.php"); } else { echo "<script>alert('Kayıt Başarısız!');</script>"; } } } ?> </body> </html> <!-- <div class="container d-flex justify-content-center"> <div class="card " style="width:50%;"> <div class="card-body"> </div> </div> </div> --><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Profil Güncelle</title> </head> <body> <?php include('ust_menu.php'); $sorgu =$db->prepare("SELECT * FROM kullanici WHERE id=".(int)$_GET['id']); $sorgu->execute(); $count = $sorgu->rowCount(); $sonuc = $sorgu->fetch(PDO::FETCH_ASSOC); ?> <div class="container d-flex justify-content-center"> <div class="card " style="width:50%;"> <div class="card-body"> <form method="post" id="guncelle_form"> <div class="form-label-group"> <label for="adsoyad">Ad Soyad</label> <input type="text" name="ad_soyad" class="form-control" id="ad_soyad" value="<?php echo $sonuc['ad_soyad'];?>" required autofocus> </div> <br> <div class="form-label-group"> <label for="inputEmail">E-Posta</label> <input type="text" name="eposta" class="form-control" id="eposta" value="<?php echo $sonuc['eposta'];?>" required autofocus> </div> <br> <div class="form-label-group"> <label for="tcno">Telefon Numarası</label> <input type="text" name="tel_no" class="form-control" id="tel_no" value="<?php echo $sonuc['tel_no'];?>" required autofocus> </div> <br> <div class="form-label-group"> <label for="inputPassword">Şifre</label> <input type="password" name="sifre" class="form-control" id="sifre" value="<?php echo $sonuc['sifre'];?>"> </div> <br> <input type="submit" class="btn btn-lg btn-primary btn-block text-uppercase" id="guncel_btn" value="Güncelle"> </form> </div> </div> </div> <?php if($_POST) { //$_SESSION['user_id'] = $row['id']; $id = $_SESSION['user_id']; $ad_soyad=$_POST['ad_soyad']; $eposta=$_POST['eposta']; $tel_no=$_POST['tel_no']; $sifre=$_POST['sifre']; if(!$ad_soyad|| !$eposta|| !$tel_no|| !$sifre) { echo "<script>alert('Boş Bırakılmış Alan!');</script>"; } else { $sorgu = $db->prepare("UPDATE kullanici SET ad_soyad = ?, eposta = ?, tel_no= ? , sifre = ? WHERE id = ?"); $sorgu->bindParam(1, $ad_soyad); $sorgu->bindParam(2, $eposta); $sorgu->bindParam(3, $tel_no); $sorgu->bindParam(4, $sifre); $sorgu->bindParam(5, $id); if($sorgu->execute()) { echo "<script>alert('Güncelleme Başarılı!');</script>"; header("Location: profil.php"); } else { echo "<script>alert('Güncelleme Başarısız!');</script>"; } } } ?> </body> </html><file_sep><?php ob_start(); //error_reporting(0); ?> <!DOCTYPE html> <html lang="tr"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Seferler</title> </head> <body> <?php include('yonetim_menu.php'); include('baglan.php'); ?> <div class="container d-flex justify-content-center"> <div class="card" style="width:50%;"> <div class="card-body"> <div class="card-title bg-light text-dark"> <h1 class="modal-title text-center" id="exampleModalLongTitle">SEFER</h1> </div> <form method="post" id="sefer_form"> <div class="form-label-group"> <label for="kalkis">Kalkış Yeri</label> <select name="kalkis" id="kalkis" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM duraklar"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['durak_id']; $durak = $sonuc['adi']; echo "<option value=".$id.">".$durak."</option>"; } ?> </select> <?php } ?> </div> <div class="form-label-group"> <label for="varis">Varış Yeri</label> <select name="varis" id="varis" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM duraklar"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['durak_id']; $durak = $sonuc['adi']; echo "<option value=".$id.">".$durak."</option>"; } ?> </select> <?php } ?> </div> <br> <div class="form-label-group"> <label for="inputEmail">Kalkış Tarihi</label> <input type="datetime-local" class="form-control" name="k_tarih" id="k_tarih" value="2021-01-12T19:30" min="2021-00-07T00:00" max="2021-12-14T00:00" required autofocus> </div> <br> <div class="form-label-group"> <label for="date">Varış Tarihi</label> <input type="datetime-local" class="form-control" name="v_tarih" id="v_tarih" value="2021-01-12T19:30" min="2021-00-07T00:00" max="2021-12-14T00:00" required autofocus> </div> <br> <div class="form-label-group"> <label for="firma">Firma</label> <select name="firma" id="firma" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM firmalar"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['id']; $firma = $sonuc['firma_adi']; echo "<option value=".$id.">".$firma."</option>"; } ?> </select> <?php } ?> </div> <div class="form-label-group"> <label for="sorumlu">Personel</label> <select name="sorumlu" id="sorumlu" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM sorumlu"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['id']; $s_adi = $sonuc['sofor_adi']; //$s_adi2 $sonuc['sofor_adi']; //$d_muavin = $sonuc['d_muavin']; echo "<option value=".$id.">".$s_adi."</option>"; } ?> </select> <?php } ?> </div> <div class="form-label-group"> <label for="otobus">Otobüs</label> <select name="otobus" id="otobus" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM otobusler"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['id']; $otobus = $sonuc['marka_model']; $tip = $sonuc['tipi']; $plaka = $sonuc['plaka']; echo "<option value=".$id.">".$otobus." ".$tip." ".$plaka." </option>"; } ?> </select> <?php } ?> </div> <br> <div class="form-label-group"> <label for="fiyat">Fiyat</label> <input type="text" name="fiyat" id="fiyat" class="form-control" placeholder="Fiyat" required autofocus> </div> <br> <div class="form-label-group"> <label for="guzergah">Güzergah Durakları</label> <select name="guzergah" id="guzergah" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM guzergah"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['id']; $guzergah = $sonuc['guzergah_adi']; echo "<option value=".$id.">".$guzergah."</option>"; } ?> </select> <?php } ?> </div> <br> <br> <input type="submit" class="btn btn-lg btn-secondary btn-block text-uppercase" id="otobus_btn" value="Kaydet"> </form> </div> </div> </div> <?php if($_POST) { $kalkis=$_POST['kalkis']; $varis = $_POST['varis']; $k_tarih=$_POST['k_tarih']; $v_tarih=$_POST['v_tarih']; $firma=$_POST['firma']; $fiyat=$_POST['fiyat']; $otobus=$_POST['otobus']; $guzergah=$_POST['guzergah']; $sorumlu=$_POST['sorumlu']; if( !$kalkis|| !$varis || !$k_tarih || !$v_tarih || !$fiyat) { echo "<script>alert('Boş Geçilemez');</script>"; } else { $sorgu = $db->prepare("INSERT INTO seferler(kalkis,varis,k_tarih,v_tarih,fiyat,firma_id,guzergah_id,otobus_id,sorumlu_id) VALUES(?,?,?,?,?,?,?,?,?)"); $sorgu->bindParam(1, $kalkis, PDO::PARAM_STR); $sorgu->bindParam(2, $varis, PDO::PARAM_INT); $sorgu->bindParam(3, $k_tarih, PDO::PARAM_STR); $sorgu->bindParam(4, $v_tarih, PDO::PARAM_STR); $sorgu->bindParam(5, $fiyat, PDO::PARAM_STR); $sorgu->bindParam(6, $firma, PDO::PARAM_STR); $sorgu->bindParam(7, $guzergah, PDO::PARAM_STR); $sorgu->bindParam(8, $otobus, PDO::PARAM_STR); $sorgu->bindParam(9, $sorumlu, PDO::PARAM_STR); //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu->execute()) { echo "<script>alert('Sefer Kaydı Başarılı!');</script>"; //header('location:yonetim.php'); header("Refresh:1 ;url=yonetim.php"); } else { echo "<script>alert('Kayıt Başarısız!');</script>"; } } } ?> </body> </html> <?php ob_flush(); ?> <file_sep># otobus-bilet-satis<file_sep><?php error_reporting(0); ?> <!DOCTYPE html> <html lang="tr"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Güzergah Ekle</title> </head> <body> <?php include('yonetim_menu.php'); include('baglan.php'); ?> <div class="container d-flex justify-content-center"> <div class="card " style="width:50%;"> <div class="card-body"> <div class="card-title bg-light text-dark"> <h1 class="modal-title text-center" id="exampleModalLongTitle">GÜZERGAH</h1> </div> <form method="post" id="otobus_form"> <div class="form-label-group"> <label for="adsoyad">Güzergah Sayısı</label> <input type="text" name="g_sayi" id="g_sayi" class="form-control" id="marka_model" autofocus> <input type="submit" class="btn btn-lg btn-primary btn-block text-uppercase" value="Sayı Ekle"> </div> <br> <?php $sorgu =$db->prepare("SELECT * FROM duraklar"); $sorgu->execute(); $g_sayi = $_POST['g_sayi']; ?> <input type="hidden" name="count" value=<?php echo $g_sayi?>> <?php $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { for($i = 1; $i <= $g_sayi; $i++) { ?> <select class="form-select form-select-lg mb-3" name="guzergah-<?php echo $i?>" id="guzergah-<?php echo $i ?>" aria-label=".form-select-sm example" style="width :100%;"> <?php $sorgu =$db->prepare("SELECT * FROM duraklar"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { //$dizi = array($sonuc); $id = $sonuc['durak_id']; $durak = $sonuc['adi']; echo "<option value=".$durak.">".$durak."</option>"; } ?> </select> <?php } } } ?> <input type="submit" class="btn btn-lg btn-secondary btn-block text-uppercase" id="g_kaydet" name="g_kaydet" value="Kaydet"> </form> </div> </div> </div> <?php if(isset($_POST["g_kaydet"])) { $guzergah=""; for($i=1;$i<=$_POST['count'];$i++){ $guzergah.=$_POST['guzergah-'.$i]." - "; } //$guzergah=$_POST['guzergah']; $sorgu = $db->prepare("INSERT INTO guzergah(guzergah_adi) VALUES(?)"); $sorgu->bindParam(1, $guzergah, PDO::PARAM_STR); if($sorgu->execute()) { echo "<script>alert('Güzergah Kaydı Başarılı!');</script>"; //header('location:yonetim.php'); //header("Refresh:1 ;url=yonetim.php"); } else { echo "<script>alert('Kayıt Başarısız!');</script>"; } } ?> </body> </html><file_sep><?php /*for($i=1;$i<=5;$i++) { for($a=1;$a<=$i;$a++) { echo"*"; } echo"<br>"; } for($i=1;$i<=30;$i++) { for($a=1;$a<=$i;$a++) { echo $ } } */ ?> <?php ?><file_sep>-- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Anamakine: 127.0.0.1 -- Üretim Zamanı: 17 May 2021, 20:13:51 -- Sunucu sürümü: 10.4.18-MariaDB -- PHP Sürümü: 8.0.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Veritabanı: `otobus` -- -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `biletler` -- CREATE TABLE `biletler` ( `id` int(11) NOT NULL, `kullanici_id` int(11) DEFAULT NULL, `ad_soyad` varchar(250) DEFAULT NULL, `cinsiyet` enum('E','K') DEFAULT NULL, `eposta` varchar(250) DEFAULT NULL, `tc_no` varchar(11) DEFAULT NULL, `tel_no` varchar(13) DEFAULT NULL, `sefer_id` int(11) DEFAULT NULL, `guzergah_id` int(11) DEFAULT NULL, `koltuk_no` int(50) DEFAULT NULL, `durum` tinyint(4) DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `biletler` -- INSERT INTO `biletler` (`id`, `kullanici_id`, `ad_soyad`, `cinsiyet`, `eposta`, `tc_no`, `tel_no`, `sefer_id`, `guzergah_id`, `koltuk_no`, `durum`) VALUES (5, NULL, '<NAME>', 'E', '<EMAIL>', '14653145', '465444655', 25, NULL, 9, NULL), (20, NULL, 'aaa', 'E', 'aaa', '123', '123', 20, NULL, 10, NULL), (21, NULL, 'bb', 'E', 'aaabb', '123', '123', 20, NULL, 10, NULL), (22, NULL, 'Kerim', 'E', '<EMAIL>', '5555', '123', 20, NULL, 14, NULL), (23, NULL, '<NAME>', 'E', '<EMAIL>', '123456', '123456', 23, NULL, 29, NULL), (24, NULL, 'sss', 'E', 'ss', '123', '123', 25, NULL, 8, NULL), (25, NULL, 'deneme', 'K', 'deneme', '123', '123', 21, NULL, 10, NULL), (26, NULL, 'Kerim', 'K', 'deneme', '123', '123', 21, NULL, 10, NULL), (27, NULL, 'Kerim', 'K', 'deneme', '123', '1234', 21, NULL, 10, NULL), (28, NULL, 'aaa', 'E', 'aaa', 'aaaaa', 'aaaaaa', 20, NULL, 24, NULL), (32, NULL, 'aaa', 'E', 'aaa', '111', '11', 20, NULL, 8, NULL), (33, 7, NULL, 'E', '<EMAIL>', '2147483647', '5555555555', 20, NULL, 11, NULL), (34, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 20, NULL, 7, NULL), (35, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 25, NULL, 14, NULL), (36, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 24, NULL, 28, NULL), (37, NULL, 'satinalma', 'K', 'satinalma', '12353', '1235', 21, NULL, 25, NULL), (38, 95, 'Hakkı', 'E', '<EMAIL>', '222222222', '12345', 20, NULL, 26, NULL), (39, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 20, NULL, 13, NULL), (40, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 23, NULL, 10, NULL), (41, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 42, NULL, 30, NULL), (42, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 42, NULL, 38, NULL), (43, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 21, NULL, 12, NULL), (44, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 31, NULL, 10, NULL), (45, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 43, NULL, 17, NULL), (46, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 43, NULL, 20, NULL), (47, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 45, NULL, 12, NULL), (48, 7, 'ker', 'E', 'ker', '1111', '111', 18, NULL, 10, NULL), (49, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 25, NULL, 31, NULL), (50, NULL, 'awww', 'E', '<EMAIL>', '111111111', '11111111', 21, NULL, 9, NULL), (51, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 46, NULL, 19, 1), (52, NULL, '<NAME>', 'E', '<EMAIL>', '5555555555', '555555555', 46, NULL, 39, 1), (53, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 46, NULL, 7, 1), (54, 7, '<NAME>', 'E', '<EMAIL>', '2147483647', '5555555555', 46, NULL, 2, 1); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `duraklar` -- CREATE TABLE `duraklar` ( `durak_id` int(11) NOT NULL, `adi` varchar(75) DEFAULT NULL, `sehir_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `duraklar` -- INSERT INTO `duraklar` (`durak_id`, `adi`, `sehir_id`) VALUES (1, '<NAME>', 1), (8, '<NAME>', 2), (9, '<NAME>', 3), (10, '<NAME>', 4), (11, '<NAME>', 68), (12, '<NAME>', 5), (13, '<NAME>', 75), (14, '<NAME>', 8), (15, '<NAME>', 9), (16, 'Balıkesir(Ayvalık Otogarı)', 10), (17, '<NAME>', 10), (18, '<NAME>', 74), (19, '<NAME>', 72), (20, '<NAME>', 69), (21, '<NAME>', 11), (22, '<NAME>', 12), (23, '<NAME>', 13), (24, '<NAME>ı(Muğla)', 48), (25, '<NAME>', 14), (26, '<NAME>', 15), (27, '<NAME>', 17), (28, '<NAME>', 18), (29, '<NAME>', 19), (30, '<NAME>', 20), (31, '<NAME>', 21), (32, '<NAME>', 81), (33, '<NAME>', 22), (34, '<NAME>', 23), (35, '<NAME>ı', 24), (36, 'Erzurum Otogarı', 25), (37, 'Eskişehir Otogarı', 26), (38, 'GaziAntep Otogarı', 27), (39, 'Gelibolu Otogarı(Çanakkale)', 17), (40, 'Giresun Otogarı', 28), (41, 'Gümüşhane Otogarı', 29), (42, 'Hakkari Otogarı', 30), (43, 'Hatay Otogarı', 31), (44, 'Iğdır Otogarı', 76), (45, 'Isparta Otogarı', 32), (46, 'İstanbul(Dudullu Ataşehir Terminali)', 34), (47, 'İstanbul(Harem Otogarı)', 34), (48, 'İstanbul Esenler Otogarı', 34), (49, 'İstanbul(Alibeyköy Terminali)', 34), (50, 'İzmir Otogarı', 35), (51, 'Kahramanmaraş Otogarı', 46), (52, 'Karabük Otogarı', 78), (53, 'Karaman Otogarı', 70), (54, 'Kars Otogarı', 36), (55, 'Kastamonu Otogarı', 37), (56, 'Kayseri Otogarı', 38), (57, 'Kırıkkale Otogarı', 71), (58, 'Kırklareli Otogarı', 39), (59, 'Kırşehir Otogarı', 40), (60, 'Kocaeli Otogarı', 41), (61, 'Konya Otogarı', 42), (62, '<NAME>', 43), (63, '<NAME>ı', 44), (64, '<NAME>', 45), (65, '<NAME>', 47), (66, '<NAME>', 48), (67, '<NAME>ı', 49), (68, '<NAME>ı', 50), (69, '<NAME>ı', 51), (70, '<NAME>', 52), (71, '<NAME>', 80), (72, '<NAME>', 53), (73, '<NAME>', 54), (74, '<NAME>', 55), (75, '<NAME>', 56), (76, '<NAME>', 57), (77, '<NAME>', 58), (78, '<NAME>ı', 63), (79, '<NAME>ı', 73), (80, '<NAME>', 59), (81, '<NAME>', 60), (82, '<NAME>', 61), (83, '<NAME>', 62), (84, '<NAME>', 64), (85, '<NAME>', 65), (86, '<NAME>', 77), (87, '<NAME>ı', 66), (88, '<NAME>ı', 67), (89, '<NAME>ı', 16), (90, 'Ankara Otogari', 6); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `firmalar` -- CREATE TABLE `firmalar` ( `id` int(11) NOT NULL, `firma_adi` text DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `firmalar` -- INSERT INTO `firmalar` (`id`, `firma_adi`) VALUES (1, 'Kamilkoç'), (2, 'Metro'), (3, 'Pamukkale'), (4, 'Nilüfer'), (5, '<NAME>'), (6, 'E<NAME>'), (7, '<NAME>'), (8, '<NAME>'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `guzergah` -- CREATE TABLE `guzergah` ( `id` int(11) NOT NULL, `guzergah_adi` text DEFAULT NULL, `sehir_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `guzergah` -- INSERT INTO `guzergah` (`id`, `guzergah_adi`, `sehir_id`) VALUES (1, 'Bursa Otogarı - Bandırma Otogarı -Çanakkale Otogarı ', 16), (2, 'Bursa Otogarı - Yalova Otogarı - Kocaeli Otogarı -İstanbul Otogarı ', 16), (3, 'Bursa Otogarı - Bilecik Otogarı - Eskişehir Otogarı - Ankara Otogarı', 16), (4, 'Bursa Otogarı - İnegöl Otogarı - Kütahya Otogarı ', 16), (5, 'Bursa Otogarı - Balıkesir Otogarı - Manisa Otogarı - İzmir Otogarı ', 16), (6, 'Bursa Otogarı - Eskişehir Otogarı - Afyon Otogarı - Burdur Otogarı - Antalya Otogarı', 16), (7, 'Bursa Otogarı - Eskişehir Otogarı - Kütahya Otogarı - Afyon Otogarı - Ispart Otogarı', 16), (8, 'Ankara Otogarı-Eskişehir Otogarı - İstanbul', 6), (64, 'Ardahan -Amasya -', NULL), (65, 'Adana - Artvin - Bartın - ', NULL), (66, 'Adana - Artvin - Bartın - ', NULL), (67, 'Adıyaman - Amasya - Ardahan - Burdur - Çankırı - ', NULL), (68, 'Ağrı - Adana - Amasya - Adana - Bolu - Adana - ', NULL), (69, 'Ankara - Eskişehir - Bilecik - Bursa - Çanakkale - ', NULL), (70, 'Adana - Adana - Adana - Adana - Adana - ', NULL), (71, 'İstanbul - Kocaeli - Bursa - Balıkesir - Manisa - İzmir - ', NULL); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `kullanici` -- CREATE TABLE `kullanici` ( `id` int(11) NOT NULL, `ad_soyad` varchar(50) NOT NULL, `eposta` varchar(100) NOT NULL, `cinsiyet` enum('E','K') NOT NULL, `tc_no` varchar(11) NOT NULL, `k_rol` enum('admin','üye') NOT NULL DEFAULT 'üye', `tel_no` varchar(13) NOT NULL, `sifre` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `kullanici` -- INSERT INTO `kullanici` (`id`, `ad_soyad`, `eposta`, `cinsiyet`, `tc_no`, `k_rol`, `tel_no`, `sifre`) VALUES (7, '<NAME>', '<EMAIL>', 'E', '1111111111', 'admin', '5555555555', '1234'), (95, 'Hakkı', '<EMAIL>', 'E', '222222222', 'üye', '12345', '1234'), (96, '<NAME>', '<EMAIL>', 'E', '1111111111', 'üye', '0555555499', '1234'), (99, 'Mehmet', '<EMAIL>', 'E', '', 'üye', '', '1234'), (100, '<NAME>', '<EMAIL>', 'E', '11111111111', 'üye', '55555555555', '1234'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `muavin` -- CREATE TABLE `muavin` ( `id` int(11) NOT NULL, `a_muavin` varchar(100) DEFAULT NULL, `d_muavin` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `muavin` -- INSERT INTO `muavin` (`id`, `a_muavin`, `d_muavin`) VALUES (1, 'Recep Akdağ', 'Şafak Gündoğdu'), (3, '<NAME>', '<NAME>'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `otobusler` -- CREATE TABLE `otobusler` ( `id` int(11) NOT NULL, `marka_model` varchar(100) DEFAULT NULL, `cikis_yili` smallint(4) DEFAULT NULL, `tipi` enum('2+1','2+2') DEFAULT NULL, `kapasite` int(11) DEFAULT NULL, `plaka` varchar(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `otobusler` -- INSERT INTO `otobusler` (`id`, `marka_model`, `cikis_yili`, `tipi`, `kapasite`, `plaka`) VALUES (1, '<NAME>', 2008, '2+1', 40, '16OTB68'), (3, 'Mercedes Tourismo', 2012, '2+2', 45, '17OTB68'), (4, 'Setra Neoplan', 2009, '2+1', 40, '34TCO88'), (12, '<NAME>', 2010, '2+1', 40, '34TCB44'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `seferler` -- CREATE TABLE `seferler` ( `id` int(11) NOT NULL, `otobus_id` int(11) DEFAULT NULL, `kalkis` int(11) DEFAULT NULL, `varis` int(11) DEFAULT NULL, `k_tarih` datetime DEFAULT NULL, `v_tarih` datetime DEFAULT NULL, `fiyat` int(11) DEFAULT NULL, `firma_id` int(11) DEFAULT NULL, `sorumlu_id` int(11) DEFAULT NULL, `guzergah_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `seferler` -- INSERT INTO `seferler` (`id`, `otobus_id`, `kalkis`, `varis`, `k_tarih`, `v_tarih`, `fiyat`, `firma_id`, `sorumlu_id`, `guzergah_id`) VALUES (18, 3, 27, 89, '2021-01-12 19:30:00', '2021-01-13 19:30:00', 65, 3, 2, 1), (20, 1, 48, 90, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 100, 1, 1, 1), (21, 4, 48, 90, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 95, 4, 1, 8), (22, 3, 48, 89, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 85, 5, 2, 1), (23, 4, 48, 90, '2021-01-14 22:30:00', '2021-01-12 19:30:00', 100, 2, 3, 1), (24, 4, 48, 90, '2021-01-20 22:30:00', '2021-01-12 19:30:00', 85, 5, 1, 8), (25, 1, 48, 90, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 100, 1, 1, 8), (26, 3, 8, 1, '2021-04-21 00:28:56', '2021-04-21 00:28:56', 50, 7, 4, 65), (27, 3, 8, 9, '2021-04-25 16:44:27', '2021-04-25 16:44:28', 75, 5, NULL, NULL), (28, 3, 89, 1, '2021-04-25 16:45:43', '2021-04-25 16:45:43', 50, 7, NULL, NULL), (29, 1, 89, 27, '2021-04-25 16:45:44', '2021-04-25 16:45:44', 60, 6, NULL, NULL), (30, 1, 89, 27, '2021-04-25 16:49:27', '2021-04-25 16:49:27', 50, 3, NULL, NULL), (31, 12, 89, 27, '2021-04-26 02:21:54', '2021-04-26 02:21:55', 60, 3, 3, 5), (32, NULL, 89, 90, '2021-04-26 16:38:11', '2021-04-26 16:38:11', 70, 7, 2, 6), (33, 1, 1, 1, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 100, 1, 1, 1), (34, 1, 10, 12, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 50, 1, 1, 1), (35, 1, 10, 12, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 100, 1, 1, 1), (36, 1, 1, 10, '2021-05-02 18:34:38', '2021-05-02 18:34:38', 75, 7, 2, 5), (37, 1, 90, 27, '2021-01-12 19:30:00', '2021-01-12 23:30:00', 100, 3, 1, 69), (38, 4, 90, 27, '2021-05-02 19:30:00', '2021-05-02 23:30:00', 100, 3, 1, 69), (39, 1, 1, 1, '2021-05-05 19:30:00', '2021-05-05 19:30:00', 100, 1, 1, 70), (40, 1, 1, 1, '2021-01-12 19:30:00', '2021-01-12 19:30:00', 444, 1, 1, 1), (41, 1, 90, 27, '2021-05-03 19:30:00', '2021-05-03 21:30:00', 100, 3, 1, 69), (42, 3, 89, 27, '2021-05-09 20:30:00', '2021-05-09 23:30:00', 95, 3, 1, 1), (43, 4, 48, 90, '2021-05-10 19:30:00', '2021-05-11 19:30:00', 100, 3, 1, 8), (44, 1, 27, 48, '2021-05-10 16:30:00', '2021-05-10 19:30:00', 100, 6, 2, 8), (45, 4, 48, 50, '2021-05-10 19:30:00', '2021-05-10 02:30:00', 120, 5, 3, 71), (46, 3, 48, 50, '2021-05-16 19:30:00', '2021-05-16 19:30:00', 100, 6, 1, 71); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `sehirler` -- CREATE TABLE `sehirler` ( `sehir_id` int(11) NOT NULL, `sehir_adi` text DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `sehirler` -- INSERT INTO `sehirler` (`sehir_id`, `sehir_adi`) VALUES (1, 'Adana'), (2, 'Adıyaman'), (3, 'Afyon'), (4, 'Ağrı'), (5, 'Amasya'), (6, 'Ankara'), (7, 'Antalya'), (8, 'Artvin'), (9, 'Aydın'), (10, 'Balıkesir'), (11, 'Bilecik'), (12, 'Bingöl'), (13, 'Bitlis'), (14, 'Bolu'), (15, 'Burdur'), (16, 'Bursa'), (17, 'Çanakkale'), (18, 'Çankırı'), (19, 'Çorum'), (20, 'Denizli'), (21, 'Diyarbakır'), (22, 'Edirne'), (23, 'Elazığ'), (24, 'Erzincan'), (25, 'Erzurum'), (26, 'Eskişehir'), (27, 'Gaziantep'), (28, 'Giresun'), (29, 'Gümüşhane'), (30, 'Hakkari'), (31, 'Hatay'), (32, 'Isparta'), (33, 'Mersin'), (34, 'İstanbul'), (35, 'İzmir'), (36, 'Kars'), (37, 'Kastamonu'), (38, 'Kayseri'), (39, 'Kırklareli'), (40, 'Kırşehir'), (41, 'Kocaeli'), (42, 'Konya'), (43, 'Kütahya'), (44, 'Malatya'), (45, 'Manisa'), (46, 'Kahramanmaraş'), (47, 'Mardin'), (48, 'Muğla'), (49, 'Muş'), (50, 'Nevşehir'), (51, 'Niğde'), (52, 'Ordu'), (53, 'Rize'), (54, 'Sakarya'), (55, 'Samsun'), (56, 'Siirt'), (57, 'Sinop'), (58, 'Sivas'), (59, 'Tekirdağ'), (60, 'Tokat'), (61, 'Trabzon'), (62, 'Tunceli'), (63, 'Şanlıurfa'), (64, 'Uşak'), (65, 'Van'), (66, 'Yozgat'), (67, 'Zonguldak'), (68, 'Aksaray'), (69, 'Bayburt'), (70, 'Karaman'), (71, 'Kırıkkale'), (72, 'Batman'), (73, 'Şırnak'), (74, 'Bartın'), (75, 'Ardahan'), (76, 'Iğdır'), (77, 'Yalova'), (78, 'Karabük'), (79, 'Kilis'), (80, 'Osmaniye'), (81, 'Düzce'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `sorumlu` -- CREATE TABLE `sorumlu` ( `id` int(11) NOT NULL, `sofor_adi` varchar(50) DEFAULT NULL, `sofor_adi2` varchar(50) DEFAULT NULL, `firma_id` int(11) DEFAULT NULL, `muavin_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `sorumlu` -- INSERT INTO `sorumlu` (`id`, `sofor_adi`, `sofor_adi2`, `firma_id`, `muavin_id`) VALUES (1, '<NAME>', '<NAME>', 1, 1), (2, '<NAME>', NULL, 3, 1), (3, '<NAME>', NULL, 3, 1), (4, 'Murat', NULL, 2, 1); -- -- Dökümü yapılmış tablolar için indeksler -- -- -- Tablo için indeksler `biletler` -- ALTER TABLE `biletler` ADD PRIMARY KEY (`id`), ADD KEY `kullanici_id` (`kullanici_id`), ADD KEY `sefer_id` (`sefer_id`); -- -- Tablo için indeksler `duraklar` -- ALTER TABLE `duraklar` ADD PRIMARY KEY (`durak_id`) USING BTREE, ADD KEY `sehir_id` (`sehir_id`); -- -- Tablo için indeksler `firmalar` -- ALTER TABLE `firmalar` ADD PRIMARY KEY (`id`); -- -- Tablo için indeksler `guzergah` -- ALTER TABLE `guzergah` ADD PRIMARY KEY (`id`), ADD KEY `sehir_id` (`sehir_id`); -- -- Tablo için indeksler `kullanici` -- ALTER TABLE `kullanici` ADD PRIMARY KEY (`id`); -- -- Tablo için indeksler `muavin` -- ALTER TABLE `muavin` ADD PRIMARY KEY (`id`); -- -- Tablo için indeksler `otobusler` -- ALTER TABLE `otobusler` ADD PRIMARY KEY (`id`); -- -- Tablo için indeksler `seferler` -- ALTER TABLE `seferler` ADD PRIMARY KEY (`id`), ADD KEY `otobus_id` (`otobus_id`), ADD KEY `firma_id` (`firma_id`), ADD KEY `sorumlu_id` (`sorumlu_id`), ADD KEY `kalkis` (`kalkis`), ADD KEY `varis` (`varis`), ADD KEY `guzergah_id` (`guzergah_id`); -- -- Tablo için indeksler `sehirler` -- ALTER TABLE `sehirler` ADD PRIMARY KEY (`sehir_id`); -- -- Tablo için indeksler `sorumlu` -- ALTER TABLE `sorumlu` ADD PRIMARY KEY (`id`), ADD KEY `firma_id` (`firma_id`), ADD KEY `muavin_id` (`muavin_id`); -- -- Dökümü yapılmış tablolar için AUTO_INCREMENT değeri -- -- -- Tablo için AUTO_INCREMENT değeri `biletler` -- ALTER TABLE `biletler` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=55; -- -- Tablo için AUTO_INCREMENT değeri `duraklar` -- ALTER TABLE `duraklar` MODIFY `durak_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=91; -- -- Tablo için AUTO_INCREMENT değeri `firmalar` -- ALTER TABLE `firmalar` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- Tablo için AUTO_INCREMENT değeri `guzergah` -- ALTER TABLE `guzergah` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=72; -- -- Tablo için AUTO_INCREMENT değeri `kullanici` -- ALTER TABLE `kullanici` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=101; -- -- Tablo için AUTO_INCREMENT değeri `muavin` -- ALTER TABLE `muavin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Tablo için AUTO_INCREMENT değeri `otobusler` -- ALTER TABLE `otobusler` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- Tablo için AUTO_INCREMENT değeri `seferler` -- ALTER TABLE `seferler` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=47; -- -- Tablo için AUTO_INCREMENT değeri `sehirler` -- ALTER TABLE `sehirler` MODIFY `sehir_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=82; -- -- Tablo için AUTO_INCREMENT değeri `sorumlu` -- ALTER TABLE `sorumlu` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- Dökümü yapılmış tablolar için kısıtlamalar -- -- -- Tablo kısıtlamaları `biletler` -- ALTER TABLE `biletler` ADD CONSTRAINT `biletler_ibfk_1` FOREIGN KEY (`kullanici_id`) REFERENCES `kullanici` (`id`), ADD CONSTRAINT `biletler_ibfk_2` FOREIGN KEY (`sefer_id`) REFERENCES `seferler` (`id`); -- -- Tablo kısıtlamaları `duraklar` -- ALTER TABLE `duraklar` ADD CONSTRAINT `duraklar_ibfk_1` FOREIGN KEY (`sehir_id`) REFERENCES `sehirler` (`sehir_id`); -- -- Tablo kısıtlamaları `guzergah` -- ALTER TABLE `guzergah` ADD CONSTRAINT `guzergah_ibfk_1` FOREIGN KEY (`sehir_id`) REFERENCES `sehirler` (`sehir_id`); -- -- Tablo kısıtlamaları `seferler` -- ALTER TABLE `seferler` ADD CONSTRAINT `seferler_ibfk_1` FOREIGN KEY (`kalkis`) REFERENCES `duraklar` (`durak_id`), ADD CONSTRAINT `seferler_ibfk_2` FOREIGN KEY (`varis`) REFERENCES `duraklar` (`durak_id`), ADD CONSTRAINT `seferler_ibfk_3` FOREIGN KEY (`otobus_id`) REFERENCES `otobusler` (`id`), ADD CONSTRAINT `seferler_ibfk_4` FOREIGN KEY (`firma_id`) REFERENCES `firmalar` (`id`), ADD CONSTRAINT `seferler_ibfk_5` FOREIGN KEY (`sorumlu_id`) REFERENCES `sorumlu` (`id`), ADD CONSTRAINT `seferler_ibfk_6` FOREIGN KEY (`guzergah_id`) REFERENCES `guzergah` (`id`); -- -- Tablo kısıtlamaları `sorumlu` -- ALTER TABLE `sorumlu` ADD CONSTRAINT `sorumlu_ibfk_1` FOREIGN KEY (`firma_id`) REFERENCES `firmalar` (`id`), ADD CONSTRAINT `sorumlu_ibfk_2` FOREIGN KEY (`muavin_id`) REFERENCES `muavin` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><!DOCTYPE html> <html lang="tr"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap" rel="stylesheet"> <title>Bilet</title> </head> <body> <?php ?> <?php require_once('baglan.php'); include('ust_menu.php'); $biletsec = $_SESSION['biletsec']; $sorgu = $db->prepare("SELECT s.id, fiyat, k_tarih, firma_adi, tipi, kapasite, (SELECT guzergah_adi FROM guzergah WHERE id=s.guzergah_id)guzergah_ad, (SELECT adi FROM duraklar WHERE durak_id=s.kalkis)kalkis_adi, (SELECT adi FROM duraklar WHERE durak_id=s.varis)varis_adi FROM seferler s INNER JOIN firmalar f ON s.firma_id = f.id INNER JOIN otobusler o ON s.otobus_id = o.id WHERE s.id =" . $biletsec); $sorgu->execute(); $count = $sorgu->rowCount(); $row = $sorgu->fetch(PDO::FETCH_ASSOC); $gelen_veri = $_SESSION['name']; $posta_veri = $_SESSION['postae']; $cins_veri = $_SESSION['cinsiyeti']; $tc_veri = $_SESSION['tc_num']; $tel_veri = $_SESSION['tel_num']; $koltuk = $_SESSION['koltuk']; $k_tarih = $row['k_tarih']; $fiyat = $row['fiyat']; $kalkis_adi = $row['kalkis_adi']; $varis_adi = $row['varis_adi']; $firma_adi = $row['firma_adi']; //$tipi = $row['tipi']; $kapasite = $row['kapasite']; $guzergah = $row['guzergah_ad']; //var_dump($gelen_veri,$posta_veri,$cins_veri,$tc_veri,$tel_veri); ?> <div class="container"> <div class="row-12"> <div class="col-md-3 mt-5"> <div class="container d-flex justify-content-center"> <div class="card" style="width:40%; border-radius: 10px;"> <div class="card-body"> <div class="card-title bg-light text-dark" style="border-radius: 10px;"> <h1 class="modal-title text-center" id="exampleModalLongTitle">BİLET BİLGİSİ</h1> <h3 class="modal-title text-center" id="exampleModalLongTitle"><?php echo $firma_adi?></h3> </div> <div class="row"> <div class="col-6 " style="margin-left:3%;"> <label for="inputEmail" class="text-center">TC Kimlik</label> <p><?php echo $tc_veri ?></p> <label for="adsoyad">Ad Soyad</label> <p><?php echo $gelen_veri ?></p> <label for="inputEmail" class="text-center">E-Posta</label> <p><?php echo $posta_veri ?></p> <label for="Cinsiyet" class="text-center">Cinsiyet</label> <p><?php if ($cins_veri == "K") { echo 'Kadın'; } else { echo 'Erkek'; } ?></p> <label for="telefon" class="text-center">Telefon Numarası</label> <p><?php echo $tel_veri ?></p> </div> <div class="col-5" style="margin-left:5%;"> <label for="inputEmail" class="text-center">Kalkış-Varış</label> <p><?php echo $kalkis_adi." ".$varis_adi ?></p> <label for="adsoyad">Koltuk No</label> <p><?php echo $koltuk ?></p> <label for="inputEmail" class="text-center">Kalkış Tarihi</label> <p><?php echo $k_tarih?> </p> <label for="adsoyad">Fiyat</label> <p><?php echo $fiyat?>₺</p> </div> <label for="guzergah" class="text-center wd-100">Güzergah</label> <p class="text-center"><?php echo $guzergah?></p> </div> <a href="index.php" class="btn btn-lg btn-secondary btn-block text-uppercase" id="satin_al" name="satin_al">Tamam</a> </div> </div> </div> </div> </div> </div> </body> </html><file_sep><?php ob_start(); error_reporting(0); ?> <!DOCTYPE html> <html lang="tr"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Otobüs</title> </head> <body> <?php include('yonetim_menu.php'); ?> <div class="container d-flex justify-content-center"> <div class="card " style="width:50%;"> <div class="card-body"> <div class="card-title bg-light text-dark"> <h1 class="modal-title text-center" id="exampleModalLongTitle">OTOBÜSLER</h1> </div> <form method="post" id="otobus_form"> <div class="form-label-group"> <label for="adsoyad">Marka Model</label> <input type="text" name="marka_model" class="form-control" id="marka_model" placeholder="Marka Model" required autofocus> </div> <br> <div class="form-label-group"> <label for="inputEmail">Cıkış Yılı</label> <input type="text" name="cikis_yili" class="form-control" id="cikis_yili" placeholder="Cıkış Yılı" required autofocus> </div> <br> <div class="form-label-group"> <label for="tipi">Otobüs Tipi</label> <br> <label for="2+1">2+1</label> <input type="radio" id="tipi" name="tipi" value="2+1"> <br> <label for="kadin">2+2</label> <input type="radio" id="tipi" name="tipi" value="2+2"> </div> <br> <div class="form-label-group"> <label for="tcno">Kapasite</label> <input type="text" name="kapasite" class="form-control" id="kapasite" placeholder="Kapasite" required autofocus> </div> <br> <div class="form-label-group"> <label for="tcno">Plaka</label> <input type="text" name="plaka" class="form-control" id="plaka" placeholder="Plaka" required autofocus> </div> <br> <br> <input type="submit" class="btn btn-lg btn-secondary btn-block text-uppercase" id="otobus_btn" value="Kaydet"> </form> </div> </div> </div> <?php require_once("baglan.php"); if($_POST) { $marka_model=$_POST['marka_model']; $cikis_yili = $_POST['cikis_yili']; $tipi=$_POST['tipi']; $kapasite=$_POST['kapasite']; $plaka=$_POST['plaka']; if( !$marka_model|| !$cikis_yili || !$tipi || !$kapasite || !$plaka) { echo "<script>alert('Boş Geçilemez');</script>"; } else { $sorgu = $db->prepare("INSERT INTO otobusler(marka_model,cikis_yili,tipi,kapasite,plaka) VALUES(?,?,?,?,?)"); $sorgu->bindParam(1, $marka_model, PDO::PARAM_STR); $sorgu->bindParam(2, $cikis_yili, PDO::PARAM_INT); $sorgu->bindParam(3, $tipi, PDO::PARAM_STR); $sorgu->bindParam(4, $kapasite, PDO::PARAM_STR); $sorgu->bindParam(5, $plaka, PDO::PARAM_STR); //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu->execute()) { echo "<script>alert('Kaydınız Başarılı!');</script>"; // header('location:index.php'); header("Refresh:1 ; url=yonetim.php"); } else { echo "<script>alert('Kayıt Başarısız!');</script>"; } } } ?> </body> </html> <?php ob_flush(); ?> <file_sep><!DOCTYPE html> <html lang="tr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap" rel="stylesheet"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>İstanbul-İzmir</title> </head> <body> <?php error_reporting(0); require_once('baglan.php'); include('ust_menu.php'); include('giris.php'); include('uye_ol.php'); include('tarih.php'); $sorgu = $db->prepare("SELECT s.id, fiyat, k_tarih, firma_adi, tipi, kapasite, (SELECT adi FROM duraklar WHERE durak_id=s.kalkis)kalkis_adi, (SELECT adi FROM duraklar WHERE durak_id=s.varis)varis_adi FROM seferler s INNER JOIN firmalar f ON s.firma_id = f.id INNER JOIN otobusler o ON s.otobus_id = o.id WHERE kalkis = 48 AND varis = 50"); $sorgu->execute(); $count = $sorgu->rowCount(); //$row = $sorgu->fetch(PDO::FETCH_ASSOC); //$id = $row['id']; //$s_sayi = $sorgu->rowCount(); ?> <?php $a_sorgu = $db->prepare("SELECT * FROM biletler"); $a_sorgu->execute(); $count = $a_sorgu->rowCount(); $row = $a_sorgu->fetch(PDO::FETCH_ASSOC); $bosmu = $row['durum']; ?> <?php $i = 0; if ($sorgu->rowCount() <= 0) { echo "<script>alert('İstediğiniz Kriterde Sefer Bulunamadı!');</script>"; header("Refresh: 1; url=index.php"); } if ($sorgu->rowCount() > 0) { while ($row = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $row['id']; $k_tarih = $row['k_tarih']; $fiyat = $row['fiyat']; $kalkis_adi = $row['kalkis_adi']; $varis_adi = $row['varis_adi']; $firma_adi = $row['firma_adi']; $tipi = $row['tipi']; $kapasite = $row['kapasite']; $guzergahlar = $row['guzergahlar']; $i++; ?> <br> <div class="container"> <div class="bilet-sec" id="bilet-sec-<?php echo $id ?>"> <div class="row"> <div class="col"> <label for="firma" type="text" style="font-size:150%" class="mt-5"><?= $firma_adi ?></label> </div> <div class="col"> <label for="firma" style="font-size:130%" class="mt-5">Sefer Tarihi</label> <label for="firma" class="mt-3"><?= $k_tarih ?></label> </div> <div class="col" style="font-size:85%"> <label for="tipi" style="font-size:150%"><?= $tipi ?></label> <br> <label for="firma"><?= $kalkis_adi ?></label> <br> <label for="" style="font-size:150%">></label> <br> <label for="firma"><?= $varis_adi ?></label> <br> </div> <div class="col"> <label for="firma" style="font-size:150%" class="mt-5"><?= $fiyat ?>₺</label> </div> <div class="col"> <a href="#<?php echo $id ?>" name="count" value=<?php echo $id ?> class="btn btn-danger mt-5 koltuk-sec" id="koltuk-sec_<?php echo $id ?>" onclick="koltuk_sec(<?php echo $id; ?>)">KOLTUK SEÇ</a> <!--<input type="submit" class="btn btn-danger mt-5 koltuk-sec" value="KOLTUK SEÇ" id="koltuk-sec_<?php echo $id ?>" onclick="koltuk_sec(<?php echo $id; ?>)">--> <a href="#" class="btn btn-secondary mt-5 koltuk-kapa buton-ayar dipslay_none" id="koltuk-kapa_<?php echo $id ?>" onclick="koltuk_kapa(<?php echo $id; ?>)">KAPAT</a> </div> <hr style="width: 90%; margin-left:4%;"> <form action="bilet_al.php" method="get"> <label class="guzergah dipslay_none" style="margin-top:0%; color:black;" id="guzergah_<?php echo $id ?>"> <?php echo $guzergahlar ?> </label> <div class="row"> <div class="otobus dipslay_none col-sm-8" style="margin-top:0%" id="otobus_<?php echo $id ?>"> <div class="koltuklar"> <table> <?php $b_sorgu = $db->prepare("SELECT * FROM biletler where sefer_id =" . $id); $b_sorgu->execute(); $koltuklar = []; while ($row2 = $b_sorgu->fetch(PDO::FETCH_ASSOC)) { $koltuklar[] = $row2['koltuk_no']; } for ($a = 1; $a <= $kapasite; $a++) { ?> <input type="text" hidden name="count" type="text" value="<?php echo $id ?>"> <?php if (in_array($a, $koltuklar)) { ?> <?php if ($tipi == '2+1') { if ($a == 9) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 14) { ?> <br> <?php } if ($a == 22) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 27) { ?> <br> <div class="araci" style="margin-top: 10%; "> </div> <?php } } if ($tipi == '2+2') { if ($a == 7) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 12) { ?> <br> <?php } if ($a == 18) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 23) { ?> <br> <div class="araci" style="margin-top: 5%; "> </div> <?php } if ($a == 34) { ?> <br> <?php } } ?> <tr> <input disabled type="submit" style="width: 43px;" name="koltuk" class="k_<?php echo $a ?> btn btn-danger" value="<?php echo $a ?>"> </tr> <?php } else { ?> <?php if ($tipi == '2+1') { if ($a == 9) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 14) { ?> <br> <?php } if ($a == 22) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 27) { ?> <br> <div class="araci" style="margin-top: 10%; "> </div> <?php } } if ($tipi == '2+2') { if ($a == 7) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 12) { ?> <br> <?php } if ($a == 18) { ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php } if ($a == 23) { ?> <br> <div class="araci" style="margin-top: 5%; "> </div> <?php } if ($a == 34) { ?> <br> <?php } } ?> <tr> <input type="submit" name="koltuk" style="width: 43px;" class="k_<?php echo $a ?> btn btn-primary" value="<?php echo $a ?>"> </tr> <?php } ?> <?php } ?> </table> </div> </div> </form> <div class="col-sm-2 " style="margin-top:15%;"> <div disabled style="background-color: #d9534f; width:50px; height:50px; margin-top:-75%; margin-left:15%;" class="bos dipslay_none" id="bos_<?php echo $id ?>"> <label style="margin-left:120%; margin-top:20%;">DOLU</label> </div> <div disabled style="background-color: #0275d8; width:50px; height:50px;margin-left:15%; margin-top:5%;" class="dolu dipslay_none" id="dolu_<?php echo $id ?>"> <label style="margin-left:120%; margin-top:20%;">BOŞ</label> </div> <img src="img/steering-wheel.png" class="direksiyon" alt="" style="margin-left: -1000%; margin-top:-30%;"> </div> <div class="col-sm-1 dvm-btn dipslay_none" id="dvm-btn_<?php echo $id ?> "> </div> </div> </div> </div> </div> <br> <?php } } ?> </form> <script> /*$('.koltuk-kapa').attr('style','display:none'); $('#koltuk-kapa_'+id).attr('style','display:none');*/ $(".koltuk-kapa").hide(); $(".dvm-btn").hide(); function koltuk_sec(id) { $('.otobus').addClass('dipslay_none'); $('.otobus').removeClass('dipslay_block'); $('#otobus_' + id).addClass('dipslay_block'); $('.guzergah').addClass('dipslay_none'); $('.guzergah').removeClass('dipslay_block'); $('#guzergah_' + id).addClass('dipslay_block'); $('.dvm-btn').addClass('dipslay_none'); $('.dvm-btn').removeClass('dipslay_block'); $('#dvm-btn_' + id).addClass('dipslay_block'); $('.bos').addClass('dipslay_none'); $('.bos').removeClass('dipslay_block'); $('#bos_' + id).addClass('dipslay_block'); $('.dolu').addClass('dipslay_none'); $('.dolu').removeClass('dipslay_block'); $('#dolu_' + id).addClass('dipslay_block'); $('.bilet-sec').attr('style', 'height:120px'); $('#bilet-sec-' + id).attr('style', 'height:400px'); $('.koltuk-kapa').attr('style', 'display:block'); $('#koltuk-kapa_' + id).attr('style', 'display:block'); $(".koltuk-kapa").show(); $(".koltuk-sec").hide(); } function koltuk_kapa(id) { $('.otobus').addClass('dipslay_none'); $('.otobus').removeClass('dipslay_block'); $('#otobus_' + id).addClass('dipslay_none'); $('.bilet-sec').attr('style', 'height:120px'); $('.guzergah').addClass('dipslay_none'); $('.guzergah').removeClass('dipslay_block'); $('#guzergah_' + id).addClass('dipslay_none'); $('.dvm-btn').addClass('dipslay_none'); $('.dvm-btn').removeClass('dipslay_block'); $('#dvm-btn_' + id).addClass('dipslay_none'); $('.dolu').addClass('dipslay_none'); $('.dolu').removeClass('dipslay_block'); $('#dolu_' + id).addClass('dipslay_none'); $('.bos').addClass('dipslay_none'); $('.bos').removeClass('dipslay_block'); $('#bos_' + id).addClass('dipslay_none'); $('#bilet-sec-' + id).attr('style', 'height:120px'); $(".koltuk-kapa").hide(); $(".koltuk-sec").show(); /*$('.koltuk-kapa').attr('style','display:none'); $('#koltuk-kapa_'+id).attr('style','display:none'); */ /*('.koltuk-sec').attr('style','display:display'); $('#koltuk-sec_'+id).attr('style','display:display'); */ } </script> <br> <br> <br> <?php include('footer.php'); ?> </body> </html><file_sep><?php require_once('baglan.php'); $girisyap = $db->prepare("SELECT * FROM kullanici"); $girisyap->execute(); $count = $girisyap->rowCount(); $row = $girisyap->fetch(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <meta charset="UTF-8"> </head> <body> <div class="topnav" id="myTopnav"> <a href="index.php"><i class="fa fa-home"></i> Anasayfa</a> <!--<a href="bilet.php"><i class="fa fa-ticket" aria-hidden="true"></i> Bilet Satın Al</a>--> <div class="d-flex justify-content-end"> <?php if (isset($_SESSION['user_id'])) { ?> <a href="biletlerim.php"><i class="fa fa-ticket"></i>Biletlerim</a></li> <?php if ($_SESSION['rol'] == 'admin') { ?> <a href="yonetim.php"><i class="fa fa-tachometer" aria-hidden="true"></i> Yönetim</a> <?php } ?> <a href="profil.php"><i class="fa fa-user"></i> <?php echo $_SESSION['ad'] ?></a></li> <a href="cikis.php"><i class="fa fa-sign-out" aria-hidden="true"></i> Çıkış</a> <?php } else { ?> <a href="#" data-toggle="modal" data-target="#giris"><i class="fa fa-sign-in " aria-hidden="true"></i>Giriş</a> <a href="#" data-toggle="modal" data-target="#uyelik"><i class="fa fa-user"></i> Üye Ol</a> <?php } ?> </div> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <i class="fa fa-bars"></i> </a> </div> <script> function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } </script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="y_style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> </body> </html> <?php require_once('baglan.php'); ?> <div class="nav-side-menu"> <div class="brand fa fa-tachometer"> YÖNETİM PANELİ</div> <i class="fa fa-bars fa-2x toggle-btn" data-toggle="collapse" data-target="#menu-content"></i> <div class="menu-list"> <ul id="menu-content" class="menu-content collapse out"> <li data-toggle="collapse" data-target="#products" class="collapsed"> <li> <a href="yonetim.php" > <i class="fa fa-home"></i>Panel</a> </li> <li> <a href="seferler.php" > <i class="fa fa-map-marker"></i>Seferler</a> </li> <li> <a href="tum_bilet.php" > <i class="fa fa-ticket"></i>Biletler</a> </li> <!-- <li data-toggle="collapse" data-target="#products" class="collapsed"> <a href="hareketler.php"><i class="fa fa-compass fa-lg"></i> Güzergah</a> </li>--> <li data-toggle="collapse" data-target="#service" class="collapsed"> <a href="otobus.php"><i class="fa fa-bus fa-lg"></i> Otobüsler</a> </li> <li data-toggle="collapse" data-target="#new" class="collapsed"> <a href="guzergah.php"><i class="fa fa-compass fa-lg"></i> Güzergah</a> </li> <li data-toggle="collapse" data-target="#new" class="collapsed"> <a href="personel.php"><i class="fa fa-users fa-lg"></i> Personel</a> </li> <li data-toggle="collapse" data-target="#new" class="collapsed"> <a href="muavin.php"><i class="fa fa-users fa-lg"></i> Muavin</a> </li> <li> <a href="index.php"> <i class="fa fa-sign-out fa-lg" id="cikis" name="cikis"></i> Anasayfaya Dön </a> </li> </ul> </div> </div> </div> <file_sep><?php ob_start(); error_reporting(0); ?> <!DOCTYPE html> <html lang="tr"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Personel</title> </head> <body> <?php require_once('baglan.php'); include('yonetim_menu.php'); ?> <div class="container d-flex justify-content-center"> <div class="card " style="width:50%;"> <div class="card-body"> <div class="card-title bg-light text-dark"> <h1 class="modal-title text-center" id="exampleModalLongTitle">PERSONEL</h1> </div> <form method="post" id="personel_form"> <div class="form-label-group"> <label for="adsoyad">Şoför Adı Soyadı</label> <input type="text" name="s_adi" class="form-control" id="s_adi" placeholder="Şoför Adı" required autofocus> </div> <br> <div class="form-label-group"> <label for="firma">Firma</label> <select name="firma" id="firma" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM firmalar"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['id']; $firma = $sonuc['firma_adi']; echo "<option value=".$id.">".$firma."</option>"; } ?> </select> <?php } ?> </div> <div class="form-label-group"> <label for="muavin">Muavin</label> <select name="muavin" id="muavin" class="form-select form-select-lg mb-3"> <?php $sorgu =$db->prepare("SELECT * FROM muavin"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['id']; $muavin = $sonuc['a_muavin']; $d_muavin = $sonuc['d_muavin']; echo "<option value=".$id.">".$muavin." -- ".$d_muavin."</option>"; } ?> </select> <?php } ?> </div> <br> <input type="submit" class="btn btn-lg btn-secondary btn-block text-uppercase" id="otobus_btn" value="Kaydet"> </form> </div> </div> </div> <?php if($_POST) { $s_adi=$_POST['s_adi']; $firma = $_POST['firma']; $muavin=$_POST['muavin']; if( !$s_adi|| !$firma || !$muavin) { echo "<script>alert('Boş Geçilemez');</script>"; } else { $sorgu = $db->prepare("INSERT INTO sorumlu(sofor_adi,firma_id,muavin_id) VALUES(?,?,?)"); $sorgu->bindParam(1, $s_adi, PDO::PARAM_STR); $sorgu->bindParam(2, $firma, PDO::PARAM_INT); $sorgu->bindParam(3, $muavin, PDO::PARAM_STR); //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu->execute()) { echo "<script>alert('Kaydınız Başarılı!');</script>"; // header('location:index.php'); header("Refresh:1 ; url=yonetim.php"); } else { echo "<script>alert('Kayıt Başarısız!');</script>"; } } } ?> </body> </html> <?php ob_flush(); ?> <file_sep><!DOCTYPE html> <html lang="tr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="y_style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <?php include('yonetim_menu.php'); require_once('baglan.php'); $sorgu = $db->prepare("SELECT s.id, fiyat, k_tarih, (SELECT marka_model FROM otobusler o WHERE o.id = s.otobus_id)otobus_adi, (SELECT kapasite FROM otobusler o WHERE o.id = s.otobus_id)kapasite, (SELECT tipi FROM otobusler o WHERE o.id = s.otobus_id)tipi, (SELECT firma_adi FROM firmalar f WHERE f.id = s.firma_id)firma_adi, (SELECT adi FROM duraklar WHERE durak_id=s.kalkis)kalkis_adi, (SELECT adi FROM duraklar WHERE durak_id=s.varis)varis_adi FROM seferler s ORDER BY id DESC "); $sorgu->execute(); $count = $sorgu->rowCount(); $link = "<script>window.open('https://www.google.com.tr/?,'width=710,height=555,left=160,top=170')</script>"; ?> <div class="container d-flex justify-content-center"> <div class="card" style="width:60%;"> <div class="card-body"> <form action="" method="GET"> <div class="row-12"> <div class="col-sm-6"> <label for="" class="text-center">Arama</label> <input type="text" name="arama" id="arama" class="form-control"> </div> <div class="col-sm-5 " style="margin-top: 3.8%;"> <button class="btn btn-primary" name="arama_btn">ARA</button> </div> </div> </form> <?php if (isset($_GET['arama_btn'])) { $arama = $_GET['arama']; $sorgu = $db->prepare('SELECT s.id, fiyat, k_tarih, (SELECT marka_model FROM otobusler o WHERE o.id = s.otobus_id)otobus_adi, (SELECT kapasite FROM otobusler o WHERE o.id = s.otobus_id)kapasite, (SELECT tipi FROM otobusler o WHERE o.id = s.otobus_id)tipi, (SELECT firma_adi FROM firmalar f WHERE f.id = s.firma_id)firma_adi, (SELECT adi FROM duraklar WHERE durak_id=s.kalkis)kalkis_adi, (SELECT adi FROM duraklar WHERE durak_id=s.varis)varis_adi FROM seferler s INNER JOIN duraklar ON s.kalkis = duraklar.durak_id WHERE adi LIKE :keywords ORDER BY id DESC'); $sorgu->bindValue(':keywords', '%' . $arama . '%'); $sorgu->execute(); } ?> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col"></th> <th scope="col">Sefer Numarası</th> <th scope="col">Otobüs</th> <th scope="col">Kalkış Yeri</th> <th scope="col">Varış Yeri</th> <th scope="col">Kalkış Tarihi</th> <th scope="col">Fiyat</th> <th scope="col">Firma Adi</th> </tr> </thead> <tbody> <form method="get" action="tum_bilet.php"> <?php foreach ($sorgu as $listele) { ?> <tr> <th scope="row"> <th scope="col"><input type="submit" name="bilet_id" id="bilet_id" class="btn btn-primary" value="<?php echo $listele['id']; ?>"></th> </th> <td><?= $listele['otobus_adi']; ?></td> <td><?= $listele['kalkis_adi']; ?></td> <td><?= $listele['varis_adi']; ?></td> <td><?= $listele['k_tarih']; ?></td> <td><?= $listele['fiyat']; ?>₺</td> <td><?= $listele['firma_adi']; ?></td> </tr> <?php } ?> </form> </tbody> </table> </div> </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="tr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>Anasayfa</title> </head> <body> <?php require_once('baglan.php'); include('ust_menu.php'); include('giris.php'); include('uye_ol.php'); /*$girisyap = $db ->prepare("SELECT * FROM seferler"); $girisyap->execute(); $count = $girisyap->rowCount(); $row = $girisyap->fetch(PDO::FETCH_ASSOC); $kalkis =$row['kalkis'];*/ ?> <div class="container-fluid w-50 mt-3 mb-3 g-5" style="margin-left: 5%; margin-top:5%;"> <div class="card w-50 mb-5 g-5" style="border-radius: 10px; border:0px"> <div class="card-body align-self-center"> <label><i class="fa fa-map-marker"></i> Nereden</label> <form method="POST" action="sefer_arama.php" name="sefer_arama_form" id="sefer_arama_form"> <select class="form-select form-select-lg mb-3" name="kalkis" id="kalkis" aria-label=".form-select-sm example" style="width :100%;"> <?php $sorgu = $db->prepare("SELECT * FROM duraklar ORDER BY sehir_id ASC"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['durak_id']; $sehir = $sonuc['adi']; $kalkis = $_POST['kalkis']; echo "<option value=" . $id . ">" . $sehir . "</option>"; } ?> </select> <?php } ?> <label><i class="fa fa-map-marker"></i> Nereye</label> <select class="form-select form-select-lg mb-3" name="varis" id="varis" aria-label=".form-select-sm example" style="width :100%;"> <?php $sorgu = $db->prepare("SELECT * FROM duraklar ORDER BY sehir_id ASC"); $sorgu->execute(); $count = $sorgu->rowCount(); if ($sorgu->rowCount() > 0) { while ($sonuc = $sorgu->fetch(PDO::FETCH_ASSOC)) { $id = $sonuc['durak_id']; $sehir = $sonuc['adi']; echo "<option value=" . $id . ">" . $sehir . "</option>"; } ?> </select> <?php } ?> <label for="birthday"><i class="fa fa-calendar"></i> Yolculuk Tarihi</label> <br> <input type="date" id="date-time" name="date-time" class="form-control" required> <br> <br> <input type="submit" value="Bilet Ara" name="sefer_arama" id="sefer_arama" class="btn btn-primary w-100"> </form> </div> </div> </div> <div class="arka_ust mb-5"> <img src="img/arka_ust.jpg" width="100%" height="350px" alt=""> </div> <br><br> <h1 class="modal-title text-center mt-5 mb-3" id="exampleModalLongTitle">POPÜLER SEYAHATLER</h1> <br> <div class="row row-cols-1 row-cols-md-3 g-5"> <div class="col"> <div class="card" style="width:100%; border-radius:10px; "> <div class="card-header"> İstanbul - Ankara </div> <img src="img/ankara.jpg" class="card-img-top" alt="..."> <div class="card-body"> <a href="populer1.php" class="btn btn-primary ">Bilet Al</a> </div> </div> </div> <div class="col"> <div class="card" style="width:100%; border-radius: 10px; "> <div class="card-header"> İstanbul - İzmir </div> <img src="img/izmir.jpeg" class="card-img-top" alt="..."> <div class="card-body"> <a href="populer2.php" class="btn btn-primary">Bilet Al</a> </div> </div> </div> <div class="col"> <div class="card" style="width:100%; border-radius: 10px; "> <div class="card-header"> İstanbul - Çanakkale </div> <img src="img/canakkale.jpg" class="card-img-top" alt="..."> <div class="card-body"> <a href="populer3.php" class="btn btn-primary">Bilet Al</a> </div> </div> </div> <div class="col"> <div class="card" style="width:100%; border-radius: 10px;"> <div class="card-header"> İzmir - Bursa </div> <img src="img/ankara.jpg" class="card-img-top" alt="..."> <div class="card-body"> <a href="populer4.php" class="btn btn-primary">Bilet Al</a> </div> </div> </div> <div class="col"> <div class="card" style="width:100%; border-radius: 10px; "> <div class="card-header"> Ankara - Eskişehir </div> <img src="img/eskisehir.jpg" class="card-img-top" alt="..."> <div class="card-body"> <a href="populer5.php" class="btn btn-primary">Bilet Al</a> </div> </div> </div> <div class="col"> <div class="card" style="width:100%; border-radius: 10px; "> <div class="card-header"> İstanbul - Kars </div> <img src="img/kars.jpg" class="card-img-top" alt="..."> <div class="card-body"> <a href="populer6.php" class="btn btn-primary ">Bilet Al</a> </div> </div> </div> </div> <br> <?php include('footer.php'); ?> </body> </html><file_sep>$(document).ready(function () { $('#btncu').click(function () { $.ajax({ method: "POST", url: "ajax.php?type=giris.php", data: $('#baslik_form').serialize() }) .done(function( msg ) { if(msg == "bos") { swal("Boş Bırakılmış Alan!","","error"); } else if(msg == "ok") { swal("Giriş Başarılı","","success"); location.href = "index.php"; } else if(msg == "hata") { swal("Hatalı giriş!","","error"); } }); }); // $('#uye_btn').click(function () { /* $("#uye_btn").on('click', function() { $.ajax({ method: "POST", url: "ajax.php?type=uye_ol.php", data: $('#uyelik_form').serialize() }) .done(function( msg ) { if(msg == "bos") { sweetAlert("Boş Bırakılmış Alan!","","error"); } else if(msg == "ok") { sweetAlert("Üyelik Başarılı","","success"); //location.href = "index.php"; } else if(msg == "hata") { sweetAlert("Üyelik Başarısız","Sorun Oluştu!","error"); } }); }); */ }); <file_sep><?php $tarih = date("d.m.Y"); // Geçerli sistem tarihini almak için $saat = date("H:i:s"); // Geçerli sistem saatini almak için //echo "Tarih : ".$tarih."<br>"; //echo "Saat : ".$saat; ?><file_sep> data-toggle="modal" data-target="#uyelik" <div class="container d-flex justify-content-center"> <div class="card " style="width:50%;"> <div class="card-body"> <form method="post" id="uyelik_form" onsubmit="return false;"> <div class="form-label-group"> <label for="adsoyad">Ad Soyad</label> <input type="text" name="ad_soyad" class="form-control" id="ad_soyad" placeholder="Ad Soyad" required autofocus> </div> <br> <div class="form-label-group"> <label for="inputEmail">E-Posta</label> <input type="text" name="eposta" class="form-control" id="eposta" placeholder="E-Posta" required autofocus> </div> <br> <div class="form-label-group"> <label for="tcno">TC Kimlik Numarası</label> <input type="text" name="tc_no" class="form-control" id="tc_no" placeholder="TC Kimlik Numarası" required autofocus> </div> <br> <div class="form-label-group"> <label for="cinsiyet">Cinsiyet</label> <br> <label for="erkek">Erkek</label> <input type="radio" id="cinsiyet" name="cinsiyet" value="E"> <br> <label for="kadin">Kadın</label> <input type="radio" id="cinsiyet" name="cinsiyet" value="K"> </div> <br> <div class="form-label-group"> <label for="tcno">Telefon Numarası</label> <input type="text" name="tel_no" class="form-control" id="tel_no" placeholder="Telefon Numarası" required autofocus> </div> <br> <div class="form-label-group"> <label for="inputPassword">Şifre</label> <input type="password" name="<PASSWORD>" class="form-control" id="sifre" placeholder="<PASSWORD>"> </div> <br> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="button">Üye Ol</button> </form> </div> </div> </div> $ad_soyad=$_POST['ad_soyad']; $eposta = $_POST['eposta']; $cinsiyet=$_POST['cinsiyet']; $tc_no=$_POST['tc_no']; $tel_no=$_POST['tel_no']; $sifre=$_POST['sifre']; //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu = $db->prepare("INSERT INTO kullanici(ad_soyad,eposta,cinsiyet,tc_no,tel_no,sifre) VALUES(?,?,?,?,?,?)")) { $sorgu->bindParam(1, $ad_soyad, PDO::PARAM_STR); $sorgu->bindParam(2, $eposta, PDO::PARAM_STR); $sorgu->bindParam(3, $cinsiyet, PDO::PARAM_STR); $sorgu->bindParam(4, $tc_no, PDO::PARAM_STR); $sorgu->bindParam(5, $tel_no, PDO::PARAM_STR); $sorgu->bindParam(6, $sifre, PDO::PARAM_STR); $sorgu->execute(); echo 'ok'; } else { echo 'hata'; } $ad_soyad=$_POST['ad_soyad']; $eposta = $_POST['eposta']; $cinsiyet=$_POST['cinsiyet']; $tc_no=$_POST['tc_no']; $tel_no=$_POST['tel_no']; $sifre=$_POST['sifre']; if( !$eposta|| !$sifre || !$ad_soyad || !$cinsiyet || !$tc_no || !$tel_no) { echo "bos"; } else { $sorgu = $db->prepare("INSERT INTO kullanici(ad_soyad,eposta,cinsiyet,tc_no,tel_no,sifre) VALUES(?,?,?,?,?,?)"); $sorgu->bindParam(1, $ad_soyad, PDO::PARAM_STR); $sorgu->bindParam(2, $eposta, PDO::PARAM_STR); $sorgu->bindParam(3, $cinsiyet, PDO::PARAM_STR); $sorgu->bindParam(4, $tc_no, PDO::PARAM_STR); $sorgu->bindParam(5, $tel_no, PDO::PARAM_STR); $sorgu->bindParam(6, $sifre, PDO::PARAM_STR); //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu->execute()) { echo "ok"; } else { echo "hata"; } $sorgu=$db->prepare("SELECT * FROM seferler INNER JOIN otobusler ON seferler.id = otobusler.id INNER JOIN firmalar ON seferler.id = firmalar.id INNER JOIN sehirler ON seferler.id = sehirler.sehir_id "); $sorgu->execute(); $count = $sorgu->rowCount(); $row = $sorgu->fetch(PDO::FETCH_ASSOC); $id =$row['id'] ?> <div class="container d-flex justify-content-center"> <div class="card " style="width:60%;"> <div class="card-body"> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Otobüs</th> <th scope="col">Kalkış Yeri</th> <th scope="col">Varış Yeri</th> <th scope="col">Fiyat</th> <th scope="col">Firma Adi</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td><?=$row['marka_model'];?></td> <td><?=$row['sehir_adi'];?></td> <td><?=$row['sehir_adi'];?></td> <td><?=$row['sehir_adi'];?></td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> <table class="table"> <thead class="thead-light"> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> </div> </div> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Firma</th> <th scope="col">Kalkış Yeri</th> <th scope="col">Varış Yeri</th> <th scope="col">Fiyat</th> </tr> </thead> <tbody> <?php foreach($sorgu as $listele) {?> <tr> <th scope="row"><?=$listele['id'];?></th> <td><?=$listele['firma_id'];?></td> <td><?=$listele['kalkis'];?></td> <td><?=$listele['varis'];?></td> <td><?=$listele['fiyat'];?></td> </tr> <?php } ?> </tbody> </table> ?> <?php foreach($sorgu as $listele) { ?> <br> <div class="container d-flex justify-content-center"> <a href="#?id=<?php echo $id;?>" > <div class="bilet-sec "> <div class="row"> <div class="col"> <label for="firma" class="mt-5"><?=$listele['firma_adi'];?></label> </div> <div class="col"> <label for="firma" class="mt-5"><?=$listele['k_tarih'];?></label> </div> <div class="col"> <label for="firma" class="mt-4"><?=$listele['adi'];?></label> <br> <label for="">-</label> <br> <label for="firma" class=""><?=$listele['adi'];?></label> </div> <div class="col"> <label for="firma" class="mt-5"><?=$listele['fiyat'];?>₺</label> </div> <div class="col"> <button type="button" class="btn btn-danger mt-5">KOLTUK SEÇ</button> </div> </div> </div> </a> </div> <br> <?php } ?> POPULER1 <!DOCTYPE html> <html lang="tr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap" rel="stylesheet"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>İstanbul - Ankara</title> </head> <body> <?php require_once('baglan.php'); include('ust_menu.php'); include('giris.php'); include('uye_ol.php'); $sorgu = $db->prepare("SELECT s.id, fiyat, k_tarih, firma_adi, tipi, (SELECT adi FROM duraklar WHERE durak_id=s.kalkis)kalkis_adi, (SELECT adi FROM duraklar WHERE durak_id=s.varis)varis_adi FROM seferler s INNER JOIN firmalar f ON s.firma_id = f.id INNER JOIN otobusler o ON s.otobus_id = o.id WHERE kalkis = 48 AND varis = 90"); $sorgu->execute(); $count = $sorgu->rowCount(); $row = $sorgu->fetch(PDO::FETCH_ASSOC); $id = $row['id']; ?> <h1 class="modal-title text-center" id="exampleModalLongTitle">İSTANBUL - ANKARA</h1> <?php foreach ($sorgu as $listele) { ?> <br> <div class="container"> <a href="#?id=<?php echo $id; ?>"> <div class="bilet-sec "> <div class="row"> <div class="col"> <label for="firma" style="font-size:150%" class="mt-5"><?= $listele['firma_adi']; ?></label> </div> <div class="col"> <label for="firma" class="mt-5"><?= $listele['k_tarih']; ?></label> </div> <div class="col" style="font-size:85%"> <label for="tipi" style="font-size:150%"><?= $listele['tipi']; ?></label> <br> <label for="firma"><?= $listele['kalkis_adi']; ?></label> <br> <label for="" style="font-size:150%">></label> <br> <label for="firma"><?= $listele['varis_adi']; ?></label> </div> <div class="col"> <label for="firma" style="font-size:150%" class="mt-5"><?= $listele['fiyat']; ?>₺</label> </div> <div class="col"> <button type="button" class="btn btn-danger mt-5">KOLTUK SEÇ</button> </div> </div> </div> </a> </div> <br> <?php } ?> <br> <br> <br> <?php include('footer.php'); ?> </body> </html> <?php foreach ($sorgu as $listele) { ?> <br> <form method="post" action=""> <div class="container"> <div class="bilet-sec" id="bilet-sec"> <div class="row"> <div class="col"> <label for="firma" style="font-size:150%" class="mt-5"><?= $listele['firma_adi']; ?></label> </div> <div class="col"> <label for="firma" class="mt-5"><?= $listele['k_tarih']; ?></label> </div> <div class="col" style="font-size:85%"> <label for="tipi" style="font-size:150%"><?= $listele['tipi']; ?></label> <br> <label for="firma"><?= $listele['kalkis_adi']; ?></label> <br> <label for="" style="font-size:150%">></label> <br> <label for="firma"><?= $listele['varis_adi']; ?></label> </div> <div class="col"> <label for="firma" style="font-size:150%" class="mt-5"><?= $listele['fiyat']; ?>₺</label> </div> <div class="col"> <button type="button" id="koltuk-sec" class="btn btn-danger mt-5" >KOLTUK SEÇ</button> </div> <hr style="width: 95%; margin-left:2%;" ></hr> <div class="secim-yap" id="secim-yap"> </div> <br> </div> </div> </div> </form> <br> <?php } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Profil</title> </head> <body> <?php include('ust_menu.php'); $sorgu = $db->prepare("SELECT * FROM kullanici where id=" . $_SESSION['user_id']); $sorgu->execute(); $count = $sorgu->rowCount(); $row = $sorgu->fetch(PDO::FETCH_ASSOC); $id = $row['id']; ?> <div class="container-xl mt-5"> <div class="row"> <div class="col-xl-4"> <div class="profil"> <div class="kutu"> <img src="img/profile.png" width="100%" height="250px" alt=""> </div> <center><p style="font-size: 35px;" class="mt-5"><?= $row['ad_soyad']; ?></p></center> </div> </div> <div class="col-sm-8"> <div class="bilgi-panel"> <div class="card-body" style="width:75%; margin-left: 12%;"> <p style="font-size: 15px;" class="mt-5">Ad Soyad</p> <input type="text" class="form-control bg-white" disabled value="<?= $row['ad_soyad']; ?>"> <p style="font-size: 15px;" class="mt-5 ">TC Kimlik Numarası</p> <input type="text" class="form-control bg-white" disabled value="<?= $row['tc_no']; ?>"> <p style="font-size: 15px;" class="mt-5">E-Posta</p> <input type="text" class="form-control bg-white " disabled value="<?= $row['eposta']; ?>"> <p style="font-size: 15px;" class="mt-5">Cinsiyet</p> <input type="text" class="form-control bg-white" disabled value="<?= $row['cinsiyet']; ?>"> <p style="font-size: 15px;" class="mt-5">Telefon Numarası</p> <input type="text" class="form-control bg-white" disabled value="<?= $row['tel_no']; ?>"> <p style="font-size: 15px;" class="mt-5">Şifre</p> <input type="text" class="form-control bg-white" disabled value="<?= $row['sifre']; ?>"> <a href="profil_guncelle.php?id=<?php echo $id; ?>" style="width: 100%;" class="btn btn-primary mt-5">Güncelle</a> </div> <div class="bos" style="width: 100%; height:100px"> </div> </div> </div> </div> </div> </body> </html><file_sep><?php require_once('baglan.php'); //var_dump($_GET,$_POST); if($_GET['type'] == 'giris.php') { $kadi= $_POST['kadi']; $sifre = $_POST['sifre']; if(!$kadi || !$sifre) { echo "bos"; } else { $girisyap = $db ->prepare("SELECT * FROM kullanici WHERE eposta =:kadi AND sifre=:sifre"); $girisyap->bindParam('kadi', $kadi, PDO::PARAM_STR); $girisyap->bindValue('sifre', $sifre, PDO::PARAM_STR); $girisyap->execute(); $count = $girisyap->rowCount(); $row = $girisyap->fetch(PDO::FETCH_ASSOC); if($count == 1 && !empty($row)) { $_SESSION['user_id'] = $row['id']; $_SESSION['ad'] = $row['ad_soyad']; $_SESSION['rol'] = $row['k_rol']; echo "ok"; } else { echo 'hata'; } } } /*else if($_GET['type'] == 'uye_ol.php') { $ad_soyad=$_POST['ad_soyad']; $eposta = $_POST['eposta']; $cinsiyet=$_POST['cinsiyet']; $tc_no=$_POST['tc_no']; $tel_no=$_POST['tel_no']; $sifre=$_POST['sifre']; if( !$eposta|| !$sifre || !$ad_soyad || !$cinsiyet || !$tc_no || !$tel_no) { echo "bos"; } else { $sorgu = $db->prepare("INSERT INTO kullanici(ad_soyad,eposta,cinsiyet,tc_no,tel_no,sifre) VALUES(?,?,?,?,?,?)"); $sorgu->bindParam(1, $ad_soyad, PDO::PARAM_STR); $sorgu->bindParam(2, $eposta, PDO::PARAM_STR); $sorgu->bindParam(3, $cinsiyet, PDO::PARAM_STR); $sorgu->bindParam(4, $tc_no, PDO::PARAM_STR); $sorgu->bindParam(5, $tel_no, PDO::PARAM_STR); $sorgu->bindParam(6, $sifre, PDO::PARAM_STR); //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu->execute()) { echo "ok"; } else { echo "hata"; } } } */ <file_sep><?php ob_start(); error_reporting(0); ?> <!DOCTYPE html> <html lang="tr"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Personel</title> </head> <body> <?php require_once('baglan.php'); include('yonetim_menu.php'); ?> <div class="container d-flex justify-content-center"> <div class="card " style="width:50%;"> <div class="card-body"> <div class="card-title bg-light text-dark"> <h1 class="modal-title text-center" id="exampleModalLongTitle">MUAVİN EKLE</h1> </div> <form method="post" id="personel_form"> <div class="form-label-group"> <label for="adsoyad">1.Muavin Adı Soyadı</label> <input type="text" name="m_adi" class="form-control" id="m_adi" placeholder="Muavin Adı" required autofocus> <br> <label for="adsoyad">2.Muavin Adı Soyadı</label> <input type="text" name="d_adi" class="form-control" id="d_adi" placeholder="2.Muavin Adı" required autofocus> </div> <br> <br> <input type="submit" class="btn btn-lg btn-secondary btn-block text-uppercase" id="otobus_btn" value="Kaydet"> </form> </div> </div> </div> <?php if($_POST) { $m_adi=$_POST['m_adi']; $d_adi = $_POST['d_adi']; if( !$d_adi|| !$m_adi) { echo "<script>alert('Boş Geçilemez');</script>"; } else { $sorgu = $db->prepare("INSERT INTO muavin(a_muavin,d_muavin) VALUES(?,?)"); $sorgu->bindParam(1, $m_adi, PDO::PARAM_STR); $sorgu->bindParam(2, $d_adi, PDO::PARAM_STR); //$sorgu->bindParam(4, $_SESSION['user_id']); // $sorgu->execute(); if($sorgu->execute()) { echo "<script>alert('Kaydınız Başarılı!');</script>"; // header('location:index.php'); header("Refresh:1 ; url=yonetim.php"); } else { echo "<script>alert('Kayıt Başarısız!');</script>"; } } } ?> </body> </html> <?php ob_flush(); ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="y_style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <?php error_reporting(0); include('yonetim_menu.php'); require_once('baglan.php'); //$bilet_id = $_SESSION['bilet_id']; //$sorgu = $db->prepare("SELECT * FROM biletler WHERE id=" .$bilet_id); $sorgu = $db->prepare("SELECT * FROM biletler b INNER JOIN seferler s ON b.sefer_id = s.id WHERE s.id=" . (int)$_GET['bilet_id']); $sorgu->execute(); $count = $sorgu->rowCount(); //$sonuc = $sorgu->fetch(PDO::FETCH_ASSOC); /* $sorgu = $db->prepare("SELECT * FROM biletler"); $sorgu->execute(); $count = $sorgu->rowCount();*/ ?> <div class="container " style="margin-left: 27%;"> <div class="card " style="width:80%;"> <div class="card-body"> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Ad Soyad</th> <th scope="col">Cinsiyet</th> <th scope="col">E-Posta</th> <th scope="col">Tc No</th> <th scope="col">Tel_No</th> <th scope="col">Koltuk_No</th> <th scope="col">Fiyat</th> <th scope="col">Güzergah</th> </tr> </thead> <tbody> <?php foreach ($sorgu as $listele) { ?> <tr> <th scope="row"><?= $listele['id']; ?></th> <td><?= $listele['ad_soyad']; ?></td> <td><?= $listele['cinsiyet']; ?></td> <td><?= $listele['eposta']; ?></td> <td><?= $listele['tc_no']; ?></td> <td><?= $listele['tel_no']; ?></td> <td><?= $listele['koltuk_no']; ?></td> <td><?= $listele['fiyat']; ?></td> <td><?= $listele['guzergah_id']; ?></td> </tr> <?php } ?> </div> </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="style.css" crossorigin="anonymous"> <script src="js/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/app.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap" rel="stylesheet"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Bilet Satın Al</title> </head> <body> <?php require_once('baglan.php'); include('ust_menu.php'); include('giris.php'); include('uye_ol.php'); $k_no = $_GET['koltuk']; $biletsec = $_GET['count']; $sorgu = $db->prepare("SELECT s.id, fiyat, k_tarih, firma_adi, tipi, kapasite, (SELECT guzergah_adi FROM guzergah WHERE id=s.guzergah_id)guzergah_ad, (SELECT adi FROM duraklar WHERE durak_id=s.kalkis)kalkis_adi, (SELECT adi FROM duraklar WHERE durak_id=s.varis)varis_adi FROM seferler s INNER JOIN firmalar f ON s.firma_id = f.id INNER JOIN otobusler o ON s.otobus_id = o.id WHERE s.id =" . $biletsec); $sorgu->execute(); $count = $sorgu->rowCount(); $row = $sorgu->fetch(PDO::FETCH_ASSOC); $id = $row['id']; $k_tarih = $row['k_tarih']; $fiyat = $row['fiyat']; $kalkis_adi = $row['kalkis_adi']; $varis_adi = $row['varis_adi']; $firma_adi = $row['firma_adi']; $tipi = $row['tipi']; $kapasite = $row['kapasite']; $guzergah = $row['guzergah_ad']; ?> <?php error_reporting(0); if ($_SESSION['user_id']) { $k_sorgu = $db->prepare("SELECT * FROM kullanici WHERE id=" . $_SESSION['user_id']); $k_sorgu->execute(); $count = $k_sorgu->rowCount(); $row = $k_sorgu->fetch(PDO::FETCH_ASSOC); $s_ad = $row['ad_soyad']; $s_eposta = $row['eposta']; $s_cinsiyet = $row['cinsiyet']; $s_tel = $row['tel_no']; $s_tc = $row['tc_no']; } ?> <div class="container"> <div class="row-12"> <div class="col-sm-1 mt-5 px-5" style="margin-left:-5%; "> <div class="card" style="width: 30rem;border-radius: 10px;"> <div class="card-body"> <center> <h4 class="card-title" style="font-size:200%"><?php echo $firma_adi ?></h5> </center> <br> <h6 class="card-subtitle mb-2 text-muted"><?php echo $k_tarih ?></h6> <p class="card-text"> <label for="">Kalkış</label><br> <?php echo $kalkis_adi ?> </p> <p class="card-text"> <label for="">Varış</label><br> <?php echo $varis_adi ?> </p> <p class="card-text"> <label for="">Koltuk No</label><br> <?php echo $k_no ?> </p> </div> </div> </div> <div class="col-md-3 mt-5" style="margin-left:-7%;"> <div class="container d-flex justify-content-center"> <div class="card" style="width:40%; border-radius: 10px;"> <div class="card-body"> <div class="card-title bg-light text-dark" style="border-radius: 10px;"> <h1 class="modal-title text-center" id="exampleModalLongTitle">BİLET SATIN AL</h1> </div> <form method="POST" name="satinal_form" id="satinal_form"> <?php $kullanici_id = $_SESSION['user_id']; if (isset($_SESSION['user_id'])) { ?> <center> Üye Bilgilerimi Kullan <input type="checkbox" name="myCheck" id="myCheck" onclick="myFunction()"> </center> <?php } ?> <div id="text" style="display: block;"> <div class="form-label-group"> <label for="adsoyad">Ad Soyad</label> <input type="text" name="adi_soyadi" class="form-control" id="adi_soyadi" placeholder="Ad Soyad"> </div> <br> <div class="form-label-group"> <label for="inputEmail">E-Posta</label> <input type="text" name="e-posta" class="form-control" id="e-posta" placeholder="E-Posta" autofocus> </div> <br> <div class="form-label-group"> <label for="tc">TC Kimlik No</label> <input type="text" name="tc_num" class="form-control" id="tc_num" placeholder="TC No"> </div> <br> <div class="form-label-group"> <label for="cinsiyet">Cinsiyet</label> <br> <label for="erkek">Erkek</label> <input type="radio" id="cinsiyet1" name="cinsiyet1" value="E"> <br> <label for="kadin">Kadın</label> <input type="radio" id="cinsiyet1" name="cinsiyet1" value="K"> </div> <br> <div class="form-label-group"> <label for="tcno">Telefon Numarası</label> <input type="text" name="tel_num" class="form-control" id="tel_num" placeholder="Telefon No"> </div> <br> </div> <input type="submit" class="btn btn-lg btn-secondary btn-block text-uppercase" id="satin_al" name="satin_al" value="Satın Al"> </form> </div> </div> </div> </div> <div class="col-sm-1 mt-5 px-5" style="margin-left: 49%;"> <div class="card" style="width: 30rem; border-radius: 10px;"> <div class="card-body"> <center> <h4 class="card-title" style="font-size:200%; ">GÜZERGAH</h5> </center> <br> <h6 class="card-subtitle mb-2 text-muted"><?php echo $k_tarih ?></h6> <p class="card-text"> <label for=""></label><br> <?php echo $guzergah ?> </p> </div> </div> </div> </div> </div> <input type="hidden" name="deneme" value="1"> <?php if (isset($_POST['satin_al'])) { $adi_soyadi = $_POST['adi_soyadi']; $e_posta = $_POST['e-posta']; $cinsiyeti = $_POST['cinsiyet1']; $tc_num = $_POST['tc_num']; $tel_num = $_POST['tel_num']; $deneme = 1; if (isset($_POST['myCheck'])) { $sorgu = $db->prepare("INSERT INTO biletler(kullanici_id,ad_soyad,eposta,cinsiyet,tc_no,tel_no,koltuk_no,sefer_id,durum) VALUES(?,?,?,?,?,?,?,?,?)"); $sorgu->bindParam(1, $kullanici_id, PDO::PARAM_INT); $sorgu->bindParam(2, $s_ad, PDO::PARAM_STR); $sorgu->bindParam(3, $s_eposta, PDO::PARAM_STR); $sorgu->bindParam(4, $s_cinsiyet, PDO::PARAM_STR); $sorgu->bindParam(5, $s_tc, PDO::PARAM_STR); $sorgu->bindParam(6, $s_tel, PDO::PARAM_STR); $sorgu->bindParam(7, $k_no, PDO::PARAM_INT); $sorgu->bindParam(8, $biletsec, PDO::PARAM_INT); $sorgu->bindParam(9, $deneme, PDO::PARAM_INT); if ($sorgu->execute()) { echo "<script>alert('Satın Alma Başarılı!');</script>"; header("Refresh: 1; url=bilet_bilgi.php"); $_SESSION['name'] = $s_ad; $_SESSION['postae'] = $s_eposta; $_SESSION['cinsiyeti'] = $s_cinsiyet; $_SESSION['tc_num'] = $s_tc; $_SESSION['tel_num'] = $s_tel; $_SESSION['biletsec'] = $biletsec; $_SESSION['koltuk'] = $k_no; } else { echo "<script>alert('Satın Alma Başarısız!');</script>"; } } else { if (!$e_posta || !$adi_soyadi || !$cinsiyeti || !$tc_num || !$tel_num) { echo "<script>alert('Boş Geçilemez');</script>"; } else { $sorgu = $db->prepare("INSERT INTO biletler(ad_soyad,eposta,cinsiyet,tc_no,tel_no,koltuk_no,sefer_id,durum) VALUES(?,?,?,?,?,?,?,?)"); $sorgu->bindParam(1, $adi_soyadi, PDO::PARAM_STR); $sorgu->bindParam(2, $e_posta, PDO::PARAM_STR); $sorgu->bindParam(3, $cinsiyeti, PDO::PARAM_STR); $sorgu->bindParam(4, $tc_num, PDO::PARAM_STR); $sorgu->bindParam(5, $tel_num, PDO::PARAM_STR); $sorgu->bindParam(6, $k_no, PDO::PARAM_INT); $sorgu->bindParam(7, $biletsec, PDO::PARAM_INT); $sorgu->bindParam(8, $deneme, PDO::PARAM_INT); if ($sorgu->execute()) { echo "<script>alert('Satın Alma Başarılı!');</script>"; /*if(isset($_GET['koltuk'])) { $deneme = 1; //$idne =1; } $sorgu = $db->prepare("UPDATE biletler SET durum = ? WHERE koltuk_no = ?"); $sorgu->bindParam(1, $deneme); $sorgu->bindParam(2, $k_no); $sorgu->execute();*/ header("Refresh: 1; url=bilet_bilgi.php"); $_SESSION['name'] = $adi_soyadi; $_SESSION['postae'] = $e_posta; $_SESSION['cinsiyeti'] = $cinsiyeti; $_SESSION['tc_num'] = $tc_num; $_SESSION['tel_num'] = $tel_num; $_SESSION['biletsec'] = $biletsec; $_SESSION['koltuk'] = $k_no; } else { echo "<script>alert('Satın Alma Başarısız!');</script>"; } } } } ?> <script> function myFunction() { var checkBox = document.getElementById("myCheck"); var text = document.getElementById("text"); if (checkBox.checked == true) { text.style.display = "none"; } else { text.style.display = "block"; } } </script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> </head> <body> <?php require_once('baglan.php'); include('ust_menu.php'); $sorgu = $db->prepare("SELECT * FROM biletler b INNER JOIN seferler s ON b.sefer_id = s.id INNER JOIN duraklar d ON s.kalkis = d.durak_id WHERE kullanici_id=" . $_SESSION['user_id']); $sorgu->execute(); $count = $sorgu->rowCount(); ?> <?php $a_sorgu = $db->prepare("SELECT * FROM seferler"); $a_sorgu->execute(); $count = $a_sorgu->rowCount(); ?> <?php ?> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">Ad Soyad</th> <th scope="col">Cinsiyet</th> <th scope="col">E-Posta</th> <th scope="col">TC Kimlik No</th> <th scope="col">Telefon Numarası</th> <th scope="col">Kalkış</th> <th scope="col">Güzergah</th> <th scope="col">Koltuk</th> </tr> </thead> <tbody> <?php foreach ($sorgu as $listele) { ?> <tr> <th scope="row"><?= $listele['ad_soyad']; ?></th> <td><?= $listele['cinsiyet']; ?></td> <td><?= $listele['eposta']; ?></td> <td><?= $listele['tc_no']; ?></td> <td><?= $listele['tel_no']; ?></td> <td><?= $listele['sefer_id']; ?></td> <td><?= $listele['guzergah_id']; ?></td> <td><?= $listele['koltuk_no']; ?></td> </tr> <?php } ?> </tbody> </table> </body> </html>
6fcfd1dd7b27361c4bf052215a01948705fe4079
[ "Markdown", "SQL", "JavaScript", "PHP" ]
24
PHP
novilgan/otobus-bilet-satis
ad1015ec17a4a1a16dee26dc4a9401f63e30a2a8
b8775aaa356709d91ad6004fff9c91044b57b07c
refs/heads/main
<repo_name>maartenhummel/testrepo<file_sep>/README.md # testrepo It is a markdown file for this repository. Thats it. <file_sep>/testchild.py #adding file to child branch print("file inside child branch")
93bf38f9eb9bcb55c67ef205e7cdd8992e3da12e
[ "Markdown", "Python" ]
2
Markdown
maartenhummel/testrepo
f10a0727580952b9dca92ab95298920912439eda
e93e9e47c3eceb2873e486679d774d9c51a10eab
refs/heads/master
<file_sep>import { PanelPlugin } from '@grafana/data'; import { SimpleOptions, defaults } from './types'; import { CircularCalendarPanel } from './CircularCalendarPanel'; import { CircularCalendarEditor } from './CircularCalendarEditor'; export const plugin = new PanelPlugin<SimpleOptions>(CircularCalendarPanel) .setDefaults(defaults) .setEditor(CircularCalendarEditor); <file_sep>import { DataFrame, ArrayVector, getTimeField, FieldType } from '@grafana/data'; import { DateTime } from 'luxon'; export interface DayBucket { date: DateTime; count: number; sum: number; scale: number; // 0-1 for min/max on sum } export interface DayBucketInfo { year: number; day: DayBucket[]; outside: DayBucket; } export const toDayBucketsInfo = (year: number, data: DataFrame[]): DayBucketInfo => { const start = DateTime.local().set({ year, ordinal: 1, hour: 0, minute: 0, second: 0, millisecond: 0, }); const values: DayBucket[] = []; for (let i = 1; i <= start.daysInYear; i++) { const d = start.set({ ordinal: i }); values.push({ date: d, count: 0, sum: 0, scale: 0, }); } const outside = { date: start, // IGNORE count: 0, sum: 0, scale: 0, }; let min = Number.MAX_VALUE; let max = Number.MIN_VALUE; for (const frame of data) { const { timeField, timeIndex } = getTimeField(frame); if (!timeField) { continue; } const timeVector = timeField.values; for (let i = 0; i < frame.fields.length; i++) { if (i === timeIndex) { continue; } if (frame.fields[i].type === FieldType.number) { const vector = frame.fields[i].values; for (let j = 0; j < vector.length; j++) { const value = vector.get(j); if (value) { const time = DateTime.fromMillis(timeVector.get(j)); const bucket = time.year !== year ? outside : values[time.ordinal - 1]; bucket.count = bucket.count + 1; bucket.sum = bucket.sum + value; if (bucket.sum > max) { max = bucket.sum; } if (bucket.sum < min) { min = bucket.sum; } } } continue; // the first number field } } } const range = max - min; if (range > 0) { for (const bucket of values) { if (bucket.count > 0) { bucket.scale = (bucket.sum - min) / range; } } } return { year, day: values, outside, }; }; export const toDayBuckets = (year: number, data: DataFrame[]): DataFrame => { const start = DateTime.local().set({ year, ordinal: 1, hour: 0, minute: 0, second: 0, millisecond: 0, }); const dates = new ArrayVector<DateTime>(); const weekNumber = new ArrayVector<number>(); // const weekday = new ArrayVector<number>(); // const count = new ArrayVector<number>(); const sum = new ArrayVector<number>(); for (let i = 1; i <= start.daysInYear; i++) { const d = start.set({ ordinal: i }); dates.add(d); weekNumber.add(d.weekNumber); weekday.add(d.weekday); count.add(0); sum.add(0); } let outside = 0; for (const frame of data) { const { timeField, timeIndex } = getTimeField(frame); if (!timeField) { continue; } const timeVector = timeField.values; for (let i = 0; i < frame.fields.length; i++) { if (i === timeIndex) { continue; } if (frame.fields[i].type === FieldType.number) { const vector = frame.fields[i].values; for (let j = 0; j < vector.length; j++) { const value = vector.get(j); if (value) { const time = DateTime.fromMillis(timeVector.get(j)); if (time.year !== year) { outside++; } else { const idx = time.ordinal; count.set(idx, count.get(idx) + 1); sum.set(idx, sum.get(idx) + value); } } } continue; // the first number field } } } return { fields: [ { name: 'Date', values: dates, config: {}, type: FieldType.other }, { name: 'Week', values: weekNumber, config: {}, type: FieldType.number }, { name: 'Day', values: weekday, config: {}, type: FieldType.number }, { name: 'Count', values: count, config: {}, type: FieldType.number }, { name: 'Sum', values: sum, config: {}, type: FieldType.number }, ], length: dates.length, meta: { custom: { outside, // Someplace more general? }, }, }; }; <file_sep>export interface SimpleOptions { text: string; pad: number; } export const defaults: SimpleOptions = { text: 'The default text!', pad: 50, };
77b94c1a266dc24cc23b35b82ffaa2515a622ebb
[ "TypeScript" ]
3
TypeScript
ryantxu/calendar-circle-panel
56f07e52811a32dbfcb9576d32017b3288b2b291
6f083a95587bc67fc4c0a56d31ab8549b92890f2
refs/heads/master
<repo_name>guilhermegregio/java-data-structure-and-algorithm<file_sep>/src/main/java/net/gregio/Fibonacci.java package net.gregio; public class Fibonacci { public static long iteractive(int n) { int i = 1; int j = 0; int t; for (int k = 1; k <= n; k+=1) { t = i + j; i = j; j = t; } return j; } public static long recurcive(int n) { if(n == 0 || n == 1) { return n; } return recurcive(n-1) + recurcive(n-2); } }
9e49f33514d8b7f0442c6ed24a7106c4556eeb3f
[ "Java" ]
1
Java
guilhermegregio/java-data-structure-and-algorithm
90cdcfd0dc4e593a49abcdd41400012aae5166bf
71d70e63751ff25537314676947e4e1cf60a9692
refs/heads/master
<repo_name>cannawen/sculpture<file_sep>/SwiftSculptures/PictureTakingViewController.swift // // PictureTakingViewController.swift // SwiftSculptures // // Created by <NAME> on 2015-10-09. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit class PictureTakingViewController : UIViewController { @IBOutlet weak var imageView: UIImageView! let imagePickerController = UIImagePickerController() } // MARK: - Taking pictures extension PictureTakingViewController : UIImagePickerControllerDelegate { override func viewDidLoad() { super.viewDidLoad() imagePickerController.delegate = self } @IBAction func selectedCamera(sender: UIBarButtonItem) { presentViewController(imagePickerController, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { imageView.image = image dismissViewControllerAnimated(true, completion: nil) } } extension PictureTakingViewController : UINavigationControllerDelegate { } <file_sep>/SwiftSculpturesTests/UIBarButtonItem+TestHelpers.swift // // UIBarButtonItem+TestHelpers.swift // SwiftSculptures // // Created by <NAME> on 2015-10-16. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit extension UIBarButtonItem { func tap() { UIApplication.sharedApplication().sendAction(self.action, to: self.target, from: self, forEvent: nil) } } <file_sep>/SwiftSculpturesTests/HomeViewControllerSpec.swift // // HomeViewControllerSpec.swift // SwiftSculptures // // Created by <NAME> on 2015-10-17. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import XCTest class HomeViewControllerSpec: XCTestCase { var viewController: HomeViewController! override func setUp() { super.setUp() viewController = HomeViewController().viewController() as! HomeViewController } func X_testTappingRightBarButtonItemShowsPictureTakingVc() { let button = viewController.navigationItem.rightBarButtonItem as UIBarButtonItem! button.tap() let topVC = viewController.navigationController?.topViewController XCTAssert(topVC is PictureTakingViewController, "Picture taking VC should be shown") } } <file_sep>/SwiftSculpturesTests/UIViewController+TestHelper.swift // // UIViewController+TestHelper.swift // SwiftSculptures // // Created by <NAME> on 2015-10-16. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit extension UIViewController { func viewController() -> UIViewController { let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.classForCoder)) let identifier = toString(self.dynamicType).componentsSeparatedByString(".").last let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier!) as! UIViewController let navController = UINavigationController(rootViewController: viewController) UIApplication.sharedApplication().keyWindow!.rootViewController = navController let _ = viewController.view return viewController } }<file_sep>/SwiftSculptures/CustomTextField.swift // // CustomTextField.swift // SwiftSculptures // // Created by <NAME> on 2015-10-17. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit class CustomTextField: UITextField { override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, 10, 10); } override func editingRectForBounds(bounds: CGRect) -> CGRect { return self.textRectForBounds(bounds) } } <file_sep>/SwiftSculpturesTests/PictureTakingViewControllerSpec.swift // // PictureTakingViewControllerSpec.swift // SwiftSculptures // // Created by <NAME> on 2015-10-16. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import XCTest class PictureTakingViewControllerSpec : XCTestCase { var viewController: PictureTakingViewController! override func setUp() { super.setUp() viewController = PictureTakingViewController().viewController() as! PictureTakingViewController } func testTappingRightBarButtonItemShowsImagePicker() { let button = viewController.navigationItem.rightBarButtonItem as UIBarButtonItem! button.tap() let presentedVc = viewController.navigationController?.presentedViewController XCTAssert(presentedVc is UIImagePickerController, "Image picker should be shown") } } <file_sep>/SwiftSculptures/HomeViewController.swift // // HomeViewController.swift // SwiftSculptures // // Created by <NAME> on 2015-10-16. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit class HomeViewController: UIViewController { } <file_sep>/SwiftSculpturesTests/UIControl+TestHelpers.swift // // UIControl+TestHelpers.swift // SwiftSculptures // // Created by <NAME> on 2015-10-16. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit extension UIControl { func tap() { self.sendActionsForControlEvents(UIControlEvents.TouchDown) self.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } }
8a9a740ce485d044e778c9c3a2b8fcce9e089257
[ "Swift" ]
8
Swift
cannawen/sculpture
74040e87775d6b879362531eabb53c6cb3a5d401
ef96dbde04830d2f7da308c12ba65f938b198bb2
refs/heads/master
<file_sep><?php require_once('model/userModel.php'); require_once('model/DisciplinaModel.php'); require_once('view/AlunoView.php'); class AlunoController{ var $userModel, $disciplinaModel, $alunoView; public function __construct(){ $this->userModel = new UserModel(); $this->disciplinaModel = new DisciplinaModel(); $this->alunoView = new AlunoView(); } public function action($username){ $alunoName = $this->userModel->getUserName($username); $alunoID = $this->userModel->getAlunoID($username); if($_SERVER['REQUEST_METHOD']=='GET' && isset($_GET['disciplina'])){ $disciplina = $_GET['disciplina']; $notas = $this->disciplinaModel->getNotasWithAlunoAndDisciplina($alunoID, $disciplina); $this->alunoView->drawNotas($notas); }else{ $disciplinas = $this->disciplinaModel->getDisciplinasAluno($alunoID); $this->alunoView->drawDisciplineButtons($disciplinas); } } public function media($username){ $alunoName = $this->userModel->getUserName($username); $notaMedia = $this->getnotaMedia($username); $this->alunoView->drawMedia($username, $notaMedia); } public function getnotaMedia($username){ $alunoID = $this->userModel->getAlunoID($username); $alunoDisciplinas = $this->disciplinaModel->getAlunoDisciplinasFromALuno($alunoID); $i = 0; $notasECTSMultiplied = 0; $ectsTotal = 0; $nAlunoDisciplinas = count($alunoDisciplinas); if($nAlunoDisciplinas == 0){return 0;} for($i=0; $i<$nAlunoDisciplinas; $i++){ $this->disciplinaModel->setNotaFinal($alunoDisciplinas[$i][0]); } $nDisciplinasFinished = 0; $alunoDisciplinas = $this->disciplinaModel->getAlunoDisciplinasFromALuno($alunoID); for($i=0; $i<$nAlunoDisciplinas; $i++){ if(!is_null($alunoDisciplinas[$i][2])){ $ects = $this->disciplinaModel->getECTS($alunoDisciplinas[$i][1]); $notaECTSMultiplied = $alunoDisciplinas[$i][2] * $ects; $notasECTSMultiplied = $notasECTSMultiplied + $notaECTSMultiplied; $ectsTotal = $ectsTotal + $ects; $nDisciplinasFinished = $nDisciplinasFinished + 1; //echo $ects; echo $alunoDisciplinas[$i][0]; } } //echo $alunoDisciplinas[1][2]; if($nDisciplinasFinished == 0){ return false; }else{ $media = $notasECTSMultiplied / ($ectsTotal); $media = round($media, 2); return $media; } } } ?><file_sep><?php if(!defined('SMARTY_DIR'))define('SMARTY_DIR','view/smarty/libs/'); if(!defined('SMARTY_TPL'))define('SMARTY_TPL','view/templates/'); if(!defined('SMARTY_CPL'))define('SMARTY_CPL','view/templates/compile/'); require_once(SMARTY_DIR.'Smarty.class.php'); class AuthenticationView{ var $smarty; public function __construct(){ $this->smarty = new Smarty(); $this->smarty->template_dir = './view/templates/'; $this->smarty->compile_dir = './view/templates/compile/'; } public function drawAuthenticationPage($situation){ if($situation != 'normal'){ $this->smarty->assign('showAuthenticationString', true); $this->smarty->assign('authenticationString', $situation); }else{$this->smarty->assign('showAuthenticationString', false);} $this->smarty->display('authentication.tpl'); } } ?><file_sep><?php /* Smarty version 3.1.30, created on 2016-09-21 17:37:14 from "C:\wamp64\www\daw\projeto\view\templates\professorHomePage.tpl" */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.30', 'unifunc' => 'content_57e2c54a48d4b7_68409228', 'has_nocache_code' => false, 'file_dependency' => array ( 'c48eae76b5335469226f86c8efa29801f1fd9207' => array ( 0 => 'C:\\wamp64\\www\\daw\\projeto\\view\\templates\\professorHomePage.tpl', 1 => 1474479433, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_57e2c54a48d4b7_68409228 (Smarty_Internal_Template $_smarty_tpl) { ?> <!DOCTYPE html> <html lang="pt-PT"> <head> <meta charset="utf-8"> <!-- <meta http-equiv="X-UA-Compatible" content="IE=edge"> --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gestão de notas</title> <link rel="stylesheet" href="view/bootstrap/css/bootstrap.min.css"> <link href="view/css/navbar.css" rel="stylesheet"> <link href="view/css/jumbotron.css" rel="stylesheet"> <?php echo '<script'; ?> src="../../assets/js/ie-emulation-modes-warning.js"><?php echo '</script'; ?> > </head> <body> <!-- <div class="container"> --> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php">Sistema de Gestão de notas</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="controller/logout.php">Terminar sessão</a></li> </ul> </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </nav> <!-- </div> --> <div class="container"> <div class="row"> <form action="index.php" method="get"> <?php $_smarty_tpl->tpl_vars['i'] = new Smarty_Variable(null, $_smarty_tpl->isRenderingCache);$_smarty_tpl->tpl_vars['i']->step = 1;$_smarty_tpl->tpl_vars['i']->total = (int) ceil(($_smarty_tpl->tpl_vars['i']->step > 0 ? $_smarty_tpl->tpl_vars['nDisciplinas']->value-1+1 - (0) : 0-($_smarty_tpl->tpl_vars['nDisciplinas']->value-1)+1)/abs($_smarty_tpl->tpl_vars['i']->step)); if ($_smarty_tpl->tpl_vars['i']->total > 0) { for ($_smarty_tpl->tpl_vars['i']->value = 0, $_smarty_tpl->tpl_vars['i']->iteration = 1;$_smarty_tpl->tpl_vars['i']->iteration <= $_smarty_tpl->tpl_vars['i']->total;$_smarty_tpl->tpl_vars['i']->value += $_smarty_tpl->tpl_vars['i']->step, $_smarty_tpl->tpl_vars['i']->iteration++) { $_smarty_tpl->tpl_vars['i']->first = $_smarty_tpl->tpl_vars['i']->iteration == 1;$_smarty_tpl->tpl_vars['i']->last = $_smarty_tpl->tpl_vars['i']->iteration == $_smarty_tpl->tpl_vars['i']->total;?> <div class="col-lg-4"> <button type="submit" name="disciplina" value="<?php echo $_smarty_tpl->tpl_vars['disciplinas']->value[$_smarty_tpl->tpl_vars['i']->value][0];?> " class="btn btn-info"><?php echo $_smarty_tpl->tpl_vars['disciplinas']->value[$_smarty_tpl->tpl_vars['i']->value][1];?> </button><p/> </div> <?php } } ?> </form> </div> </div> <?php echo '<script'; ?> src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><?php echo '</script'; ?> > <?php echo '<script'; ?> >window.jQuery || document.write('<?php echo '<script'; ?> src="view/bootstrap/js/jquery.min.js"><\/script>')<?php echo '</script'; ?> > <?php echo '<script'; ?> src="view/bootstrap/js/bootstrap.min.js"><?php echo '</script'; ?> > </body> </html><?php } } <file_sep><?php require_once('controller/authenticationController.php'); session_start(); $authenticationController = new AuthenticationController(); $authenticationController->media(); ?><file_sep><?php /* Smarty version 3.1.30, created on 2016-09-19 16:57:10 from "C:\wamp64\www\daw\projeto\view\templates\authentication.tpl" */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.30', 'unifunc' => 'content_57e018e678c087_73470339', 'has_nocache_code' => false, 'file_dependency' => array ( '13ed3e2d2f42c8b4fb6c56f29f2d5747a2c041c2' => array ( 0 => 'C:\\wamp64\\www\\daw\\projeto\\view\\templates\\authentication.tpl', 1 => 1474304228, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_57e018e678c087_73470339 (Smarty_Internal_Template $_smarty_tpl) { ?> <!DOCTYPE html> <html lang="pt-pt"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gestão de notas</title> <link rel="stylesheet" href="view/bootstrap/css/bootstrap.min.css"> <link href="view/css/navbar.css" rel="stylesheet"> <link href="view/css/jumbotron.css" rel="stylesheet"> <link href="view/css/signin.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Sistema de gestão de notas</a> </div> <div id="navbar" class="collapse navbar-collapse"> </div> </div> </nav> <div class="container"> <div class="page-header"> <h1>Bem-vindo ao sistema de gestão de notas do IPBeja</h1> </div> <p class="lead">Esta página destina-se apenas a alunos e professores do Instituto Politécnico de Beja.</p> <div class="jumbotron"> <div class="container"> <?php if ($_smarty_tpl->tpl_vars['showAuthenticationString']->value) {?> <p class="text-danger"><?php echo $_smarty_tpl->tpl_vars['authenticationString']->value;?> </p> <?php }?> <p>Para entrar introduza os seu nome de utilizador e senha:</p> <form class="form-signin" role="form" method="post" action="index.php"> <label for="username">Nome de utilizador</label> <input type="text" id="username" name="username" class="form-control" placeholder="username" required autofocus> <label for="password">Senha</label> <input type="password" id="password" name="password" class="form-control" placeholder="<PASSWORD>" required> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <!-- <button class="btn btn-lg btn-primary btn-block" id="loginButton" name="login" type="submit"> Sign in </button> --> <input class="btn btn-lg btn-primary btn-block" type="submit" value="login" name="login"> </form> </div> </div> </div> <?php echo '<script'; ?> src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><?php echo '</script'; ?> > <?php echo '<script'; ?> >window.jQuery || document.write('<?php echo '<script'; ?> src="view/bootstrap/js/jquery.min.js"><\/script>')<?php echo '</script'; ?> > <?php echo '<script'; ?> src="view/bootstrap/js/bootstrap.min.js"><?php echo '</script'; ?> > </body> </html><?php } } <file_sep><?php /* Smarty version 3.1.30, created on 2016-09-19 17:29:10 from "C:\wamp64\www\daw\projeto\view\templates\alunoNotas.tpl" */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.30', 'unifunc' => 'content_57e02066a12160_88184279', 'has_nocache_code' => false, 'file_dependency' => array ( '5e13549aff2f365b17294252fb1492a335267100' => array ( 0 => 'C:\\wamp64\\www\\daw\\projeto\\view\\templates\\alunoNotas.tpl', 1 => 1474306149, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_57e02066a12160_88184279 (Smarty_Internal_Template $_smarty_tpl) { ?> <!DOCTYPE html> <html lang="pt-PT"> <head> <meta charset="utf-8"> <!-- <meta http-equiv="X-UA-Compatible" content="IE=edge"> --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gestão de notas</title> <link rel="stylesheet" href="view/bootstrap/css/bootstrap.min.css"> <link href="view/css/navbar.css" rel="stylesheet"> <link href="view/css/jumbotron.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php">Sistema de Gestão de notas</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="media.php">ver Média</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="controller/logout.php">Terminar sessão</a></li> </ul> </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </nav> <div class="container disciplinas"> <table class="table"> <tr><th>Avaliação</th><th>nota<th></tr> <?php $_smarty_tpl->tpl_vars['i'] = new Smarty_Variable(null, $_smarty_tpl->isRenderingCache);$_smarty_tpl->tpl_vars['i']->step = 1;$_smarty_tpl->tpl_vars['i']->total = (int) ceil(($_smarty_tpl->tpl_vars['i']->step > 0 ? $_smarty_tpl->tpl_vars['nNotas']->value-1+1 - (0) : 0-($_smarty_tpl->tpl_vars['nNotas']->value-1)+1)/abs($_smarty_tpl->tpl_vars['i']->step)); if ($_smarty_tpl->tpl_vars['i']->total > 0) { for ($_smarty_tpl->tpl_vars['i']->value = 0, $_smarty_tpl->tpl_vars['i']->iteration = 1;$_smarty_tpl->tpl_vars['i']->iteration <= $_smarty_tpl->tpl_vars['i']->total;$_smarty_tpl->tpl_vars['i']->value += $_smarty_tpl->tpl_vars['i']->step, $_smarty_tpl->tpl_vars['i']->iteration++) { $_smarty_tpl->tpl_vars['i']->first = $_smarty_tpl->tpl_vars['i']->iteration == 1;$_smarty_tpl->tpl_vars['i']->last = $_smarty_tpl->tpl_vars['i']->iteration == $_smarty_tpl->tpl_vars['i']->total;?> <tr><td><?php echo $_smarty_tpl->tpl_vars['notas']->value[$_smarty_tpl->tpl_vars['i']->value][2];?> (<?php echo $_smarty_tpl->tpl_vars['notas']->value[$_smarty_tpl->tpl_vars['i']->value][3];?> )</td><td><?php echo $_smarty_tpl->tpl_vars['notas']->value[$_smarty_tpl->tpl_vars['i']->value][1];?> <?php } } ?> </table> </div> <?php echo '<script'; ?> src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><?php echo '</script'; ?> > <?php echo '<script'; ?> >window.jQuery || document.write('<?php echo '<script'; ?> src="view/bootstrap/js/jquery.min.js"><\/script>')<?php echo '</script'; ?> > <?php echo '<script'; ?> src="view/bootstrap/js/bootstrap.min.js"><?php echo '</script'; ?> > </body> </html><?php } } <file_sep><?php define('SMARTY_DIR','view/smarty/libs/'); define('SMARTY_TPL','view/templates/'); define('SMARTY_CPL','view/templates/compile/'); require_once(SMARTY_DIR.'Smarty.class.php'); class AlunoView{ var $smarty; public function __construct(){ $this->smarty = new Smarty(); $this->smarty->template_dir = './view/templates/'; $this->smarty->compile_dir = './view/templates/compile/'; } public function drawDisciplineButtons($disciplinas){ $this->smarty->assign('disciplinas', $disciplinas); $numberOfDisciplinas = count($disciplinas); $this->smarty->assign('nDisciplinas', $numberOfDisciplinas); $this->smarty->display('alunoHomePage.tpl'); } public function drawNotas($notas){ $this->smarty->assign('notas', $notas); $numberOfNotas = count($notas); $this->smarty->assign('nNotas', $numberOfNotas); $this->smarty->display('alunoNotas.tpl'); } public function drawMedia($alunoName, $notaMedia){ $this->smarty->assign('name', $alunoName); $this->smarty->assign('media', $notaMedia); $this->smarty->display('alunoMedia.tpl'); } } ?><file_sep><?php /* Smarty version 3.1.30, created on 2016-09-22 19:21:45 from "C:\wamp64\www\daw\projeto\view\templates\alunoMedia.tpl" */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.30', 'unifunc' => 'content_57e42f49494da7_27252288', 'has_nocache_code' => false, 'file_dependency' => array ( 'ffab821bef35d74d66a137afa9d194067f1fae51' => array ( 0 => 'C:\\wamp64\\www\\daw\\projeto\\view\\templates\\alunoMedia.tpl', 1 => 1474572102, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_57e42f49494da7_27252288 (Smarty_Internal_Template $_smarty_tpl) { ?> <!DOCTYPE html> <html lang="pt-PT"> <head> <meta charset="utf-8"> <!-- <meta http-equiv="X-UA-Compatible" content="IE=edge"> --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gestão de notas</title> <link rel="stylesheet" href="view/bootstrap/css/bootstrap.min.css"> <link href="view/css/navbar.css" rel="stylesheet"> <link href="view/css/jumbotron.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php">Sistema de Gestão de notas</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="media.php">ver Média</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="controller/logout.php">Terminar sessão</a></li> </ul> </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </nav> <div class="container disciplinas"> <?php if ($_smarty_tpl->tpl_vars['media']->value == false) {?> <h2>O aluno ainda não completou nenhuma disciplina<h2> <?php } else { ?> <h2>A sua média é de <?php echo $_smarty_tpl->tpl_vars['media']->value;?> valores<h2> <?php }?> </div> <?php echo '<script'; ?> src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><?php echo '</script'; ?> > <?php echo '<script'; ?> >window.jQuery || document.write('<?php echo '<script'; ?> src="view/bootstrap/js/jquery.min.js"><\/script>')<?php echo '</script'; ?> > <?php echo '<script'; ?> src="view/bootstrap/js/bootstrap.min.js"><?php echo '</script'; ?> > </body> </html><?php } } <file_sep><?php require_once('model/userModel.php'); require_once('model/DisciplinaModel.php'); require_once('view/ProfessorView.php'); class ProfessorController{ var $userModel, $disciplinaModel, $professorView; public function __construct(){ $this->userModel = new UserModel(); $this->disciplinaModel = new DisciplinaModel(); $this->professorView = new ProfessorView(); } public function action($username){ $professorName = $this->userModel->getUserName($username); $professorID = $this->userModel->getProfessorID($username); if($_SERVER['REQUEST_METHOD']=='GET' && isset($_GET['disciplina'])){ $disciplina = $_GET['disciplina']; $evaluations = $this->disciplinaModel->getEvaluations($disciplina); $this->professorView->drawEvaluationButtons($disciplina, $evaluations); }else if($_SERVER['REQUEST_METHOD']=='GET' && isset($_GET['evaluation'])){ $evaluation = $_GET['evaluation']; $notas = $this->disciplinaModel->getNotas($evaluation); $disciplina = $this->disciplinaModel->getDisciplinaFromEvaluation($evaluation); $this->professorView->drawEvaluationForm($disciplina, $evaluation, $notas); } else if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['changeGrades'])){ $i = 0; $notasNovas = array(); foreach($_POST['nota'] as $gradeID=>$grade){ $notasNovas[$i] = array($gradeID, $grade); $i++; } $evaluation = $_POST['evaluation']; $disciplina = $this->disciplinaModel->getDisciplinaFromEvaluation($evaluation); $save = $this->disciplinaModel->changeGrades($notasNovas); $notas = $this->disciplinaModel->getNotas($evaluation); $this->professorView->drawEvaluationForm($disciplina, $evaluation, $notas); } else{ /* $professorID = $this->userModel->getProfessorID($username); $professorName = $this->userModel->getUserName($username); */ $disciplinas = $this->disciplinaModel->getDisciplinasLecionadas($professorID); $this->professorView->drawDisciplineButtons($disciplinas); } } } ?><file_sep><?php require_once('model/DataBaseConnection.php'); class DisciplinaModel{ var $db; public function __construct(){ $this->db = new DataBaseConnection(); } public function getDisciplinaFromEvaluation($evaluation){ $this->db->connect(); $disciplinas = array(); $query = "select nDisciplina from evaluation where numero = ".$evaluation; $result = mysqli_query($this->db->getConnection(), $query); $this->db->disconnect(); if($result){ $row = $result->fetch_assoc(); return $this->getDisciplinaName($row['nDisciplina']); } } public function getDisciplinaName($nDisciplina){ $this->db->connect(); $disciplinas = array(); $query = "select nome from disciplina where numero = ".$nDisciplina; $result = mysqli_query($this->db->getConnection(), $query); $this->db->disconnect(); if($result){ $row = $result->fetch_assoc(); return ($row['nome']); } } public function getDisciplinasLecionadas($professorid){ $this->db->connect(); $disciplinas = array(); $query = "select * from disciplina where nProfessor = '".$professorid."'"; $i = 0; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); while($row = mysqli_fetch_array($result)) { $disciplinas[$i] = array($row['numero'],$row['nome']); $i++; } return $disciplinas; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'este professor não tem disciplinas'; $this->db->disconnect(); return false; } } public function getDisciplinasAluno($alunoID){ $this->db->connect(); $disciplinas = array(); //$disciplinasID = $this->getDisciplinasIDsFromADs($alunoID); $query = "select * from disciplina where disciplina.numero in (select alunodisciplina.nDisciplina from alunodisciplina where alunodisciplina.nAluno = ".$alunoID.")"; $i = 0; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); while($row = mysqli_fetch_array($result)) { $disciplinas[$i] = array($row['numero'],$row['nome']); $i++; } return $disciplinas; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'este aluno não tem disciplinas'; $this->db->disconnect(); return false; } } public function getEvaluations($disciplina){ $this->db->connect(); $evaluations = array(); $query = "select * from avaliacao where nDisciplina = ".$disciplina; $i = 0; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); while($row = mysqli_fetch_array($result)) { $evaluations[$i] = array($row['numero'],$row['nome'],$row['tipo']); $i++; } return $evaluations; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'Esta disciplina não é lecionada por este professor'; $this->db->disconnect(); return false; } } public function getNotas($evaluation){ $this->db->connect(); $notas = array(); $query = "select * from nota where nAvaliacao = ".$evaluation; $i = 0; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); while($row = mysqli_fetch_array($result)) { $nomeAluno = $this->getNomeAlunoWithADID($row['nAlunoDisciplina']); $notas[$i] = array($row['numero'], $row['nota'], $nomeAluno); $i++; } return $notas; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'Esta disciplina não é lecionada por este professor'; $this->db->disconnect(); return false; } } public function getNotasWithAlunoAndDisciplina($alunoID, $disciplinaID){ $notas = array(); $ad = $this->getADWithAlunoAndDisciplina($alunoID, $disciplinaID); $this->db->connect(); $query = "select * from nota where nAlunoDisciplina = ".$ad; $i = 0; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); while($row = mysqli_fetch_array($result)) { $nomeAvaliacao = $this->getNomeAvaliacaoWithID($row['nAvaliacao']); $tipoAvaliacao = $this->gettipoAvaliacaoWithID($row['nAvaliacao']); $valorAvaliacao = $this->getValorAvaliacaoWithID($row['nAvaliacao']); $notaMinima = $this->getNotaMinima($row['nAvaliacao']); if(is_null($row['nota'])){$row['nota'] = "esta avaliação ainda não foi realizada";} $notas[$i] = array($row['numero'], $row['nota'], $nomeAvaliacao, $tipoAvaliacao, $valorAvaliacao, $notaMinima); $i++; } return $notas; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'Esta aluno não tem avaliações nesta disciplina '; $this->db->disconnect(); return false; } } private function getAlunoWithAD($alunoDisciplina){ $this->db->connect(); $query = "select nAluno from alunodisciplina where numero = ".$alunoDisciplina; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['nAluno']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'não existe aluno'; $this->db->disconnect(); return false; } } private function getDisciplinaWithAD($alunoDisciplina){ $this->db->connect(); $query = "select * from alunodisciplina where numero = ".$alunoDisciplina; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['nDisciplina']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'não existe aluno'; $this->db->disconnect(); return false; } } private function getUSerIdFromAluno($alunoID){ $this->db->connect(); $query = "select * from aluno where numero = ".$alunoID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['nUser']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'não existe utilizador'; $this->db->disconnect(); return false; } } private function getNomeAlunoWithADID($adID){ $alunoID = $this->getAlunoWithAD($adID); $userID = $this->getUSerIdFromAluno($alunoID); $this->db->connect(); $query = "select nome from user where numero = ".$userID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['nome']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'não existe utilizador'; $this->db->disconnect(); return false; } } private function getDisciplinasIDsFromADs($adID){ $this->db->connect(); $disciplinas = array(); $query = "select * from alunoDisciplina where numero = ".$adID; $i = 0; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); while($row = mysqli_fetch_array($result)) { $row = $disciplinasID[$i] = $row['nDisciplina']; $i++; } return $disciplinasID; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'este aluno não tem disciplinas'; $this->db->disconnect(); return false; } } private function getADWithAlunoAndDisciplina($alunoID, $disciplinaID){ $this->db->connect(); $disciplinas = array(); $query = "select * from alunodisciplina where nAluno = ".$alunoID." and nDisciplina = ".$disciplinaID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['numero']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'este aluno não tem disciplinas'; $this->db->disconnect(); return false; } } private function getNomeAvaliacaoWithID($avaliacaoID){ $this->db->connect(); $query = "select * from avaliacao where numero = ".$avaliacaoID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['nome']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'erro a aceder ao nome das avaliações'; $this->db->disconnect(); return false; } } private function gettipoAvaliacaoWithID($avaliacaoID){ $this->db->connect(); $query = "select * from avaliacao where numero = ".$avaliacaoID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['tipo']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'erro a aceder ao nome das avaliações'; $this->db->disconnect(); return false; } } private function getValorAvaliacaoWithID($avaliacaoID){ $this->db->connect(); $query = "select * from avaliacao where numero = ".$avaliacaoID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['valor']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'erro a aceder ao nome das avaliações'; $this->db->disconnect(); return false; } } private function getNotaMinima($avaliacaoID){ $this->db->connect(); $query = "select * from avaliacao where numero = ".$avaliacaoID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['notaMinima']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'erro a aceder ao nome das avaliações'; $this->db->disconnect(); return false; } } public function changeGrades($notas){ $sizeNotas = count($notas); $result; for($i=0; $i<$sizeNotas; $i++){ $this->db->connect(); $query = "update nota set nota = ".$notas[$i][1]." where numero = ".$notas[$i][0]; $result = mysqli_query($this->db->getConnection(), $query); } if($result){return true;} else{return false;} } public function getAlunoDisciplinasFromALuno($alunoID){ $this->db->connect(); $i = 0; $alunoDisciplinas = array(); $query = "select * from alunoDisciplina where nAluno = ".$alunoID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); while($row = mysqli_fetch_array($result)) { $alunoDisciplinas[$i] = array($row['numero'],$row['nDisciplina'], $row['notaFinal']); $i++; } return $alunoDisciplinas; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'este aluno não tem disciplinas'; $this->db->disconnect(); return false; } } public function getECTS($disciplinaID){ $this->db->connect(); $query = "select * from disciplina where numero = ".$disciplinaID; $result = mysqli_query($this->db->getConnection(), $query); if ($result) { $this->db->disconnect(); $row = mysqli_fetch_array($result); return $row['ECTS']; } else { //printf("Errormessage: %s\n", mysqli_error($this->db->getConnection())); echo 'erro a aceder ao nome das avaliações'; $this->db->disconnect(); return false; } } public function getnotaECTS($alunoID){ $alunoDisciplinas = $this->getAlunoDisciplinasFromALuno($alunoID); $i = 0; $notaECTSMultiplied; $nAlunoDisciplinas = count($alunoDisciplinas); for($i=0; $i<$nAlunoDisciplinas; $i++){ if(!is_null($alunoDisciplinas[$i][2])){ $ects = $this->getECTS($alunoDisciplinas[$i][0]); } } } public function setNotaFinal($alunoDisciplinaID){ $x = 0; $alunoID =$this->getAlunoWithAD($alunoDisciplinaID); $disciplinaID = $this->getDisciplinaWithAD($alunoDisciplinaID); $notas = $this->getNotasWithAlunoAndDisciplina($alunoID, $disciplinaID); $nNotas = count($notas); $differentEvaluations = array(); $notasMaisAltas = array(); for($i=0; $i<$nNotas; $i++){ if($notas[$i][3] === "normal"){ array_push($differentEvaluations, $notas[$i][2]); $notasMaisAltas[$x] = array($notas[$i][2], $notas[$i][1], $notas[$i][4], $notas[$i][5]); $x++; } } $nNotasMaisAltas = count($notasMaisAltas); for($i=0; $i<$nNotas; $i++){ for($j=0; $j<$nNotasMaisAltas;$j++){ if($notas[$i][2] == $notasMaisAltas[$j][0]){ if($notas[$i][1] > $notasMaisAltas[$j][1]){ $notasMaisAltas[$j][1] = $notas[$i][1]; } } } } $notaSemiFinal = 0; $fracaoNota; for($i=0; $i<$nNotasMaisAltas; $i++){ if(is_null($notasMaisAltas[$i][1])){return 0;} if($notasMaisAltas[$i][1]<$notasMaisAltas[$i][3]){ return 0; }else{ $fracaoNota = $notasMaisAltas[$i][2]/100; $notaSemiFinal = $notaSemiFinal + ($notasMaisAltas[$i][1] * $fracaoNota); } } $notaFinal = round($notaSemiFinal); if($notaFinal >= 10){ $this->db->connect(); $query = "update alunodisciplina set notaFinal = ".$notaFinal." where numero = ".$alunoDisciplinaID; $result = mysqli_query($this->db->getConnection(), $query); if($result){return 1;} else{return 2;} } } } ?><file_sep><?php class DataBaseConnection{ var $con; public function __construct(){ } function connect(){ $this->con = mysqli_connect("localhost","root","", "projeto"); if(!$this->con){ die('Could not connect:'.mysql_error()); echo 'erro'; } else{ //mysqli_select_db($this->con, "projetopcr"); } } function disconnect(){ mysqli_close($this->con); } public function getConnection(){ return $this->con; } } ?><file_sep><?php /* session_save_path('sessions'); ini_set('session.gc_probability', 1); */ session_start(); require_once("controller/authenticationController.php"); $authentication = new AuthenticationController(); $authentication->action(); ?><file_sep><?php /* define('SMARTY_DIR','view/smarty/libs/'); define('SMARTY_TPL','view/templates/'); define('SMARTY_CPL','view/templates/compile/'); */ require_once(SMARTY_DIR.'Smarty.class.php'); class ProfessorView{ var $smarty; public function __construct(){ $this->smarty = new Smarty(); $this->smarty->template_dir = './view/templates/'; $this->smarty->compile_dir = './view/templates/compile/'; } public function drawDisciplineButtons($disciplinas){ $this->smarty->assign('disciplinas', $disciplinas); $numberOfDisciplinas = count($disciplinas); $this->smarty->assign('nDisciplinas', $numberOfDisciplinas); $this->smarty->display('professorHomePage.tpl'); } public function drawEvaluationButtons($disciplina, $evaluations){ $this->smarty->assign('disciplina', $disciplina); $this->smarty->assign('evaluations', $evaluations); $numberOfEvaluations = count($evaluations); $this->smarty->assign('nEvaluations', $numberOfEvaluations); $this->smarty->display('professorDisciplina.tpl'); } public function drawEvaluationForm($disciplina, $evaluation, $notas){ $this->smarty->assign('disciplina', $disciplina); $this->smarty->assign('evaluation', $evaluation); $numberOfNotas = count($notas); $this->smarty->assign('nNotas', $numberOfNotas); $this->smarty->assign('notas', $notas); $this->smarty->display('professorEvaluation.tpl'); } } ?><file_sep><?php session_start(); require_once("authenticationController.php"); $authentication = new AuthenticationController(); $authentication->action(); ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.5.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Sep 22, 2016 at 07:28 PM -- Server version: 5.7.11 -- PHP Version: 5.6.19 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `projeto` -- -- -------------------------------------------------------- -- -- Table structure for table `aluno` -- CREATE TABLE `aluno` ( `numero` int(6) NOT NULL, `nUser` int(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `aluno` -- INSERT INTO `aluno` (`numero`, `nUser`) VALUES (1, 2), (2, 3); -- -------------------------------------------------------- -- -- Table structure for table `alunodisciplina` -- CREATE TABLE `alunodisciplina` ( `numero` int(11) NOT NULL, `nAluno` int(6) NOT NULL, `nDisciplina` int(8) NOT NULL, `notaFinal` int(2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `alunodisciplina` -- INSERT INTO `alunodisciplina` (`numero`, `nAluno`, `nDisciplina`, `notaFinal`) VALUES (1, 1, 1, 13), (2, 2, 1, NULL), (3, 1, 2, NULL); -- -------------------------------------------------------- -- -- Table structure for table `avaliacao` -- CREATE TABLE `avaliacao` ( `numero` int(10) NOT NULL, `nome` varchar(30) NOT NULL, `tipo` varchar(15) NOT NULL, `valor` int(3) NOT NULL, `nDisciplina` int(8) NOT NULL, `notaMinima` int(2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `avaliacao` -- INSERT INTO `avaliacao` (`numero`, `nome`, `tipo`, `valor`, `nDisciplina`, `notaMinima`) VALUES (1, 'teste 1', 'normal', 25, 1, NULL), (2, 'teste 2', 'normal', 25, 1, NULL), (3, 'trabalho', 'normal', 50, 1, NULL), (4, 'teste 1', 'normal', 30, 2, 5), (5, 'teste 2', 'normal', 30, 2, NULL), (6, 'trabalho', 'normal', 40, 2, NULL); -- -------------------------------------------------------- -- -- Table structure for table `curso` -- CREATE TABLE `curso` ( `numero` int(3) NOT NULL, `nome` varchar(40) NOT NULL, `totalECTS` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `curso` -- INSERT INTO `curso` (`numero`, `nome`, `totalECTS`) VALUES (1, 'Engenharia Informática', 180); -- -------------------------------------------------------- -- -- Table structure for table `cursoaluno` -- CREATE TABLE `cursoaluno` ( `numero` int(7) NOT NULL, `nAluno` int(6) NOT NULL, `nCurso` int(3) NOT NULL, `media` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `disciplina` -- CREATE TABLE `disciplina` ( `numero` int(8) NOT NULL, `nome` varchar(50) NOT NULL, `nProfessor` int(5) NOT NULL, `ECTS` int(11) NOT NULL, `nCurso` int(3) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `disciplina` -- INSERT INTO `disciplina` (`numero`, `nome`, `nProfessor`, `ECTS`, `nCurso`) VALUES (1, 'Desenvolvimento de Aplicações Web', 1, 6, 1), (2, 'Tecnologias para a Web e Ambiente Móveis', 1, 6, 1); -- -------------------------------------------------------- -- -- Table structure for table `nota` -- CREATE TABLE `nota` ( `numero` int(10) NOT NULL, `nAlunoDisciplina` int(11) NOT NULL, `nAvaliacao` int(10) NOT NULL, `nota` int(2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `nota` -- INSERT INTO `nota` (`numero`, `nAlunoDisciplina`, `nAvaliacao`, `nota`) VALUES (1, 1, 1, 10), (2, 1, 2, 10), (3, 1, 3, 15), (4, 2, 1, 10), (5, 2, 2, NULL), (6, 2, 3, NULL), (7, 3, 4, NULL), (8, 3, 5, NULL), (9, 3, 6, NULL); -- -------------------------------------------------------- -- -- Table structure for table `professor` -- CREATE TABLE `professor` ( `numero` int(5) NOT NULL, `nUser` int(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `professor` -- INSERT INTO `professor` (`numero`, `nUser`) VALUES (1, 1); -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `numero` int(6) NOT NULL, `passe` varchar(100) NOT NULL, `nome` varchar(40) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `user` -- INSERT INTO `user` (`numero`, `passe`, `nome`) VALUES (1, ' ', '<NAME>'), (2, ' ', '<NAME>'), (3, ' ', 'Alexandre'); -- -- Indexes for dumped tables -- -- -- Indexes for table `aluno` -- ALTER TABLE `aluno` ADD PRIMARY KEY (`numero`), ADD UNIQUE KEY `numero` (`numero`), ADD KEY `nUser` (`nUser`); -- -- Indexes for table `alunodisciplina` -- ALTER TABLE `alunodisciplina` ADD PRIMARY KEY (`numero`), ADD KEY `nDisciplina` (`nDisciplina`), ADD KEY `nAluno` (`nAluno`); -- -- Indexes for table `avaliacao` -- ALTER TABLE `avaliacao` ADD PRIMARY KEY (`numero`), ADD KEY `nDisciplina` (`nDisciplina`); -- -- Indexes for table `curso` -- ALTER TABLE `curso` ADD PRIMARY KEY (`numero`); -- -- Indexes for table `cursoaluno` -- ALTER TABLE `cursoaluno` ADD PRIMARY KEY (`numero`), ADD KEY `nAluno` (`nAluno`), ADD KEY `nCurso` (`nCurso`); -- -- Indexes for table `disciplina` -- ALTER TABLE `disciplina` ADD PRIMARY KEY (`numero`), ADD UNIQUE KEY `numero` (`numero`), ADD KEY `nProfessor` (`nProfessor`), ADD KEY `nCurso` (`nCurso`); -- -- Indexes for table `nota` -- ALTER TABLE `nota` ADD PRIMARY KEY (`numero`), ADD KEY `nAlunoDisciplina` (`nAlunoDisciplina`), ADD KEY `nAvaliacao` (`nAvaliacao`); -- -- Indexes for table `professor` -- ALTER TABLE `professor` ADD PRIMARY KEY (`numero`), ADD UNIQUE KEY `numero` (`numero`), ADD KEY `nUser` (`nUser`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`numero`), ADD UNIQUE KEY `numero` (`numero`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `aluno` -- ALTER TABLE `aluno` MODIFY `numero` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `alunodisciplina` -- ALTER TABLE `alunodisciplina` MODIFY `numero` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `avaliacao` -- ALTER TABLE `avaliacao` MODIFY `numero` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `curso` -- ALTER TABLE `curso` MODIFY `numero` int(3) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `cursoaluno` -- ALTER TABLE `cursoaluno` MODIFY `numero` int(7) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `disciplina` -- ALTER TABLE `disciplina` MODIFY `numero` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `nota` -- ALTER TABLE `nota` MODIFY `numero` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `professor` -- ALTER TABLE `professor` MODIFY `numero` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `numero` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Constraints for dumped tables -- -- -- Constraints for table `aluno` -- ALTER TABLE `aluno` ADD CONSTRAINT `aluno_ibfk_1` FOREIGN KEY (`nUser`) REFERENCES `user` (`numero`); -- -- Constraints for table `alunodisciplina` -- ALTER TABLE `alunodisciplina` ADD CONSTRAINT `alunodisciplina_ibfk_1` FOREIGN KEY (`nDisciplina`) REFERENCES `disciplina` (`numero`), ADD CONSTRAINT `alunodisciplina_ibfk_2` FOREIGN KEY (`nAluno`) REFERENCES `aluno` (`numero`); -- -- Constraints for table `avaliacao` -- ALTER TABLE `avaliacao` ADD CONSTRAINT `avaliacao_ibfk_1` FOREIGN KEY (`nDisciplina`) REFERENCES `disciplina` (`numero`); -- -- Constraints for table `cursoaluno` -- ALTER TABLE `cursoaluno` ADD CONSTRAINT `cursoaluno_ibfk_1` FOREIGN KEY (`nAluno`) REFERENCES `aluno` (`numero`), ADD CONSTRAINT `cursoaluno_ibfk_2` FOREIGN KEY (`nCurso`) REFERENCES `curso` (`numero`); -- -- Constraints for table `disciplina` -- ALTER TABLE `disciplina` ADD CONSTRAINT `disciplina_ibfk_1` FOREIGN KEY (`nProfessor`) REFERENCES `professor` (`numero`), ADD CONSTRAINT `disciplina_ibfk_2` FOREIGN KEY (`nCurso`) REFERENCES `curso` (`numero`); -- -- Constraints for table `nota` -- ALTER TABLE `nota` ADD CONSTRAINT `nota_ibfk_1` FOREIGN KEY (`nAlunoDisciplina`) REFERENCES `alunodisciplina` (`numero`), ADD CONSTRAINT `nota_ibfk_2` FOREIGN KEY (`nAvaliacao`) REFERENCES `avaliacao` (`numero`); -- -- Constraints for table `professor` -- ALTER TABLE `professor` ADD CONSTRAINT `professor_ibfk_1` FOREIGN KEY (`nUser`) REFERENCES `user` (`numero`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php require_once('model/userModel.php'); require_once('controller/alunoController.php'); require_once('controller/professorController.php'); require_once('view/authenticationView.php'); class AuthenticationController{ var $userModel, $alunoController, $professorController, $authenticationView; public function __construct(){ $this->userModel = new UserModel(); $this->alunoController = new AlunoController(); $this->professorController = new ProfessorController(); $this->authenticationView = new AuthenticationView(); } public function action(){ //$_SESSION['loggedin']= false; if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['login'])){ $username = $_POST['username']; if(is_numeric($username)){ $username = (int)$username; } $password = $_POST['<PASSWORD>']; $authentication = $this->userModel->authentication($username,$password); if($authentication == 'correct'){ $_SESSION['loggedin'] = true; $_SESSION['user'] = $username; $userType = $this->getUserType($username); $_SESSION['type'] = $userType; if($userType == 'aluno'){ $this->alunoController->action($username); }else if($userType == 'professor'){ $this->professorController->action($username); } }else if($authentication == 'password fail'){ $_SESSION['situation'] = 'password fail'; }else{ $_SESSION['situation'] = 'invalid username'; } //header('Location: '.$_SERVER['REQUEST_URI']); }else if(isset($_SESSION['loggedin'])&& $_SESSION['loggedin'] == true){ if($_SESSION['type'] == 'aluno'){ $this->alunoController->action($_SESSION["user"]); }else if($_SESSION['type'] == 'professor'){ $this->professorController->action($_SESSION["user"]); } }else if(!isset($_SESSION['situation'])||$_SESSION['situation'] == 'normal'){ $this->authenticationView->drawAuthenticationPage('normal'); }else{ $situation = $_SESSION['situation']; $_SESSION['situation'] = 'normal'; $this->authenticationView->drawAuthenticationPage($situation); } } private function getUserType($username){ $isALuno = $this->userModel->checkIfIsAluno($username); if($isALuno){return 'aluno';} $isProfessor = $this->userModel->checkIfIsProfessor($username); if($isProfessor){return 'professor';} else{return 'error';} } public function media(){ if(isset($_SESSION['loggedin'])&& $_SESSION['loggedin'] == true && $_SESSION['type'] == 'aluno'){ $this->alunoController->media($_SESSION["user"]); }else{ $this->authenticationView->drawAuthenticationPage($_SESSION['situation']); } } public function authenticationFailed(){ } } ?><file_sep><?php require_once('model/DataBaseConnection.php'); class UserModel{ var $db; public function __construct(){ $this->db = new DataBaseConnection(); } public function authentication($username, $password){ if($this->getUserNameIsValid($username)){ if($this->getPasswordIsValid($username, $password)){ return 'correct'; }else{return 'password fail';} }else{return 'username fail';} } public function checkIfIsAluno($username){ $this->db->connect(); if(!is_numeric($username)){ return false; } $query = "select * from aluno where nUser = ".$username; $result = mysqli_query($this->db->getConnection(), $query); if(mysqli_num_rows($result) != 0){ $row = mysqli_fetch_array($result); $this->db->disconnect(); return true; }else{ $this->db->disconnect(); return false; } } public function checkIfIsProfessor($username){ $this->db->connect(); if(!is_numeric($username)){ return false; } $query = "select * from professor where nUser = ".$username; $result = mysqli_query($this->db->getConnection(), $query); if(mysqli_num_rows($result) != 0){ $row = mysqli_fetch_array($result); $this->db->disconnect(); return true; }else{ $this->db->disconnect(); return false; } } public function getUserName($username){ $this->db->connect(); $query = "SELECT nome FROM user WHERE numero = ".$username; $result = mysqli_query($this->db->getConnection(), $query); if($result){ $row = mysqli_fetch_array($result); $this->db->disconnect(); return $row['nome']; } else{ $this->db->disconnect(); return 'error'; } } public function getProfessorID($username){ $this->db->connect(); $query = "SELECT numero FROM `professor` WHERE nUser = ".$username; $result = mysqli_query($this->db->getConnection(), $query); if($result){ $row = mysqli_fetch_array($result); $this->db->disconnect(); return $row['numero']; } else{ $this->db->disconnect(); return 'error'; } } public function getAlunoID($username){ $this->db->connect(); $query = "SELECT numero FROM `aluno` WHERE nUser = ".$username; $result = mysqli_query($this->db->getConnection(), $query); if($result){ $row = mysqli_fetch_array($result); $this->db->disconnect(); return $row['numero']; } else{ $this->db->disconnect(); return 'error'; } } private function getUserNameIsValid($username){ $this->db->connect(); if(is_numeric($username)){ $username = (int)$username; }else{ $this->db->disconnect(); return false; } $query = "SELECT * FROM user WHERE numero = ".$username; $result = mysqli_query($this->db->getConnection(), $query); if(mysqli_num_rows($result) != 0){ $row = mysqli_fetch_array($result); $this->db->disconnect(); return true; } else{ $this->db->disconnect(); return false; } } private function getPasswordIsValid($username, $password){ $this->db->connect(); $query = "select * from user where numero = ".$username." and passe = '".$password."'"; $result = mysqli_query($this->db->getConnection(), $query); if(mysqli_num_rows($result) != 0){ $row = mysqli_fetch_array($result); $this->db->disconnect(); return true; } else{ $this->db->disconnect(); return false; } } } ?>
9944521c5111fd982a1ed8c58050e32f2c643826
[ "SQL", "PHP" ]
17
PHP
pedrolemosfigueiredo/projeto
dc28a64fdfcacf307475b6c0a8c3ea8a98df867d
978e66d600091ed5eff598cc4ef55a6f7753279f
refs/heads/master
<repo_name>nontage24/it<file_sep>/frontend/views/pasadu/_search.php <?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model frontend\models\PasaduSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="pasadu-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'Pasadu_ID') ?> <?= $form->field($model, 'Oder_ID') ?> <?= $form->field($model, 'Noid') ?> <?= $form->field($model, 'NOID_Old') ?> <?= $form->field($model, 'NAME') ?> <?php // echo $form->field($model, 'Model') ?> <?php // echo $form->field($model, 'SERIAL_NO') ?> <?php // echo $form->field($model, 'COMPANY') ?> <?php // echo $form->field($model, 'TYPE') ?> <?php // echo $form->field($model, 'DIV_1234') ?> <?php // echo $form->field($model, 'Div') ?> <?php // echo $form->field($model, 'Code_DIV') ?> <?php // echo $form->field($model, 'DIV_old') ?> <?php // echo $form->field($model, 'RECEIVE') ?> <?php // echo $form->field($model, 'PERUNIT') ?> <?php // echo $form->field($model, 'KMONEY') ?> <?php // echo $form->field($model, 'TMONEY') ?> <?php // echo $form->field($model, 'Expire_DOC') ?> <?php // echo $form->field($model, 'DOCNO') ?> <?php // echo $form->field($model, 'Doc_Section') ?> <?php // echo $form->field($model, 'REMARK') ?> <?php // echo $form->field($model, 'DAY') ?> <?php // echo $form->field($model, 'QTY') ?> <?php // echo $form->field($model, 'N16') ?> <?php // echo $form->field($model, 'REMARK2') ?> <?php // echo $form->field($model, 'ID_Cal') ?> <?php // echo $form->field($model, 'Expire_DOC_Date') ?> <?php // echo $form->field($model, 'KIND') ?> <?php // echo $form->field($model, 'Code') ?> <?php // echo $form->field($model, 'FY') ?> <?php // echo $form->field($model, 'LOCATE') ?> <?php // echo $form->field($model, 'DEPT') ?> <?php // echo $form->field($model, 'UNIT') ?> <?php // echo $form->field($model, 'EXPIRED') ?> <?php // echo $form->field($model, 'DEPREC') ?> <?php // echo $form->field($model, 'NOTES') ?> <?php // echo $form->field($model, 'Eng_Name') ?> <?php // echo $form->field($model, 'Help') ?> <?php // echo $form->field($model, 'LOCATEDIVISION') ?> <?php // echo $form->field($model, 'LOCATEDEPT') ?> <?php // echo $form->field($model, 'LOCATESECTION') ?> <?php // echo $form->field($model, 'WAY_NAME') ?> <?php // echo $form->field($model, 'DOC_NO') ?> <?php // echo $form->field($model, 'CHANGE') ?> <?php // echo $form->field($model, 'SALER') ?> <?php // echo $form->field($model, 'CCC') ?> <?php // echo $form->field($model, 'New_Date') ?> <?php // echo $form->field($model, 'Type_MC') ?> <?php // echo $form->field($model, 'Range') ?> <?php // echo $form->field($model, 'Err') ?> <?php // echo $form->field($model, 'Risk') ?> <?php // echo $form->field($model, 'Special_Tool') ?> <?php // echo $form->field($model, 'Share_Tool') ?> <?php // echo $form->field($model, 'Location') ?> <?php // echo $form->field($model, 'Index') ?> <?php // echo $form->field($model, 'Expand_Code') ?> <?php // echo $form->field($model, 'The_Man') ?> <?php // echo $form->field($model, 'Tel_man') ?> <?php // echo $form->field($model, 'ID_Refer') ?> <?php // echo $form->field($model, 'Field1') ?> <?php // echo $form->field($model, 'Field2') ?> <?php // echo $form->field($model, 'SM') ?> <?php // echo $form->field($model, 'I_E') ?> <?php // echo $form->field($model, 'IEVC') ?> <?php // echo $form->field($model, 'Note_1') ?> <?php // echo $form->field($model, 'Note_2') ?> <?php // echo $form->field($model, 'Note_3') ?> <?php // echo $form->field($model, 'Expire_Anumat') ?> <?php // echo $form->field($model, 'Reject') ?> <?php // echo $form->field($model, 'range_usage') ?> <?php // echo $form->field($model, 'Accept_criteria') ?> <?php // echo $form->field($model, 'Medical_Instruments') ?> <?php // echo $form->field($model, 'cc') ?> <?php // echo $form->field($model, 'Month_Recieve') ?> <?php // echo $form->field($model, 'Year__Recieve') ?> <?php // echo $form->field($model, 'psuedo_sode') ?> <?php // echo $form->field($model, 'mount') ?> <?php // echo $form->field($model, 'notation') ?> <?php // echo $form->field($model, 'Replace_Price') ?> <?php // echo $form->field($model, 'Replace_Year') ?> <?php // echo $form->field($model, 'GMDN') ?> <?php // echo $form->field($model, 'Eng_Names') ?> <?php // echo $form->field($model, 'date') ?> <?php // echo $form->field($model, 'year_est') ?> <?php // echo $form->field($model, 'Section_oder') ?> <?php // echo $form->field($model, 'num_date') ?> <?php // echo $form->field($model, 'date_su') ?> <?php // echo $form->field($model, 'date_calcu') ?> <?php // echo $form->field($model, 'date_calcu1') ?> <?php // echo $form->field($model, 'Lifetime') ?> <?php // echo $form->field($model, 'wreck_values') ?> <?php // echo $form->field($model, 'wreck_values1') ?> <?php // echo $form->field($model, 'Accu_Depreciation') ?> <?php // echo $form->field($model, 'Values_end') ?> <?php // echo $form->field($model, 'AgeY') ?> <?php // echo $form->field($model, 'AgeM') ?> <?php // echo $form->field($model, 'AgeD') ?> <div class="form-group"> <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?> <?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div> <file_sep>/frontend/views/pasadu/_form.php <?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\Pasadu */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="pasadu-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'Oder_ID')->textInput() ?> <?= $form->field($model, 'Noid')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'NAME')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Model')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'TYPE')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Div')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Code_DIV')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'RECEIVE')->textInput() ?> <?= $form->field($model, 'PERUNIT')->textInput() ?> <?= $form->field($model, 'KMONEY')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'TMONEY')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Expire_DOC')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'QTY')->textInput() ?> <?= $form->field($model, 'UNIT')->textInput() ?> <?= $form->field($model, 'Help')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'New_Date')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'date')->textInput() ?> <?= $form->field($model, 'year_est')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Section_oder')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'num_date')->textInput() ?> <?= $form->field($model, 'date_su')->textInput() ?> <?= $form->field($model, 'Lifetime')->textInput() ?> <?= $form->field($model, 'AgeY')->textInput() ?> <?= $form->field($model, 'AgeM')->textInput() ?> <?= $form->field($model, 'AgeD')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div> <file_sep>/frontend/views/pasadu/_form_1.php <?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\Pasadu */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="pasadu-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'Oder_ID')->textInput() ?> <?= $form->field($model, 'Noid')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'NOID_Old')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'NAME')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Model')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'SERIAL_NO')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'COMPANY')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'TYPE')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DIV_1234')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Div')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Code_DIV')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DIV_old')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'RECEIVE')->textInput() ?> <?= $form->field($model, 'PERUNIT')->textInput() ?> <?= $form->field($model, 'KMONEY')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'TMONEY')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Expire_DOC')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DOCNO')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Doc_Section')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'REMARK')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DAY')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'QTY')->textInput() ?> <?= $form->field($model, 'N16')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'REMARK2')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'ID_Cal')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Expire_DOC_Date')->textInput() ?> <?= $form->field($model, 'KIND')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Code')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'FY')->textInput() ?> <?= $form->field($model, 'LOCATE')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DEPT')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'UNIT')->textInput() ?> <?= $form->field($model, 'EXPIRED')->textInput() ?> <?= $form->field($model, 'DEPREC')->textInput() ?> <?= $form->field($model, 'NOTES')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Eng_Name')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Help')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'LOCATEDIVISION')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'LOCATEDEPT')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'LOCATESECTION')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'WAY_NAME')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'DOC_NO')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'CHANGE')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'SALER')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'CCC')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'New_Date')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Type_MC')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Range')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Err')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Risk')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Special_Tool')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Share_Tool')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Location')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Index')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Expand_Code')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'The_Man')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Tel_man')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'ID_Refer')->textInput() ?> <?= $form->field($model, 'Field1')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Field2')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'SM')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'I_E')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'IEVC')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Note_1')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Note_2')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Note_3')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Expire_Anumat')->textInput() ?> <?= $form->field($model, 'Reject')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'range_usage')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Accept_criteria')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Medical_Instruments')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'cc')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Month_Recieve')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Year__Recieve')->textInput() ?> <?= $form->field($model, 'psuedo_sode')->textInput() ?> <?= $form->field($model, 'mount')->textInput() ?> <?= $form->field($model, 'notation')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Replace_Price')->textInput() ?> <?= $form->field($model, 'Replace_Year')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'GMDN')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Eng_Names')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'date')->textInput() ?> <?= $form->field($model, 'year_est')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'Section_oder')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'num_date')->textInput() ?> <?= $form->field($model, 'date_su')->textInput() ?> <?= $form->field($model, 'date_calcu')->textInput() ?> <?= $form->field($model, 'date_calcu1')->textInput() ?> <?= $form->field($model, 'Lifetime')->textInput() ?> <?= $form->field($model, 'wreck_values')->textInput() ?> <?= $form->field($model, 'wreck_values1')->textInput() ?> <?= $form->field($model, 'AgeY')->textInput() ?> <?= $form->field($model, 'AgeM')->textInput() ?> <?= $form->field($model, 'AgeD')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div> <file_sep>/frontend/models/PasaduSearch.php <?php namespace frontend\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\Pasadu; /** * PasaduSearch represents the model behind the search form about `app\models\Pasadu`. */ class PasaduSearch extends Pasadu { /** * @inheritdoc */ public function rules() { return [ [['Pasadu_ID', 'Oder_ID', 'ID_Refer', 'AgeY', 'AgeM', 'AgeD'], 'integer'], [['Noid', 'NOID_Old', 'NAME', 'Model', 'SERIAL_NO', 'COMPANY', 'TYPE', 'DIV_1234', 'Div', 'Code_DIV', 'DIV_old', 'RECEIVE', 'KMONEY', 'TMONEY', 'Expire_DOC', 'DOCNO', 'Doc_Section', 'REMARK', 'DAY', 'N16', 'REMARK2', 'ID_Cal', 'Expire_DOC_Date', 'KIND', 'Code', 'LOCATE', 'DEPT', 'NOTES', 'Eng_Name', 'Help', 'LOCATEDIVISION', 'LOCATEDEPT', 'LOCATESECTION', 'WAY_NAME', 'DOC_NO', 'CHANGE', 'SALER', 'CCC', 'New_Date', 'Type_MC', 'Range', 'Err', 'Risk', 'Special_Tool', 'Share_Tool', 'Location', 'Index', 'Expand_Code', 'The_Man', 'Tel_man', 'Field1', 'Field2', 'SM', 'I_E', 'IEVC', 'Note_1', 'Note_2', 'Note_3', 'Expire_Anumat', 'Reject', 'range_usage', 'Accept_criteria', 'Medical_Instruments', 'cc', 'Month_Recieve', 'notation', 'Replace_Year', 'GMDN', 'Eng_Names', 'date', 'year_est', 'Section_oder', 'date_su', 'date_calcu'], 'safe'], [['PERUNIT', 'QTY', 'FY', 'UNIT', 'EXPIRED', 'DEPREC', 'Year__Recieve', 'psuedo_sode', 'mount', 'Replace_Price', 'num_date', 'date_calcu1', 'Lifetime', 'wreck_values', 'wreck_values1'], 'number'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Pasadu::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'Pasadu_ID' => $this->Pasadu_ID, 'Oder_ID' => $this->Oder_ID, 'RECEIVE' => $this->RECEIVE, 'PERUNIT' => $this->PERUNIT, 'QTY' => $this->QTY, 'Expire_DOC_Date' => $this->Expire_DOC_Date, 'FY' => $this->FY, 'UNIT' => $this->UNIT, 'EXPIRED' => $this->EXPIRED, 'DEPREC' => $this->DEPREC, 'ID_Refer' => $this->ID_Refer, 'Expire_Anumat' => $this->Expire_Anumat, 'Year__Recieve' => $this->Year__Recieve, 'psuedo_sode' => $this->psuedo_sode, 'mount' => $this->mount, 'Replace_Price' => $this->Replace_Price, 'date' => $this->date, 'num_date' => $this->num_date, 'date_su' => $this->date_su, 'date_calcu' => $this->date_calcu, 'date_calcu1' => $this->date_calcu1, 'Lifetime' => $this->Lifetime, 'wreck_values' => $this->wreck_values, 'wreck_values1' => $this->wreck_values1, //'Accu_Depreciation' => $this->Accu_Depreciation, //'Values_end' => $this->Values_end, 'AgeY' => $this->AgeY, 'AgeM' => $this->AgeM, 'AgeD' => $this->AgeD, ]); $query->andFilterWhere(['like', 'Noid', $this->Noid]) ->andFilterWhere(['like', 'NOID_Old', $this->NOID_Old]) ->andFilterWhere(['like', 'NAME', $this->NAME]) ->andFilterWhere(['like', 'Model', $this->Model]) ->andFilterWhere(['like', 'SERIAL_NO', $this->SERIAL_NO]) ->andFilterWhere(['like', 'COMPANY', $this->COMPANY]) ->andFilterWhere(['like', 'TYPE', $this->TYPE]) ->andFilterWhere(['like', 'DIV_1234', $this->DIV_1234]) ->andFilterWhere(['like', 'Div', $this->Div]) ->andFilterWhere(['like', 'Code_DIV', $this->Code_DIV]) ->andFilterWhere(['like', 'DIV_old', $this->DIV_old]) ->andFilterWhere(['like', 'KMONEY', $this->KMONEY]) ->andFilterWhere(['like', 'TMONEY', $this->TMONEY]) ->andFilterWhere(['like', 'Expire_DOC', $this->Expire_DOC]) ->andFilterWhere(['like', 'DOCNO', $this->DOCNO]) ->andFilterWhere(['like', 'Doc_Section', $this->Doc_Section]) ->andFilterWhere(['like', 'REMARK', $this->REMARK]) ->andFilterWhere(['like', 'DAY', $this->DAY]) ->andFilterWhere(['like', 'N16', $this->N16]) ->andFilterWhere(['like', 'REMARK2', $this->REMARK2]) ->andFilterWhere(['like', 'ID_Cal', $this->ID_Cal]) ->andFilterWhere(['like', 'KIND', $this->KIND]) ->andFilterWhere(['like', 'Code', $this->Code]) ->andFilterWhere(['like', 'LOCATE', $this->LOCATE]) ->andFilterWhere(['like', 'DEPT', $this->DEPT]) ->andFilterWhere(['like', 'NOTES', $this->NOTES]) ->andFilterWhere(['like', 'Eng_Name', $this->Eng_Name]) ->andFilterWhere(['like', 'Help', $this->Help]) ->andFilterWhere(['like', 'LOCATEDIVISION', $this->LOCATEDIVISION]) ->andFilterWhere(['like', 'LOCATEDEPT', $this->LOCATEDEPT]) ->andFilterWhere(['like', 'LOCATESECTION', $this->LOCATESECTION]) ->andFilterWhere(['like', 'WAY_NAME', $this->WAY_NAME]) ->andFilterWhere(['like', 'DOC_NO', $this->DOC_NO]) ->andFilterWhere(['like', 'CHANGE', $this->CHANGE]) ->andFilterWhere(['like', 'SALER', $this->SALER]) ->andFilterWhere(['like', 'CCC', $this->CCC]) ->andFilterWhere(['like', 'New_Date', $this->New_Date]) ->andFilterWhere(['like', 'Type_MC', $this->Type_MC]) ->andFilterWhere(['like', 'Range', $this->Range]) ->andFilterWhere(['like', 'Err', $this->Err]) ->andFilterWhere(['like', 'Risk', $this->Risk]) ->andFilterWhere(['like', 'Special_Tool', $this->Special_Tool]) ->andFilterWhere(['like', 'Share_Tool', $this->Share_Tool]) ->andFilterWhere(['like', 'Location', $this->Location]) ->andFilterWhere(['like', 'Index', $this->Index]) ->andFilterWhere(['like', 'Expand_Code', $this->Expand_Code]) ->andFilterWhere(['like', 'The_Man', $this->The_Man]) ->andFilterWhere(['like', 'Tel_man', $this->Tel_man]) ->andFilterWhere(['like', 'Field1', $this->Field1]) ->andFilterWhere(['like', 'Field2', $this->Field2]) ->andFilterWhere(['like', 'SM', $this->SM]) ->andFilterWhere(['like', 'I_E', $this->I_E]) ->andFilterWhere(['like', 'IEVC', $this->IEVC]) ->andFilterWhere(['like', 'Note_1', $this->Note_1]) ->andFilterWhere(['like', 'Note_2', $this->Note_2]) ->andFilterWhere(['like', 'Note_3', $this->Note_3]) ->andFilterWhere(['like', 'Reject', $this->Reject]) ->andFilterWhere(['like', 'range_usage', $this->range_usage]) ->andFilterWhere(['like', 'Accept_criteria', $this->Accept_criteria]) ->andFilterWhere(['like', 'Medical_Instruments', $this->Medical_Instruments]) ->andFilterWhere(['like', 'cc', $this->cc]) ->andFilterWhere(['like', 'Month_Recieve', $this->Month_Recieve]) ->andFilterWhere(['like', 'notation', $this->notation]) ->andFilterWhere(['like', 'Replace_Year', $this->Replace_Year]) ->andFilterWhere(['like', 'GMDN', $this->GMDN]) ->andFilterWhere(['like', 'Eng_Names', $this->Eng_Names]) ->andFilterWhere(['like', 'year_est', $this->year_est]) ->andFilterWhere(['like', 'Section_oder', $this->Section_oder]); return $dataProvider; } } <file_sep>/frontend/models/Pasadu.php <?php namespace app\models; use Yii; /** * This is the model class for table "pasadu". * * @property integer $Pasadu_ID * @property integer $Oder_ID * @property string $Noid * @property string $NOID_Old * @property string $NAME * @property string $Model * @property string $SERIAL_NO * @property string $COMPANY * @property string $TYPE * @property string $DIV_1234 * @property string $Div * @property string $Code_DIV * @property string $DIV_old * @property string $RECEIVE * @property double $PERUNIT * @property string $KMONEY * @property string $TMONEY * @property string $Expire_DOC * @property string $DOCNO * @property string $Doc_Section * @property string $REMARK * @property string $DAY * @property double $QTY * @property string $N16 * @property string $REMARK2 * @property string $ID_Cal * @property string $Expire_DOC_Date * @property string $KIND * @property string $Code * @property double $FY * @property string $LOCATE * @property string $DEPT * @property double $UNIT * @property double $EXPIRED * @property double $DEPREC * @property string $NOTES * @property string $Eng_Name * @property string $Help * @property string $LOCATEDIVISION * @property string $LOCATEDEPT * @property string $LOCATESECTION * @property string $WAY_NAME * @property string $DOC_NO * @property string $CHANGE * @property string $SALER * @property string $CCC * @property string $New_Date * @property string $Type_MC * @property string $Range * @property string $Err * @property string $Risk * @property string $Special_Tool * @property string $Share_Tool * @property string $Location * @property string $Index * @property string $Expand_Code * @property string $The_Man * @property string $Tel_man * @property integer $ID_Refer * @property string $Field1 * @property string $Field2 * @property string $SM * @property string $I_E * @property string $IEVC * @property string $Note_1 * @property string $Note_2 * @property string $Note_3 * @property string $Expire_Anumat * @property string $Reject * @property string $range_usage * @property string $Accept_criteria * @property string $Medical_Instruments * @property string $cc * @property string $Month_Recieve * @property double $Year__Recieve * @property double $psuedo_sode * @property double $mount * @property string $notation * @property double $Replace_Price * @property string $Replace_Year * @property string $GMDN * @property string $Eng_Names * @property string $date * @property string $year_est * @property string $Section_oder * @property double $num_date * @property string $date_su * @property string $date_calcu * @property double $date_calcu1 * @property double $Lifetime * @property double $wreck_values * @property double $wreck_values1 * @property double $ Accu_Depreciation * @property double $Values_end * @property integer $AgeY * @property integer $AgeM * @property integer $AgeD */ class Pasadu extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'pasadu'; } /** * @inheritdoc */ public function rules() { return [ [['Oder_ID', 'ID_Refer', 'AgeY', 'AgeM', 'AgeD'], 'integer'], [['RECEIVE', 'Expire_DOC_Date', 'Expire_Anumat', 'date', 'date_su', 'date_calcu'], 'safe'], [['PERUNIT', 'QTY', 'FY', 'UNIT', 'EXPIRED', 'DEPREC', 'Year__Recieve', 'psuedo_sode', 'mount', 'Replace_Price', 'num_date', 'date_calcu1', 'Lifetime', 'wreck_values', 'wreck_values1'], 'number'], [['Noid', 'Replace_Year', 'GMDN', 'Eng_Names', 'year_est'], 'string', 'max' => 50], [['NOID_Old', 'NAME', 'Model', 'SERIAL_NO', 'COMPANY', 'TYPE', 'DIV_1234', 'Div', 'DIV_old', 'KMONEY', 'TMONEY', 'Expire_DOC', 'DOCNO', 'Doc_Section', 'REMARK', 'DAY', 'N16', 'REMARK2', 'ID_Cal', 'KIND', 'Code', 'LOCATE', 'DEPT', 'NOTES', 'Eng_Name', 'Help', 'LOCATEDIVISION', 'LOCATEDEPT', 'LOCATESECTION', 'WAY_NAME', 'DOC_NO', 'CHANGE', 'SALER', 'CCC', 'New_Date', 'Type_MC', 'Range', 'Err', 'Risk', 'Special_Tool', 'Share_Tool', 'Location', 'Index', 'Expand_Code', 'The_Man', 'Tel_man', 'Field1', 'Field2', 'SM', 'I_E', 'IEVC', 'Note_1', 'Note_2', 'Note_3', 'Reject', 'range_usage', 'Accept_criteria', 'Medical_Instruments', 'cc', 'Month_Recieve', 'notation', 'Section_oder'], 'string', 'max' => 254], [['Code_DIV'], 'string', 'max' => 4], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'Pasadu_ID' => Yii::t('app', 'Pasadu ID'), 'Oder_ID' => Yii::t('app', 'Oder ID'), 'Noid' => Yii::t('app', 'Noid'), 'NOID_Old' => Yii::t('app', 'Noid Old'), 'NAME' => Yii::t('app', 'Name'), 'Model' => Yii::t('app', 'Model'), 'SERIAL_NO' => Yii::t('app', 'Serial No'), 'COMPANY' => Yii::t('app', 'Company'), 'TYPE' => Yii::t('app', 'Type'), 'DIV_1234' => Yii::t('app', 'Div 1234'), 'Div' => Yii::t('app', 'Div'), 'Code_DIV' => Yii::t('app', 'Code Div'), 'DIV_old' => Yii::t('app', 'Div Old'), 'RECEIVE' => Yii::t('app', 'Receive'), 'PERUNIT' => Yii::t('app', 'Perunit'), 'KMONEY' => Yii::t('app', 'Kmoney'), 'TMONEY' => Yii::t('app', 'Tmoney'), 'Expire_DOC' => Yii::t('app', 'Expire Doc'), 'DOCNO' => Yii::t('app', 'Docno'), 'Doc_Section' => Yii::t('app', 'Doc Section'), 'REMARK' => Yii::t('app', 'Remark'), 'DAY' => Yii::t('app', 'Day'), 'QTY' => Yii::t('app', 'Qty'), 'N16' => Yii::t('app', 'N16'), 'REMARK2' => Yii::t('app', 'Remark2'), 'ID_Cal' => Yii::t('app', 'Id Cal'), 'Expire_DOC_Date' => Yii::t('app', 'Expire Doc Date'), 'KIND' => Yii::t('app', 'Kind'), 'Code' => Yii::t('app', 'Code'), 'FY' => Yii::t('app', 'Fy'), 'LOCATE' => Yii::t('app', 'Locate'), 'DEPT' => Yii::t('app', 'Dept'), 'UNIT' => Yii::t('app', 'Unit'), 'EXPIRED' => Yii::t('app', 'Expired'), 'DEPREC' => Yii::t('app', 'Deprec'), 'NOTES' => Yii::t('app', 'Notes'), 'Eng_Name' => Yii::t('app', 'Eng Name'), 'Help' => Yii::t('app', 'Help'), 'LOCATEDIVISION' => Yii::t('app', 'Locatedivision'), 'LOCATEDEPT' => Yii::t('app', 'Locatedept'), 'LOCATESECTION' => Yii::t('app', 'Locatesection'), 'WAY_NAME' => Yii::t('app', 'Way Name'), 'DOC_NO' => Yii::t('app', 'Doc No'), 'CHANGE' => Yii::t('app', 'Change'), 'SALER' => Yii::t('app', 'Saler'), 'CCC' => Yii::t('app', 'Ccc'), 'New_Date' => Yii::t('app', 'New Date'), 'Type_MC' => Yii::t('app', 'Type Mc'), 'Range' => Yii::t('app', 'Range'), 'Err' => Yii::t('app', 'Err'), 'Risk' => Yii::t('app', 'Risk'), 'Special_Tool' => Yii::t('app', 'Special Tool'), 'Share_Tool' => Yii::t('app', 'Share Tool'), 'Location' => Yii::t('app', 'Location'), 'Index' => Yii::t('app', 'Index'), 'Expand_Code' => Yii::t('app', 'Expand Code'), 'The_Man' => Yii::t('app', 'The Man'), 'Tel_man' => Yii::t('app', 'Tel Man'), 'ID_Refer' => Yii::t('app', 'Id Refer'), 'Field1' => Yii::t('app', 'Field1'), 'Field2' => Yii::t('app', 'Field2'), 'SM' => Yii::t('app', 'Sm'), 'I_E' => Yii::t('app', 'I E'), 'IEVC' => Yii::t('app', 'Ievc'), 'Note_1' => Yii::t('app', 'Note 1'), 'Note_2' => Yii::t('app', 'Note 2'), 'Note_3' => Yii::t('app', 'Note 3'), 'Expire_Anumat' => Yii::t('app', 'Expire Anumat'), 'Reject' => Yii::t('app', 'Reject'), 'range_usage' => Yii::t('app', 'Range Usage'), 'Accept_criteria' => Yii::t('app', 'Accept Criteria'), 'Medical_Instruments' => Yii::t('app', 'Medical Instruments'), 'cc' => Yii::t('app', 'Cc'), 'Month_Recieve' => Yii::t('app', 'Month Recieve'), 'Year__Recieve' => Yii::t('app', 'Year Recieve'), 'psuedo_sode' => Yii::t('app', 'Psuedo Sode'), 'mount' => Yii::t('app', 'Mount'), 'notation' => Yii::t('app', 'Notation'), 'Replace_Price' => Yii::t('app', 'Replace Price'), 'Replace_Year' => Yii::t('app', 'Replace Year'), 'GMDN' => Yii::t('app', 'Gmdn'), 'Eng_Names' => Yii::t('app', 'Eng Names'), 'date' => Yii::t('app', 'Date'), 'year_est' => Yii::t('app', 'Year Est'), 'Section_oder' => Yii::t('app', 'Section Oder'), 'num_date' => Yii::t('app', 'Num Date'), 'date_su' => Yii::t('app', 'Date Su'), 'date_calcu' => Yii::t('app', 'Date Calcu'), 'date_calcu1' => Yii::t('app', 'Date Calcu1'), 'Lifetime' => Yii::t('app', 'Lifetime'), 'wreck_values' => Yii::t('app', 'Wreck Values'), 'wreck_values1' => Yii::t('app', 'Wreck Values1'), 'Accu_Depreciation' => Yii::t('app', 'Accu Depreciation'), 'Values_end' => Yii::t('app', 'Values End'), 'AgeY' => Yii::t('app', 'Age Y'), 'AgeM' => Yii::t('app', 'Age M'), 'AgeD' => Yii::t('app', 'Age D'), ]; } } <file_sep>/frontend/views/pasadu/view.php <?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\models\Pasadu */ $this->title = $model->NAME; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Pasadus'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="pasadu-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->Pasadu_ID], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->Pasadu_ID], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'), 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'Pasadu_ID', 'Oder_ID', 'Noid', 'NOID_Old', 'NAME', 'Model', 'SERIAL_NO', 'COMPANY', 'TYPE', 'DIV_1234', 'Div', 'Code_DIV', 'DIV_old', 'RECEIVE', 'PERUNIT', 'KMONEY', 'TMONEY', 'Expire_DOC', 'DOCNO', 'Doc_Section', 'REMARK', 'DAY', 'QTY', 'N16', 'REMARK2', 'ID_Cal', 'Expire_DOC_Date', 'KIND', 'Code', 'FY', 'LOCATE', 'DEPT', 'UNIT', 'EXPIRED', 'DEPREC', 'NOTES', 'Eng_Name', 'Help', 'LOCATEDIVISION', 'LOCATEDEPT', 'LOCATESECTION', 'WAY_NAME', 'DOC_NO', 'CHANGE', 'SALER', 'CCC', 'New_Date', 'Type_MC', 'Range', 'Err', 'Risk', 'Special_Tool', 'Share_Tool', 'Location', 'Index', 'Expand_Code', 'The_Man', 'Tel_man', 'ID_Refer', 'Field1', 'Field2', 'SM', 'I_E', 'IEVC', 'Note_1', 'Note_2', 'Note_3', 'Expire_Anumat', 'Reject', 'range_usage', 'Accept_criteria', 'Medical_Instruments', 'cc', 'Month_Recieve', 'Year__Recieve', 'psuedo_sode', 'mount', 'notation', 'Replace_Price', 'Replace_Year', 'GMDN', 'Eng_Names', 'date', 'year_est', 'Section_oder', 'num_date', 'date_su', 'date_calcu', 'date_calcu1', 'Lifetime', 'wreck_values', 'wreck_values1', //'Accu_Depreciation', //'Values_end', 'AgeY', 'AgeM', 'AgeD', ], ]) ?> </div>
bb2433f11f0185684bcf3d6e0ce2e729edc608db
[ "PHP" ]
6
PHP
nontage24/it
a9662fe450498fcbae10c5c5d18f87a7a8ff3df6
7fa438847d49d8118b7ab8b60735dd4d6798dd46
refs/heads/master
<repo_name>gbingham18/PopulationSimulatorBackEnd<file_sep>/Populations.py from flask import Flask, request, jsonify from flask_cors import CORS import json from random import randint app = Flask(__name__) CORS(app) def generateGenerations(p, q, numGens, popSize, fitAA, fitAa, fitaa, mutAa, mutaA): q = 1-p pValues = [None] * numGens freqAA = p*p freqAa = 2*p*q freqaa = q*q pValues[0] = [0, p] for i in range(1, numGens): freqAA = freqAA * fitAA freqAa = freqAa * fitAa freqaa = freqaa * fitaa totalLeft = freqAA + freqAa + freqaa freqAA = freqAA / totalLeft freqAa = freqAa / totalLeft freqaa = freqaa / totalLeft numAA = int(round(freqAA * popSize)) numAa = int(round(freqAa * popSize)) numaa = int(round(freqaa * popSize)) numAA, numAa, numaa = randomMating(numAA, numAa, numaa) freqAA = numAA / popSize freqAa = numAa / popSize freqaa = numaa / popSize curr = [i, (freqAA + freqAa/2)] pValues[i] = curr return jsonify({'data': pValues}) @app.route('/', methods=['POST']) def postMethod(): if (request.method == 'POST'): data = request.get_json() p = float(data.get("p")) numGens = int(data.get("numGens")) popSize = int(data.get("popSize")) fitA1 = float(data.get("fitA1")) fitA2 = float(data.get("fitA2")) fitA3 = float(data.get("fitA3")) mutAa = float(data.get("mutAa")) mutaA = float(data.get("mutaA")) returnData = generateGenerations(p, 0, numGens, popSize, fitA1, fitA2, fitA3, mutAa, mutaA) return returnData.json def randomMating(freqAA, freqAa, freqaa): popSize = freqAA + freqAa + freqaa newAA = 0 newAa = 0 newaa = 0 while popSize > 0: allele1 = "" allele2 = "" #Select two random alleles from population (ex: Aa, AA) for i in range(0, 2): if (popSize > 0): x = randint(1, popSize) if 0 < x and x <= freqAA: popSize = popSize - 1 if i == 0: allele1 = "AA" freqAA = freqAA - 1 else: allele2 = "AA" freqAA = freqAA - 1 elif freqAA < x and x <= (freqAA + freqAa): popSize = popSize - 1 if i == 0: allele1 = "Aa" freqAa = freqAa - 1 else: allele2 = "Aa" freqAa = freqAa - 1 elif (freqAA + freqAa) < x and x <= popSize: popSize = popSize - 1 if i == 0: allele1 = "aa" freqaa = freqaa - 1 else: allele2 = "aa" freqaa = freqaa - 1 #Concatenate two allele strings into one (ex: Aa, AA => AaAA) #Run through process twice to generate two new offspring per pair for i in range(0, 2): if allele1 + allele2 == "AAAA": newAA = newAA + 1 elif allele1 + allele2 == "aaaa": newaa = newaa + 1 elif allele1 + allele2 == "Aaaa" or allele1 + allele2 == "aaAa": x = randint(0, 99) if 0 <= x and x < 50: newAa = newAa + 1 else: newaa = newaa + 1 elif allele1 + allele2 == "AAaa" or allele1 + allele2 == "aaAA": newAa = newAa + 1 elif allele1 + allele2 == "AaAa": x = randint(0, 99) if 0 <= x < 25: newAA = newAA + 1 elif 25 <= x < 75: newAa = newAa + 1 elif 75 <= x < 100: newaa = newaa + 1 elif allele1 + allele2 == "AAAa" or allele1 + allele2 == "AaAA": x = randint(0, 99) if 0 <= x and x < 50: newAA = newAA + 1 else: newAa = newAa + 1 return newAA, newAa, newaa if __name__ == '__main__': app.run()
110f3891fa312ab1bc26d57df6d970f4c696b53a
[ "Python" ]
1
Python
gbingham18/PopulationSimulatorBackEnd
ce4a1241a2197d7aa4fcb202c6a9bca8e8c9b303
58c4e846e1bd9fb2df39e9bfa5288987a4fe431e
refs/heads/master
<file_sep># Unknown-Signal Coursework for COMS20011 Using least squares regression and cross-validation to account for overfitting in order to determine the function type of each line segment and produce the total reconstruction error for each file. `--plot` can be given as an extra argument to visualise the result. The report documents the procedures and results optained. <file_sep>import os import sys import pandas as pd import numpy as np from matplotlib import pyplot as plt def load_points_from_file(filename): """Loads 2d points from a csv called filename Args: filename : Path to .csv file Returns: (xs, ys) where xs and ys are a numpy array of the co-ordinates. """ points = pd.read_csv(filename, header=None) return points[0].values, points[1].values def view_data_segments(xs, ys, new_xs, new_ys): """Visualises the input file with each segment plotted in a different colour. Args: xs : List/array-like of x co-ordinates. ys : List/array-like of y co-ordinates. line: type of function equation: parameters of function Returns: None """ assert len(xs) == len(ys) assert len(xs) % 20 == 0 len_data = len(xs) num_segments = len_data // 20 colour = np.concatenate([[i] * 20 for i in range(num_segments)]) plt.set_cmap('Dark2') plt.scatter(xs, ys, c=colour) for i in range(num_segments): plt.plot(new_xs[i], new_ys[i]) plt.xlabel("x") plt.ylabel("y") plt.show() def linear_line(xs, ys): """ Use least squares method to determine parameters of linear line """ # extend matrix with column of 1's matrix = np.column_stack((np.ones(xs.shape), xs)) # Calculation of (𝑋^𝑇*𝑋)^−1*𝑋^𝑇*𝑌 # First column of fit is the y-intercept and gradient is second column return np.linalg.inv(matrix.T.dot(matrix)).dot(matrix.T).dot(ys) def poly_line(xs, ys): """ Use least squares method to predict parameters of polynomial line """ matrix = np.column_stack((np.ones(xs.shape), xs, np.square(xs), np.power(xs, 3))) return np.linalg.inv(matrix.T.dot(matrix)).dot(matrix.T).dot(ys) def sine_line(xs, ys): """ Use least squares method to predict parameters of sinusoidal line """ matrix = np.column_stack((np.ones(xs.shape), np.sin(xs))) return np.linalg.inv(matrix.T.dot(matrix)).dot(matrix.T).dot(ys) def square_error(y, y_hat): """ Calculate error in predicted line using sum squared error i.e. ∑𝑖(𝑦̂𝑖−𝑦𝑖)2 """ return np.sum((y - y_hat) ** 2) def linear_cve(train_xs, train_ys, test_xs, test_ys): weights = linear_line(train_xs, train_ys) test_ys_hat = np.column_stack((np.ones(test_xs.shape), test_xs)).dot(weights) return square_error(test_ys, test_ys_hat).mean() def poly_cve(train_xs, train_ys, test_xs, test_ys): weights = poly_line(train_xs, train_ys) test_ys_hat = np.column_stack((np.ones(test_xs.shape), test_xs, np.square(test_xs), np.power(test_xs, 3))).dot(weights) return square_error(test_ys, test_ys_hat).mean() def sine_cve(train_xs, train_ys, test_xs, test_ys): weights = sine_line(train_xs, train_ys) test_ys_hat = np.column_stack((np.ones(test_xs.shape), np.sin(test_xs))).dot(weights) return square_error(test_ys, test_ys_hat).mean() def k_fold_cross_val(xs, ys, k): """ 1. Shuffle the dataset randomly. 2. Split the dataset into k groups 3. For each unique group: Take the group as a hold out or test data set Take the remaining groups as a training data set Fit a model on the training set and evaluate it on the test set Retain the evaluation score and discard the model Summarize the skill of the model using the sample of model evaluation scores """ # shuffle indices indices = np.arange(xs.shape[0]) np.random.shuffle(indices) # Split the dataset into k groups split_xs, split_ys = np.array_split(xs[indices], k), np.array_split(ys[indices], k) cve_linear = cve_poly = cve_sine = 0 for i in range(k): test_xs, test_ys = split_xs[i], split_ys[i] train_xs = np.append(split_xs[:i], split_xs[i+1:]) train_ys = np.append(split_ys[:i], split_ys[i+1:]) cve_linear += linear_cve(train_xs, train_ys, test_xs, test_ys) cve_poly += poly_cve(train_xs, train_ys, test_xs, test_ys) cve_sine += sine_cve(train_xs, train_ys, test_xs, test_ys) return cve_linear/k, cve_poly/k, cve_sine/k if __name__ == '__main__': points = load_points_from_file(sys.argv[1]) # split into line segments of 20 points x_segments = np.split(points[0], len(points[0]) / 20) y_segments = np.split(points[1], len(points[1]) / 20) num_segments = len(x_segments) total_error = 0 new_xs_list = [] new_ys_list =[] function = [] for i in range(num_segments): new_xs = np.linspace(min(x_segments[i]), max(x_segments[i]), 100) cve_linear, cve_poly, cve_sine = k_fold_cross_val(x_segments[i], y_segments[i], 20) min_cve = min(cve_linear, cve_poly, cve_sine) if min_cve == cve_linear: weights = linear_line(x_segments[i], y_segments[i]) ys_hat = test_ys_hat = np.column_stack((np.ones(x_segments[i].shape), x_segments[i])).dot(weights) error = square_error(y_segments[i], ys_hat) new_ys = np.column_stack((np.ones(new_xs.shape), new_xs)).dot(weights) # print("linear") elif min_cve == cve_poly: weights = poly_line(x_segments[i], y_segments[i]) ys_hat = np.column_stack((np.ones(x_segments[i].shape), x_segments[i], np.square(x_segments[i]), np.power(x_segments[i], 3))).dot(weights) error = square_error(y_segments[i], ys_hat) new_ys = np.column_stack((np.ones(new_xs.shape), new_xs, np.square(new_xs), np.power(new_xs, 3))).dot(weights) # print("cubic") elif min_cve == cve_sine: weights = sine_line(x_segments[i], y_segments[i]) ys_hat = np.column_stack((np.ones(x_segments[i].shape), np.sin(x_segments[i]))).dot(weights) error = square_error(y_segments[i], ys_hat) new_ys = np.column_stack((np.ones(new_xs.shape), np.sin(new_xs))).dot(weights) # print("sine") new_xs_list.append(new_xs) new_ys_list.append(new_ys) total_error += error print(total_error) # if --plot parameter given, visualise result if len(sys.argv) == 3 and sys.argv[2] == "--plot": view_data_segments(points[0], points[1], new_xs_list, new_ys_list)
e54f7ceab3a1df24ed6fe7eeefc4b512f30e86fc
[ "Markdown", "Python" ]
2
Markdown
lokhei/Unknown-Signal
f0142ee047db1b5c9c2f2a67d92042e4c1a51b17
4e1f2ebee0d09db50f6cdcef7dcdc538797073c3
refs/heads/master
<file_sep>package com.planty.app.fragments.main; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.planty.app.R; public class webgame extends Fragment { private WebView mWebView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.web,container,false); mWebView = (WebView) view.findViewById(R.id.webview); mWebView.loadUrl("https://msakuta.github.io/farmsim/farmsim.html"); // Enable Javascript WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); // Force links and redirects to open in the WebView instead of in a browser mWebView.setWebViewClient(new WebViewClient()); return view; } } <file_sep>package com.planty.app.fragments.main; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.planty.app.R; import com.planty.app.customclass.ActiveInactive; import com.planty.logasventor.Addproducts; public class FragmentHomeFeed extends Fragment { RecyclerView rec_y; boolean sub_category_enable = true; TextView active; TextView Inactive; ImageView menu; public static FragmentHomeFeed newInstance() { final FragmentHomeFeed fragment = new FragmentHomeFeed(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle sis) { final View view = inflater.inflate(R.layout.fragmenthomefeed, parent, false); getIntents(); initializeViews(view); setUpValues(); setUpListeners(); return view; } public void getIntents() { } public void initializeViews(View view) { // rec_y=view.findViewById(R.id.rec_v); // active=view.findViewById(R.id.activebutton); // Inactive=view.findViewById(R.id.inactivebutton); menu=view.findViewById(R.id.burger_menu); } public void setUpValues() { // RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); // rec_y.setLayoutManager(mLayoutManager); // rec_y.setItemAnimator(new DefaultItemAnimator()); // // rec_y.setAdapter(new RecyclerViewCategory(getActivity())); } public void setUpListeners() { menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ((MainActivity)).drawerContral(); } }); } public class RecyclerViewCategory extends RecyclerView.Adapter<RecyclerViewHolder> { Activity act; public RecyclerViewCategory(Activity activity) { this.act = activity; } @Override public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.homefeedfragment_itemlayout, null); RecyclerViewHolder rcv = new RecyclerViewHolder(layoutView); return rcv; } @Override public void onBindViewHolder(final RecyclerViewHolder holder, final int position) { RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); holder.sub_category_rv.setLayoutManager(mLayoutManager); holder.sub_category_rv.setItemAnimator(new DefaultItemAnimator()); holder.parent_ly.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (sub_category_enable) { holder.sub_category_rv.setVisibility(View.VISIBLE); holder.sub_category_rv.setAdapter(new RecyclerViewSubCategory(getActivity())); sub_category_enable = false; } else { holder.sub_category_rv.setVisibility(View.GONE); sub_category_enable = true; } } }); } @Override public int getItemCount() { return 11; } } class RecyclerViewHolder extends RecyclerView.ViewHolder { RecyclerView sub_category_rv; RelativeLayout parent_ly; TextView addpro; public RecyclerViewHolder(View itemView) { super(itemView); sub_category_rv = itemView.findViewById(R.id.sub_category_rv); parent_ly = itemView.findViewById(R.id.parent_ly); } } // public class RecyclerViewSubCategory extends RecyclerView.Adapter<RecyclerViewSubCategory.ViewHolder> { // ArrayList<HomeModel>models; Context context; public RecyclerViewSubCategory(Context context) { // this.models=models; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.homefeedfragment_subitemlayout, viewGroup, false); ViewHolder viewHolder = new ViewHolder(v); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { viewHolder.active_tv .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getActivity(), ActiveInactive.class); intent.putExtra("active",true); startActivity(intent); } }); viewHolder.inactive .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getActivity(), ActiveInactive.class); intent.putExtra("inactive",true); startActivity(intent); } }); viewHolder.product.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getActivity(),Addproducts.class); startActivity(intent); } }); } @Override public int getItemCount() { return 1; } public class ViewHolder extends RecyclerView.ViewHolder { TextView temper, product, active_tv, inactive; public ViewHolder(@NonNull View itemView) { super(itemView); // temper = itemView.findViewById(R.id.home_temper_tv); product = itemView.findViewById(R.id.addproductbutton); active_tv= itemView.findViewById(R.id.activebutton); inactive = itemView.findViewById(R.id.inactivebutton); } } } } <file_sep>Planty is an open-sourced project aimed to automatically provide minerals to plants connected to a wastewater reservoir. Clients of these applications are provided with an android application where they get notified when plants are hungry. They are provided to choose between two modes automatic and manual. In case of automatic plants are automatically watered else they will be notified with push notification until they water. The user can add a plant by scanning it through the app the server recognizes the type of plant it is and minerals needed according to weather and moisture content of the soil. The sensor is placed in soil to send values. The app also includes a community between users where they can chat. A simple game-like interface is created to encourage users to play. An e-commerce part is designed to recommend users the fertilizers and extras required for proper growth. Tech Stack: Android development with JAVA Firebase for push notifications and community PHP and MySQL server for data storage TensorFlow for image recognition trained with 10,000+ images IoT sensors Raspberry pi DeepLearning with Python JavaScript Game Engine PixiJS Find server side scripts in PlantyServer Repo <file_sep>package com.planty.app.activity; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.Toast; import com.planty.app.R; import com.planty.app.customclass.CustomAppCompatActivity; import com.planty.app.fragments.FragmentLogin; import com.planty.app.fragments.FragmentOtpCall; public class LoginActivity extends CustomAppCompatActivity { final public static int FRAGMENT_LOGIN = 1; final public static int FRAGMENT_OTP_CALL = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); getIntents(); initializeViews(); setUpValues(); setUpListeners(); setUpValues(); } public void getIntents() { } public void initializeViews() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); FragmentLogin fragmentLogin = new FragmentLogin(); fragmentTransaction.add(R.id.fragment_activity, fragmentLogin, FragmentLogin.class.getSimpleName()); fragmentTransaction.commit(); } public void setUpValues() { requestCameraPermission(); } public void setUpListeners() { } public void moveNextFragment(int current_frg) { Log.e("moveNextFragment", current_frg + "++++++"); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); switch (current_frg) { case FRAGMENT_LOGIN: FragmentLogin fragmantLogin = new FragmentLogin(); fragmentTransaction.replace(R.id.fragment_activity, fragmantLogin, FragmentLogin.class.getSimpleName()); break; case FRAGMENT_OTP_CALL: FragmentOtpCall fragmentOtpCall = new FragmentOtpCall(); fragmentTransaction.replace(R.id.fragment_activity, fragmentOtpCall, FragmentOtpCall.class.getSimpleName()); break; } fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } public void requestCameraPermission() { int write_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.CAMERA); int location_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.ACCESS_FINE_LOCATION); int location2_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION); int read_sms_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_SMS); int read_rece_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.RECEIVE_SMS); int write_external = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE); int read_external = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE); if (android.os.Build.VERSION.SDK_INT < 22 || (write_permission == PackageManager.PERMISSION_GRANTED && location_permission == PackageManager.PERMISSION_GRANTED && location2_permission == PackageManager.PERMISSION_GRANTED)) { } else ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 115); if (android.os.Build.VERSION.SDK_INT < 22 || (read_sms_permission == PackageManager.PERMISSION_GRANTED && read_rece_permission == PackageManager.PERMISSION_GRANTED && location2_permission == PackageManager.PERMISSION_GRANTED)) { } else ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 116); if (android.os.Build.VERSION.SDK_INT < 22 || (read_external == PackageManager.PERMISSION_GRANTED && write_external == PackageManager.PERMISSION_GRANTED)) { } else ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 117); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { int write_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.CAMERA); int location_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.ACCESS_FINE_LOCATION); int location_permission_2 = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION); int read_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_SMS); int receive_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.RECEIVE_SMS); int read_external_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE); int write_external_permission = ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (requestCode == 115) { if (write_permission == PackageManager.PERMISSION_GRANTED && location_permission == PackageManager.PERMISSION_GRANTED && location_permission_2 == PackageManager.PERMISSION_GRANTED) { Log.e("onRequestPermissions", "accepted"); } else { Toast.makeText(LoginActivity.this, "Permission denied by user.", Toast.LENGTH_LONG); } } if (requestCode == 116) { if (read_permission == PackageManager.PERMISSION_GRANTED && receive_permission == PackageManager.PERMISSION_GRANTED) { Log.e("onRequestPermissions", "accepted"); } else { Toast.makeText(LoginActivity.this, "Permission denied by user.", Toast.LENGTH_LONG); } } if (requestCode == 117) { if (read_external_permission == PackageManager.PERMISSION_GRANTED && write_external_permission == PackageManager.PERMISSION_GRANTED) { Log.e("camera_access", "accepted"); } else { Toast.makeText(LoginActivity.this, "Permission denied by user.", Toast.LENGTH_LONG); } } } }<file_sep>package com.planty.app.fragments; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.planty.app.R; import com.planty.app.activity.MainActivity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class FragmentOtpCall extends Fragment { LinearLayout submit_ly, login; EditText uname, pass; public static String username = ""; public static FragmentOtpCall newInstance() { final FragmentOtpCall fragment = new FragmentOtpCall(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle sis) { final View view = inflater.inflate(R.layout.fragment_otp_call, parent, false); getIntents(); login = view.findViewById(R.id.login_otpcc); uname = view.findViewById(R.id.uname); pass = view.findViewById(R.id.pass); setUpValues(); setUpListeners(); return view; } public void getIntents() { } public void setUpValues() { } public void setUpListeners() { login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { username = uname.getText().toString(); sendPostRequest(uname.getText().toString(), pass.getText().toString()); }catch (Exception e){e.printStackTrace();} }});} private void sendPostRequest(String givenUsername, String givenPassword) { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String paramUsername = params[0]; String paramPassword = params[1]; // System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://plant123456.000webhostapp.com/check_login.php"); BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("phoneno", paramUsername); BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("password", paramPassword); BasicNameValuePair regBasicNameValuePAir = new BasicNameValuePair("reg_user", "1"); List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); nameValuePairList.add(usernameBasicNameValuePair); nameValuePairList.add(passwordBasicNameValuePAir); nameValuePairList.add(regBasicNameValuePAir); try { // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. //This is typically useful while sending an HTTP POST request. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList); // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request. httpPost.setEntity(urlEncodedFormEntity); try { // HttpResponse is an interface just like HttpPost. //Therefore we can't initialize them HttpResponse httpResponse = httpClient.execute(httpPost); // According to the JAVA API, InputStream constructor do nothing. //So we can't initialize InputStream although it is not an interface InputStream inputStream = httpResponse.getEntity().getContent(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk = null; while ((bufferedStrChunk = bufferedReader.readLine()) != null) { stringBuilder.append(bufferedStrChunk); } return stringBuilder.toString(); } catch (ClientProtocolException cpe) { System.out.println("First Exception caz of HttpResponese :" + cpe); cpe.printStackTrace(); } catch (IOException ioe) { System.out.println("Second Exception caz of HttpResponse :" + ioe); ioe.printStackTrace(); } } catch (UnsupportedEncodingException uee) { System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee); uee.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.e("result",""+result); if(result.contains("0")) { startActivity(new Intent(getActivity(), MainActivity.class)); }else{ Toast.makeText(getActivity(),"Please reverify the details",Toast.LENGTH_SHORT).show(); } } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(givenUsername, givenPassword); } } <file_sep>package com.planty.app.activity; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.util.Base64; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.planty.app.R; import com.planty.app.customclass.CustomAppCompatActivity; import com.planty.app.fragments.FragmentOtpCall; import com.planty.app.fragments.main.FragmentHomeFeed; import com.planty.app.fragments.main.FragmentOffer; import com.planty.app.fragments.main.FragmentSupport; import com.planty.app.fragments.main.webgame; import com.planty.app.fragments.plant_list; import com.planty.app.model.NavigationModel; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends CustomAppCompatActivity { LinearLayout home_ly, search_ly, offer_ly, support_ly; ImageView home_iv, search_iv, offer_iv, support_iv, cart_iv; // TextView home_tv, search_tv, offer_tv, support_tv; private DrawerLayout mDrawerLayout; ListView mDrawerList; LayoutInflater inflater; DrawerAdapter navDrawerAdapter; RelativeLayout cart_ly; static Context mctx; final public static int NAV_MY_PROFILE = 1; final public static int NAV_MY_ORDER = 2; final public static int NAV_MY_RETURN = 3; final public static int NAV_MY_CART = 4; final public static int NAV_INVITE = 5; final public static int NAV_CONTACT_US = 6; final public static int NAV_TERMS_OF_USE = 7; final public static int NAV_DELIVERY_CHARGES_ = 8; final public static int NAV_NOTIFICATION = 9; final public static int NAV_CHECK_UPDATES = 10; final public static int NAV_ABOUT_US = 11; final public static int NAV_LOGOUT = 12; final public static int FRAGMENT_HOME_FEED = 1; final public static int FRAGMENT_SEARCH = 2; final public static int FRAGMENT_OFFERS = 3; public static String encoded_string, image_name; private static Bitmap bitmap; private static File file; public static Uri file_uri; final public static int FRAGMENT_SUPPORT = 4; public int FRAGMENT_CURRENT = FRAGMENT_HOME_FEED; Boolean refresh = false; public static Activity activity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); getIntents(); initializeViews(); setUpValues(); setUpListeners(); } public void getIntents() { } public void initializeViews() { activity = MainActivity.this; mctx = MainActivity.this; home_ly = findViewById(R.id.home_ly); search_ly = findViewById(R.id.search_ly); offer_ly = findViewById(R.id.offer_ly); support_ly = findViewById(R.id.support_ly); home_iv = findViewById(R.id.home_iv); search_iv = findViewById(R.id.search_iv); offer_iv = findViewById(R.id.offer_iv); support_iv = findViewById(R.id.support_iv); // home_tv = findViewById(R.id.home_tv); // search_tv = findViewById(R.id.search_tv); // offer_tv = findViewById(R.id.offer_tv); // support_tv = findViewById(R.id.support_tv); // mDrawerLayout = findViewById(R.id.drawer_layout); mDrawerList = findViewById(R.id.left_drawer); inflater = getLayoutInflater(); } public void setUpValues() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); FragmentHomeFeed fragmentHomeFeed = new FragmentHomeFeed(); fragmentTransaction.add(R.id.fragment_activity_1, fragmentHomeFeed, FragmentHomeFeed.class.getSimpleName()); fragmentTransaction.commit(); // home_iv.setColorFilter(Constants.color_selected, PorterDuff.Mode.SRC_IN); // home_tv.setTextColor(Constants.color_selected); navDrawerAdapter = new DrawerAdapter(MainActivity.this, getNavigationModelList()); mDrawerList.setAdapter(navDrawerAdapter); } public void setUpListeners() { home_ly.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setUpFooterTabs(FRAGMENT_HOME_FEED); } }); search_ly.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setUpFooterTabs(FRAGMENT_SEARCH); } }); offer_ly.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setUpFooterTabs(FRAGMENT_OFFERS); } }); support_ly.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setUpFooterTabs(FRAGMENT_SUPPORT); } }); // (findViewById(R.id.burger_menu)).setOnClickListener(new View.OnClickListener() { // + @Override // public void onClick(View v) { // drawerContral(); // } // }); } public void setUpFooterTabs(final int tab_to_set) { setUpFooterTabs(tab_to_set, false); } public void setUpFooterTabs(final int tab_to_set, final Boolean proceed_refresh) { Log.e("foot_Tab_to", "===" + tab_to_set + "=="); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (tab_to_set != FRAGMENT_CURRENT || refresh) { Boolean isFront = FRAGMENT_CURRENT < tab_to_set; FRAGMENT_CURRENT = tab_to_set; if (!proceed_refresh) { if (isFront) fragmentTransaction.setCustomAnimations(R.anim.fragmententering_oncreate, R.anim.fragmentleaveing_oncreate); else fragmentTransaction.setCustomAnimations(R.anim.fragmententering_onfinish, R.anim.fragmentleaving_onfinish); } // // home_iv.setColorFilter(Constants.color_deselected, PorterDuff.Mode.SRC_IN); // search_iv.setColorFilter(Constants.color_deselected, PorterDuff.Mode.SRC_IN); // offer_iv.setColorFilter(Constants.color_deselected, PorterDuff.Mode.SRC_IN); // support_iv.setColorFilter(Constants.color_deselected, PorterDuff.Mode.SRC_IN); // // home_tv.setTextColor(Constants.color_deselected); // offer_tv.setTextColor(Constants.color_deselected); // search_tv.setTextColor(Constants.color_deselected); // support_tv.setTextColor(Constants.color_deselected); switch (tab_to_set) { case FRAGMENT_HOME_FEED: // home_iv.setColorFilter(Constants.color_selected, PorterDuff.Mode.SRC_IN); // home_tv.setTextColor(Constants.color_selected); // // plant_list fragmentMenu = new plant_list(); // fragmentTransaction.replace(R.id.fragment_activity_1, fragmentMenu, FragmentHomeFeed.class.getSimpleName()); webgame fragmentMenu = new webgame(); fragmentTransaction.replace(R.id.fragment_activity_1, fragmentMenu); break; case FRAGMENT_SEARCH: // search_iv.setColorFilter(Constants.color_selected, PorterDuff.Mode.SRC_IN); // search_tv.setTextColor(Constants.color_selected); // FragmentSearch fragmentSearch = new FragmentSearch(); // fragmentTransaction.replace(R.id.fragment_activity_1, fragmentSearch, FragmentSearch.class.getSimpleName()); Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.koddev.chatapp"); if (launchIntent != null) { startActivity(launchIntent);//null pointer check in case package name was not found } break; case FRAGMENT_OFFERS: // offer_iv.setColorFilter(Constants.color_selected, PorterDuff.Mode.SRC_IN); // offer_tv.setTextColor(Constants.color_selected); FragmentOffer fragmentOffer = new FragmentOffer(); fragmentTransaction.replace(R.id.fragment_activity_1, fragmentOffer, FragmentOffer.class.getSimpleName()); break; case FRAGMENT_SUPPORT: // support_iv.setColorFilter(Constants.color_selected, PorterDuff.Mode.SRC_IN); // support_tv.setTextColor(Constants.color_selected); FragmentSupport FragmentSupportfragmentSupport = new FragmentSupport(); plant_list fragmentSupport = new plant_list(); fragmentTransaction.replace(R.id.fragment_activity_1, fragmentSupport, FragmentSupport.class.getSimpleName()); break; } fragmentTransaction.commit(); } } class DrawerAdapter extends BaseAdapter { Context context; ArrayList<NavigationModel> naviModels; public DrawerAdapter(Context context, ArrayList<NavigationModel> naviModelArrayList) { this.context = context; this.naviModels = naviModelArrayList; } @Override public View getView(final int position, View convertView, ViewGroup parent) { Log.e("getView: ", position + "===="); if (position == 0) { convertView = inflater.inflate(R.layout.item_header_navigation, null); // // } else { // final NavigationModel navigationModel = naviModels.get(position - 1); convertView = inflater.inflate(R.layout.item_content_navi, null); ImageView iv = convertView.findViewById(R.id.iv); // convertView = inflater.inflate(R.layout.item_app_version, null); // TextView app_version_tv = convertView.findViewById(R.id.app_version_tv); // app_version_tv.setText(CommonMethods.getAppVersion(MainActivity.this)); // TextView nav_title_tv = convertView.findViewById(R.id.nav_title_tv); LinearLayout divider_ly = convertView.findViewById(R.id.divider_ly); if (navigationModel.nav_title.equals("Return Product") || navigationModel.nav_title.equals("Sign Out")) { divider_ly.setVisibility(View.VISIBLE); } else { divider_ly.setVisibility(View.GONE); } // // if (navigationModel.nav_title.equals("My Return") || navigationModel.nav_title.equals("Sign Out")) { // divider_ly.setVisibility(View.VISIBLE); // } else { // divider_ly.setVisibility(View.GONE); // } iv.setImageResource(navigationModel.nav_image_id); nav_title_tv.setText(navigationModel.nav_title); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("onClick: ", navigationModel.nav_title + "===" + position); sideNavProceed(position); } }); } return convertView; } @Override public long getItemId(int position) { return 0; } @Override public Object getItem(int position) { return 0; } @Override public int getCount() { return naviModels.size() + 1; } } public ArrayList<NavigationModel> getNavigationModelList() { ArrayList<NavigationModel> navigationModels = new ArrayList<NavigationModel>(); navigationModels.add(new NavigationModel(R.drawable.home, "Home")); return navigationModels; } public void sideNavProceed(int sideposition) { switch (sideposition) { case 1: startActivity(new Intent(getApplicationContext(), com.planty.app.activity.plant_list.class)); break; case 2: startActivity(new Intent(getApplicationContext(), com.planty.app.activity.plant_list.class)); break; case NAV_MY_RETURN: break; case NAV_MY_CART: break; case NAV_INVITE: sendInvites(); break; case NAV_CONTACT_US: break; case NAV_TERMS_OF_USE: break; case NAV_DELIVERY_CHARGES_: break; case NAV_NOTIFICATION: break; case NAV_CHECK_UPDATES: break; case NAV_ABOUT_US: break; case NAV_LOGOUT: break; } } public void logOutDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Logout"); builder.setMessage("Are you sure want Logout ?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 10 && resultCode == RESULT_OK) { updatetableforurl(); Log.e("on activity result", ""); new Encode_image().execute(); } } private void updatetableforurl() { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { // System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://plant123456.000webhostapp.com/userplant_server.php"); BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("userid", FragmentOtpCall.username); BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("pid", "1"); BasicNameValuePair regBasicNameValuePAir = new BasicNameValuePair("reg_user", "1"); BasicNameValuePair fileBasicNameValuePAir = new BasicNameValuePair("filename", image_name); List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); nameValuePairList.add(usernameBasicNameValuePair); nameValuePairList.add(passwordBasicNameValuePAir); nameValuePairList.add(regBasicNameValuePAir); nameValuePairList.add(fileBasicNameValuePAir); try { // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. //This is typically useful while sending an HTTP POST request. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList); // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request. httpPost.setEntity(urlEncodedFormEntity); it is to being a product, how creative your solution is and how convincing your pitch presentation is. try { // HttpResponse is an interface just like HttpPost. //Therefore we can't initialize them HttpResponse httpResponse = httpClient.execute(httpPost); // According to the JAVA API, InputStream constructor do nothing. //So we can't initialize InputStream although it is not an interface InputStream inputStream = httpResponse.getEntity().getContent(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk = null; while ((bufferedStrChunk = bufferedReader.readLine()) != null) { stringBuilder.append(bufferedStrChunk); } return stringBuilder.toString(); } catch (ClientProtocolException cpe) { System.out.println("First Exception caz of HttpResponese :" + cpe); cpe.printStackTrace(); } catch (IOException ioe) { System.out.println("Second Exception caz of HttpResponse :" + ioe); ioe.printStackTrace(); } } catch (UnsupportedEncodingException uee) { System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee); uee.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.e("result",""+result); if(result.contains("Record updated successfully")) { Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(),"Please wait while it uploads in background",Toast.LENGTH_SHORT).show(); } } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(); } public static class Encode_image extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { bitmap = BitmapFactory.decodeFile(file_uri.getPath()); Log.e("file url path", file_uri.getPath()); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); bitmap.recycle(); byte[] array = stream.toByteArray(); encoded_string = Base64.encodeToString(array, 0); return null; } @Override protected void onPostExecute(Void aVoid) { makeRequest(); } } private static void makeRequest() { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { Log.e("request made", "photo"); RequestQueue requestQueue = Volley.newRequestQueue(mctx); StringRequest request = new StringRequest(Request.Method.POST, "http://plant123456.000webhostapp.com/image_upload.php", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("upload status", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("upload error", "" + error); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put("encoded_string", encoded_string); map.put("image_name", image_name); Log.e("enocoded", "" + encoded_string); return map; } }; requestQueue.add(request); return null; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(); } public void sendInvites() { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); sendIntent.setType("text/plain"); startActivity(sendIntent); } public void drawerContral() { if (mDrawerLayout.isDrawerOpen(mDrawerList)) { mDrawerLayout.closeDrawer(Gravity.LEFT); } else { mDrawerLayout.openDrawer(Gravity.LEFT); } } } <file_sep>package com.planty.app.activity; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.planty.MyListAdapter; import com.planty.app.MyListData; import com.planty.app.R; import com.planty.app.customclass.JSONParser; import com.planty.app.fragments.FragmentOtpCall; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class plant_list extends AppCompatActivity { ArrayList<MyListData> plantdetails; JSONArray schooldetails; MyListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_plant_list); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); plantdetails = new ArrayList<>(); adapter = new MyListAdapter(plantdetails); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); getBusList(); } private void getBusList() { class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { JSONParser jParser = new JSONParser(); JSONObject json = jParser.getJSONFromUrl("http://plant123456.000webhostapp.com/plantsofuser.php?user="+ FragmentOtpCall.username); try { schooldetails = json.getJSONArray("server_response"); for (int i = 0; i < schooldetails.length(); i++) { JSONObject c = schooldetails.getJSONObject(i); plantdetails.add(new MyListData(c.getString("pname"),c.getString("details"),R.drawable.man)); Log.e("plant added",c.getString("pname")); } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); adapter.notifyDataSetChanged(); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(); } } <file_sep>package com.planty.app.supportfiles; import com.android.volley.Request; import com.planty.app.Constants; import com.planty.app.network.CustomJsonObjectRequest; import com.planty.app.network.CustomResponseListener; import com.planty.app.utils.DataUtils; import org.json.JSONObject; import java.util.HashMap; /** * Not used */ public class CommonNetwork { public static void reportError(final HashMap<String, String> report_error_map) { String url = Constants.URL_REPORT_ERROR; JSONObject request_obj = DataUtils.convertMapToJsonObj(report_error_map); new CustomJsonObjectRequest(null, Request.Method.POST, url, request_obj, new CustomResponseListener() { @Override public void responseSuccess(JSONObject response) { } @Override public void responseFailure(JSONObject response) { } @Override public void responseError(String message) { } }); } }
28db2269652bc0de78b4561e2c44b03954a478e6
[ "Markdown", "Java" ]
8
Java
LogaPrakash531/prakash
c8fd5198370c52ae26b6cf62a09e71f59e77380f
627486d3014c05240ff95a74f9462cb258347cb1
refs/heads/master
<file_sep>$(document).ready(function () { $(window).scroll(function () { // check if scroll event happened if ($(document).scrollTop() >= 10) { $(".navbar").css({ backgroundColor: "rgba(0, 0, 0, 0.8)", borderBottom: "1px solid black", }); $(".navbar-collapse").css({ backgroundColor: "transparent", }); } }); function myMap() { var mapProp = { center: new google.maps.LatLng(51.508742, -0.12085), zoom: 5, }; var map = new google.maps.Map( document.getElementById("googleMap"), mapProp ); } });
1218126341343e984904203c9c3e62733a59b8ad
[ "JavaScript" ]
1
JavaScript
OgMan1/advokatvlado
2326434d6cb0ca384d9771af186103901658bacf
d002d3a3ec9a08a51d57172233fea43f951c7a59
refs/heads/master
<file_sep>package ejb; import javax.ejb.Local; import model.Rangement; @Local public interface RangementEjbLocal { public Rangement chercherRangement(String allee, String etagere, String section); public Rangement chercherRangement(int key); } <file_sep>package model; import java.io.Serializable; import java.text.Format; import java.text.SimpleDateFormat; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the utilisateurs database table. * */ @Entity @Table(name="utilisateurs") @NamedQuery(name="Utilisateur.findAll", query="SELECT u FROM Utilisateur u") public class Utilisateur implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int num; private String acces; @Temporal(TemporalType.DATE) private Date dateInscription; private String identifiant; private String mdp; @Transient private Format formatter; public String toString() { formatter = new SimpleDateFormat("yyyy-MM-dd"); String s = formatter.format(dateInscription); return identifiant+", "+acces+". Date : "+s; } //bi-directional many-to-one association to Location @OneToMany(mappedBy="utilisateur", fetch=FetchType.EAGER) private List<Location> locations; public Utilisateur() { } public int getNum() { return this.num; } public void setNum(int num) { this.num = num; } public String getAcces() { return this.acces; } public void setAcces(String acces) { this.acces = acces; } public Date getDateInscription() { return this.dateInscription; } public void setDateInscription(Date dateInscription) { this.dateInscription = dateInscription; } public String getIdentifiant() { return this.identifiant; } public void setIdentifiant(String identifiant) { this.identifiant = identifiant; } public String getMdp() { return this.mdp; } public void setMdp(String mdp) { this.mdp = mdp; } @JsonbTransient public List<Location> getLocations() { return this.locations; } public void setLocations(List<Location> locations) { this.locations = locations; } public Location addLocation(Location location) { getLocations().add(location); location.setUtilisateur(this); return location; } public Location removeLocation(Location location) { getLocations().remove(location); location.setUtilisateur(null); return location; } public Utilisateur(String identifiant, String mdp, String acces, Date dateInscription) { this.identifiant = identifiant; this.mdp = mdp; this.acces = acces; this.dateInscription=dateInscription; } }<file_sep>package ejb; import java.util.List; import javax.ejb.Local; import model.Auteur; @Local public interface AuteurEjbLocal { public Auteur persistAuteur(Auteur auteur); public void removeAuteur(Auteur auteur); public List<Auteur> getAuteurFindAll(); public Auteur chercherAuteur(int key); } <file_sep>package ejb; import java.util.List; import javax.ejb.Local; import model.Livre; import model.Location; import model.Utilisateur; @Local public interface LocationEjbLocal { public Location persistLocation(Location location); public void removeLocation(Location location); public Location mergeLocation(Location location); public List<Location> getLocationUtilisateurEnCours(Utilisateur ut); public List<Location> getLocationEnCours(); public List<Location> getAllLocationUtilisateur(Utilisateur ut); public List<Location> getAllLocationLivre(Livre liv); public Location chercherLocation(int key); } <file_sep>package services; import java.io.Serializable; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.sql.Date; import java.util.List; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import ejb.AuteurEjbLocal; import ejb.LivreEjbLocal; import ejb.LocationEjbLocal; import ejb.RangementEjbLocal; import ejb.UtilisateurEjbLocal; import model.Auteur; import model.Livre; import model.Location; import model.Rangement; import model.Utilisateur; @SessionScoped @Path("services") public class ServiceBibliotheque implements Serializable { /** * */ private static final long serialVersionUID = 1L; @EJB private AuteurEjbLocal ejbAuteur; @EJB private LivreEjbLocal ejbLivre; @EJB private UtilisateurEjbLocal ejbUtilisateur; @EJB private RangementEjbLocal ejbRangement; @EJB private LocationEjbLocal ejbLocation; final String etatDisponible ="disponible"; final String etatEmprunte ="emprunte"; final String etatQRCodeAGenerer = "QRCode à générer"; //----------------------------METHODE GET---------------------------- //#######################AUTEUR####################### @Path("auteurs") @GET @Produces(MediaType.APPLICATION_JSON) public List<Auteur> voirLesAuteurs() { return ejbAuteur.getAuteurFindAll(); } @Path("auteurs/{numauteur}") @GET @Produces(MediaType.APPLICATION_JSON) public Auteur voirUnAuteur(@PathParam("numauteur") String numAuteur) { int num = Integer.valueOf(numAuteur); Auteur a = ejbAuteur.chercherAuteur(num); if (a != null) return a; else return null; } //#######################LIVRE####################### @Path("livres") @GET @Produces(MediaType.APPLICATION_JSON) public List<Livre> voirLesLivres() { List<Livre> listeLivre = ejbLivre.getLivreFindAll(); return listeLivre; } @Path("livres/{numlivre}") @GET @Produces(MediaType.APPLICATION_JSON) public Livre voirUnLivre(@PathParam("numlivre") String numLivre) { int num = Integer.valueOf(numLivre); Livre l = ejbLivre.chercherLivre(num); if (l != null) return l; else return null; } @Path("livres/{genre}/{etat}") @GET @Produces(MediaType.APPLICATION_JSON) public List<Livre> voirLesLivresParGenre(@PathParam("genre") String genre, @PathParam("etat") String etat ) { return ejbLivre.getLivreGenre(genre, etat); } @Path("livres/auteurs/{numauteur}") @GET @Produces(MediaType.APPLICATION_JSON) public List<Livre> voirLesLivresParAuteur(@PathParam("numauteur") String numAuteur) { int num = Integer.valueOf(numAuteur); Auteur aut = ejbAuteur.chercherAuteur(num); return ejbLivre.getLivreAuteur(aut); } @Path("livres/rangements/{numrangement}") @GET @Produces(MediaType.APPLICATION_JSON) public List<Livre> voirLesLivresParRangement(@PathParam("numrangement") String numRangement) { int num = Integer.valueOf(numRangement); Rangement rgt = ejbRangement.chercherRangement(num); return ejbLivre.getLivreRangement(rgt); } @Path("livres/rangements/null") @GET @Produces(MediaType.APPLICATION_JSON) public List<Livre> getLesLivresRangementNull() { return ejbLivre.getLivreRangementNull(); } //#######################UTILISATEUR####################### @Path("utilisateurs") @GET @Produces(MediaType.APPLICATION_JSON) public List<Utilisateur> voirLesUtilisateurs() { List<Utilisateur> listeUtilisateur = ejbUtilisateur.getUtilisateurFindAll(); return listeUtilisateur; } @Path("utilisateurs/clients") @GET @Produces(MediaType.APPLICATION_JSON) public List<Utilisateur> voirLesClients() { List<Utilisateur> listeUtilisateur = ejbUtilisateur.chercheClient(); return listeUtilisateur; } @Path("utilisateurs/{identifiant}") @GET @Produces(MediaType.APPLICATION_JSON) public Utilisateur voirUnUtilisateur(@PathParam("identifiant") String id) { Utilisateur u = ejbUtilisateur.chercheUtilisateur(id); if (u != null) return u; else return null; } //#######################RANGEMENT####################### @Path("rangements/{allee}/{etagere}/{section}") @GET @Produces(MediaType.APPLICATION_JSON) public Rangement voirUnRangement (@PathParam("allee") String allee1, @PathParam("etagere") String etagere1, @PathParam("section") String section1) { Rangement rgt = ejbRangement.chercherRangement(allee1, etagere1, section1); if (rgt != null) return rgt; else return null; } //#######################LOCATION####################### @Path("locations/{numlocation}") @GET @Produces(MediaType.APPLICATION_JSON) public Location voirUneLocation(@PathParam("numlocation") String numLocation) { int num = Integer.valueOf(numLocation); Location loc = ejbLocation.chercherLocation(num); if (loc != null) return loc; else return null; } @Path("locations/{identifiant}/encours") @GET @Produces(MediaType.APPLICATION_JSON) public List<Location> voirLesLocationParUtilisateurEnCours(@PathParam("identifiant") String id) { Utilisateur ut = ejbUtilisateur.chercheUtilisateur(id); List<Location> liste = ejbLocation.getLocationUtilisateurEnCours(ut); return liste; } @Path("locations/utilisateurs/{identifiant}") @GET @Produces(MediaType.APPLICATION_JSON) public List<Location> voirLesLocationsParUtilisateur(@PathParam("identifiant") String id) { Utilisateur ut = ejbUtilisateur.chercheUtilisateur(id); List<Location> liste = ejbLocation.getAllLocationUtilisateur(ut); return liste; } @Path("locations/encours") @GET @Produces(MediaType.APPLICATION_JSON) public List<Location> voirLesLocationsEnCours() { List<Location> liste = ejbLocation.getLocationEnCours(); return liste; } @Path("locations/livres/{numlivre}") @GET @Produces(MediaType.APPLICATION_JSON) public List<Location> voirLesLocationsDunLivre(@PathParam("numlivre") String numLivre) { int num = Integer.valueOf(numLivre); Livre liv = ejbLivre.chercherLivre(num); List<Location> liste = ejbLocation.getAllLocationLivre(liv); return liste; } //----------------------------METHODE POST---------------------------- //#######################AUTEUR####################### @Path("auteurs/add") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Auteur ajouterAuteur(@FormParam("nom") String n, @FormParam("prenom") String p, @FormParam("nationalite") String nat) { Auteur auteur = new Auteur(n, p, nat); return ejbAuteur.persistAuteur(auteur); } //#######################LIVRE####################### @Path("livres/add") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Livre ajouterLivre(@FormParam("titre") String titre, @FormParam("editeur") String edit, @FormParam("isbn") String isbn, @FormParam("annee") String a, @FormParam("auteur") String numAuteur, @FormParam("genre") String genre, @FormParam("resume") String resume) { int num = Integer.valueOf(numAuteur); Auteur aut = ejbAuteur.chercherAuteur(num); short annee = Short.valueOf(a); Livre livre = new Livre(annee, edit, genre, isbn, resume, titre, aut, etatQRCodeAGenerer); ejbLivre.persistLivre(livre); return livre; } //#######################UTILISATEUR####################### @Path("utilisateurs/add") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Utilisateur ajouterUtilisateur(@FormParam("identifiant") String i, @FormParam("mdp") String m, @FormParam("acces") String a, @FormParam("dateInscription") String d) { Date date = Date.valueOf(d); Utilisateur utilisateur = new Utilisateur(i, m, a, date); return ejbUtilisateur.persistUtilisateur(utilisateur); } //#######################LOCATION####################### @Path("locations/add") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public void ajouterLocation(@FormParam("utilisateur") String id, @FormParam("livre") String numLivre, @FormParam("dateEmprunt") String dateEmprunt, @FormParam("dateRetour") String dateRetour) { Utilisateur ut = ejbUtilisateur.chercheUtilisateur(id); int key = Integer.valueOf(numLivre); Livre liv = ejbLivre.chercherLivre(key); Date dateE = Date.valueOf(dateEmprunt); Date dateR = Date.valueOf(dateRetour); Location loc = new Location(dateE, dateR, liv, ut); ejbLocation.persistLocation(loc); liv.setEtat(etatEmprunte); ejbLivre.mergeLivre(liv); } //----------------------------METHODE PUT---------------------------- //#######################LIVRE####################### @Path("livres/{numlivre}/qrcode") @PUT @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Livre ajoutQRCode(@PathParam("numlivre") String n, @FormParam("texteQRCode") String t) { int num = Integer.valueOf(n); Livre l = ejbLivre.chercherLivre(num); l.setTexte_qrcode(t); l.setEtat(etatDisponible); ejbLivre.mergeLivre(l); return l; } @Path("livres/{numlivre}/rangement") @PUT @Produces(MediaType.APPLICATION_JSON) public void rangerUnLivre(@PathParam("numlivre") String numLivre, @FormParam("numrangement") String numrangement) { int numL = Integer.valueOf(numLivre); Livre l = ejbLivre.chercherLivre(numL); int numR = Integer.valueOf(numrangement); Rangement rgt = ejbRangement.chercherRangement(numR); l.setRangement(rgt); ejbLivre.mergeLivre(l); } //#######################UTILISATEUR####################### @Path("utilisateurs/{identifiant}/nouveaumdp") @PUT @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Utilisateur modifierMotDePasse(@PathParam("identifiant") String id, @FormParam("nouveaumdp") String m) throws NoSuchAlgorithmException, InvalidKeySpecException { Utilisateur ut = ejbUtilisateur.chercheUtilisateur(id); String mHach = hachageMdp(m); ut.setMdp(mHach); ejbUtilisateur.mergeUtilisateur(ut); return ut; } //#######################LOCATION####################### @Path("locations/{numlocation}/retour") @PUT @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public void validerRetourLivre(@PathParam("numlocation") String num, @FormParam("dateRetourReel") String date) { int numL = Integer.valueOf(num); Location loc = ejbLocation.chercherLocation(numL); Date dateR = Date.valueOf(date); loc.setDateRetourReel(dateR); ejbLocation.mergeLocation(loc); Livre liv = loc.getLivre(); liv.setEtat(etatDisponible); ejbLivre.mergeLivre(liv); } //----------------------------METHODE DELETE---------------------------- //#######################AUTEUR####################### @Path("auteurs/del/{numAuteur}") @DELETE @Produces(MediaType.APPLICATION_JSON) public Auteur supprimerAuteur(@PathParam("numAuteur") String n) { int num = Integer.valueOf(n); Auteur a = ejbAuteur.chercherAuteur(num); ejbAuteur.removeAuteur(a); return a; } //#######################LIVRE####################### @Path("livres/del/{numLivre}") @DELETE @Produces(MediaType.APPLICATION_JSON) public Livre supprimerLivre(@PathParam("numLivre") String n) { int num = Integer.valueOf(n); Livre l = ejbLivre.chercherLivre(num); ejbLivre.removeLivre(l); return l; } //#######################UTILISATEUR####################### @Path("utilisateurs/del/{identifiantUtilisateur}") @DELETE @Produces(MediaType.APPLICATION_JSON) public void supprimerUtilisateur(@PathParam("identifiantUtilisateur") String id) { Utilisateur u = ejbUtilisateur.chercheUtilisateur(id); ejbUtilisateur.removeUtilisateur(u); } //#######################LOCATION####################### @Path("locations/del/{numLocation}") @DELETE @Produces(MediaType.APPLICATION_JSON) public void supprimerLocation(@PathParam("numLocation") String id) { int key = Integer.valueOf(id); Location loc = ejbLocation.chercherLocation(key); ejbLocation.removeLocation(loc); } public String hachageMdp(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { SecureRandom random = new SecureRandom(); byte[] salt = new byte[32]; random.nextBytes(salt); // 70000 itérations, clef sur 256 bits ou 32 octets PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 70000, 256); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); SecretKey secret = factory.generateSecret(spec); byte[] hash = secret.getEncoded(); salt = spec.getSalt(); String mdphach = bytesToHex(hash)+bytesToHex(salt); return mdphach; } public static String bytesToHex(byte[] b) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; StringBuffer buffer = new StringBuffer(); for (int j = 0; j < b.length; j++) { buffer.append(hexDigits[(b[j] >> 4) & 0x0f]); buffer.append(hexDigits[b[j] & 0x0f]); } return buffer.toString(); } } <file_sep>package model; import java.io.Serializable; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import java.util.List; /** * The persistent class for the rangement database table. * */ @Entity @NamedQuery(name="Rangement.findAll", query="SELECT r FROM Rangement r") public class Rangement implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int num; private String allee; private String etagere; private String section; //bi-directional many-to-one association to Livre @OneToMany(mappedBy="rangement", fetch=FetchType.EAGER) private List<Livre> livres; public Rangement() { } public int getNum() { return this.num; } public void setNum(int num) { this.num = num; } public String getAllee() { return this.allee; } public void setAllee(String allee) { this.allee = allee; } public String getEtagere() { return this.etagere; } public void setEtagere(String etagere) { this.etagere = etagere; } public String getSection() { return this.section; } public void setSection(String section) { this.section = section; } @JsonbTransient public List<Livre> getLivres() { return this.livres; } public void setLivres(List<Livre> livres) { this.livres = livres; } public Livre addLivre(Livre livre) { getLivres().add(livre); livre.setRangement(this); return livre; } public Livre removeLivre(Livre livre) { getLivres().remove(livre); livre.setRangement(null); return livre; } public String toString() { return livres.toString(); } }
d393b3340f6157dd566048d3cbe3e289f5144d47
[ "Java" ]
6
Java
gdelestre/bilbio-rest-ejb
f6ace905d93bb0124aaf4d0a99a9124ecdcd70f9
907ac353a2205790b2d45d148dcd314b7acbdffd
refs/heads/master
<repo_name>dankim9/lambdaChat<file_sep>/src/store/mqtt/createWebSocketStream.ts import MqttWebSocketStream from 'mqtt-websocket-stream' import createUrlSigner from './createUrlSigner' export default (WebSocket, awsOptions) => { const urlSigner = createUrlSigner(awsOptions) const createWebSocketWithCredentials = callback => { urlSigner.getAndSign({ expiration: 15 }, (err, url) => { if (err) { return callback(err) } callback(null, new WebSocket(url, ['mqttv3.1'])) }) } return new MqttWebSocketStream(createWebSocketWithCredentials) } <file_sep>/src/api-ai-client/Request/UserEntitiesRequest.ts /** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { ApiAiClient } from '../ApiAiClient' import { IRequestOptions } from '../Interfaces' import { IEntity } from '../Models/Entity' import ApiAiUtils from '../Utils' import XhrRequest from '../XhrRequest' import Request from './Request' export class UserEntitiesRequest extends Request { private static ENDPOINT: string = 'userEntities' private baseUri: string constructor( apiAiClient: ApiAiClient, protected options: IUserEntitiesRequestOptions = {} ) { super(apiAiClient, options) this.baseUri = this.apiAiClient.getApiBaseUrl() + UserEntitiesRequest.ENDPOINT } public create(entities: IEntity[] | IEntity) { this.uri = this.baseUri const options = ApiAiUtils.cloneObject(this.options) options.entities = Array.isArray(entities) ? entities : [entities] return this.perform(options) } public retrieve(name: string) { this.uri = this.baseUri + '/' + name this.requestMethod = XhrRequest.Method.GET return this.perform() } public update( name: string, entries: IEntity.IEntry[], extend: boolean = false ) { this.uri = this.baseUri + '/' + name this.requestMethod = XhrRequest.Method.PUT const options = ApiAiUtils.cloneObject(this.options) options.extend = extend options.entries = entries options.name = name return this.perform(options) } public delete(name: string) { this.uri = this.baseUri + '/' + name this.requestMethod = XhrRequest.Method.DELETE return this.perform() } } interface IUserEntitiesRequestOptions extends IRequestOptions { extend?: boolean name?: string entities?: IEntity[] entries?: IEntity.IEntry[] } <file_sep>/src/themes/index.ts import { darkTheme, elegantTheme, purpleTheme } from '@livechat/ui-kit' export const themes:any = { defaultTheme: { FixedWrapperMaximized: { css: { boxShadow: '0 0 1em rgba(0, 0, 0, 0.1)', }, }, }, purpleTheme: { ...purpleTheme, TextComposer: { ...purpleTheme.TextComposer, css: { ...purpleTheme.TextComposer.css, marginTop: '1em', }, }, OwnMessage: { ...purpleTheme.OwnMessage, secondaryTextColor: '#fff', }, }, elegantTheme: { ...elegantTheme, Message: { ...darkTheme.Message, secondaryTextColor: '#fff', }, OwnMessage: { ...darkTheme.OwnMessage, secondaryTextColor: '#fff', }, }, darkTheme: { ...darkTheme, Message: { ...darkTheme.Message, css: { ...darkTheme.Message.css, color: '#fff', }, }, OwnMessage: { ...darkTheme.OwnMessage, secondaryTextColor: '#fff', }, TitleBar: { ...darkTheme.TitleBar, css: { ...darkTheme.TitleBar.css, padding: '1em', }, }, }, }<file_sep>/src/api-ai-client/ApiAiConstants.ts /** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ enum AVAILABLE_LANGUAGES { EN = 'en' as any, DE = 'de' as any, ES = 'es' as any, PT_BR = 'pt-BR' as any, ZH_HK = 'zh-HK' as any, ZH_CN = 'zh-CN' as any, ZH_TW = 'zh-TW' as any, NL = 'nl' as any, FR = 'fr' as any, IT = 'it' as any, JA = 'ja' as any, KO = 'ko' as any, PT = 'pt' as any, RU = 'ru' as any, UK = 'uk' as any } export class ApiAiConstants { public static AVAILABLE_LANGUAGES = AVAILABLE_LANGUAGES public static VERSION: string = '2.0.0-beta.20' public static DEFAULT_BASE_URL: string = 'https://api.api.ai/v1/' public static DEFAULT_API_VERSION: string = '20150910' // public static DEFAULT_CLIENT_LANG: AVAILABLE_LANGUAGES = AVAILABLE_LANGUAGES.EN public static DEFAULT_CLIENT_LANG: string = 'en' } <file_sep>/.types/livechat/index.d.ts declare module '@livechat/ui-kit' { import * as React from 'react' export class AddIcon extends React.Component<{ style?: any },{}> {} export class AgentBar extends React.Component<{},{}> {} export class Avatar extends React.Component<{ imgUrl: string style?: any }, {}> {} // darkTheme, elegantTheme, purpleTheme, defaultTheme export const darkTheme:any export const elegantTheme:any export const purpleTheme:any export const defaultTheme:any export const Bubble:any export class CloseIcon extends React.Component<{},{}> {} export class Column extends React.Component<{ flexFill? flexFit? },{}> {} export class ChatIcon extends React.Component<{},{}> {} export class EmojiIcon extends React.Component<{},{}> {} export class Fill extends React.Component<{},{}> {} export class Fit extends React.Component<{},{}> {} export class IconButton extends React.Component<{ color?: string onClick?: () => void style?: any },{}> {} interface IChatroom { active?: boolean maximizedOnInit?: boolean style?: any } class ChatroomComponent extends React.Component<IChatroom, {}> {} export class FixedWrapper { static Maximized = ChatroomComponent static Minimized = ChatroomComponent static Root = ChatroomComponent } export class Message extends React.Component<{ isOwn?: boolean authorName?: string date?: string style?: any key? avatarUrl? }, {}> {} export class MessageButton extends React.Component<{ className?: string label?: string onClick?: (e: any) => void primary?: boolean }, {}> {} export class MessageButtons extends React.Component<{}, {}> {} export class MessageGroup extends React.Component<{ avatar?: string | null onlyFirstWithMeta?: boolean }, {}> {} export class MessageList extends React.Component<{ active: boolean containScrollInSubtree: boolean }, {}> {} export class MessageMedia extends React.Component<{ className?: string style?: any }, {}> {} export class MessageText extends React.Component<{}, {}> {} export class MessageTitle extends React.Component<{ className?: string style?: any title? }, {}> {} export class QuickReplies extends React.Component<{ className?: string onSelect: (message: string, key: string) => void, replies: string[] style?: any }, {}> {} export class RateBadIcon extends React.Component<{ style? }, {}> {} export class RateGoodIcon extends React.Component<{ style? }, {}> {} export class Row extends React.Component<{ align?: string flexFill? },{}> {} export class SendButton extends React.Component<{}, {}> {} export class Subtitle extends React.Component<{}, {}> {} export class TextComposer extends React.Component<{ active?: boolean defaultValue?: string onButtonClick?: (e: any) => void onChange?: (text: string) => void onKeyDown?: (e: any) => void onSend: (message: string) => void value?: string }, {}> {} export class TextInput extends React.Component<{ autoCapitalize?: string autoCorrect?: string defaultValue?: string maxRows?: number minRows?: number onChange?: (text: string) => void onHeightChange?: (height: number) => void onKeyDown?: (e: any) => void placeholder?: string type?: string value?: string }, {}> {} export class Title extends React.Component<{}, {}> {} export class TitleBar extends React.Component<{ className?: string rightIcons: JSX.Element[] title: string style?: any }, {}> {} export class ThemeProvider extends React.Component<{ vars: any }, {}> {} } <file_sep>/src/store/mqtt/publisher.ts import Client from './Client' // Connect to broker, publish message to a topic and then disconnect const publisher = options => (topic, message) => new Promise((resolve, reject) => { const client = new Client(options) client.once('connect', () => { client.publish(topic, message, {}, err => { if (err) { client.end() reject(err) } else { client.end() resolve() } }) }) client.once('error', err => { client.end() reject(err) }) client.once('offline', () => { client.end() reject(new Error('MQTT went offline')) }) }) export default publisher <file_sep>/src/store/mqtt/index.ts import Client from './Client' import createWebSocketStream from './createWebSocketStream' import publisher from './publisher' const connect: any = options => new Client(options) export const AWSMqtt = { Client, connect, createWebSocketStream, publisher } <file_sep>/src/store/mqtt/processOptions.ts export default (options: any = {}) => { return { WebSocket: options.WebSocket || window.Websocket, aws: { credentials: options.credentials, endpoint: options.endpoint, region: options.region }, mqtt: { clean: options.clean || true, // need to re-subscribe after offline/disconnect, clientId: options.clientId || 'mqtt-client-' + Math.floor(Math.random() * 100000 + 1), connectTimeout: options.connectTimeout || 5 * 1000, protocolId: options.protocolId || 'MQTT', reconnectPeriod: options.reconnectPeriod || 10 * 1000, will: options.will || {} } } } <file_sep>/src/store/mqtt/createUrlSigner.ts // import STS from 'aws-sdk/clients/sts' import v4 from 'aws-signature-v4' import crypto from 'crypto' export default ({ region, endpoint, credentials }) => { const sign = async ({ credentials1, expiration }) => { let url = v4.createPresignedURL( 'GET', endpoint, '/mqtt', 'iotdevicegateway', crypto .createHash('sha256') .update('', 'utf8') .digest('hex'), { expiration, key: credentials.accessKeyId, protocol: 'wss', region, secret: credentials.secretAccessKey } ) if (credentials.sessionToken) { url += '&X-Amz-Security-Token=' + encodeURIComponent(credentials.sessionToken) } return url } return { getAndSign: ({ expiration = 15 }, callback) => { credentials.get(async err => { if (err) { return callback(err) } const url = await sign({ credentials1: credentials, expiration }) callback(null, url) }) } } } <file_sep>/src/store/index.ts import AWS from 'aws-sdk' import axios from 'axios' import { flow, types } from 'mobx-state-tree' import { AWSMqtt } from './mqtt' import { delay, get } from 'lodash' // import { ApiApiClient } from '../src/api-ai-client/ApiApiClient' import { IServerResponse } from '../api-ai-client/Interfaces' export const Text = types.model({ text: types.optional(types.string, '') }) export const Message = types.model({ author: types.optional(types.string, ''), type: types.optional(types.string, ''), data: types.optional(Text, {}) }) const sendToDialogflow = (message, client, fingerprint) => { return new Promise((resolve, reject) => { delay(async () => { const response:IServerResponse = await client.textRequest(message) console.log(response, 'res') const intentName = get(response, 'result.metadata.intentName', '') const responseMessage = get(response, 'result.fulfillment.speech', 'sorry can you rephrase that?') const userMessage = get(response, 'result.resolvedQuery', 'user inquery') if (intentName === 'human') { await axios.post('https://5cc7b242.ngrok.io/log/message', { fingerprint, role: 'user', message: userMessage }) } resolve(responseMessage) }, 400) }) } const sendToSlack = async (message, fingerprint) => { await axios.post('https://5cc7b242.ngrok.io/log/message', { fingerprint, role: 'user', message: message }) } export const RootStore = types .model({ fingerprint: types.optional(types.string, ''), messageList: types.optional(types.array(Message), []), newMessagesCount: types.optional(types.number, 0), isOpen: types.optional(types.boolean, false), aiPaused: types.optional(types.boolean, false) }) .actions(self => { let client return { setClient(value) { client = value }, sendTextMessage: flow(function* (data) { const text = data.data.text if (self.aiPaused) { yield sendToSlack(text, self.fingerprint) return } const answer = yield sendToDialogflow(text, client, self.fingerprint) self.messageList.push(Message.create({ author: 'them', type: 'text', data: Text.create({ text: answer }) })) self.newMessagesCount++ }), setFingerPrint(fingerprint) { self.fingerprint = fingerprint }, sendOwnMessage(message) { self.messageList.push(Message.create(message)) }, sendMessage(text) { self.messageList.push(Message.create({ author: 'them', type: 'text', data: Text.create({ text }) })) self.newMessagesCount++ }, pauseAi() { self.aiPaused = true }, resumeAi() { self.aiPaused = false } }}) .views(self => ({ get jJ(): any { console.log( process.env.REACT_APP_AWS_IOT_COGNITO_IDENTITY, process.env.REACT_APP_AWS_IOT_ENDPOINT, 'aws esh' ) try { AWS.config.region = 'us-east-2' AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: process.env.REACT_APP_AWS_IOT_COGNITO_IDENTITY }) const client = AWSMqtt.connect({ WebSocket: window.WebSocket, clientId: 'mqtt-client-' + Math.floor(Math.random() * 100000 + 1), // clientId to register with MQTT broker. Need to be unique per client credentials: AWS.config.credentials, endpoint: process.env.REACT_APP_AWS_IOT_ENDPOINT, region: AWS.config.region, will: { payload: '', qos: 0, retain: false, topic: `/twilio/${self.fingerprint}` } }) client.subscribe(`/twilio/${self.fingerprint}`) client.on('connect', () => { console.log('connected to Aws IoT endpoint!') }) client.on('message', (topic, message) => { const msg: any = new TextDecoder('utf-8').decode(message) console.log(msg, 'message') if (msg === 'resume') { //turn ai back on self.resumeAi() return } //pause ai self.pauseAi() self.sendMessage(msg) return // client.end() }) client.on('close', () => { // ... console.log('close') }) client.on('offline', () => { // ... console.log('offline') }) return true } catch (error) { console.log(error, 'error log') return false } } })) export type IRootStore = typeof RootStore<file_sep>/.types/livechat/api-ai/index.d.ts declare var AudioContext, webkitAudioContext: any // ADDED declare module "api-ai-javascript" { const content: any export default content export class ApiAiClient { constructor({accessToken: string}) textRequest(message: string): Promise<any> } }<file_sep>/src/store/mqtt/Client.ts import MqttClient from 'mqtt/lib/client' import createWebSocketStream from './createWebSocketStream' import processOptions from './processOptions' class Client extends MqttClient { public once: any public publish: any public end: any constructor(options) { const { WebSocket, aws, mqtt } = processOptions(options) super(() => createWebSocketStream(WebSocket, aws), mqtt) } } export default Client <file_sep>/src/api-ai-client/Interfaces.ts /** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // import {ApiAiConstants} from "./ApiAiConstants" export interface IRequestOptions { query?: string event?: { name: string; data?: IStringMap } sessionId?: string lang?: string // ApiAiConstants.AVAILABLE_LANGUAGES originalRequest?: { source: string; data?: IStringMap } } export interface IServerResponse { id?: string result?: { action: string resolvedQuery: string speech: string fulfillment?: { speech: string } } status: { code: number errorDetails?: string errorID?: string errorType: string } } export interface IStringMap { [s: string]: string } export interface IApiClientOptions { lang?: string // ApiAiConstants.AVAILABLE_LANGUAGES version?: string baseUrl?: string sessionId?: string streamClientClass?: IStreamClientConstructor accessToken: string } export interface IStreamClientConstructor { new (options: IStreamClientOptions): IStreamClient } export enum ERROR { ERR_NETWORK, ERR_AUDIO, ERR_SERVER, ERR_CLIENT } export enum EVENT { MSG_WAITING_MICROPHONE, MSG_MEDIA_STREAM_CREATED, MSG_INIT_RECORDER, MSG_RECORDING, MSG_SEND, MSG_SEND_EMPTY, MSG_SEND_EOS_OR_JSON, MSG_WEB_SOCKET, MSG_WEB_SOCKET_OPEN, MSG_WEB_SOCKET_CLOSE, MSG_STOP, MSG_CONFIG_CHANGED } export interface IStreamClient { init(): void open(): void close(): void startListening(): void stopListening(): void } export interface IStreamClientOptions { server?: string token?: string sessionId?: string lang?: string // ApiAiConstants.AVAILABLE_LANGUAGES contentType?: string readingInterval?: string onOpen?: () => void onClose?: () => void onInit?: () => void onStartListening?: () => void onStopListening?: () => void onResults?: (data: IServerResponse) => void onEvent?: (eventCode: EVENT, message: string) => void onError?: (errorCode: ERROR, message: string) => void } // export namespace IStreamClient { // export enum ERROR { // ERR_NETWORK, // ERR_AUDIO, // ERR_SERVER, // ERR_CLIENT // } // export enum EVENT { // MSG_WAITING_MICROPHONE, // MSG_MEDIA_STREAM_CREATED, // MSG_INIT_RECORDER, // MSG_RECORDING, // MSG_SEND, // MSG_SEND_EMPTY, // MSG_SEND_EOS_OR_JSON, // MSG_WEB_SOCKET, // MSG_WEB_SOCKET_OPEN, // MSG_WEB_SOCKET_CLOSE, // MSG_STOP, // MSG_CONFIG_CHANGED // } // }
e90d8c07aca843f595e13cb9a01675bf213b9c50
[ "TypeScript" ]
13
TypeScript
dankim9/lambdaChat
e1e3f4c44f088da05c36fb70248c45c3a420ada5
6df9ff16de450f8a15050bbf1103168bb8db03e2
refs/heads/master
<file_sep># Anti-violence-cracking-example 防止暴力破解的例子 <file_sep><?php session_start(); date_default_timezone_set('PRC'); $msg = ''; $host = 'localhost'; $user = 'root'; $pwd = '<PASSWORD>'; $dbname = 'user'; $dsn = "mysql:host={$host};dbname={$dbname}"; if (!empty($_REQUEST['login']) && !empty($_REQUEST['u']) && !empty($_REQUEST['p'])) { $u = isset($_REQUEST['u']) ? $_REQUEST['u'] : ''; $p = isset($_REQUEST['p']) ? $_REQUEST['p'] : ''; try { $db = new PDO($dsn, $user, $pwd); // 判断用户是否存在 $sql = "select * from user where username = :username"; $sqlr = $db->prepare($sql); $res = $sqlr->execute([':username' => $u]); $data = $sqlr->fetch(); if ($sqlr->rowCount() > 0) { // 用户存在 判断用户登录时间是否正常 $nowtime = time(); $lasttime = intval($data['lasttime']); $locktime = intval($data['locktime']); // 如果为负数 锁定解除 $oktime = ($lasttime + $locktime) - $nowtime; // 取出的数据可能有问题的时候使用 if ($oktime > 100000 || $oktime < -100000) { $oktime == -1; } if ($oktime <= 0) { // 已经可以登录了 if (md5($p) === $data['password']) { // 密码正确 $_SESSION['user'] = $data['username']; $msg = ':)成功登录[' . $_SESSION['user'] . '] ' . date('H:i:s');; } else { // 密码错误 更新用户登录时间 随机生成锁定时间 $lock = rand(10, 30); $sql = "update user set `lasttime` = '{$nowtime}', `locktime` = '{$lock}' where username = :username"; $sqlr = $db->prepare($sql); $sqlr->execute([':username' => $u]); $msg = '!!!密码错误,请' . $lock . '秒后再登录' . date('H:i:s');; } } else { // 用户锁定中 $msg = '用户锁定! 请' . $oktime . '秒后在登录' . date('H:i:s');; } } else { $msg = '!!!用户不存在' . date("H:i:s"); } } catch (PDOException $e) { $msg = '数据库连接错误' . $e->getMessage(); } } else { $msg = '输入用户名密码登录'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>登录</title> </head> <body> <div style="text-align: center"> <form action="" method="post"> <p> <h1>登录-防止暴力破解</h1> </p> <p><?php echo $msg; ?></p> <p><input type="text" name="u" placeholder="默认: admin"></p> <p><input type="password" name="p" placeholder="默认: <PASSWORD>"></p> <p><input type="submit" value="登录" name="login"></p> </form> </div> <div> <a href="php.txt" target="__blank">PHP文件查看</a> <a href="sql.png" target="_blank">数据库查看</a> </div> </body> </html>
6485e35438e2c6349fff1d0f935ef9f61c943049
[ "Markdown", "PHP" ]
2
Markdown
yuunie/Anti-violence-cracking-example
4be854e70a6203db36e6f13547792523698af689
1776884d271f8afd39a532acb0b72436d6374186
refs/heads/master
<repo_name>lmnzr/ASP<file_sep>/ADO.NET/pert 9/webservice/webservice/tampilservice.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace webservice { public partial class tampilservice : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { tampilservicetes.WebServicetest nambah = new tampilservicetes.WebServicetest(); int angka1 = Convert.ToInt32(TextBox1.Text); int angka2 = Convert.ToInt32(TextBox2.Text); int hasil = nambah.tambah(angka1, angka2); Label1.Text = hasil.ToString(); } } }<file_sep>/n-tier/pert3/sekolah/sekolah/sekolah/default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BusinessLayer; using System.Data; namespace sekolah { public partial class _default : System.Web.UI.Page { businesslayer objbl = new businesslayer(); protected void Page_Load(object sender, EventArgs e) { refreshgrid(); } private void refreshgrid() { GridView1.DataSource = objbl.viewdatab(); GridView1.DataBind(); } protected void save_Click(object sender, EventArgs e) { string nama = TextBox2.Text; string alamat = TextBox3.Text; objbl.insertdatab(nama, alamat); refreshgrid(); } void cleardata() { TextBox2.Text = ""; TextBox3.Text = ""; } protected void delete_Click(object sender, EventArgs e) { string nis = TextBox1.Text; objbl.deletedatab(nis); refreshgrid(); } protected void update_Click(object sender, EventArgs e) { string nis = TextBox1.Text; string nama = TextBox2.Text; string alamat = TextBox3.Text; objbl.updatedatab(nis, nama, alamat); refreshgrid(); } protected void Button1_Click(object sender, EventArgs e) { string nis = TextBox1.Text; DataTable dt = new DataTable(); dt = objbl.viewdataisib(nis); TextBox2.Text = dt.Rows[0]["nama_siswa"].ToString(); TextBox3.Text = dt.Rows[0]["alamat"].ToString(); } } }<file_sep>/dengokowstore/View/Member/Logout.aspx.cs using BussinessLayer; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Logout : System.Web.UI.Page { business objB = new business(); protected void Page_Load(object sender, EventArgs e) { if (objB.MemberLoginValidator() || objB.AdminLoginValidator()) { string ID = Session["Logout"].ToString(); objB.LogoutStat(Int32.Parse(ID)); objB.LogoutSession(); Response.Redirect("../../Default.aspx"); } else { Response.Redirect("/View/Member/Login.aspx"); } } }<file_sep>/dengokowstore/View/Member/Bio.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class Bio : System.Web.UI.Page { business objB = new business(); int memberID; string username; public void refresh() { string path = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect(path); } protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.MemberLoginValidator(); if (!logstat) { Response.Redirect("~/View/Member/Login.aspx"); } else { memberID = Convert.ToInt32(Session["ID"].ToString()); DataTable dt = objB.SelectMemberMemberId(memberID); ori_alamat.Text = dt.Rows[0]["Adresss"].ToString(); ori_contact.Text = dt.Rows[0]["Contact"].ToString(); ori_email.Text = dt.Rows[0]["email"].ToString(); ori_kota.Text = dt.Rows[0]["City"].ToString(); ori_nama.Text = dt.Rows[0]["Nama"].ToString(); ori_post.Text = dt.Rows[0]["Postcode"].ToString(); ori_provinsi.Text = dt.Rows[0]["Province"].ToString(); ori_username.Text = dt.Rows[0]["userName"].ToString(); username = dt.Rows[0]["userName"].ToString(); if (!DBNull.Value.Equals(dt.Rows[0]["Photo_path"])) { productImage.ImageUrl = dt.Rows[0]["Photo_path"].ToString(); } } } protected void Edit_Click(object sender, EventArgs e) { bool stat = edt_alamat.Enabled; if (!stat) { edt_alamat.Enabled = true; edt_alamat.Text = ori_alamat.Text; edt_contact.Enabled = true; edt_contact.Text = ori_contact.Text; edt_kota.Enabled = true; edt_kota.Text = ori_kota.Text; edt_nama.Enabled = true; edt_nama.Text = ori_nama.Text; edt_post.Enabled = true; edt_post.Text = ori_post.Text; edt_provinsi.Enabled = true; edt_provinsi.Text = ori_provinsi.Text; Submit.Visible = true; } else { edt_alamat.Enabled = false; edt_contact.Enabled = false; edt_kota.Enabled = false; edt_nama.Enabled = false; edt_post.Enabled = false; edt_provinsi.Enabled = false; Submit.Visible = false; } } protected void Submit_Click(object sender, EventArgs e) { int ID = Convert.ToInt32(Session["ID"].ToString()); string Address = edt_alamat.Text; string City = edt_kota.Text; string Province = edt_provinsi.Text; int Postcode = Convert.ToInt32(edt_post.Text); long Contact = Convert.ToInt64(edt_contact.Text); objB.updateBio(ID, Address, City, Province, Postcode, Contact); refresh(); } protected void uploadbtn_Click(object sender, EventArgs e) { if (ImageUpload.HasFiles) { string filename = ImageUpload.FileName; string dt = DateTime.Now.DayOfYear.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Hour.ToString(); string pathdir = Server.MapPath("~//img//userpic//" + dt + username); string pathfile = Server.MapPath("~//img//userpic//" + dt + username + "//" + filename); string savedpath = "~\\img\\userpic\\" + dt + username + "\\" + filename; if (!Directory.Exists(pathdir)) { Directory.CreateDirectory(pathdir); } ImageUpload.PostedFile.SaveAs(pathfile); objB.updateProfpic(memberID, savedpath); } refresh(); } }<file_sep>/dengokowstore/SQLQuery33.sql SELECT * FROM members INNER JOIN users ON members.userID = users.userID WHERE members.memberID = 1;<file_sep>/ADO.NET/pert5/gridview/gridview/repeater.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace gridview { public partial class repeater : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string ad = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ad1;Data Source=R3B-03\\SQLEXPRESS"; SqlConnection koneksi = new SqlConnection(ad); SqlCommand cmd = new SqlCommand("select*from produk", koneksi); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); try { koneksi.Open(); da.SelectCommand = cmd; da.Fill(ds,"ms_produkcopy"); da.Dispose(); cmd.Dispose(); koneksi.Dispose(); Repeater1.DataSource=ds.Tables["ms_produkcopy"]; Repeater1.DataBind(); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } } } <file_sep>/ADO.NET/pert4/DATASET/DATASET/default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace DATASET { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string a = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ad1;Data Source=(local)"; SqlConnection koneksi = new SqlConnection(a); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand("select*from ms_member", koneksi); try { koneksi.Open(); da.SelectCommand = cmd; da.Fill(ds, "ms_membercopy"); da.Dispose(); cmd.Dispose(); koneksi.Close(); for (int i = 0; i <= ds.Tables["ms_membercopy"].Rows.Count - 1; i++) { Response.Write(ds.Tables["ms_membercopy"].Rows[i][4]+", "+ ds.Tables["ms_membercopy"].Rows[i][2]); Response.Write("<br>"); } } catch (Exception salah) { Response.Write("can not open connection"); Response.Write(salah.ToString()); } } } }<file_sep>/ADO.NET/pert8/WebApplication1/WebApplication1/formisi.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class formisi : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { DataClasses1DataContext baru = new DataClasses1DataContext(); ms_member member = new ms_member { email = TextBox1.Text, password = <PASSWORD>, tanggal_lahir = Convert.ToDateTime(TextBox3.Text), status_aktif = TextBox4.Text, online_status = TextBox5.Text }; baru.ms_members.InsertOnSubmit(member); try { baru.SubmitChanges(); } catch(Exception salah) { salah.ToString(); } } } }<file_sep>/ADO.NET/pert3/01/delistorelain/delistorelain/WebForm1.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace delistorelain { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //memberid.Text = Convert.ToString(delistorelain._default.global.nilaiid + 1); //cobab cara lain string b = "select top 1 memberID from ms_member order by memberId desc "; SqlConnection a = new SqlConnection(delistorelain._default.global.stringkoneksi()); SqlCommand tes = new SqlCommand(b, a); a.Open(); SqlDataReader bc=tes.ExecuteReader(); bc.Read(); int da = bc.GetInt32(0)+1; memberid.Text = Convert.ToString(da); a.Close(); } protected void Button1_Click(object sender, EventArgs e) { string nama = TextBox1.Text; string id = memberid.Text; string email1 = TextBox2.Text; string lahir = Calendar1.SelectedDate.ToShortDateString(); string word = TextBox4.Text; string jln = TextBox5.Text; string kota1 = TextBox6.Text; string prov = TextBox7.Text; string gara = TextBox8.Text; string pos = TextBox9.Text; string tlp = TextBox10.Text; SqlConnection konek = new SqlConnection(delistorelain._default.global.stringkoneksi()); string query="begin transaction insert into ms_member(memberID,password_,email,tanggal_lahir,nama)"+ "values('"+id+"','"+word+"','"+email1+"','"+lahir+"','"+nama+"');"+ " insert into ms_delivery(memberID,recipient_name,jalan,kota,provinsi,negara,kodepos,telpon)" + "values('"+id+"','"+nama+"','"+jln+"','"+kota1+"','"+prov+"','"+gara+"','"+pos+"','"+tlp+"') commit; "; SqlCommand perintah = new SqlCommand(query, konek); try { konek.Open(); perintah.ExecuteNonQuery(); Response.Redirect("default.aspx"); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { konek.Close(); } } protected void usia_TextChanged(object sender, EventArgs e) { int umur = Convert.ToInt32(usia.Text); Calendar1.VisibleDate = DateTime.Now.AddYears(-umur).Date; } } }<file_sep>/dengokowstore/View/Products/ProductView.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class ProductView : System.Web.UI.Page { BusinessCatalog objBC = new BusinessCatalog(); business objB = new business(); BusinessOrder objBO = new BusinessOrder(); int soldItem; int orderedItem; int stockItem; int pID; int memberID; public void refresh() { string path = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect(path); } protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.MemberLoginValidator(); if (logstat) { memberID = Convert.ToInt32(Session["ID"].ToString()); pID = Convert.ToInt32(Request.QueryString["productID"]); if (pID != 0) { DataTable dp = objBC.GetProduct(pID); DataTable dc = objBC.CommentList(pID); string productName = dp.Rows[0]["productName"].ToString(); Name.Text = productName; string dtl = dp.Rows[0]["details"].ToString(); details.Text = dtl; string prc = dp.Rows[0]["price"].ToString(); Harga.Text = prc; string sld = dp.Rows[0]["numbersold"].ToString(); sold.Text = sld; string qty = dp.Rows[0]["quantity"].ToString(); soldItem = Convert.ToInt32(sld); stockItem = Convert.ToInt32(qty); int total = stockItem - soldItem - orderedItem; quantity.Text = total.ToString(); string upload = dp.Rows[0]["uploadDate"].ToString(); uploadDate.Text = upload; string update = dp.Rows[0]["updateDate"].ToString(); lastUpdate.Text = update; string star = "Rating: " + dp.Rows[0]["rating"].ToString() + "/5"; Rating.Text = star; string imgPath = dp.Rows[0]["picturePath"].ToString(); productImage.ImageUrl = imgPath; commentRepeater.DataSource = dc; commentRepeater.DataBind(); } else { Response.Redirect("../StoreView.aspx"); } } else { Response.Redirect("../Member/Login.aspx"); } } protected void checkOut_Click(object sender, EventArgs e) { int qty = Convert.ToInt32(edt_qty.Text); long prc = Convert.ToInt64(Harga.Text); long total = qty * prc; int chkInvoice = objBO.checkOut(memberID, pID, qty, total); Response.Redirect("~/View/Products/checkOutPage.aspx?invoiceID=" + chkInvoice.ToString()); } protected void cartbtn_Click(object sender, EventArgs e) { int qty = Convert.ToInt32(edt_qty.Text); long prc = Convert.ToInt64(Harga.Text); long total = qty * prc; objBO.placeCart(memberID, pID, qty, total); Response.Redirect("~/View/Products/StoreView.aspx"); } }<file_sep>/dengokowstore/View/Admin/AdminOrder.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class View_Admin_AdminOrder : System.Web.UI.Page { public void refresh() { string path = "AdminOrder.aspx"; Response.Redirect(path); } BusinessCatalog objBC = new BusinessCatalog(); business objB = new business(); protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.AdminLoginValidator(); if (logstat) { int edit = Convert.ToInt32(Request.QueryString["edit"]); int del = Convert.ToInt32(Request.QueryString["delete"]); if (edit == 1) { int id = Convert.ToInt32(Request.QueryString["id"]); string stat = Request.QueryString["stat"]; string payment = Request.QueryString["payment"]; long bayar = Convert.ToInt64(Request.QueryString["bayar"]); string resi = Request.QueryString["resi"]; objBC.UpdateInvoice(id, payment, stat, bayar, resi); refresh(); } else if (del == 1) { int id = Convert.ToInt32(Request.QueryString["id"]); objBC.deleteInvoice(id); refresh(); } else { DataTable dt = objBC.InvoiceList(); GV_Invoices.DataSource = dt; GV_Invoices.DataBind(); } } else { Response.Redirect("~/View/Member/Login.aspx"); } } }<file_sep>/ADO.NET/pert3/01/delistore/delistore/default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace delistore { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string stringkoneksi = "Integrated Security=SSPI;"+"Persist Security Info=False;"+ "User ID=kurakura;"+"Initial Catalog=delistore;"+"Data Source=GIRI-PC\\SQLEXPRESS"; string perintahstring = "select ms_member.memberID,ms_member.nama,ms_member.email,ms_member.tanggal_lahir,ms_delivery.kota,ms_delivery.telpon from ms_member join ms_delivery on ms_member.memberID=ms_delivery.memberID order by ms_member.memberID desc"; SqlConnection koneksi = new SqlConnection(stringkoneksi); SqlCommand perintah = new SqlCommand(perintahstring, koneksi); try { koneksi.Open(); SqlDataReader baca = perintah.ExecuteReader(); Response.Write("<h2>Data Member Delistore</h2>"); Response.Write("<table border=1><tr><th>" + "memberID" + "</th><th>" + "nama" + "</th>" + "<th>email</th>" + "<th>tanggal lahir</th>" + "<th>kota</th>" + "<th>telpon</th></tr>"); while (baca.Read()) { string memberID = baca.GetInt32(0).ToString(); string nama = baca.GetString(1); string email = baca.GetString(2); string tanggal_lahir = baca.GetDateTime(3).ToShortDateString(); string kota = baca.GetString(4); string telpon = baca.GetInt64(5).ToString(); Response.Write("<tr><td>" + memberID + "</td><td>" + nama + "</td><td>" + email + "</td><td>" + tanggal_lahir + "</td><td>" + kota + "</td><td>" + telpon + "</td></tr>"); } Response.Write("</table>"); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } } }<file_sep>/n-tier/pert1/a/n-tier/bisnislayer/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using DataLayer; using System.Data; namespace bisnislayer { public class clsbisnislayer { clsdatalayer obj1 = new clsdatalayer(); public DataTable loadsiswa() { DataSet ds = obj1.loadisisiswa(); DataTable dt = ds.Tables[0]; // boleh juga ds.tables["siswa"]; return dt; } } } <file_sep>/dengokowstore/View/Member/ChangePass.aspx.cs using BussinessLayer; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ChangePass : System.Web.UI.Page { business objB = new business(); protected void Page_Load(object sender, EventArgs e) { } protected void SubmitChange_Click(object sender, EventArgs e) { string userName = userid.Text; string userPass = pass.Text; string inputEmail = e_mail.Text; DataTable dt = objB.getUserData(userName); if (dt.Rows.Count > 0) { string email = dt.Rows[0]["email"].ToString(); if (inputEmail != email) { ChangeFail.Text = "E-mail salah"; } else { int ID = Int32.Parse(dt.Rows[0]["userID"].ToString()); if (dt.Rows[0]["userPass"].ToString() != userPass) { int debuger = objB.updPassMember(ID, userPass); if (debuger > 0) { ChangeSucess.Text = "Password Berhasil Diganti"; Redirect.Text = "Menuju Halaman Utama Dalam 3 detik"; userid.ReadOnly = true; userid.Enabled = false; pass.ReadOnly = true; pass.Enabled = false; repass.ReadOnly = true; repass.Enabled = false; e_mail.ReadOnly = true; e_mail.Enabled = false; SubmitChange.Visible = false; Response.AppendHeader("Refresh", "3;url=../../Default.aspx"); } else { ChangeFail.Text = "Password Gagal Diganti"; } } else { ChangeFail.Text = "Password Baru harus berbeda"; } } } else { ChangeFail.Text = "User Tidak Terdaftar"; } } }<file_sep>/ADO.NET/pert2/WebSite1/WebSite1/insert.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class insert : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string stringkoneksi = "Integrated Security=SSPI;" + "Persist Security Info=False;" + "Initial Catalog=ada;" + "Data Source=(local)"; string perintahstring = "insert into ms_santri values('dini')"; SqlConnection koneksi = new SqlConnection(stringkoneksi); SqlCommand perintah = new SqlCommand(perintahstring, koneksi); try { koneksi.Open(); perintah.ExecuteNonQuery(); Response.Write("insert sukses"); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } }<file_sep>/ADO.NET/PERT-1/WebApplication1/WebApplication1/default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace WebApplication1 { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection konek = new SqlConnection("User ID=kurakura;password=<PASSWORD>;Initial Catalog=ada;Data Source=(local)"); SqlCommand cmd = new SqlCommand("select*from ms_member", konek); cmd.CommandType = CommandType.Text; try { konek.Open(); //Response.Write("koneksi terbuka"); SqlDataReader rd = cmd.ExecuteReader(); //while (rd.Read()) //{ //rd.Read(); //TextBox1.Text = rd.GetString(1).ToString(); //Response.Write(rd.GetString(0) + " - " + rd.GetString(1) + "<br>"); //} Response.Write("<table border = 1>"+"<td>" + rd.GetString(0) + "</td>" while (rd.Read()) { Response.Write( "<table border = 1>"+"<td>" + rd.GetString(0) + "</td>" + "<td>" + rd.GetString(1) + "<td>"+ "</table>"); } } catch (Exception ex) { Response.Write(ex.ToString()); } finally { konek.Close(); //Response.Write("\n koneksi ditutup"); } } } }<file_sep>/ADO.NET/db_ds.sql create table ms_member ( memberID int primary key not null identity(1401,1), password nvarchar(250) not null , email nvarchar(250), tanggal_lahir datetime, status_aktif nvarchar(50), online_status nvarchar (100) ) create table ms_deliverydetail ( deliveryID int primary key not null identity(1,1), memberID int not null references ms_member(memberID), street nvarchar(250) not null , city nvarchar(250) not null, state nvarchar(250) not null, country nvarchar(250) not null, postalcode int not null, RecipientName nvarchar(250) not null, digunakan nvarchar(250) ) create table ms_staff ( staffID int primary key not null identity(1201,1), password nvarchar(250) ) create table ms_deliveryorder ( orderID int primary key not null identity(1,1), orderDate datetime not null , deliveryDate datetime not null, deliveryHour datetime not null, deliveryID int not null references ms_deliverydetail(deliveryID), staffID int not null references ms_staff(staffID), memberID int not null references ms_member(memberID), notes nvarchar(250), orderpoint int ) create table ms_produk ( produkID int primary key not null identity(1,1), typeID nvarchar(100) not null, namaproduk nvarchar(250) not null, price money ) create table ms_orderdetail ( uid int primary key not null identity(1,1), orderID int not null references ms_deliveryorder(orderID), produkID int not null references ms_produk(produkID), Qty nvarchar(100) ) <file_sep>/dengokowstore/View/Admin/AdminDash.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class View_Admin_AdminDash : System.Web.UI.Page { public void refresh() { string path = "AdminDash.aspx"; Response.Redirect(path); } BusinessCatalog objBC = new BusinessCatalog(); business objB = new business(); public int curpage { get { if (ViewState["curpage"] != null) { return Convert.ToInt32(ViewState["curpage"]); } else { return 0; } } set { ViewState["curpage"] = value; } } protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.AdminLoginValidator(); if (logstat) { int del = Convert.ToInt32(Request.QueryString["delete"]); if (del == 1) { int id = Convert.ToInt32(Request.QueryString["id"]); objBC.deleteProduct(id); } DataTable dc = null; if (Request.QueryString["menu"] == null) { dc = objBC.CatalogList(); } else { int catmenu = Convert.ToInt32(Request.QueryString["menu"]); dc = objBC.CatalogList(catmenu); } int count = dc.Rows.Count; PagedDataSource pageproduct = new PagedDataSource(); pageproduct.DataSource = dc.DefaultView; pageproduct.AllowPaging = true; pageproduct.PageSize = 5; pageproduct.CurrentPageIndex = curpage; int total = count / pageproduct.PageSize; ProductRepeater.DataSource = pageproduct; ProductRepeater.DataBind(); DataTable dt = objBC.CategoryList(); menuRepeater.DataSource = dt; menuRepeater.DataBind(); if (!IsPostBack) { for (int i = 0; i < dt.Rows.Count; i++) { category.DataSource = dt; category.DataTextField = "categoryName"; category.DataValueField = "categoryID"; category.DataBind(); } } } else { Response.Redirect("~/View/Member/Login.aspx"); } } protected void submit(object sender, EventArgs e) { string nama = namaproduk.Text; int ctg = int.Parse(category.SelectedItem.Value); string dtl = details.Text; int qty = int.Parse(quantity.Text); long prc = long.Parse(price.Text); DateTime myDateTime = DateTime.Now; string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff"); if (imageUpload.HasFiles) { string filename = imageUpload.FileName; string dt = DateTime.Now.DayOfYear.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Hour.ToString(); string pathdir = Server.MapPath("~//img//upload//" + dt + nama); string pathfile = Server.MapPath("~//img//upload//" + dt + nama + "//" + filename); string savedpath = "~\\img\\upload\\" + dt + nama + "\\" + filename; if (!Directory.Exists(pathdir)) { Directory.CreateDirectory(pathdir); } imageUpload.PostedFile.SaveAs(pathfile); int stat = objBC.SaveNewProduct(nama, ctg, dtl, qty, prc, savedpath, sqlFormattedDate, sqlFormattedDate); } else { string pathfile = Server.MapPath("~//img//upload//anon.png"); string savedpath = "~\\img\\upload\\anon.png"; int stat = objBC.SaveNewProduct(nama, ctg, dtl, qty, prc, savedpath, sqlFormattedDate, sqlFormattedDate); } Response.Redirect("AdminDash.aspx"); } protected void delete_item(object source, RepeaterCommandEventArgs e) { string id = ""; if (e.CommandName == "delete") { id = e.CommandArgument.ToString(); } } }<file_sep>/n-tier/bhnujian/tescsss1/tescsss1/manage.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using bisnislayer; using System.Data; using System.Data.SqlClient; namespace tescsss1 { public partial class manage : System.Web.UI.Page { bisnislyr obj3 = new bisnislyr(); DataTable dt = new DataTable(); protected void Page_Load(object sender, EventArgs e) { obj3.validadmin(); refreshgrid(); } private void refreshgrid() { GridView1.DataSource = obj3.viewbisnis(); GridView1.DataBind(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id_artikel"].ToString()); obj3.delete(id); refreshgrid(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { Response.Redirect("update.aspx"); } } }<file_sep>/n-tier/SQLQuery2.sql create table siswa ( nis int , nama nvarchar(30), alamat nvarchar(30) ) insert into siswa values(1,'ronaldo','portugal') insert into siswa values(2,'rossi','italia') insert into siswa values(3,'messi','argentina') select*from siswa<file_sep>/n-tier/pert3/sekolah/sekolah/DataLayer/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Configuration; using System.Data; namespace DataLayer { public class datalayer { SqlConnection objcon = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString()); private DataSet ExecuteSql(string sqlcmd) { DataSet ds = new DataSet(); SqlCommand objcmd = new SqlCommand(sqlcmd, objcon); SqlDataAdapter objda = new SqlDataAdapter(objcmd); objcon.Open(); objda.Fill(ds); objcon.Close(); return ds; } public DataSet viewdata() { DataSet ds = new DataSet(); string sql = "select * from siswa"; ds = ExecuteSql(sql); return ds; } public void insertdata(string nama, string alamat) { string insert = "insert into siswa (nama_siswa,alamat) values (@nama,@alamat)"; SqlCommand cmd = new SqlCommand(insert, objcon); cmd.Parameters.AddWithValue("@nama", nama); cmd.Parameters.AddWithValue("@alamat", alamat); objcon.Open(); cmd.ExecuteNonQuery(); objcon.Close(); } public void deletedata(string nis) { string delete = "delete from siswa where nis=@nis"; SqlCommand cmd = new SqlCommand(delete, objcon); cmd.Parameters.AddWithValue("@nis", nis); objcon.Open(); cmd.ExecuteNonQuery(); objcon.Close(); } public void updatedata(string nis, string nama, string alamat) { string update = "update siswa set nama_siswa=@nama, alamat=@alamat where nis=@nis"; SqlCommand cmd = new SqlCommand(update, objcon); cmd.Parameters.AddWithValue("@nis", nis); cmd.Parameters.AddWithValue("@nama", nama); cmd.Parameters.AddWithValue("@alamat", alamat); objcon.Open(); cmd.ExecuteNonQuery(); objcon.Close(); } public DataSet viewdataisi(string nis) { DataSet ds = new DataSet(); string sql = "select * from siswa where nis='" + nis + "'"; ds = ExecuteSql(sql); return ds; } } } <file_sep>/dengokowstore/MasterPage.master.cs using BussinessLayer; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class MasterPage : System.Web.UI.MasterPage { business objB = new business(); public string path; public bool auth; public string userName; protected void Page_Load(object sender, EventArgs e) { //path = HttpContext.Current.Request.ApplicationPath + "View//Products//StoreView.aspx"; //Response.Write(path); if (objB.MemberLoginValidator()) { auth = true; userName = Session["Member"].ToString(); } else if (objB.AdminLoginValidator()) { auth = true; userName = Session["Admin"].ToString(); } else { auth = false; } } } <file_sep>/dengokowstore/View/Products/ItemDetails.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class ItemDetails : System.Web.UI.Page { BusinessCatalog objBC = new BusinessCatalog(); business objB = new business(); int soldItem; int orderedItem; int stockItem; public void refresh() { string path = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect(path); } protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.AdminLoginValidator(); if (logstat) { int pID = Convert.ToInt32(Request.QueryString["productID"]); if (pID != 0) { DataTable dp = objBC.GetProduct(pID); DataTable dc = objBC.CommentList(pID); string productName = dp.Rows[0]["productName"].ToString(); Name.Text = productName; string dtl = dp.Rows[0]["details"].ToString(); details.Text = dtl; string prc = dp.Rows[0]["price"].ToString(); price.Text = prc; string ord = dp.Rows[0]["numberOrdered"].ToString(); ordered.Text = ord; string sld = dp.Rows[0]["numbersold"].ToString(); sold.Text = sld; string qty = dp.Rows[0]["quantity"].ToString(); soldItem = Convert.ToInt32(sld); orderedItem = Convert.ToInt32(ord); stockItem = Convert.ToInt32(qty); int total = stockItem - soldItem - orderedItem; quantity.Text = total.ToString(); string upload = dp.Rows[0]["uploadDate"].ToString(); uploadDate.Text = upload; string update = dp.Rows[0]["updateDate"].ToString(); lastUpdate.Text = update; string star = "Rating: " + dp.Rows[0]["rating"].ToString() + "/5"; Rating.Text = star; string imgPath = dp.Rows[0]["picturePath"].ToString(); productImage.ImageUrl = imgPath; commentRepeater.DataSource = dc; commentRepeater.DataBind(); } else { Response.Redirect("../Admin/AdminDash.aspx"); } } else { Response.Redirect("../Member/Login.aspx"); } } protected void editbtn_Click(object sender, EventArgs e) { bool st = editName.Visible; if (!st) { Name.Visible = false; editName.Visible = true; editName.Text = Name.Text; details.Visible = false; editDetails.Visible = true; editDetails.Text = details.Text; editQty.Visible = true; editQty.Text = quantity.Text; editPrice.Visible = true; editPrice.Text = price.Text; submitbtn.Visible = true; } else { Name.Visible = true; editName.Visible = false; details.Visible = true; editDetails.Visible = false; editQty.Visible = false; editPrice.Visible = false; submitbtn.Visible = false; } } protected void submitbtn_Click(object sender, EventArgs e) { int d_productID = Convert.ToInt32(Request.QueryString["productID"]); string d_productName = editName.Text; string d_details = editDetails.Text; int d_quantity = Convert.ToInt32(editQty.Text); d_quantity = (d_quantity + soldItem + orderedItem); int d_price = Convert.ToInt32(editPrice.Text); DateTime myDateTime = DateTime.Now; string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff"); objBC.UpdateProduct(d_productID, d_productName, d_details, d_quantity, d_price, sqlFormattedDate); refresh(); } }<file_sep>/dengokowstore/View/Member/Registration.aspx.cs using BussinessLayer; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Registration : System.Web.UI.Page { business objB = new business(); protected void Page_Load(object sender, EventArgs e) { if (objB.MemberLoginValidator()) { Response.Redirect("Bio.aspx"); } else if (objB.AdminLoginValidator()) { Response.Redirect("AdminDash.aspx"); } } protected void SubmitRegistration_Click(object sender, EventArgs e) { string userName = userid.Text; string userPass = <PASSWORD>.Text; string email = e_mail.Text; int debuger = objB.SaveUserMember(userName,userPass,email); if (debuger > 0) { LoginSucess.Text = "Registrasi berhasil"; userid.ReadOnly = true; userid.Enabled = false; pass.ReadOnly = true; pass.Enabled = false; repass.ReadOnly = true; repass.Enabled = false; e_mail.ReadOnly = true; e_mail.Enabled = false; SubmitRegistration.Visible = false; } else if (debuger < 0) { LoginFail.Text = "Akun sudah terdaftar"; } else { LoginFail.Text = "Registrasi gagal"; } } protected void LoginRedirect_Click(object sender, EventArgs e) { Response.Redirect("Login.aspx"); } }<file_sep>/ADO.NET/pert5/gridview/gridview/pakedataset.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace gridview { public partial class pakedataset : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GridView1.Visible =false; } protected void Buttonmember_Click(object sender, EventArgs e) { string ad = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ad1;Data Source=R3B-03\\SQLEXPRESS"; SqlConnection koneksi = new SqlConnection(ad); SqlCommand cmd = new SqlCommand("select*from ms_member", koneksi); SqlCommand cmd1 = new SqlCommand("select*from ms_delivery", koneksi); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); try { koneksi.Open(); da.SelectCommand = cmd; da.Fill(ds, "ms_membercopy"); da.SelectCommand = cmd1; da.Fill(ds, "ms_deliverycopy"); da.Dispose(); GridView1.DataSource = ds.Tables["ms_membercopy"]; GridView1.DataBind(); GridView1.Visible = true; } catch (Exception salah) { Response.Write(salah.ToString()); } } protected void Buttondeliver_Click(object sender, EventArgs e) { string ad = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ad1;Data Source=R3B-03\\SQLEXPRESS"; SqlConnection koneksi = new SqlConnection(ad); SqlCommand cmd = new SqlCommand("select*from ms_member", koneksi); SqlCommand cmd1 = new SqlCommand("select*from ms_delivery", koneksi); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); try { koneksi.Open(); da.SelectCommand = cmd; da.Fill(ds, "ms_membercopy"); da.SelectCommand = cmd1; da.Fill(ds, "ms_deliverycopy"); da.Dispose(); GridView1.DataSource = ds.Tables["ms_deliverycopy"]; GridView1.DataBind(); GridView1.Visible = true; } catch (Exception salah) { Response.Write(salah.ToString()); } } } }<file_sep>/n-tier/ujian/rentaldvdujiann_tier/rentaldvdujiann_tier/default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using bisnislayer; namespace rentaldvdujiann_tier { public partial class _default : System.Web.UI.Page { bisnislyr obj2 = new bisnislyr(); protected void Page_Load(object sender, EventArgs e) { } private void refresh() { nama.Text =""; alamat.Text=""; kate.Text=""; judul.Text=""; harga.Text=""; } protected void Button2_Click(object sender, EventArgs e) { string nm = nama.Text; string alm = alamat.Text; string kat = kate.Text; string jud = judul.Text; string har = harga.Text; string a = jud.Substring(0, 3); string b = jud.Substring(jud.Length-3, 3); string order = a + b; int ca = obj2.save(order, nm, alm, kat, jud, har); if (ca > 0) { refresh(); err.Text = "data berhasil disimpan"; err.ForeColor = System.Drawing.Color.Red; } else { err.Text = "data gagal disimpan"; err.ForeColor = System.Drawing.Color.Red; } } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("menu.aspx"); } } }<file_sep>/n-tier/pert3/sekolah/sekolah/BusinessLayer/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using DataLayer; using System.Data; namespace BusinessLayer { public class businesslayer { datalayer objdl = new datalayer(); public DataTable viewdatab() { DataSet ds = new DataSet(); DataTable dt = new DataTable(); ds = objdl.viewdata(); dt = ds.Tables[0]; return dt; } public void insertdatab(string nama, string alamat) { objdl.insertdata(nama, alamat); } public void deletedatab(string nis) { objdl.deletedata(nis); } public void updatedatab(string nis, string nama, string alamat) { objdl.updatedata(nis, nama, alamat); } public DataTable viewdataisib(string nis) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); ds = objdl.viewdataisi(nis); dt = ds.Tables[0]; return dt; } } } <file_sep>/n-tier/pet2/Projects/2pert2/bisnislayer/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using datalayer; using System.Data; using System.Data.SqlClient; namespace bisnislayer { public class layerbisnis { datalayersiswa obj1 = new datalayersiswa(); public DataTable loadsiswa() { DataSet ds = obj1.perquery(); DataTable dt = ds.Tables[0]; return dt; } public SqlDataReader siswaisibisinis() { SqlDataReader dr; dr = obj1.siswaisi(); return dr; } public DataTable loaddropdown(string nama) { DataSet ds = obj1.dropdownload(nama); DataTable dt = ds.Tables[0]; return dt; } public SqlDataReader ddnisb(string nis) { SqlDataReader dr; dr = obj1.ddnis(nis); return dr; } } } <file_sep>/dengokowstore/View/Products/checkOutPage.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; public partial class View_Products_checkOutPage : System.Web.UI.Page { BusinessOrder objBO = new BusinessOrder(); business objB = new business(); BusinessCatalog objBC = new BusinessCatalog(); bool logstat; int memberID; int invoiceID; protected void Page_Load(object sender, EventArgs e) { logstat = objB.MemberLoginValidator(); invoiceID = Convert.ToInt32(Request.QueryString["invoiceID"]); if (!logstat || (invoiceID == 0)) { Response.Redirect("~/Default.aspx"); } else { memberID = Convert.ToInt32(Session["ID"].ToString()); DataTable dt = objBO.GetCartItem(invoiceID, memberID); DataTable dt2 = objBO.getInvoice(invoiceID); int pLen = dt.Rows.Count; string TotalBill = dt2.Rows[0]["totalBill"].ToString(); harga.Text = TotalBill; GV_Cart.DataSource = dt; GV_Cart.DataBind(); } } protected void Bayar_Click(object sender, EventArgs e) { string paymentMethod = ddlPayment.SelectedItem.Text; string orderMsg = msgOrder.Text; string ship = ddlShipping.SelectedItem.Text; objBO.UpdateInvoiceDetails(invoiceID, paymentMethod, orderMsg, ship); Response.Redirect("~/View/Member/Order.aspx"); } }<file_sep>/n-tier/ujian/SQLQuery2.sql create table ms_peminjam ( id_log int primary key not null identity(1,1), order_id nvarchar(150) not null, nama_customer nvarchar(250) not null, alamat_customer nvarchar(250) not null, kategori_buku nvarchar(250) not null, judul_buku nvarchar(250) not null, harga_perhari money not null ) create trigger rental on ms_peminjam <file_sep>/dengokowstore/View/Member/Login.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; public partial class Login : System.Web.UI.Page { business objB = new business(); protected void Page_Load(object sender, EventArgs e) { if (objB.MemberLoginValidator()) { Response.Redirect("Dashboard.aspx"); } else if (objB.AdminLoginValidator()) { Response.Redirect("/View/Admin/AdminDash.aspx"); } } protected void SubmitLogin_Click(object sender, EventArgs e) { string inputName = userid.Text; string inputPass = pass.Text; DataTable dt = objB.getUserData(inputName); if (dt.Rows.Count > 0) { string userID = dt.Rows[0]["userID"].ToString(); string userPass = dt.Rows[0]["userPass"].ToString(); if (inputPass == userPass) { if (!bool.Parse(dt.Rows[0]["loginStat"].ToString())) { DataTable dtAdmin = objB.getAdminData(Int32.Parse(userID)); if (dtAdmin.Rows.Count > 0) { objB.LoginStat(Int32.Parse(userID)); Session["Admin"] = dtAdmin.Rows[0]["Position"].ToString(); Session["ID"] = dtAdmin.Rows[0]["adminID"].ToString(); Session["Logout"] = userID; Response.Redirect("/View/Admin/AdminDash.aspx"); } else { DataTable dtMember = objB.getMemberData(Int32.Parse(userID)); if (dtMember.Rows.Count > 0) { objB.LoginStat(Int32.Parse(userID)); Session["Member"] = dtMember.Rows[0]["Nama"].ToString(); Session["ID"] = dtMember.Rows[0]["memberID"].ToString(); Session["Logout"] = userID; Response.Redirect("Dashboard.aspx"); } else { LoginFailed.Text = "Login Gagal"; } } } else { LoginFailed.Text = "Ak<NAME> Digunakan"; AlterLogout.Visible = true; } } else { LoginFailed.Text = "Login Gagal"; } } else { LoginFailed.Text = "Login Gagal"; } } protected void AlterLogout_Click(object sender, EventArgs e) { Response.Redirect("tryLogOut.aspx"); } }<file_sep>/dengokowstore/View/Member/Order.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class Order : System.Web.UI.Page { BusinessOrder objBO = new BusinessOrder(); business objB = new business(); BusinessCatalog objBC = new BusinessCatalog(); int memberID; int userID; int count; public void refresh() { string path = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect(path); } protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.MemberLoginValidator(); if (!logstat) { Response.Redirect("~/View/Member/Login.aspx"); } else { if (IsPostBack) { String ButtonID = Request["__EVENTTARGET"]; if (ButtonID.Contains("submitrate")) { int numVisible = 0; foreach (GridViewRow row in GV_Purchased.Rows) { if (row.Visible == true) { numVisible += 1; } } if (numVisible > 1) { mp1.Show(); } else { } } } memberID = Convert.ToInt32(Session["ID"].ToString()); userID = Convert.ToInt32(Session["Logout"].ToString()); DataTable dt = objBC.InvoiceListMember(memberID); GV_Orders.DataSource = dt; GV_Orders.DataBind(); count = 0; } } protected void deletebtn_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); string[] args = btn.CommandArgument.ToString().Split(new char[] { ',' }); int invoiceID = Convert.ToInt32(args[0]); string invoiceStat = args[1]; if ((invoiceStat == "Dipesan") || (invoiceStat == "Tunggu Bayar")) { objBO.DeleteInvoice(invoiceID, memberID); refresh(); } } protected void payconfirm_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); string[] args = btn.CommandArgument.ToString().Split(new char[] { ',' }); int invoiceID = Convert.ToInt32(args[0]); string invoiceStat = args[1]; if (invoiceStat == "Tunggu Bayar") { objBO.InvoiceUpdatePaymentDone(invoiceID); refresh(); } } protected void accepted_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); string[] args = btn.CommandArgument.ToString().Split(new char[] { ',' }); int invoiceID = Convert.ToInt32(args[0]); string invoiceStat = args[1]; if (invoiceStat == "Sudah Kirim") { objBO.InvoiceUpdateTransDone(invoiceID, memberID); DataTable dt = objBO.GetCartItem(invoiceID, memberID); int nlength = dt.Rows.Count; GV_Purchased.DataSource = dt; GV_Purchased.DataBind(); Panl1.Height = 100 + nlength * 100; mp1.Show(); } } protected void complete_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); string[] args = btn.CommandArgument.ToString().Split(new char[] { ',' }); int invoiceID = Convert.ToInt32(args[0]); string invoiceStat = args[1]; if (invoiceStat == "Dipesan") { Response.Redirect("~/View/Products/checkOutPage.aspx?invoiceID=" + invoiceID.ToString()); } } protected void GV_Purchased_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton lnkPostType = (LinkButton)e.Row.FindControl("submitrate"); lnkPostType.CommandArgument = count.ToString(); count++; } } protected void submitrate_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); int RowIndex = int.Parse(btn.CommandArgument.ToString().Trim()); DropDownList ddlNew = (DropDownList)GV_Purchased.Rows[RowIndex].FindControl("ddlStar"); Label prodID = (Label)GV_Purchased.Rows[RowIndex].FindControl("pID"); TextBox cmnt = (TextBox)GV_Purchased.Rows[RowIndex].FindControl("TextBox1"); int productID = Convert.ToInt32(prodID.Text); decimal rate = Convert.ToDecimal(ddlNew.SelectedValue); string comment = cmnt.Text; objBO.insertComment(userID, productID, comment, rate); GV_Purchased.Rows[RowIndex].Visible = false; Panl1.Height = Convert.ToInt32(Panl1.Height.Value) - 100; } }<file_sep>/n-tier/ujian1/rentaldvdujiann_tier/bisnislayer/bisnislyr.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using datalayer; using System.Data; namespace bisnislayer { public class bisnislyr { datalyr obj1 = new datalyr(); public int save(string order, string nama, string alamat, string kate, string judul, string harga) { int a= obj1.simpan(order, nama, alamat, kate, judul, harga); return a; } public DataTable view() { DataSet ds = new DataSet(); ds = obj1.perintah(); DataTable dt = new DataTable(); dt = ds.Tables["copytabel"]; return dt; } public void delete(int id) { obj1.hapus(id); } public DataTable selekviewbisnis(int log) { DataSet ds = new DataSet(); ds = obj1.selek(log); DataTable dt = new DataTable(); dt = ds.Tables["copytabel"]; return dt; } } } <file_sep>/ADO.NET/pert2/WebSite1/WebSite1/Default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string stringkoneksi="Integrated Security=SSPI;"+"Persist Security Info=False;"+ "Initial Catalog=ada;"+ "Data Source=(local)" ; string perintahstring = "select*from ms_santri" ; SqlConnection koneksi = new SqlConnection(stringkoneksi); SqlCommand perintah = new SqlCommand(perintahstring, koneksi); try { koneksi.Open(); SqlDataReader baca = perintah.ExecuteReader(); Response.Write("<table border=1><tr><th>"+"id santri"+"</th><th>"+"nama"+"</th></tr>"); while (baca.Read()) { string a = baca.GetInt32(0).ToString(); Response.Write("<tr><td>" + a + "</td>><td>" + baca.GetString(1) + "</td></tr>"); } Response.Write("</table>"); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } }<file_sep>/dengokowstore/View/Admin/AdminHistory.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class View_Admin_AdminHistory : System.Web.UI.Page { BusinessCatalog objBC = new BusinessCatalog(); business objB = new business(); protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.AdminLoginValidator(); if (logstat) { DataTable dt = objBC.DoneList(); GV_Invoices.DataSource = dt; GV_Invoices.DataBind(); } else { Response.Redirect("~/View/Member/Login.aspx"); } } }<file_sep>/dengokowstore/View/Member/Dashboard.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; public partial class Dashboard : System.Web.UI.Page { BusinessOrder objBO = new BusinessOrder(); business objB = new business(); BusinessCatalog objBC = new BusinessCatalog(); bool logstat; int memberID; int invoiceID; //int[] qtylist; //int[] pIDlist; public void refresh() { string path = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect(path); } protected void Page_Load(object sender, EventArgs e) { logstat = objB.MemberLoginValidator(); if (!logstat) { Response.Redirect("~/View/Member/Login.aspx"); } else { memberID = Convert.ToInt32(Session["ID"].ToString()); invoiceID = objBO.GetInvoiceID(memberID); if (invoiceID >= 0) { DataTable dt = objBO.GetCartItem(invoiceID, memberID); DataTable dt2 = objBO.getInvoice(invoiceID); int pLen = dt.Rows.Count; //qtylist = (from row in dt.AsEnumerable() select row.Field<int>("quantity")).ToArray(); //pIDlist = (from row in dt.AsEnumerable() select row.Field<int>("productID")).ToArray(); if (pLen > 0) { string TotalBill = dt2.Rows[0]["totalBill"].ToString(); harga.Text = TotalBill; GV_Cart.DataSource = dt; GV_Cart.DataBind(); } else { emptymsg.Text = "Keranjang Belanja Kosong"; LabelHarga.Text = ""; harga.Text = ""; checkOut.Visible = false; GV_Cart.Visible = false; } } else { emptymsg.Text = "Keranjang Belanja Kosong"; LabelHarga.Text = ""; harga.Text = ""; checkOut.Visible = false; GV_Cart.Visible = false; } } } protected void edtbtn_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); string[] args = btn.CommandArgument.ToString().Split(new char[] { ',' }); int pID = Convert.ToInt32(args[0]); int nqty = Convert.ToInt32(args[1]); DataTable dp = objBC.GetProduct(pID); ProductID.Text = pID.ToString(); string picPath = dp.Rows[0]["picturePath"].ToString(); Image1.ImageUrl = picPath; string productName = dp.Rows[0]["productName"].ToString(); namaProduk.Text = productName; string price = dp.Rows[0]["price"].ToString(); hargaProduk.Text = price; quantity.Text = nqty.ToString(); OldQuantity.Text = nqty.ToString(); string ord = dp.Rows[0]["numberOrdered"].ToString(); string sld = dp.Rows[0]["numbersold"].ToString(); string qty = dp.Rows[0]["quantity"].ToString(); int soldItem = Convert.ToInt32(sld); int orderedItem = Convert.ToInt32(ord); int stockItem = Convert.ToInt32(qty); int total = stockItem - soldItem - orderedItem; maxQty.Text = "/ " + total.ToString(); mp1.Show(); } protected void checkOut_Click(object sender, EventArgs e) { objBO.checkOut(invoiceID); Response.Redirect("~/View/Products/checkOutPage.aspx?invoiceID=" + invoiceID.ToString()); } protected void toCart_Click(object sender, EventArgs e) { int pID = Convert.ToInt32(ProductID.Text); int newqty = Convert.ToInt32(quantity.Text); int oldqty = Convert.ToInt32(OldQuantity.Text); int difqty = newqty - oldqty; long prc = Convert.ToInt64(hargaProduk.Text); long total = newqty * prc; objBO.updateCart(invoiceID, pID, memberID, newqty, difqty, total); refresh(); } protected void deletebtn_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); string[] args = btn.CommandArgument.ToString().Split(new char[] { ',' }); int pID = Convert.ToInt32(args[0]); long price = Convert.ToInt64(args[1]); int qty = Convert.ToInt32(args[2]); objBO.deleteCartItem(memberID, invoiceID, pID, price,qty); refresh(); } }<file_sep>/ADO.NET/pert4/datatabledimemory/datatabledimemory/default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace datatabledimemory { public partial class _default : System.Web.UI.Page { DataTable tabelproduk = new DataTable(); DataColumn[] pk = new DataColumn[1]; protected void Page_Load(object sender, EventArgs e) { tabelproduk.Columns.Add("IDproduk", Type.GetType("System.Int32")); tabelproduk.Columns.Add("namaproduk", Type.GetType("System.String")); tabelproduk.Columns.Add("harga", Type.GetType("System.Int32")); pk[0] = tabelproduk.Columns["IDproduk"]; tabelproduk.PrimaryKey = pk; tabelproduk.Columns["IDproduk"].AutoIncrement = true; tabelproduk.Columns["IDproduk"].AutoIncrementSeed = 1; tabelproduk.Columns["IDproduk"].ReadOnly = true; } protected void Button1_Click(object sender, EventArgs e) { string nilai = Convert.ToString(harga); DataRow baris = tabelproduk.NewRow(); baris["IDproduk"] = 1; baris["namaproduk"] = nama.Text; baris["harga"] = harga.Text; Response.Redirect("formhasil.aspx?id=" + baris["IDproduk"] + "&nama=" + baris["namaproduk"] + "&harga=" + baris["harga"]); } } }<file_sep>/n-tier/pert1/a/tesguru/datalayerguru/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace datalayerguru { public class datalayergr { SqlConnection koneksi = new SqlConnection(ConfigurationManager.ConnectionStrings["koneksi"].ToString()); private DataSet sqllayerguru(string sqlcmd) { DataSet ds = new DataSet(); koneksi.Open(); SqlCommand cmd = new SqlCommand(sqlcmd, koneksi); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds,"copysiswa"); koneksi.Close(); return ds; } public DataSet tampilguru() { DataSet ds = new DataSet(); string selektabel="select *from guru"; ds = sqllayerguru(selektabel); return ds; } } } <file_sep>/n-tier/ujian1/rentaldvdujiann_tier/rentaldvdujiann_tier/menu.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using bisnislayer; namespace rentaldvdujiann_tier { public partial class menu : System.Web.UI.Page { bisnislyr obj2 = new bisnislyr(); protected void Page_Load(object sender, EventArgs e) { refreshgrid(); } protected void refreshgrid() { GridView1.DataSource = obj2.view(); GridView1.DataBind(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id_log"].ToString()); obj2.delete(id); refreshgrid(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { int id = Convert.ToInt16(GridView1.DataKeys[e.NewEditIndex].Values["id_log"].ToString()); Response.Redirect("update.aspx?num="+id); } } }<file_sep>/ADO.NET/ujian/ado.netujian/ado.netujian/halamanlogin.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace ado.netujian { public partial class halamanutama : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void login_Click(object sender, EventArgs e) { string a = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=db_cd;Data Source=(local)"; SqlConnection konek = new SqlConnection(a); string perintah = "select*from db_member where user_name=@username and password_=<PASSWORD>"; string updtper = "update db_member set status_online=1 where user_name=@username and password_=<PASSWORD> "; string status = "select status_online from db_member where user_name=@username and password_=@password"; SqlCommand cmd = new SqlCommand(perintah, konek); SqlCommand updt = new SqlCommand(updtper, konek); SqlCommand stat = new SqlCommand(status, konek); cmd.Parameters.AddWithValue("@username", user.Text); cmd.Parameters.AddWithValue("@password", pass.Text); updt.Parameters.AddWithValue("@username", user.Text); updt.Parameters.AddWithValue("@password", pass.Text); stat.Parameters.AddWithValue("@username", user.Text); stat.Parameters.AddWithValue("@password", pass.Text); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); konek.Open(); updt.ExecuteNonQuery(); da.Dispose(); konek.Close(); if (dt.Rows.Count > 0) { Session["user"] = user.Text; Session["status"] = "login"; Response.Redirect("ceklogin.aspx"); } else { Label1.Text = "username/password yang anda masukan salah"; Label1.ForeColor = System.Drawing.Color.Red; } } } }<file_sep>/n-tier/bhnujian/tescsss1/tescsss1/halamanadmin.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using bisnislayer; namespace tescsss1 { public partial class halamanadmin : System.Web.UI.Page { bisnislyr obj3 = new bisnislyr(); protected void Page_Load(object sender, EventArgs e) { if (Session["login"] == null && Session["user"] == null) { Response.Redirect("ceklogin.aspx"); } else { bisa.InnerHtml = "<h4>selamat datang admin " + Session["user"] + " silahkan manage artikel nya" + "</h4>"; } } } }<file_sep>/README.md # ASP My Code Collection <file_sep>/ADO.NET/pert3/WebApplication1/WebApplication1/WebForm1.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string nama =TextBox1.Text; string email1 = TextBox2.Text; string lahir = TextBox3.Text; string word = TextBox4.Text; string jln = TextBox5.Text; string kota1 = TextBox6.Text; string prov = TextBox7.Text; string gara = TextBox8.Text; string pos = TextBox9.Text; string tlp = TextBox10.Text; string stringkoneksi = "Integrated Security=SSPI;" + "Persist Security Info=False;" + "Initial Catalog=delistore;" + "Data Source=(local)"; string member = "begin transaction insert into ms_member(password_,email,tanggal_lahir,nama)"+ "values('"+word+"','"+email1+"','"+lahir+"','"+nama+"');"+ "insert into ms_delivery(recipient_name,jalan,kota,provinsi,kodepos,telpon)" + "values('"+nama+"','"+jln+"','"+kota1+"','"+prov+"','"+pos+"',"+ tlp +")"+"commit;"; SqlConnection koneksi = new SqlConnection(stringkoneksi); SqlCommand perintah1 = new SqlCommand(member, koneksi); try { koneksi.Open(); perintah1.ExecuteNonQuery(); Response.Write("sukses"); //Response.Redirect("default.aspx"); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } } }<file_sep>/ADO.NET/DeliStore2/MemberRegistration.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Globalization; namespace DeliStore { public partial class MemberRegistration : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int MemberIDBaru = Global.idMemberTerakhir + 1; txtMemberID.Text = MemberIDBaru.ToString(); Calendar1.Visible = false; } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { txtDoB.Text = Calendar1.SelectedDate.ToShortDateString(); } protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e) { Calendar1.Visible = true; } protected void btnCal_Click(object sender, ImageClickEventArgs e) { if (Calendar1.Visible) { Calendar1.Visible = false; } else { Calendar1.Visible = true; } } protected void btnSubmit_Click(object sender, EventArgs e) { string memberID = txtMemberID.Text; string name = txtName.Text; string password = <PASSWORD>; string email = txtEmail.Text; DateTime dob = Convert.ToDateTime(txtDoB.Text); string DoB = dob.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); string street = txtStreet.Text; string city = txtCity.Text; string province = txtProvince.Text; string country = txtCountry.Text; int postalCode = Convert.ToInt32(txtPostalcode.Text); Int64 phone = Convert.ToInt64(TxtPhone.Text); string simpanDataMember = "BEGIN TRANSACTION " + "INSERT INTO MsMember(MemberID,Password,Email,DateOfBirth,Name,ActiveStatus,OnlineStatus)" + "VALUES(" + memberID + ",'" + password + "','" + email + "','" + DoB + "','" + name + "',1,1)" + "INSERT INTO MsDelivery(MemberID,RecipientName,Street,City,"+ "StateProvince,Country,PostalCode,Phone,DefaultStatus)" + "VALUES(" + memberID + ",'" + name + "','" + street + "','" + city + "','" + province + "','" + country + "'," + postalCode + "," + phone + ",1)" + "COMMIT"; SqlConnection koneksi = new SqlConnection(Global.jalurKoneksi); SqlCommand simpanData = new SqlCommand(simpanDataMember, koneksi); try { koneksi.Open(); simpanData.ExecuteNonQuery(); Response.Redirect("Member.aspx"); } catch (Exception eror) { Response.Write(eror.ToString()); //Response.Write("Maaf, telah terjadi kesalahan"); } finally { koneksi.Close(); } } } }<file_sep>/n-tier/bhnujian/tescsss1/datalayer/datalyr.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.Web; namespace datalayer { public class datalyr { SqlConnection koneksi = new SqlConnection(ConfigurationManager.ConnectionStrings["konek"].ToString()); public DataSet loginlayer(string usr,string pass) { DataSet ds = new DataSet(); string cmd = "select* from ms_admin where username=@user and password=@<PASSWORD>"; SqlCommand cmd1 = new SqlCommand(cmd, koneksi); cmd1.Parameters.AddWithValue("@user", usr); cmd1.Parameters.AddWithValue("@pass", pass); SqlDataAdapter da = new SqlDataAdapter(cmd1); koneksi.Open(); da.Fill(ds, "tabelcopy"); koneksi.Close(); return ds; } public void sesivalidnologin() { var currentsesi = HttpContext.Current.Session; var user = currentsesi["user"]; var log = currentsesi["login"]; if (user != null && log != null) { HttpContext.Current.Response.Redirect("ceklogin.aspx"); } } public void sesivaliddiadmin() { var currentsesi = HttpContext.Current.Session; var user = currentsesi["user"]; var log = currentsesi["login"]; if (user == null && log == null) { HttpContext.Current.Response.Redirect("ceklogin.aspx"); } } public int tambahdata(string jud, string des, string art, string gam) { string query = "insert into ms_artikel(judul,deskripsi,artikel,gambar)values(" + "@judul,@deskripsi,@artikel,@gambar)"; SqlCommand cmd = new SqlCommand(query, koneksi); cmd.Parameters.AddWithValue("@judul", jud); cmd.Parameters.AddWithValue("@deskripsi", des); cmd.Parameters.AddWithValue("@artikel", art); cmd.Parameters.AddWithValue("@gambar", gam); koneksi.Open(); int a = cmd.ExecuteNonQuery(); koneksi.Close(); return a; } private DataSet viewlayer(string cmd) { DataSet ds = new DataSet(); SqlCommand cmd1= new SqlCommand(cmd,koneksi); SqlDataAdapter da = new SqlDataAdapter(cmd1); koneksi.Open(); da.Fill(ds,"copynama"); koneksi.Close(); return ds; } public DataSet queryselek() { DataSet ds = new DataSet(); string query = "select * from ms_artikel"; ds = viewlayer(query); return ds; } public void hapus(int id) { string query = "delete from ms_artikel where id_artikel=@id"; SqlCommand cmd = new SqlCommand(query, koneksi); cmd.Parameters.AddWithValue("@id", id); koneksi.Open(); int b = cmd.ExecuteNonQuery(); koneksi.Close(); } public void updatedata(string judul, string deskrip, string art,string gam) { string update = "update ms_artikel set judul=@jd,deskripsi=@des,artikel=@art,gambar=@gam id_artikel=@id"; SqlCommand cmd = new SqlCommand(update,koneksi); cmd.Parameters.AddWithValue("@jd", judul); cmd.Parameters.AddWithValue("@des", deskrip); cmd.Parameters.AddWithValue("@art", art); cmd.Parameters.AddWithValue("@gam", gam); koneksi.Open(); int b =cmd.ExecuteNonQuery(); koneksi.Close(); } } } <file_sep>/dengokowstore/View/Member/tryLogOut.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BussinessLayer; using System.Data; public partial class View_Member_tryLogOut : System.Web.UI.Page { business objB = new business(); protected void Page_Load(object sender, EventArgs e) { } protected void SubmitLogout_Click(object sender, EventArgs e) { string inputName = userid.Text; string inputPass = pass.Text; DataTable dt = objB.getUserData(inputName); if (dt.Rows.Count > 0) { string userID = dt.Rows[0]["userID"].ToString(); string userPass = dt.Rows[0]["userPass"].ToString(); if (inputPass == userPass) { if (bool.Parse(dt.Rows[0]["loginStat"].ToString())) { objB.LogoutStat(Int32.Parse(userID)); Response.Redirect("/View/Member/Login.aspx"); } Response.Redirect("/View/Member/Login.aspx"); } else { LogoutFailed.Text = "Logout Gagal"; } } else { LogoutFailed.Text = "Logout Gagal"; } } }<file_sep>/ADO.NET/PERT-1/tes1/tes1/Default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace tes1 { public class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection konek = new SqlConnection("User ID=kurakura;password=<PASSWORD>;Initial Catalog=ada;Data Source=(local)"); SqlCommand cmd = new SqlCommand("select*from ms_member",konek); cmd.CommandType = CommandType.Text; try { konek.Open(); Response.Write("koneksi terbuka"); SqlDataReader rd = cmd.ExecuteReader(); while (rd.Read()) { Response.Write(rd.GetString(0)+" - "+rd.GetString(1)+"<br>"); } } catch (Exception ex) { Response.Write(ex.ToString()); } finally { konek.Close(); Response.Write("\n koneksi ditutup"); } } } } <file_sep>/ADO.NET/ujian/ado.netujian/ado.netujian/logout.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace ado.netujian { public partial class logout : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string a = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=db_cd;Data Source=(local)"; SqlConnection konek = new SqlConnection(a); string updtper = "update db_member set status_online=0 where user_name="+ Session["user"]+";"; SqlCommand updt = new SqlCommand(updtper, konek); SqlDataAdapter da = new SqlDataAdapter(updt); DataTable dt = new DataTable(); da.Fill(dt); konek.Open(); updt.ExecuteNonQuery(); da.Dispose(); konek.Close(); Session.RemoveAll(); Response.Redirect("halamanlogin.aspx"); } } }<file_sep>/n-tier/bhnujian/tescsss1/tescsss1/tambah.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using bisnislayer; namespace tescsss1 { public partial class tambah : System.Web.UI.Page { bisnislyr obj3 = new bisnislyr(); protected void Page_Load(object sender, EventArgs e) { obj3.validadmin(); } private void cleardata() { judulbox.Text = ""; TextArea1.Value = ""; arti.Text = ""; gam.Text = ""; } protected void Button1_Click(object sender, EventArgs e) { string jud = judulbox.Text; string des = TextArea1.Value.ToString(); string art = arti.Text; string gamb = gam.Text; int c= obj3.insertdata(jud,des,art,gamb); if (c> 0) { cleardata(); notif.Text = "arikel berhasil ditambahkan"; notif.ForeColor = System.Drawing.Color.Red; } else { cleardata(); notif.Text = "arikel gagal ditambahkan"; } } } }<file_sep>/dengokowstore/View/Products/StoreView.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class View_Products_StoreView : System.Web.UI.Page { public bool logstat = false; public void refresh() { string path = "StoreView.aspx"; Response.Redirect(path); } BusinessCatalog objBC = new BusinessCatalog(); business objB = new business(); BusinessOrder objBO = new BusinessOrder(); int memberID ; public int curpage { get { if (ViewState["curpage"] != null) { return Convert.ToInt32(ViewState["curpage"]); } else { return 0; } } set { ViewState["curpage"] = value; } } protected void Page_Load(object sender, EventArgs e) { logstat = objB.MemberLoginValidator(); if (logstat) { memberID = Convert.ToInt32(Session["ID"].ToString()); } DataTable dc = null; if (Request.QueryString["menu"] == null) { dc = objBC.CatalogList(); } else { int catmenu = Convert.ToInt32(Request.QueryString["menu"]); dc = objBC.CatalogList(catmenu); } int count = dc.Rows.Count; PagedDataSource pageproduct = new PagedDataSource(); pageproduct.DataSource = dc.DefaultView; pageproduct.AllowPaging = true; pageproduct.PageSize = 5; pageproduct.CurrentPageIndex = curpage; int total = count / pageproduct.PageSize; ProductRepeater.DataSource = pageproduct; ProductRepeater.DataBind(); DataTable dt = objBC.CategoryList(); menuRepeater.DataSource = dt; menuRepeater.DataBind(); } protected void LinkButton1_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)(sender); int pID = Convert.ToInt32(btn.CommandArgument); DataTable dp = objBC.GetProduct(pID); ProductID.Text = pID.ToString(); string picPath = dp.Rows[0]["picturePath"].ToString(); Image1.ImageUrl = picPath; string productName = dp.Rows[0]["productName"].ToString(); namaProduk.Text = productName; string price = dp.Rows[0]["price"].ToString(); hargaProduk.Text = price; quantity.Text = "1"; string ord = dp.Rows[0]["numberOrdered"].ToString(); string sld = dp.Rows[0]["numbersold"].ToString(); string qty = dp.Rows[0]["quantity"].ToString(); int soldItem = Convert.ToInt32(sld); int orderedItem = Convert.ToInt32(ord); int stockItem = Convert.ToInt32(qty); int total = stockItem - soldItem - orderedItem; maxQty.Text = "/ "+total.ToString(); mp1.Show(); } protected void LinkButton2_Click(object sender, EventArgs e) { Response.Redirect("~/View/Member/Login.aspx"); } protected void checkOut_Click(object sender, EventArgs e) { int pID = Convert.ToInt32(ProductID.Text); int qty = Convert.ToInt32(quantity.Text); long prc = Convert.ToInt64(hargaProduk.Text); long total = qty*prc; int chkInvoice = objBO.checkOut(memberID, pID, qty, total); Response.Redirect("~/View/Products/checkOutPage.aspx?invoiceID=" + chkInvoice.ToString()); } protected void toCart_Click(object sender, EventArgs e) { int pID = Convert.ToInt32(ProductID.Text); int qty = Convert.ToInt32(quantity.Text); long prc = Convert.ToInt64(hargaProduk.Text); long total = qty * prc; objBO.placeCart(memberID, pID, qty, total); refresh(); } }<file_sep>/ADO.NET/delistore/delistore/WebForm1.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace delistore { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string nama =TextBox1.Text; string email1 = TextBox2.Text; string lahir = TextBox3.Text; string word = TextBox4.Text; string jln = TextBox5.Text; string kota1 = TextBox6.Text; string prov = TextBox7.Text; string gara = TextBox8.Text; string pos = TextBox9.Text; string tlp = TextBox10.Text; string stringkoneksi = "Integrated Security=SSPI;" + "Persist Security Info=False;" + "User ID=kurakura;" + "Initial Catalog=delistore;" + "Data Source=GIRI-PC\\SQLEXPRESS"; string member = "insert into ms_member(password_,email,tanggal_lahir,nama)"+ "values("+word+email1+lahir+nama+")"; string deliver = "insert into ms_delivery(recipient_name,jalan,kota,provinsi,kodepos,telpon)" + "values(" + nama + jln + kota1 + prov + pos + tlp + ")"; SqlConnection koneksi = new SqlConnection(stringkoneksi); SqlCommand perintah1 = new SqlCommand(member, koneksi); SqlCommand perintah2 = new SqlCommand(deliver, koneksi); try { koneksi.Open(); perintah1.ExecuteNonQuery(); perintah2.ExecuteNonQuery(); Response.Redirect("default.aspx"); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } } }<file_sep>/n-tier/pet2/Projects/2pert2/datalayer/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Data.SqlClient; using System.Data; namespace datalayer { public class datalayersiswa { SqlConnection koneksi = new SqlConnection(ConfigurationManager.ConnectionStrings["konek"].ToString()); private DataSet sqlcmd(string cmd) { DataSet ds = new DataSet(); koneksi.Open(); SqlCommand per = new SqlCommand(cmd, koneksi); SqlDataAdapter da = new SqlDataAdapter(per); da.Fill(ds); koneksi.Close(); return ds; } public DataSet perquery() { DataSet ds = new DataSet(); string cmd1 = "select*from siswa"; ds = sqlcmd(cmd1); return ds; } public SqlDataReader siswaisi() { SqlDataReader dr; string query1 = "select*from siswa"; SqlCommand cmd2 = new SqlCommand(query1, koneksi); if (koneksi.State == ConnectionState.Closed) { koneksi.Open(); } dr = cmd2.ExecuteReader(); return dr; } public DataSet dropdownload(string nama) { DataSet ds = new DataSet(); string sql = "select*from siswa where nama='" + nama+"'"; ds = sqlcmd(sql); return ds; } public SqlDataReader ddnis(string nis) { SqlDataReader dr; string query = "select*from siswa where nis=" + nis; SqlCommand cmd = new SqlCommand(query, koneksi); koneksi.Open(); dr = cmd.ExecuteReader(); return dr; } } } <file_sep>/n-tier/ujian/rentaldvdujiann_tier/rentaldvdujiann_tier/update.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using bisnislayer; using System.Data; namespace rentaldvdujiann_tier { public partial class update : System.Web.UI.Page { bisnislyr obj2 = new bisnislyr(); protected void Page_Load(object sender, EventArgs e) { int nma = Convert.ToInt32(Request.QueryString["nama"]); obj2.selekviewbisnis(nma); DataTable dt = new DataTable(); dt = obj2.selekviewbisnis(nma); nama.Text = dt.Rows[0]["nama_customer"].ToString(); alamat.Text = dt.Rows[0]["alamat_customer"].ToString(); kate.Text = dt.Rows[0]["kategori_buku"].ToString(); judul.Text = dt.Rows[0]["judul_buku"].ToString(); harga.Text = dt.Rows[0]["harga_perhari"].ToString(); } } }<file_sep>/ADO.NET/pert7/WebApplication1/WebApplication1/gp.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace WebApplication1 { public partial class gp : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string a = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=tes;Data Source=(local)"; SqlConnection ad = new SqlConnection(a); string cmd = "select*from produk"; SqlCommand lah = new SqlCommand(cmd, ad); try { ad.Open(); SqlDataReader dr = lah.ExecuteReader(); GridView1.DataSource = dr; GridView1.DataBind(); } catch(Exception salah) { Response.Write(salah.ToString()); } finally { ad.Close(); } } protected void Button1_Click(object sender, EventArgs e) { string nama = "data yang dipilih:<br />"; string data = ""; foreach (GridViewRow baris in this.GridView1.Rows) { //CheckBox ab = (CheckBox)baris.FindControl("CheckBox1"); CheckBox chkRow = (baris.Cells[0].FindControl("CheckBox1") as CheckBox); if (chkRow.Checked) { //nama = nama + baris.Cells[2].Text + "<br />"; string storid = baris.Cells[1].Text; string storname = baris.Cells[2].Text; data = data + storid + " , " + storname + " , " + "<br>"; } else { Label1.Text = "data tidak ada yg di check"; } } Label1.Text = data; Label2.Text = GridView1.Rows[0].Cells[2].Text; } } }<file_sep>/n-tier/bhnujian/tescsss1/bisnislayer/bisnislyr.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using datalayer; using System.Data; namespace bisnislayer { public class bisnislyr { datalyr obj1 = new datalyr(); public DataTable bisnislogin(string user ,string pass) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); ds = obj1.loginlayer(user, pass); dt = ds.Tables["tabelcopy"]; return dt; } public void panggillogin() { obj1.sesivalidnologin(); } public void validadmin() { obj1.sesivaliddiadmin(); } public int insertdata(string jud, string des, string art, string gam) { int b= obj1.tambahdata(jud, des, art, gam); return b; } public DataTable viewbisnis() { DataSet ds = new DataSet(); DataTable dt = new DataTable(); ds = obj1.queryselek(); dt = ds.Tables["copynama"]; return dt; } public void delete(int id) { obj1.hapus(id); } public void update() } } <file_sep>/ADO.NET/ujian/ado.netujian/ado.netujian/halamanmusic.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace ado.netujian { public partial class halamanutama1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string a = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=db_cd;Data Source=(local)"; SqlConnection konek = new SqlConnection(a); string perintah = "select*from detail_lagu"; SqlCommand cmd = new SqlCommand(perintah, konek); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); try { konek.Open(); da.SelectCommand = cmd; da.Fill(ds,"ms_cdcopy"); da.Dispose(); cmd.Dispose(); konek.Dispose(); Repeater1.DataSource = ds.Tables["ms_cdcopy"]; Repeater1.DataBind(); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { konek.Close(); } } } }<file_sep>/n-tier/pert1/a/n-tier/DataLayer/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Configuration; using System.Data; namespace DataLayer { public class clsdatalayer { SqlConnection koneksi = new SqlConnection(ConfigurationManager.ConnectionStrings["konek"].ToString()); // ini pake web config private DataSet perintahsql(string sqlcmd) { DataSet ds = new DataSet(); koneksi.Open(); SqlCommand cmd1 = new SqlCommand(sqlcmd, koneksi); SqlDataAdapter da = new SqlDataAdapter(cmd1); da.Fill(ds); koneksi.Close(); return ds; } public DataSet loadisisiswa() { DataSet ds = new DataSet(); string tampiltabel = "select *from siswa"; ds = perintahsql(tampiltabel); return ds; } } } <file_sep>/n-tier/bhnujian/tescsss1/tescsss1/home.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using bisnislayer; using System.Data; namespace tescsss1 { public partial class home : System.Web.UI.Page { bisnislyr obj2 = new bisnislyr(); DataTable dt = new DataTable(); protected void Page_Load(object sender, EventArgs e) { obj2.panggillogin(); } void clearbox() { TextBox1.Text = ""; TextBox2.Text = ""; } protected void Button1_Click(object sender, EventArgs e) { string user = TextBox1.Text; string pass = TextBox2.Text; dt = obj2.bisnislogin(user, pass); if(dt.Rows.Count > 0) { Session["user"] = TextBox1.Text; Session["login"] = "login"; Response.Redirect("ceklogin.aspx"); } else { Labeler.Text = "username/password yang anda masukan salah"; Labeler.ForeColor = System.Drawing.Color.Red; clearbox(); } } } }<file_sep>/ADO.NET/ujian/ado.netujian/ado.netujian/member.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace ado.netujian { public partial class member : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string judul = TextBox1.Text; string penyanyi =TextBox2.Text; string negara = TextBox3.Text; string harga = TextBox4.Text; string tanggal = Calendar1.SelectedDate.ToShortDateString(); string a = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=db_cd;Data Source=(local)"; SqlConnection konek = new SqlConnection(a); string insert = "insert into detail_lagu values('" + judul + "','" + penyanyi + "','" + negara + "','" + harga + "','" + tanggal + "');"; SqlCommand perintah = new SqlCommand(insert, konek); try { konek.Open(); perintah.ExecuteNonQuery(); Response.Redirect("member.aspx"); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { konek.Close(); } } protected void Button2_Click(object sender, EventArgs e) { Response.Write("member.aspx"); } } }<file_sep>/ADO.NET/DeliStore2/Member.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace DeliStore { public static class Global { static int _idMemberTerakhir=0; static string _jalurKoneksi="Integrated Security=SSPI;"+ "Persist Security Info=False;Initial Catalog=DeliStore;Data Source=ALFI-NB-W10\\MSSQL2014"; public static int idMemberTerakhir { get { return _idMemberTerakhir; } set { _idMemberTerakhir = value; } } public static string jalurKoneksi { get { return _jalurKoneksi; } } } public partial class Member : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string ambilDataMember = "SELECT MsMember.MemberID AS IDMember, Name, Email, "+ "CONVERT(VARCHAR(12),DateOfBirth,106), Street, StateProvince, Country, Phone " + "FROM MsMember INNER JOIN MsDelivery " + "ON MsMember.MemberID = MsDelivery.MemberID"; SqlConnection koneksi = new SqlConnection(Global.jalurKoneksi); SqlCommand perintahBaca = new SqlCommand(ambilDataMember,koneksi); try { koneksi.Open(); SqlDataReader bacaData = perintahBaca.ExecuteReader(); Response.Write("<div><table border=1><tr><th>Member ID</th><th>Name</th><th>Email</th>"+ "<th>Date of Birth</th><th>Address</th><th>Phone Number</th></tr>"); while (bacaData.Read()) { Response.Write("<tr><td>" + bacaData.GetInt32(0) + "</td><td>" + bacaData.GetString(1) + "</td><td>" + bacaData.GetString(2) + "</td><td>" + bacaData.GetString(3) + "</td><td>" + bacaData.GetString(4) + ", " + bacaData.GetString(5) + ", " + bacaData.GetString(6) + "</td><td>" + bacaData.GetInt64(7) + "</td></tr>"); Global.idMemberTerakhir = bacaData.GetInt32(0); } Response.Write("</table></div>"); Response.Write("<div><a href='MemberRegistration.aspx'>Registration</a></div>"); } catch (Exception eror) { Response.Write(eror.ToString()); //Response.Write("Maaf, telah terjadi kesalahan"); } finally { koneksi.Close(); } } } }<file_sep>/n-tier/ujian1/rentaldvdujiann_tier/datalayer/datalyr.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Configuration; using System.Data; namespace datalayer { public class datalyr { SqlConnection koneksi = new SqlConnection(ConfigurationManager.ConnectionStrings["konek"].ToString()); private DataSet isi(string cmd) { DataSet ds = new DataSet(); SqlCommand query = new SqlCommand(cmd, koneksi); SqlDataAdapter da = new SqlDataAdapter(query); koneksi.Open(); da.Fill(ds,"copytabel"); koneksi.Close(); return ds; } public DataSet perintah() { DataSet ds = new DataSet(); string query = "select*from ms_peminjam"; ds = isi(query); return ds; } public DataSet selek(int id) { DataSet ds = new DataSet(); string query = "select*from ms_peminjam where id_log="+id; ds = isi(query); return ds; } public int simpan(string order,string nama, string alamat, string kate, string judul, string harga) { string query = "insert into ms_peminjam(order_id,nama_customer,alamat_customer,kategori_buku,"+ "judul_buku,harga_perhari)values(@order,@nama,@alamat,@kate,@judul,@harga)"; SqlCommand cmd = new SqlCommand(query, koneksi); cmd.Parameters.AddWithValue("@order",order); cmd.Parameters.AddWithValue("@nama",nama); cmd.Parameters.AddWithValue("@alamat",alamat); cmd.Parameters.AddWithValue("@kate",kate); cmd.Parameters.AddWithValue("@judul",judul); cmd.Parameters.AddWithValue("@harga",harga); koneksi.Open(); int b= cmd.ExecuteNonQuery(); koneksi.Close(); return b; } public void hapus(int id) { string query = "delete from ms_peminjam where id_log=@id"; SqlCommand cmd = new SqlCommand(query, koneksi); cmd.Parameters.AddWithValue("@id", id); koneksi.Open(); int b = cmd.ExecuteNonQuery(); koneksi.Close(); } public void updatedata(string order, string nama, string alamat, string kate, string judul, string harga) { string update = "update ms_peminjam set order_id=@order,nama_customer=@nama,alamat_customer=@almt,"+ "kategori_buku=@kat,judul_buku=@jud,harga_perhari=@har where id_log=@id"; SqlCommand cmd = new SqlCommand(update, koneksi); cmd.Parameters.AddWithValue("@jd", judul); koneksi.Open(); int b = cmd.ExecuteNonQuery(); koneksi.Close(); } public void selekedit(int id) { string query = "select*from ms_peminjam where id_log=@id"; SqlCommand cmd = new SqlCommand(query, koneksi); cmd.Parameters.AddWithValue("@id", id); koneksi.Open(); int b = cmd.ExecuteNonQuery(); koneksi.Close(); } } } <file_sep>/ADO.NET/ujian/ado.netujian/ado.netujian/ceklogin.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ado.netujian { public partial class ceklogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["status"] == null) { Label1.Text = "anda belum login!!!"; } else { Response.Redirect("member.aspx"); } } } }<file_sep>/n-tier/pert1/a/tesguru/bisnislayerguru/Class1.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using datalayerguru; using System.Data; namespace bisnislayerguru { public class bisnisguru { datalayergr obj1 = new datalayergr(); public DataTable loaddata() { DataSet ds = obj1.tampilguru(); DataTable dt = ds.Tables["copysiswa"]; return dt; } } } <file_sep>/dengokowstore/SQLQuery1.sql create table users ( userID int primary key not null identity(1,1), userName nvarchar(250) not null UNIQUE, userPass nvarchar(250) not null, email nvarchar(250) not null, loginStat bit not null, ) create table members ( memberID int primary key not null identity(1,1), userID int references users (userID) not null, Nama nvarchar(250), Adresss nvarchar(250), City nvarchar(250), Province nvarchar(250), Postcode int, Contact bigint, Photo_path nvarchar(250), ) create table admins ( adminID int primary key not null identity(1,1), userID int references users (userID) not null, Position nvarchar(20), ) insert into users(userName,userPass,email,loginStat) values('dengokowcoffeeid','dnwk13','<EMAIL>') insert into admins(userID, Position) select users.userID, 'SuperAdmin' from users where userName = 'dengokowcoffeeid' insert into users(userName,userPass,email,loginStat) values('lmnzr','azureknight','<EMAIL>') insert into members(userID, Nama) select users.userID, '<NAME>' from users where userName = 'lmnzr' drop table olshop.admins create table category ( categoryID int primary key not null identity(1,1), categoryName nvarchar(100) not null UNIQUE, ) truncate table category insert into category(categoryName) values('Green Bean'); insert into category(categoryName) values('Roast Bean'); insert into category(categoryName) values('Cold Brew'); insert into category(categoryName) values('Manual Brewing'); insert into category(categoryName) values('Mesin Espresso'); insert into category(categoryName) values('Grinder'); insert into category(categoryName) values('Merchandise'); create table products ( productID int primary key not null identity(1,1), productName nvarchar(100) not null, category int references category (categoryID) not null, details nvarchar(250) not null, quantity int not null, price bigint not null, picturePath nvarchar(400), numberOrdered int, numberSold int, rating float, ) create table products ( productID int primary key not null identity(1,1), productName nvarchar(100) not null, category int references category (categoryID) not null, details nvarchar(250) not null, quantity int not null, price bigint not null, picturePath nvarchar(400), numberOrdered int, numberSold int, rating float, uploadDate datetime, updateDate datetime, ) create table comments ( commentsID int primary key not null identity(1,1), userID int references users (userID) not null, productID int references products (productID) not null, comments nvarchar(500), postDate datetime, rating float, ) create table invoices ( invoiceID int primary key not null identity(1,1), memberID int references members (memberID) not null, paymentMethod nvarchar(50), totalBill bigint, totalPaid bigint, orderMsg nvarchar(250), postDate datetime not null, updateDate datetime not null, invoiceStat nvarchar(50), shipingMode nvarchar(50), Resi nvarchar(50), ); create table shippings ( shippingID int primary key not null identity(1,1), memberID int references members (memberID) not null, invoiceID int references invoices (invoiceID) not null, Name nvarchar(250) not null, Adresss nvarchar(250) not null, City nvarchar(250) not null, Province nvarchar(250) not null, Postcode int not null, Contact bigint not null, Method nvarchar(50) not null, ShippingPrice bigint not null, postDate datetime not null, shippingStat nvarchar(50), ); create table orders ( ordersID int primary key not null identity(1,1), memberID int references members (memberID) not null, invoiceID int references invoices (invoiceID) not null, productID int references products (productID) not null, quantity int not null, ordersStat nvarchar(50), totalPrice bigint, postDate datetime, ); insert into invoices(memberID,postDate,updateDate,invoiceStat) values(1,GETDATE(),GETDATE(),'Kosong'); insert into orders(memberID,invoiceID,productID,quantity,totalPrice,postDate) values(1,2,1,1,75000,GETDATE()); update invoices set totalBill = 75000, invoiceStat = 'Dikeranjang' where invoiceID = 2; insert into orders(memberID,invoiceID,productID,quantity,totalPrice,postDate) values(1,2,1,1,75000,GETDATE()); update invoices set totalBill = 150000, invoiceStat = 'Dikeranjang' where invoiceID = 2; update invoices set invoiceStat = 'Dipesan' where invoiceID = 2; update invoices set paymentMethod = 'Transfer BCA',orderMsg = 'Dihaluskan', updateDate = GETDATE(), shipingMode = 'yes' where invoiceID = 2; update invoices set invoiceStat = 'Tunggu Bayar' , updateDate = GETDATE() where invoiceID = 2; update invoices set invoiceStat = 'Sudah Bayar', updateDate = GETDATE() where invoiceID = 2; update invoices set invoiceStat = 'Sudah Kirim', updateDate = GETDATE() where invoiceID = 2; update invoices set invoiceStat = 'Sudah Selesai', updateDate = GETDATE() where invoiceID = 2; truncate table orders delete from invoices where invoiceID = 1 SELECT members.Nama, invoices.invoiceID, invoices.invoiceStat, invoices.orderMsg, invoices.paymentMethod, invoices.postDate, invoices.shipingMode, invoices.totalBill, invoices.totalPaid, invoices.updateDate FROM invoices INNER JOIN members ON invoices.memberID = members.memberID WHERE invoices.invoiceStat = 'Dipesan' OR invoices.invoiceStat = 'Tunggu Bayar' OR invoices.invoiceStat = 'Sudah Bayar' OR invoices.invoiceStat = 'Sudah Kirim' OR invoices.invoiceStat = 'Sudah Selesai' Order By invoices.updateDate DESC;<file_sep>/ADO.NET/pert8/WebApplication1/WebApplication1/tes.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class tes : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataClasses1DataContext baru = new DataClasses1DataContext(); var isi = from zero in baru.ms_members select zero.email; var wildcard = from a in baru.ms_members where a.password.Contains("h") select a.email; var dijoin = from produk in baru.ms_members join deliver in baru.ms_deliverydetails on produk.memberID equals deliver.memberID select new { deliver.RecipientName,deliver.memberID, deliver.street,deliver.postalcode}; //var much = from b in baru.ms_members // select new { b.memberID, b.email, b.online_status }; foreach (string i in isi) { Response.Write(i+" <br />"); } Response.Write("hasil dari wild card dimana password yang mengandung 'h' :"); Response.Write("<br>"); foreach (string t in wildcard) { Response.Write(t + "<br>"); } Response.Write("hasil join tabel member dengan deliver <br>"); GridView1.DataSource = dijoin; GridView1.DataBind(); string ba = ""; Response.Write("hasil di grid view"); foreach (GridViewRow baris in GridView1.Rows) { string sa = baris.Cells[0].Text; string du = baris.Cells[1].Text; string ti = baris.Cells[2].Text; string ga = baris.Cells[3].Text; ba += sa + du + ti + ga + "<br>"; } } } }<file_sep>/ADO.NET/pert5/gridview/gridview/denganchekbox.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace gridview { public partial class denganchekbox : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string ad = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ad1;Data Source=R3B-03\\SQLEXPRESS"; SqlConnection koneksi = new SqlConnection(ad); SqlCommand cmd = new SqlCommand("select*from produk", koneksi); try { koneksi.Open(); SqlDataReader dr = cmd.ExecuteReader(); GridView1.DataSource = dr; GridView1.DataBind(); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } protected void tes_Click(object sender, EventArgs e) { string nama = "pesanan anda adalah:<br />"; foreach (GridViewRow baris in this.GridView1.Rows) { if (((CheckBox)baris.FindControl("CheckBox1")).Checked == true) { nama =nama+ baris.Cells[2].Text + "<br>"; //[2] kolom ke nerapa mulai dari 0 kaya array } } Label1.Text = nama; } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { } } }<file_sep>/dengokowstore/View/Member/History.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using BussinessLayer; using System.Data; using System.IO; public partial class History : System.Web.UI.Page { BusinessCatalog objBC = new BusinessCatalog(); business objB = new business(); int memberID; protected void Page_Load(object sender, EventArgs e) { bool logstat = objB.MemberLoginValidator(); if (!logstat) { Response.Redirect("~/View/Member/Login.aspx"); } else { memberID = Convert.ToInt32(Session["ID"].ToString()); DataTable dt = objBC.DoneListMember(memberID); GV_Invoices.DataSource = dt; GV_Invoices.DataBind(); } } }<file_sep>/n-tier/pet2/2pert/Default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using bisnislayer; using System.Data; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { DataTable dt = new DataTable(); layerbisnis obj2 = new layerbisnis(); protected void Page_Load(object sender, EventArgs e) { dt = obj2.loadsiswa(); GridView1.DataSource = dt; GridView1.DataBind(); TextBox1.Text = dt.Rows[0]["nis"].ToString(); TextBox2.Text = dt.Rows[0]["nama"].ToString(); TextBox3.Text = dt.Rows[0]["alamat"].ToString(); if (!this.IsPostBack) { isilistsiswa(); isilistnis(); } } void isilistsiswa() { DropDownList1.Items.Clear(); SqlDataReader dr; dr = obj2.siswaisibisinis(); while (dr.Read()) { DropDownList1.Items.Add(dr["nama"].ToString()); } dr.Close(); } void isilistnis() { DropDownList2.Items.Clear(); SqlDataReader dr; dr = obj2.siswaisibisinis(); while (dr.Read()) { DropDownList2.Items.Add(dr["nis"].ToString()); } dr.Close(); } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string nama = DropDownList1.SelectedItem.Text; DataTable dt = obj2.loaddropdown(nama); TextBox1.Text = dt.Rows[0]["nis"].ToString(); TextBox2.Text = dt.Rows[0]["nama"].ToString(); TextBox3.Text = dt.Rows[0]["alamat"].ToString(); } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { string nis = DropDownList2.SelectedItem.Text; SqlDataReader dr; dr = obj2.ddnisb(nis); while (dr.Read()) { TextBox1.Text = dr["nis"].ToString(); TextBox2.Text = dr["nama"].ToString(); TextBox3.Text = dr["alamat"].ToString(); } } }<file_sep>/dengokowstore/SQLQuery16.sql create table invoices ( invoiceID int primary key not null identity(1,1), memberID int references members (memberID) not null, paymentMethod nvarchar(50), totalBill bigint, totalPaid bigint, orderMsg nvarchar(250), postDate datetime not null, updateDate datetime not null, invoiceStat nvarchar(50), shipingMode nvarchar(50), Resi nvarchar(50), ); create table shippings ( shippingID int primary key not null identity(1,1), memberID int references members (memberID) not null, invoiceID int references invoices (invoiceID) not null, Name nvarchar(250) not null, Adresss nvarchar(250) not null, City nvarchar(250) not null, Province nvarchar(250) not null, Postcode int not null, Contact bigint not null, Method nvarchar(50) not null, ShippingPrice bigint not null, postDate datetime not null, shippingStat nvarchar(50), ); create table orders ( ordersID int primary key not null identity(1,1), memberID int references members (memberID) not null, invoiceID int references invoices (invoiceID) not null, productID int references products (productID) not null, quantity int not null, ordersStat nvarchar(50), totalPrice bigint, postDate datetime, ); insert into invoices(memberID,postDate,updateDate,invoiceStat) values(1,GETDATE(),GETDATE(),'Kosong'); insert into orders(memberID,invoiceID,productID,quantity,totalPrice,postDate) values(1,3,1,1,75000,GETDATE()); update invoices set totalBill = 75000, invoiceStat = 'Dikeranjang' where invoiceID = 3; insert into orders(memberID,invoiceID,productID,quantity,totalPrice,postDate) values(1,3,1,1,75000,GETDATE()); update invoices set totalBill = 150000, invoiceStat = 'Dikeranjang' where invoiceID = 2; update invoices set invoiceStat = 'Dipesan' where invoiceID = 2; update invoices set paymentMethod = 'Transfer BCA',orderMsg = 'Dihaluskan', updateDate = GETDATE(), shipingMode = 'yes' where invoiceID = 3; update invoices set invoiceStat = 'Tunggu Bayar' , updateDate = GETDATE() where invoiceID = 3; update invoices set invoiceStat = 'Sudah Bayar', updateDate = GETDATE() where invoiceID = 2; update invoices set invoiceStat = 'Sudah Kirim', updateDate = GETDATE() where invoiceID = 2; update invoices set invoiceStat = 'Sudah Selesai', updateDate = GETDATE() where invoiceID = 2; truncate table orders delete from orders where invoiceID = 3; delete from invoices where invoiceID = 3 SELECT members.Nama, invoices.invoiceID, invoices.invoiceStat, invoices.orderMsg, invoices.paymentMethod, invoices.postDate, invoices.shipingMode, invoices.totalBill, invoices.totalPaid, invoices.updateDate, invoices.Resi FROM invoices INNER JOIN members ON invoices.memberID = members.memberID WHERE invoices.invoiceStat = 'Dipesan' OR invoices.invoiceStat = 'Tunggu Bayar' OR invoices.invoiceStat = 'Sudah Bayar' OR invoices.invoiceStat = 'Sudah Kirim' OR invoices.invoiceStat = 'Sudah Selesai' Order By invoices.updateDate DESC; SELECT * FROM members; INNER JOIN users ON members.userID = users.userID WHERE members.userID = 1;<file_sep>/ADO.NET/pert5/gridview/gridview/default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace gridview { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string ad="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ad1;Data Source=R3B-03\\SQLEXPRESS"; SqlConnection koneksi = new SqlConnection(ad); SqlCommand cmd = new SqlCommand("select*from ms_member", koneksi); try { koneksi.Open(); SqlDataReader dr = cmd.ExecuteReader(); gp1.DataSource = dr; gp1.DataBind(); } catch (Exception salah) { Response.Write(salah.ToString()); } finally { koneksi.Close(); } } } }<file_sep>/ADO.NET/ujian/SQLQueryado.sql create table tb_admin ( id_admin int primary key not null identity (1,1), user_name nvarchar (250) not null , password_ nvarchar(250) not null , status_online int ) create table detail_lagu ( id_music int primary key not null identity(1,1), judul nvarchar (250) not null, penyanyi nvarchar(250) not null, harga money, negara nvarchar(250), release datetime ) alter table tb_admin add constraint ad1 unique(user_name) alter table tb_admin add constraint ad2 unique(password_) alter table tb_admin add constraint ad3 default 0 for status_online insert into tb_admin (user_name,password_) values('ada','<PASSWORD>') insert into detail_lagu values('carijodoh','wali',250000,'indonesia','2009-12-08') insert into detail_lagu values('laskar pelangi','nidji',450000,'indonesia','2010-11-23') insert into detail_lagu values('air mata','dewa',650000,'indonesia','2003-11-23') <file_sep>/ADO.NET/pert7/WebApplication1/WebApplication1/formlogin.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace WebApplication1 { public partial class formlogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string a = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=tes;Data Source=(local)"; SqlConnection konek = new SqlConnection(a); string perintah = "select*from identitas where user_nama=@username and password_=@password"; SqlCommand cmd = new SqlCommand(perintah, konek); cmd.Parameters.AddWithValue("@username", TextBox1.Text); cmd.Parameters.AddWithValue("@password", <PASSWORD>.Text); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); konek.Open(); int b = cmd.ExecuteNonQuery(); da.Dispose(); konek.Close(); if (dt.Rows.Count > 0) { Session["user"] = TextBox1.Text; Response.Redirect("home.aspx"); //Session.RemoveAll(); // ds.AcceptsChanges(); // da.Update(ds.Tables[TableName]); untuk mengembalikan data yg di fill } else { Label3.Text = "you're username and/or password is incorrect"; Label3.ForeColor = System.Drawing.Color.Red; } } } }
9ae0e7d8cdbf4c34b6ee6a847988c7238d33da51
[ "Markdown", "C#", "SQL" ]
72
C#
lmnzr/ASP
4a871c94ac15ca0cf79f1a1ace012a488af41f88
ed8dd2443d0b3d1b11f0844bf939fc6fd677bd3d
refs/heads/master
<repo_name>benmaier/django-rkigeonameapi<file_sep>/README.md # RKI-GeonameAPI Django-webapp for easy access to a hierarchical geo-location database. ## License This project is published under the MIT license. It uses the [geoname-data](http://www.geonames.org/) which is licensed under a [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/). ## Install and Deployment Only tested with Python 3.7 and Django 2.2. Make sure you installed the modified version of the [Geoname-DB](https://github.com/benmaier/GeoNames-MySQL-DataImport) beforehand. This app expects an instance of MySQL 8.0. Clone this repository. git clone <EMAIL>:benmaier/django-rkigeonameapi.git Then install with pip pip install ./django-rkigeonameapi ### Project settings Add `rest_framework` and `rkigeonameapi` to your `INSTALLED_APPS` setting like this ```python INSTALLED_APPS = [ ... 'rkigeonameapi', 'rest_framework', ] ``` You can also add some settings for the rest framework. Here are the ones we typically use: ```python REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', # The following is used to avoid time-outs in the browsable API # (since the automatically generated forms will try to load # all geonames in HTML-selects.) 'rkigeonameapi.renderers.BrowsableAPIRendererWithoutForms', ), } ``` Add the urls to your `projects/urls.py` ```python urlpatterns += [ path('rkigeonameapi/', include('rkigeonameapi.urls')), ] ``` In your project, you now need to perform a migration to construct the necessary tables in the database. Please continue reading before actually performing the migration. ### Database Make sure you installed the modified version of the [Geoname-DB](https://github.com/benmaier/GeoNames-MySQL-DataImport) beforehand. This app expects an instance of MySQL 8.0. Your user/database should have the following settings: ```sql CREATE SCHEMA `your_db_name` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; CREATE USER 'your_db_user'@'your_host_name' IDENTIFIED BY '<PASSWORD>'; GRANT ALL PRIVILEGES ON your_db_name.* TO 'your_db_user'@'your_host_name'; GRANT SELECT ON geonames.* TO 'your_db_user'@'your_host_name'; ``` For development, you can just use the host `localhost`. Given these settings, create a mysql-connection file `your/path/to/db.cnf` ```config [client] host = your_host_name port = 3306 user = your_db_user password = <PASSWORD> database = your_db_name default-character-set = utf8mb4 ``` Now, do the necessary migrations. In your **project** directory: python manage.py migrate The necessary tables in your `your_db_name`-database should've been created. This means we can migrate the necessary data from the original `geonames`-database. To this end, navigate back to your local clone of this repository cd /path/to/django-rkigeonameapi And generate the sql migration file `mymigration.sql` with an optional language-code argument. python make_geonamemigration_sql.py your/path/to/db.cnf mymigration.sql -l de Note that this project renames the `name` property of all locations to contain their most common German name by default. If you **don't** want this you should can specify another language using the corresponding ISO-ALPHA2 code. In case you just want to keep the english name, use `-l en` or something nonsensical like `-l XXXXX` (the script automatically uses the English name for any location for which it cannot find a name in the demanded language). Afterwards, migrate your tables with /path/to/your/bin/mysql --defaults-file=your/path/to/db.cnf -v < mymigration.sql ## Logic The Geoname-Database is an open-source dataset containing an exhaustive list of places on earth. The database contains information about a variety of properties and relationships of these places such as alternative names in multiple languages, positional data, and hierarchical relationships (e.g. to which country oder administrative division a place belongs). This project provides a simple interface to this database which allows a user to easily retrieve data and to edit hierarchical relationships. ### Geonames A Geoname is a main geographical entity. It could be a populated place, a country or something else. #### API endpoints Admin: http://localhost:8000/admin/rkigeonameapi/api/geoname/ REST: | Action | Link | Description | | ------ | ---- | ----------- | | list/create | http://localhost:8000/rkigeonameapi/api/geoname/ | Show a JSON list of all Geoname-objects and add an entry | | view/update | http://localhost:8000/rkigeonameapi/api/geoname/INTID | Show a single Geoname-object associated with the primary key as JSON | | search | http://localhost:8000/rkigeonameapi/api/geonamesearch/SEARCHSTRING | Show all Geoname-objects whose `name` and `englishname` contain the `SEARCHSTRING` | | exhaustive search | http://localhost:8000/rkigeonameapi/api/geonameexhaustivesearch/SEARCHSTRING | Show all Geoname-objects whose `alternatenames` or `englishname` start with the `SEARCHSTRING` | | search by feature code | http://localhost:8000/rkigeonameapi/api/geonamesearch/SEARCHSTRING?fcode=ADM1,PCLI | As above, but only show geonames whose feature code is in the list of feature codes provided in the URL | | exhaustive search by feature code| http://localhost:8000/rkigeonameapi/api/geonameexhaustivesearch/SEARCHSTRING?fcode=ADM1,PCLI | See definitions above | A Geoname can always contain multiple children (think of a US state containing cities). Here's how you control those hierarchical relationships Admin: http://localhost:8000/admin/rkigeonameapi/api/hierarchy/ REST: | Action | Link | Description | | ------ | ---- | ----------- | | update | http://localhost:8000/rkigeonameapi/api/geonamechildren/INTID | Show (`GET`) and update (`PATCH`) the children of a single Geoname-object | | view specific | http://localhost:8000/rkigeonameapi/api/geonamefcodechildren/INTID?fcode=ADM1,ADM2 | Show all children of a single Geoname-object that are associated with any of the specified feature codes | ### Feature codes Each Geoname is associated with a feature code. Here are the most relevant ones with explanations Admin: http://localhost:8000/admin/rkigeonameapi/api/featurecode REST: * list/create: http://localhost:8000/rkigeonameapi/api/featurecode * view/update: http://localhost:8000/rkigeonameapi/api/featurecode/STRINGID #### Continents and regions These are objectes that usually contain multiple countries fcode | name | description ----- | ---- | ----------- CONT | continent | continent: Europe, Africa, Asia, North America, South America, Oceania, Antarctica RGN | region | an area distinguished by one or more observable physical or cultural characteristics A region might also contain other places but this won't be of interest in this application. #### Countries These are used as synonyms for countries | fcode | name | ----- | ---- | PCLI | independent political entity | TERR | territory | PCLD | dependent political entity #### Places These are used as synonyms for cities/villages/places that are neither countries nor regions nor administrative sections. | fcode | name | description | ----- | ---- | ----------- | PPLC | capital of a political entity | | | PPL | populated place | a city, town, village, or other agglomeration of buildings where people live and work | PPLA | seat of a first-order administrative division | seat of a first-order administrative division (PPLC takes precedence over PPLA) | PPLX | section of populated place | | #### Administrative divisions These are hierarchically decreasing administrative divisions of a country | fcode | name | description | ----- | ---- | ----------- | ADM1| first-order administrative division | a primary administrative division of a country, such as a state in the United States | ADM2| second-order administrative division | a subdivision of a first-order administrative division | ADM3| third-order administrative division | a subdivision of a second-order administrative division | ADM4| fourth-order administrative division | a subdivision of a third-order administrative division | ADM5| fifth-order administrative division | a subdivision of a fourth-order administrative division ### Regions Custom regions are shortcuts for improved handling/grouping of countries. Admin: http://localhost:8000/admin/rkigeonameapi/api/region/ REST: * list/create: http://localhost:8000/rkigeonameapi/api/region/ * view/update: http://localhost:8000/rkigeonameapi/api/region/STRINGID You may want to alter a region's children countries by using * http://localhost:8000/rkigeonameapi/api/regioncountries/STRINGID ### Countries The database holds specific info about countries. Admin: http://localhost:8000/admin/rkigeonameapi/api/country/ REST: * list/create: http://localhost:8000/rkigeonameapi/api/country/ * view/update: http://localhost:8000/rkigeonameapi/api/country/STRINGID ### Continents The database holds specific info about continents. Admin: http://localhost:8000/admin/rkigeonameapi/api/continent/ REST: * list/create: http://localhost:8000/rkigeonameapi/api/continent/ * view/update: http://localhost:8000/rkigeonameapi/api/continent/STRINGID <file_sep>/README.rst RKI-GeonameAPI ============== Django-webapp for easy access to a hierarchical geo-location database. License ------- This project is published under the MIT license. It uses the `geoname-data <http://www.geonames.org/>`__ which is licensed under a `Creative Commons Attribution 4.0 License <https://creativecommons.org/licenses/by/4.0/>`__. Install and Deployment ---------------------- Only tested with Python 3.7 and Django 2.2. Make sure you installed the modified version of the `Geoname-DB <https://github.com/benmaier/GeoNames-MySQL-DataImport>`__ beforehand. This app expects an instance of MySQL 8.0. Clone this repository. .. code:: bash git clone <EMAIL>:benmaier/django-rkigeonameapi.git Then install with pip .. code:: bash pip install ./django-rkigeonameapi Project settings ~~~~~~~~~~~~~~~~ Add ``rest_framework`` and ``rkigeonameapi`` to your ``INSTALLED_APPS`` setting like this .. code:: python INSTALLED_APPS = [ ... 'rkigeonameapi', 'rest_framework', ] You can also add some settings for the rest framework. Here are the ones we typically use: .. code:: python REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', # The following is used to avoid time-outs in the browsable API # (since the automatically generated forms will try to load # all geonames in HTML-selects.) 'rkigeonameapi.renderers.BrowsableAPIRendererWithoutForms', ), } Add the urls to your ``projects/urls.py`` .. code:: python urlpatterns += [ path('rkigeonameapi/', include('rkigeonameapi.urls')), ] In your project, you now need to perform a migration to construct the necessary tables in the database. Please continue reading before actually performing the migration. Database ~~~~~~~~ Make sure you installed the modified version of the `Geoname-DB <https://github.com/benmaier/GeoNames-MySQL-DataImport>`__ beforehand. This app expects an instance of MySQL 8.0. Your user/database should have the following settings: .. code:: sql CREATE SCHEMA `your_db_name` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; CREATE USER 'your_db_user'@'your_host_name' IDENTIFIED BY '<PASSWORD>'; GRANT ALL PRIVILEGES ON your_db_name.* TO 'your_db_user'@'your_host_name'; GRANT SELECT ON geonames.* TO 'your_db_user'@'your_host_name'; For development, you can just use the host ``localhost``. Given these settings, create a mysql-connection file ``your/path/to/db.cnf`` .. code:: config [client] host = your_host_name port = 3306 user = your_db_user password = <PASSWORD> database = your_db_name default-character-set = utf8mb4 Now, do the necessary migrations. In your **project** directory, do .. code:: bash python manage.py makemigrations python manage.py makemigrations rkigeonameapi python manage.py migrate The necessary tables in your ``your_db_name``-database should've been created. This means we can migrate the necessary data from the original ``geonames``-database. To this end, navigate back to your local clone of this repository .. code:: bash cd /path/to/django-rkigeonameapi And generate the sql migration file ``mymigration.sql`` with an optional language-code argument. .. code:: bash python make_geonamemigration_sql.py your/path/to/db.cnf mymigration.sql -l de Note that this project renames the ``name`` property of all locations to contain their most common German name by default. If you **don't** want this you should can specify another language using the corresponding ISO-ALPHA2 code. In case you just want to keep the english name, use ``-l en`` or something nonsensical like ``-l XXXXX`` (the script automatically uses the English name for any location for which it cannot find a name in the demanded language). Afterwards, migrate your tables with .. code:: bash /path/to/your/bin/mysql --defaults-file=your/path/to/db.cnf -v < mymigration.sql Logic ----- The Geoname-Database is an open-source dataset containing an exhaustive list of places on earth. The database contains information about a variety of properties and relationships of these places such as alternative names in multiple languages, positional data, and hierarchical relationships (e.g. to which country oder administrative division a place belongs). This project provides a simple interface to this database which allows a user to easily retrieve data and to edit hierarchical relationships. Geonames ~~~~~~~~ A Geoname is a main geographical entity. It could be a populated place, a country or something else. API endpoints ^^^^^^^^^^^^^ Admin: http://localhost:8000/admin/geonameapi/geoname/ REST: +-------------------+------------+------------------------------------+ | Action | Link | Description | +===================+============+====================================+ | list/create | http://loc | Show a JSON list of all | | | alhost:800 | Geoname-objects and add an entry | | | 0/geonamea | | | | pi/geoname | | | | / | | +-------------------+------------+------------------------------------+ | view/update | http://loc | Show a single Geoname-object | | | alhost:800 | associated with the primary key as | | | 0/geonamea | JSON | | | pi/geoname | | | | /INTID | | +-------------------+------------+------------------------------------+ | search | http://loc | Show all Geoname-objects whose | | | alhost:800 | ``name`` and ``englishname`` | | | 0/geonamea | contain the ``SEARCHSTRING`` | | | pi/geoname | | | | search/SEA | | | | RCHSTRING | | +-------------------+------------+------------------------------------+ | exhaustive search | http://loc | Show all Geoname-objects whose | | | alhost:800 | ``alternatenames`` or | | | 0/geonamea | ``englishname`` start with the | | | pi/geoname | ``SEARCHSTRING`` | | | exhaustive | | | | search/SEA | | | | RCHSTRING | | +-------------------+------------+------------------------------------+ | search by feature | http://loc | As above, but only show geonames | | code | alhost:800 | whose feature code is in the list | | | 0/geonamea | of feature codes provided in the | | | pi/geoname | URL | | | search/SEA | | | | RCHSTRING? | | | | fcode=ADM1 | | | | ,PCLI | | +-------------------+------------+------------------------------------+ | exhaustive search | http://loc | See definitions above | | by feature code | alhost:800 | | | | 0/geonamea | | | | pi/geoname | | | | exhaustive | | | | search/SEA | | | | RCHSTRING? | | | | fcode=ADM1 | | | | ,PCLI | | +-------------------+------------+------------------------------------+ A Geoname can always contain multiple children (think of a US state containing cities). Here's how you control those hierarchical relationships Admin: http://localhost:8000/admin/geonameapi/hierarchy/ REST: +-------------------+------------+------------------------------------+ | Action | Link | Description | +===================+============+====================================+ | update | http://loc | Show (``GET``) and update | | | alhost:800 | (``PATCH``) the children of a | | | 0/geonamea | single Geoname-object | | | pi/geoname | | | | children/I | | | | NTID | | +-------------------+------------+------------------------------------+ | view specific | http://loc | Show all children of a single | | | alhost:800 | Geoname-object that are associated | | | 0/geonamea | with any of the specified feature | | | pi/geoname | codes | | | fcodechild | | | | ren/INTID? | | | | fcode=ADM1 | | | | ,ADM2 | | +-------------------+------------+------------------------------------+ Feature codes ~~~~~~~~~~~~~ Each Geoname is associated with a feature code. Here are the most relevant ones with explanations Admin: http://localhost:8000/admin/geonameapi/featurecode REST: - list/create: http://localhost:8000/geonameapi/featurecode - view/update: http://localhost:8000/geonameapi/featurecode/STRINGID Continents and regions ^^^^^^^^^^^^^^^^^^^^^^ These are objectes that usually contain multiple countries +-----------------+-------------+--------------------------------------+ | fcode | name | description | +=================+=============+======================================+ | CONT | continent | continent: Europe, Africa, Asia, | | | | North America, South America, | | | | Oceania, Antarctica | +-----------------+-------------+--------------------------------------+ | RGN | region | an area distinguished by one or more | | | | observable physical or cultural | | | | characteristics | +-----------------+-------------+--------------------------------------+ A region might also contain other places but this won't be of interest in this application. Countries ^^^^^^^^^ These are used as synonyms for countries ===== ============================ fcode name ===== ============================ PCLI independent political entity TERR territory PCLD dependent political entity ===== ============================ Places ^^^^^^ These are used as synonyms for cities/villages/places that are neither countries nor regions nor administrative sections. +-----------------+-------------+--------------------------------------+ | fcode | name | description | +=================+=============+======================================+ | PPLC | capital of | | | | a political | | | | entity | | +-----------------+-------------+--------------------------------------+ | PPL | populated | a city, town, village, or other | | | place | agglomeration of buildings where | | | | people live and work | +-----------------+-------------+--------------------------------------+ | PPLA | seat of a | seat of a first-order administrative | | | first-order | division (PPLC takes precedence over | | | administrat | PPLA) | | | ive | | | | division | | +-----------------+-------------+--------------------------------------+ | PPLX | section of | | | | populated | | | | place | | +-----------------+-------------+--------------------------------------+ Administrative divisions ^^^^^^^^^^^^^^^^^^^^^^^^ These are hierarchically decreasing administrative divisions of a country +-----------------+-------------+--------------------------------------+ | fcode | name | description | +=================+=============+======================================+ | ADM1 | first-order | a primary administrative division of | | | administrat | a country, such as a state in the | | | ive | United States | | | division | | +-----------------+-------------+--------------------------------------+ | ADM2 | second-orde | a subdivision of a first-order | | | r | administrative division | | | administrat | | | | ive | | | | division | | +-----------------+-------------+--------------------------------------+ | ADM3 | third-order | a subdivision of a second-order | | | administrat | administrative division | | | ive | | | | division | | +-----------------+-------------+--------------------------------------+ | ADM4 | fourth-orde | a subdivision of a third-order | | | r | administrative division | | | administrat | | | | ive | | | | division | | +-----------------+-------------+--------------------------------------+ | ADM5 | fifth-order | a subdivision of a fourth-order | | | administrat | administrative division | | | ive | | | | division | | +-----------------+-------------+--------------------------------------+ Regions ~~~~~~~ Custom regions are shortcuts for improved handling/grouping of countries. Admin: http://localhost:8000/admin/geonameapi/region/ REST: - list/create: http://localhost:8000/geonameapi/region/ - view/update: http://localhost:8000/geonameapi/region/STRINGID You may want to alter a region's children countries by using - http://localhost:8000/geonameapi/regioncountries/STRINGID .. _countries-1: Countries ~~~~~~~~~ The database holds specific info about countries. Admin: http://localhost:8000/admin/geonameapi/country/ REST: - list/create: http://localhost:8000/geonameapi/country/ - view/update: http://localhost:8000/geonameapi/country/STRINGID Continents ~~~~~~~~~~ The database holds specific info about continents. Admin: http://localhost:8000/admin/geonameapi/continent/ REST: - list/create: http://localhost:8000/geonameapi/continent/ - view/update: http://localhost:8000/geonameapi/continent/STRINGID <file_sep>/make_geonamemigration_sql.py # -*- coding: utf-8 -*- import sys from optparse import OptionParser from configparser import ConfigParser if __name__=="__main__": parser = OptionParser() #parser.add_option("-d", "--db-file", dest="db_file", # help="The database .cnf-file containing the relevant connection information.", metavar="FILE") #parser.add_option("-o", "--migration-file", dest="mig_file", # help="The .sql-file in which to store the migration commands. [default: %default]", metavar="FILE", default=None) parser.add_option("-l", "--language-code", dest="lang", help="Which language to use for the default names of the Geoname objects. [default: %default]", default="de", type=str) (options, args) = parser.parse_args() if (len(args) != 2): print('This command requires two positional arguments: 1) the cnf-file to connect to the database and 2) an output file-name to create the SQL-commands for migration.') sys.exit(1) cnf = ConfigParser() cnf.read(args[0]) with open('./sql/dummy_geonamemigration.sql','r') as f: sql = f.read() sql = sql.replace('your_db_name',cnf['client']['database']) if options.lang == 'en': options.lang = 'XXXXX' sql = sql.replace("isoLanguage = 'de'","isoLanguage = '{}'".format(options.lang.lower())) with open(args[1],'w') as f: f.write(sql) <file_sep>/sql/dummy_geonamemigration.sql -- countryinfo has to be inserted first because geonames references it SET @@local.net_read_timeout = 3600; SET @@local.net_write_timeout = 3600; INSERT IGNORE INTO your_db_name.continentCodes( code, englishname, geonameid ) SELECT code, name, geonameid FROM geonames.continentCodes; -- insert countryinfo data without proper geonameid (update after geoname insert) INSERT IGNORE INTO your_db_name.countryinfo( iso_alpha2 ,iso_alpha3 ,iso_numeric ,fips_code ,englishname ,capital ,areainsqkm ,population ,continent ,tld ,currency ,currencyName ,Phone ,postalCodeFormat ,postalCodeRegex ,geonameId ,languages ,neighbours ,equivalentFipsCode ) SELECT iso_alpha2 ,iso_alpha3 ,iso_numeric ,fips_code ,name ,capital ,areainsqkm ,population ,continent ,tld ,currency ,currencyName ,Phone ,postalCodeFormat ,postalCodeRegex ,geonameId ,languages ,neighbours ,equivalentFipsCode FROM geonames.countryinfo; INSERT IGNORE INTO your_db_name.featureCodes(code, name, description) SELECT code, name, description FROM geonames.featureCodes; INSERT IGNORE INTO your_db_name.featureCodes(code, name, description) VALUES ('GL', 'Global', 'contains every place on earth.'); -- remove the unnecessary class code in the table UPDATE your_db_name.featureCodes SET code = SUBSTR(code,3) WHERE SUBSTR(code,2,1) = '.'; START TRANSACTION; USE `your_db_name`; UPDATE featureCodes SET searchorder_detail = 21 WHERE code = 'GL'; UPDATE featureCodes SET searchorder_detail = 20 WHERE code = 'CONT' ; UPDATE featureCodes SET searchorder_detail = 19 WHERE code = 'RGN' ; UPDATE featureCodes SET searchorder_detail = 18 WHERE code = 'PCLI'; UPDATE featureCodes SET searchorder_detail = 17 WHERE code = 'PPLC'; UPDATE featureCodes SET searchorder_detail = 16.5 WHERE code = 'PPL' ; UPDATE featureCodes SET searchorder_detail = 16 WHERE code = 'PPLA'; UPDATE featureCodes SET searchorder_detail = 14 WHERE code = 'TERR'; UPDATE featureCodes SET searchorder_detail = 13 WHERE code = 'PCLX'; UPDATE featureCodes SET searchorder_detail = 12 WHERE code = 'PCLD'; UPDATE featureCodes SET searchorder_detail = 11 WHERE code = 'ADM1'; UPDATE featureCodes SET searchorder_detail = 10 WHERE code = 'ADM2'; UPDATE featureCodes SET searchorder_detail = 9 WHERE code = 'ADM3'; UPDATE featureCodes SET searchorder_detail = 8 WHERE code = 'ADM4'; UPDATE featureCodes SET searchorder_detail = 7 WHERE code = 'ADM5'; UPDATE featureCodes SET searchorder_detail = 6 WHERE code = 'ADM5'; UPDATE featureCodes SET searchorder_detail = 5 WHERE code = 'PPLX'; COMMIT; -- explicitly name all columns because django orders them in a weird way INSERT IGNORE INTO your_db_name.geoname( geonameid ,englishname ,asciiname ,latitude ,longitude ,fclass ,cc2 ,admin1 ,admin2 ,admin3 ,admin4 ,population ,elevation ,gtopo30 ,timezone ,moddate ,fcode ,country ) SELECT geonameid ,name ,asciiname ,latitude ,longitude ,fclass ,cc2 ,admin1 ,admin2 ,admin3 ,admin4 ,population ,elevation ,gtopo30 ,timezone ,moddate ,fcode ,country FROM geonames.geoname WHERE geonames.geoname.country <> ''; INSERT IGNORE INTO your_db_name.geoname( geonameid ,englishname ,asciiname ,latitude ,longitude ,fclass ,cc2 ,admin1 ,admin2 ,admin3 ,admin4 ,population ,elevation ,gtopo30 ,timezone ,moddate ,fcode ) SELECT geonameid ,name ,asciiname ,latitude ,longitude ,fclass ,cc2 ,admin1 ,admin2 ,admin3 ,admin4 ,population ,elevation ,gtopo30 ,timezone ,moddate ,fcode FROM geonames.geoname WHERE geonames.geoname.country = ''; -- copy alternatename INSERT IGNORE INTO your_db_name.alternatename( alternatenameid ,isolanguage ,alternatename ,ispreferredname ,isshortname ,iscolloquial ,ishistoric ,geonameid ) SELECT alternatenameid ,isolanguage ,alternatename ,ispreferredname ,isshortname ,iscolloquial ,ishistoric ,geonameid FROM geonames.alternatename; -- copy hierachy INSERT IGNORE INTO your_db_name.hierarchy( parentId , childId , is_custom_entry ) SELECT DISTINCT parentId , childId , 0 FROM geonames.hierarchy; -- RENAME DRC INSERT INTO your_db_name.alternatename(alternatenameId) VALUES (11092987) ON DUPLICATE KEY UPDATE alternateName = 'Kongo (DRC)'; -- DEFINE REGIONS INSERT INTO region( region_id , name , englishname , fcode , geonameid ) SELECT DISTINCT pkey , IF(alt2.alternateName IS NOT NULL, alt2.alternateName, pname) AS aname , pname , pfcode , pgid FROM ( SELECT parent.geonameid as pgid , parent.name as pname , concat(replace(lower(parent.name)," ","-"),"-",parent.geonameid) as pkey , parent.fcode as pfcode , child.geonameid as cgid , child.name as cname , child.country as ccountry , child.fcode as cfcode FROM geonames.hierarchy JOIN geonames.geoname AS parent ON parent.geonameid = geonames.hierarchy.parentid JOIN geonames.geoname AS child ON child.geonameid = geonames.hierarchy.childid WHERE child.fcode IN ('PCLI','TERR','PCLD','PCLX') AND parent.fcode IN ('CONT', 'RGN') AND child.fcode != parent.fcode AND child.country != '' ORDER BY parent.name , child.name ) as regions LEFT JOIN ( SELECT * FROM geonames.alternatename as alt WHERE alt.isoLanguage = 'de' ) as alt2 ON pgid = alt2.geonameid ; -- POPULATE REGION MANY TO MANY INSERT INTO your_db_name.region_laender(region_id, countryinfo_id) SELECT DISTINCT pkey, ccountry FROM ( SELECT parent.geonameid as pgid , parent.name as pname , reg.id as pkey , parent.fcode as pfcode , child.geonameid as cgid , child.name as cname , child.country as ccountry , child.fcode as cfcode FROM geonames.hierarchy JOIN geonames.geoname AS parent ON parent.geonameid = geonames.hierarchy.parentid JOIN geonames.geoname AS child ON child.geonameid = geonames.hierarchy.childid JOIN your_db_name.region as reg ON concat(replace(lower(parent.name) COLLATE utf8mb4_unicode_ci," ","-"),"-",parent.geonameid) = reg.region_id WHERE child.fcode IN ('RGN','PCLI','TERR','PCLD','PCLX') AND parent.fcode IN ('CONT', 'RGN') AND child.fcode != parent.fcode AND child.country != '' ORDER BY parent.name , child.name ) as regions; -- ADD GERMAN NAMES TO CONTINENTCODES, COUNTRYINFO, AND GEONAMES (Prefer short names) INSERT INTO your_db_name.continentCodes( code , name ) SELECT cont.code, alt1.alternateName as altname FROM your_db_name.continentCodes AS cont JOIN your_db_name.alternatename as alt1 ON alt1.geonameid = cont.geonameid AND alt1.alternatenameId = ( SELECT alternatenameId FROM your_db_name.alternatename as alt2 Where cont.geonameid = alt2.geonameid AND isoLanguage = 'de' ORDER BY alt2.isShortName DESC , alt2.isPreferredName DESC LIMIT 1 ) ON DUPLICATE KEY UPDATE name = VALUES(name); INSERT INTO your_db_name.countryinfo( iso_alpha2 , name ) SELECT country.iso_alpha2, alt1.alternateName as altname FROM your_db_name.countryinfo AS country JOIN your_db_name.alternatename as alt1 ON alt1.geonameid = country.geonameid AND alt1.alternatenameId = ( SELECT alternatenameId FROM your_db_name.alternatename as alt2 Where country.geonameid = alt2.geonameid AND isoLanguage = 'de' ORDER BY alt2.isShortName DESC , alt2.isPreferredName DESC LIMIT 1 ) ON DUPLICATE KEY UPDATE name = VALUES(name); INSERT INTO your_db_name.countryinfo( iso_alpha2 , name ) SELECT iso_alpha2 , englishname FROM your_db_name.countryinfo as c WHERE c.name IS NULL ON DUPLICATE KEY UPDATE name = VALUES(name) ; INSERT INTO your_db_name.geoname( geonameid , name ) SELECT gname.geonameid, alt1.alternateName as altname FROM your_db_name.geoname AS gname JOIN your_db_name.alternatename as alt1 ON alt1.geonameid = gname.geonameid AND alt1.alternatenameId = ( SELECT alternatenameId FROM your_db_name.alternatename as alt2 Where gname.geonameid = alt2.geonameid AND isoLanguage = 'de' ORDER BY alt2.isShortName DESC , alt2.isPreferredName DESC LIMIT 1 ) ON DUPLICATE KEY UPDATE name = VALUES(name); ; INSERT INTO your_db_name.geoname( geonameid , name ) SELECT geonameid , englishname FROM your_db_name.geoname AS g WHERE g.name IS NULL ON DUPLICATE KEY UPDATE name = VALUES(name) ; -- ADD EVERY COUNTRY AS A REGION FOR ITS OWN AND ADD "GLOBAL" AS A REGION INSERT INTO your_db_name.region( region_id , name , fcode , englishname ) VALUES ( 'global', 'Weltweit', 'GL', 'Global' ); INSERT INTO your_db_name.region( region_id , name , englishname , fcode , geonameid ) SELECT pkey , name , englishname , fcode , geonameid FROM ( SELECT concat(replace(lower(c.iso_alpha2)," ","-"),"-",c.geonameid) as pkey , c.name as name , c.englishname as englishname , g.fcode as fcode , g.geonameid as geonameid FROM your_db_name.countryinfo as c LEFT JOIN your_db_name.geoname as g ON g.geonameid = c.geonameid ) as country; INSERT INTO your_db_name.region_laender(region_id, countryinfo_id) SELECT (SELECT id FROM your_db_name.region where region_id='global' LIMIT 1), iso_alpha2 FROM your_db_name.countryinfo ; INSERT INTO your_db_name.region_laender(region_id, countryinfo_id) SELECT reg.id , iso_alpha2 FROM your_db_name.countryinfo as country JOIN your_db_name.region as reg ON concat(replace(lower(country.iso_alpha2) COLLATE utf8mb4_unicode_ci," ","-"),"-",country.geonameid) = reg.region_id ;
6a3f8b6d0b5da240c6cda900c0a45d337f1e307f
[ "Markdown", "SQL", "Python", "reStructuredText" ]
4
Markdown
benmaier/django-rkigeonameapi
00c0a9fc4ca1c182e4f574a5378ecdd29fcb0720
b529b91d108c58fa318123700b5be5a7a98f6854
refs/heads/master
<file_sep>{ "name": "nvm-vscode", "version": "1.0.0", "main": "index.js", "author": "<NAME>", "description": "Shows how to use NVM with VS Code", "homepage": "https://www.seafish.io/blog/nvm-and-vs-code/", "keywords": [ "nvm", "nodejs", "vscode" ], "repository": "https://github.com/seanfisher/nvm-vscode", "license": "MIT" }<file_sep># NVM and Visual Studio Code (VSCode) This repository is an example of how to use NVM with Microsoft Visual Studio Code (VSCode). For more details see the [companion blog post](https://www.seafish.io/blog/nvm-and-vs-code/). Open this project up using VS Code and run it - you might need to `chmod +x node.sh` to have the script be executable. You'll see that VS code will run the project using the version of node in the `.nvmrc` file.<file_sep>#!/bin/bash source ~/.bashrc # or ~/.bash_profile if that's what you use nvm run $*
a592422e551121189d73bf16665385453235c95c
[ "Markdown", "JSON", "Shell" ]
3
JSON
seanfisher/nvm-vscode
b852ea3513a9d2551ea5a4037b2b3355896d00eb
c653f7405d2fa867d73c9ea16548c99b049be593
refs/heads/master
<repo_name>seshukumar291/HVTHandler<file_sep>/README.md # HVTHandler Utility methods that provide advanced functionality when using Runnables on Android. Sometimes you want to post a runnable and wait until it finishes, or even get a return value. This type of functionality and even more advanced features can be provided by Future and Executors. However, it's quite common that you just want to stick with Handlers, HandlerThread in order to do simpler tasks. These methods will make your life easier. ### Post runnable and wait ``` java void yourMethod() { // the call will block HVTHandler.postAndWait(mHandler, new Runnable() { @Override public void run() { // do stuff on the other thread } }); // do stuff on the calling thread after the runnable has finished } ``` ### Post runnable and get a return value ``` java void yourMethod() { RunnableResult<Integer> result = HVTHandler.post(mHandler, new RunnableValue<Integer>() { @Override public void run() { //do stuff on the other thread and update the return value value = 2; } }); // Do other stuff on the calling thread, while the runanble is running // block until it finishes and get the return value int resultValue = result.get(); } ``` <file_sep>/HVTHandler.java import android.os.Handler; import android.os.Looper; /** * A helper class that provides more ways to post a runnable than {@link android.os.Handler}. */ public class HVTHandler { /** * Posts a runnable on a handler's thread and waits until it has finished running. * * The handler may be on the same or a different thread than the one calling this method. */ public static void postAndWait(final Handler handler, final Runnable r) { if (handler.getLooper() == Looper.myLooper()) { r.run(); } else { NotifyRunnable runnable = new NotifyRunnable(r); // we use the runnable as synchronization object synchronized (runnable) { handler.post(runnable); while (!runnable.isFinished()) { try { runnable.wait(); } catch (InterruptedException is) { // ignore } } } } } private static class NotifyRunnable implements Runnable { private final Runnable mRunnable; private boolean mFinished = false; private NotifyRunnable(final Runnable r) { mRunnable = r; } public boolean isFinished() { return mFinished; } @Override public void run() { synchronized (this) { mRunnable.run(); mFinished = true; this.notifyAll(); } } } /** * Posts a runnable on a handler's thread and returns a RunnableResult object that can be used to * get a return value. * * You should set the return value by setting {@link RunnableValue#value} in the * {@link RunnableValue#run()} method. You can retrieve it on the calling thread using * {@link RunnableResult#get()}. * * The handler may be on the same or a different thread than the one calling this method. * * @return a RunnableResult instance that can be used to retrieve the return value */ public static <T> RunnableResult<T> post(final Handler handler, final RunnableValue<T> r) { NotifyRunnable runnable = new NotifyRunnable(r); // we use the runnable as synchronization object RunnableResult<T> result = new RunnableResult<T>(r, runnable); if (handler.getLooper() == Looper.myLooper()) { r.run(); } else { handler.post(runnable); } return result; } /** * A runnable that also has a variable that can be used to return a value. * * In your {@link #run()} implementation you should set the return value to {@link #value}. * * @param <T> the type of the return value. */ public static abstract class RunnableValue<T> implements Runnable { public T value; } /** * The result of the runnable. You should call {@link #get()} to retrieve the result. */ public static class RunnableResult<T> { private final RunnableValue<T> mRunnable; private final NotifyRunnable mNotifyRunnable; private RunnableResult(final RunnableValue<T> r, final NotifyRunnable notifyRunnable) { mRunnable = r; mNotifyRunnable = notifyRunnable; } /** * Get the return value. Blocks until the runnable has finished running. */ public T get() { synchronized (mNotifyRunnable) { while (!mNotifyRunnable.isFinished()) { try { mNotifyRunnable.wait(); } catch (InterruptedException is) { // ignore } } } return mRunnable.value; } } }
1f38784e1d9bdd1d68ca4da9d8b046209b3669c3
[ "Markdown", "Java" ]
2
Markdown
seshukumar291/HVTHandler
e065117d8b5a7302b186ce15e3d50b06cc9c95e1
3a2536a438e3e7fe2aca43608bdc14f138dc619f
refs/heads/master
<repo_name>StephenWasntAvailable/1tac_misc<file_sep>/addons/tm_mag_compat/CfgMagazines.hpp class CfgMagazines { class rhs_mag_30Rnd_556x45_M855A1_Stanag; class delta_rhs_mag_60Rnd_556x45_M855A1_Stanag: rhs_mag_30Rnd_556x45_M855A1_Stanag { descriptionshort = "Caliber: 5.56x45mm NATO<br />Rounds: 60<br />Used in: M27 IAR"; displayname = "5.56mm M855A1 60rnd Mag"; count = 60; mass = 14; scope = 1; }; class rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red: rhs_mag_30Rnd_556x45_M855A1_Stanag {}; class delta_rhs_mag_60Rnd_556x45_M855A1_Stanag_Tracer_Red: rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red { descriptionshort = "Caliber: 5.56x45mm NATO<br />Rounds: 60<br />Used in: M27 IAR"; displayname = "5.56mm M855A1 Tracer 60rnd Mag"; count = 60; mass = 14; scope = 1; }; };<file_sep>/addons/tm_capacity_tweaks/CfgMagazines.hpp class CfgMagazines { class CA_Magazine; class CUP_120Rnd_TE4_LRT4_White_Tracer_762x51_Belt_M: CA_Magazine { mass = 45; }; class CA_LauncherMagazine; class rhs_fgm148_magazine_AT: CA_LauncherMagazine { mass = 200; // 286.88 }; class 30Rnd_556x45_Stanag; class hlc_100Rnd_762x51_B_M60E4: 30Rnd_556x45_Stanag { mass = 36; }; };<file_sep>/addons/tm_mag_compat/CfgMagazineWells.hpp //class CfgMagazineWells {};
befe7c9a81bf15c2d861564ecf688d9e170e2716
[ "C++" ]
3
C++
StephenWasntAvailable/1tac_misc
059e28aba004c58dc05f6eeab6267e8d49a8f87b
682bb2768764c52f75245973d9b68003e25de66d
refs/heads/main
<repo_name>serg-ios/ios-widgets<file_sep>/README.md # Widget Sandbox iOS app whose only purpose is to handle a funny iOS widget to play Magic Eight Ball game 🎱. ## Important concepts The most basic concepts in widget's development are `TimelineEntry` and `TimelineProvider`. ### TimelineEntry The widget needs a `Timeline`, a sequence of data that will determine its status as time goes by. Each piece of data is a `TimelineEntry` and the widget uses the information of each entry to configure its appearance and behaviour at a point. ```swift struct Entry: TimelineEntry { let date: Date let text: String } ``` ### TimelineProvider This is a protocol that must be implemented in order to create our own `TimelineProvider`. #### Snapshot & placeholder Provides default entry to show widget in the widget's menu. <img src="small.jpg" width="200"> <img src="medium.jpg" width="200"> <img src="big.jpg" width="200"> ```swift func placeholder(in context: Context) -> Entry { let date = Date() return Entry(date: date, text: makePrediction(for: date)) } func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { let date = Date() let model = Entry(date: date, text: makePrediction(for: date)) completion(model) } ``` #### Timeline The protocol has a method (that must be implemented) that creates the `Timeline<Entry>` that will define the status of the widget as time goes by. ```swift func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { var entries = [Entry]() var components = Calendar.current.dateComponents( [.era, .year, .month, .day, .hour, .minute, .second], from: Date() ) components.second = 0 let roundedDate = Calendar.current.date(from: components)! for second in 0..<60 { let entryDate = Calendar.current.date(byAdding: .second, value: second, to: roundedDate)! let model = Entry(date: entryDate, text: makePrediction(for: entryDate)) entries.append(model) } let timeline = Timeline(entries: entries, policy: .atEnd) completion(timeline) } ``` In the previous function, an entry is created for each second during a one-minute interval. Specifying `.atEnd` policy, the timeline starts again as soon as it is finished. ### Widget And last but not least, the heart of the widget. It must be marked as `@main` and in its body property we must return a `WidgetConfiguration` including our custom `TimelineProvider`, a view that represents the widget, the supported families (the widget's sizes that will be supported) and a description to show in the widget's menu. ```swift @main struct Config: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: "com.serg-ios.WidgetsSandbox", provider: TimeProvider()) { data in WidgetView(data: data) } .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) .description(Text("Magic Eight Ball")) } } ``` ## Bibliography https://www.hackingwithswift.com/plus/hacking-with-swift-live-2020/last-but-not-least-widgets <file_sep>/WidgetsSandbox/WidgetsSandboxApp.swift // // WidgetsSandboxApp.swift // WidgetsSandbox // // Created by <NAME> on 23/4/21. // import SwiftUI @main struct WidgetsSandboxApp: App { var body: some Scene { WindowGroup { ContentView() } } } <file_sep>/WidgetsSandbox/ContentView.swift // // ContentView.swift // WidgetsSandbox // // Created by <NAME> on 23/4/21. // import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .padding() .onOpenURL { url in print("URL received: \(url)") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>/SandboxWidget/SandboxWidget.swift // // SandboxWidget.swift // SandboxWidget // // Created by <NAME> on 23/4/21. // import WidgetKit import SwiftUI import Intents struct Entry: TimelineEntry { let date: Date let text: String } struct TimeProvider: TimelineProvider { func makePrediction(for date: Date) -> String { let positiveAnswers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "Most likely"] let uncertainAnswers = ["Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again"] let negativeAnswers = ["Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Lol nope"] let allAnswers = positiveAnswers + uncertainAnswers + negativeAnswers let predictionNumber = Int(date.timeIntervalSince1970) % allAnswers.count return allAnswers[predictionNumber] } func placeholder(in context: Context) -> Entry { let date = Date() return Entry(date: date, text: makePrediction(for: date)) } func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { let date = Date() let model = Entry(date: date, text: makePrediction(for: date)) completion(model) } func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { var entries = [Entry]() var components = Calendar.current.dateComponents( [.era, .year, .month, .day, .hour, .minute, .second], from: Date() ) components.second = 0 let roundedDate = Calendar.current.date(from: components)! for second in 0..<60 { let entryDate = Calendar.current.date(byAdding: .second, value: second, to: roundedDate)! let model = Entry(date: entryDate, text: makePrediction(for: entryDate)) entries.append(model) } let timeline = Timeline(entries: entries, policy: .atEnd) completion(timeline) } } struct WidgetView: View { let data: Entry var body: some View { ZStack { ContainerRelativeShape() .inset(by: 5) .fill(Color.white.opacity(0.1)) Text(data.text) .multilineTextAlignment(.center) .font(.headline) .padding() } .background(Color(white: 0.1)) .foregroundColor(.white) } } @main struct Config: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: "com.serg-ios.WidgetsSandbox", provider: TimeProvider()) { data in WidgetView(data: data) } .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) .description(Text("Magic Eight Ball")) } }
ed6f078db97965df8506ed28eeab9d62d5203bb3
[ "Markdown", "Swift" ]
4
Markdown
serg-ios/ios-widgets
a269b8f5936a93bcaeb8ba34bb46280c0f06a09e
504f66b3777f4359c73275ae2c04368d86e1775c
refs/heads/master
<repo_name>vatasescu-predi-andrei/lab6<file_sep>/Node.java public class Node<T> extends Tree{ private Node<T> c0; private Node<T> C1; private Node<T> c2; private Node<T> C3; private Node<T> c4; private T data; public Node<T> next; /** * * @param data the element that is in the node * @param left the left child of the node * @param right the right child of the node */ public Node(T data, Node[] array = new Node[5];){ //Assign data to the new node, set children to null setElement(data); } /** * This method return the left child of the node * @return left */ public Node<T> getLeft() { return left; } /** * This method returns the right child of the node * @return right */ public Node<T> getRight() { return right; } /** * This method returns the element in the specified node * @return data */ public T getElement() { return data; } public T getChild(int i){ return array[i]; } /** * This method sets the element in the specified node * @param data */ public void setElement(T data) { this.data = data; } public void setChildren(Node array){ for(int i=0;i<=array.length-1;i++){ this.array[i]=array[i]; } } /** * This method sets the left child * @param left */ public void setLeft(Node<T> left) { this.left = left; } /** * This method sets the right child * @param right */ public void setRight(Node<T> right) { this.right = right; } }
f5a6503eb08a9edee1a2949a0ea8817a074f9116
[ "Java" ]
1
Java
vatasescu-predi-andrei/lab6
b5f094a2c854af8fdf4bc31b496deee88c37693e
a39e8bc25e7169f884cec9685a1d234391189527
refs/heads/master
<file_sep>from mecode import G from material import init_material from utility import CNC_TRAVEL_Z, GContext, nomad_header, tool_change import argparse import math from rectangleTool import rectangleTool from hole import hole def z_tool_hill_ball(dx, r_ball, r_hill): zhc = math.sqrt(r_hill * r_hill - dx * dx) return zhc - r_hill def z_tool_hill_flat(dx, ht, r_hill): if (dx <= ht): return 0.0 zhc = math.sqrt(r_hill * r_hill - math.pow((dx - ht), 2.0)) return zhc - r_hill def hill(g, mat, diameter, dx, dy): r_hill = diameter / 2 ht = mat['tool_size'] * 0.5 hy = dy / 2 doc = mat['pass_depth'] step = 0.5 def rough_arc(bias): y = 0 end = hy + ht last_plane = 0 last_y = 0 step = ht / 4 g.move(x=dx) g.move(x=-dx/2) while y < end: do_plane = False y += step if y >= end: do_plane = True y = end if last_plane - height_func(y + step, ht, r_hill) >= doc: do_plane = True if do_plane: # move to the beginning of the plane g.move(y = bias * (y - last_y)) # cut the plane z = height_func(y, ht, r_hill) dz = z - last_plane g.comment("Cutting plane. y={} z={} dx={} dy={} dz={}".format(y, z, dx, end - y, dz)) rectangleTool(g, mat, dz, dx, end - y, 0.0, "bottom" if bias > 0 else "top", "center", True) # move to the bottom of the plane we just cut g.move(z=dz) g.comment("Cutting plane done.") last_y = y last_plane += dz g.move(-dx/2) g.abs_move(z=origin_z) g.move(y=-end*bias) def arc(bias, step): y = 0 low_x = True end = hy + ht while y < end: if y + step > end: g.move(y = (end - y) * bias) y = end else: y += step g.move(y = step * bias) dz = height_func(y, ht, r_hill) g.feed(mat['plunge_rate']) g.abs_move(z=origin_z + dz) g.feed(mat['feed_rate']) if low_x is True: g.move(x=dx) low_x = False else: g.move(x=-dx) low_x = True if low_x is False: g.move(x = -dx) g.abs_move(z=origin_z) g.move(y=-end*bias) with GContext(g): g.comment('hill') g.relative() mult = 0.2 # rough pass origin_z = g.current_position['z'] g.spindle() g.dwell(0.5) g.spindle('CW', mat['spindle_speed']) rough_arc(1) g.spindle() g.dwell(0.5) g.spindle('CCW', mat['spindle_speed']) rough_arc(-1) # smooth pass g.spindle() g.spindle() g.dwell(0.5) g.spindle('CW', mat['spindle_speed']) arc(1, mult*ht) g.spindle() g.dwell(0.5) g.spindle('CCW', mat['spindle_speed']) arc(-1, mult*ht) g.spindle() def main(): parser = argparse.ArgumentParser( description='Cut out a cylinder or valley. Very carefully accounts for tool geometry.') parser.add_argument('material', help='the material to cut (wood, aluminum, etc.)') parser.add_argument('diameter', help='diameter of the cylinder.', type=float) parser.add_argument('dx', help='dx of the cut, flat over the x direction', type=float) parser.add_argument('dy', help='dy of the cut, curves over the y direction', type=float) parser.add_argument('-o', '--overlap', help='overlap between each cut', type=float, default=0.5) parser.add_argument('-b', '--ball', help="use ball cutter", action="store_true") args = parser.parse_args() g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) mat = init_material(args.material) nomad_header(g, mat, CNC_TRAVEL_Z) g.move(z=0) hill(g, mat, args.diameter, args.dx, args.dy, args.ball) g.spindle() if __name__ == "__main__": main() <file_sep>import math import re CNC_TRAVEL_Z = 3.0 def nomad_header(g, mat, z_start): g.absolute() g.feed(mat['feed_rate']) g.rapid(x=0, y=0, z=z_start) g.spindle('CW', mat['spindle_speed']) def tool_change(g, mat, name: int): # this isn't as seamless as I would hope; need to save and # restore the absolute position. (spindle as well, but needing # to set the spindle again is a little more obvious) with GContext(g): g.absolute() x = g.current_position[0] y = g.current_position[1] z = g.current_position[2] g.write("M6 {0}".format(name)) g.feed(mat['travel_feed']) g.rapid(x=x, y=y) g.rapid(z=z + CNC_TRAVEL_Z) g.spindle('CW', mat['spindle_speed']) g.move(z=z) class Rectangle: def __init__(self, x0: float = 0, y0: float = 0, x1: float = 0, y1: float = 0): self.x0 = min(x0, x1) self.y0 = min(y0, y1) self.x1 = max(x0, x1) self.y1 = max(y0, y1) self.dx = self.x1 - self.x0 self.dy = self.y1 - self.y0 class Bounds: def __init__(self, tool_size :float, center :Rectangle): ht = tool_size / 2 self.center = center self.outer = Rectangle(center.x0 - ht, center.y0 - ht, center.x1 + ht, center.y1 + ht) self.inner = None self.cx = (center.x0 + center.x1) / 2 self.cy = (center.y0 + center.y1) / 2 if center.x0 + ht < center.x1 - ht and center.y0 + ht < center.y1 + ht: self.inner = Rectangle(center.x0 + ht, center.y0 + ht, center.x1 - ht, center.y1 - ht) # Calculates relative moves to get to a final goal. # A goal='5' and a step='2' generates: [2, 2, 1] def calc_steps(goal, step): if goal * step < 0: raise RuntimeError("Goal and step must be both positive or both negative.") bias = 1 if goal < 0: bias = -1 step = -step goal = -goal steps = [] total = 0 while total + step < goal: steps.append(step) total += step if total < goal: steps.append(goal - total) return list(map(lambda x: round(x * bias, 5), steps)) def run_3_stages(path, g, steps): g.comment("Path: initial pass") total_d = 0 path(g, 0, total_d) for d in steps: if d > 0: raise RuntimeError("Positive value for step: " + str(d)) if d > -0.0000001: d = 0 total_d += d g.comment('Path: depth={} total_depth={}'.format(d, total_d)) path(g, d, total_d) g.comment('Path: final pass') path(g, 0, total_d) g.comment('Path: complete') def run_3_stages_abs(path, g, steps): g.comment("initial pass") path(g, 0, 0) base_z = 0 for d in steps: if d > 0: raise RuntimeError("Positive value for step: " + str(d)) if d > -0.0000001: d = 0 g.comment('pass: depth={}'.format(d)) path(g, base_z, d) base_z += d g.comment('final pass') path(g, base_z, 0) g.comment('complete') # returns a negative value or none def z_on_cylinder(dy, rad): if dy >= rad: return None h = math.sqrt(rad ** 2 - dy ** 2) z = h - rad return z def read_DRL(fname): result = [] with open(fname) as f: content = f.read() # print(content) prog = re.compile('X[+-]?[0-9]+Y[+-]?[0-9]+') points = prog.findall(content) for p in points: numbers = re.findall('[+-]?[0-9]+', p) scale = 100.0 result.append({'x': float(numbers[0]) / scale, 'y': float(numbers[1]) / scale}) return result ''' fname: file to read (input) tool_size: size of the bit (input) drills: list of {x, y} holes to drill holes: list of {x, y, d} holes to cut ''' def read_DRL_2(fname): tool = {} current = 1 all_holes = [] prog_tool_change = re.compile('T[0-9][0-9]') prog_tool_size = re.compile('T[0-9][0-9]C') prog_position = re.compile('X[+-]?[0-9]+Y[+-]?[0-9]+') with open(fname) as f: for line in f: pos = prog_tool_size.search(line) if pos is not None: s = pos.group() index = int(s[1:3]) tool[index] = float(line[4:]) continue pos = prog_tool_change.search(line) if pos is not None: s = pos.group() current = int(s[1:]) continue pos = prog_position.search(line) if pos is not None: s = pos.group() numbers = re.findall('[+-]?[0-9]+', s) scale = 100.0 all_holes.append( {'size': tool[current], 'x': float(numbers[0]) / scale, 'y': float(numbers[1]) / scale}) return all_holes def index_of_closest_point(origin, points): index = 0 min_error = 10000.0 * 10000.0 x = origin['x'] y = origin['y'] for i in range(0, len(points)): p = points[i] err = (p['x'] - x) ** 2 + (p['y'] - y) ** 2 if err < min_error: min_error = err index = i return index def sort_shortest_path(points): new_points = [] c = {'x': 0, 'y': 0} while len(points) > 0: i = index_of_closest_point(c, points) c = points[i] new_points.append(points.pop(i)) for p in new_points: points.append(p) class GContext: def __init__(self, g, **kwargs): self.g = g self.check_z = None if 'z' in kwargs: self.check_z = kwargs["z"] def __enter__(self): self.is_relative = self.g.is_relative if self.check_z: assert(self.g.current_position["z"] > self.check_z - 0.1) assert(self.g.current_position["z"] < self.check_z + 0.1) def __exit__(self, exc_type, exc_val, exc_tb): if self.check_z: assert(self.g.current_position["z"] > self.check_z - 0.1) assert(self.g.current_position["z"] < self.check_z + 0.1) if self.is_relative: self.g.relative() else: self.g.absolute() # moves the head up, over, down def travel(g, mat, **kwargs): if g.is_relative: g.move(z=CNC_TRAVEL_Z) if 'x' in kwargs and 'y' in kwargs: g.rapid(x=kwargs['x'], y=kwargs['y']) elif 'x' in kwargs: g.rapid(x=kwargs['x']) elif 'y' in kwargs: g.rapid(y=kwargs['y']) g.move(z=-CNC_TRAVEL_Z) else: z = g.current_position['z'] g.move(z=z + CNC_TRAVEL_Z) if 'x' in kwargs and 'y' in kwargs: g.rapid(x=kwargs['x'], y=kwargs['y']) elif 'x' in kwargs: g.rapid(x=kwargs['x']) elif 'y' in kwargs: g.rapid(y=kwargs['y']) g.move(z=z) <file_sep>from mecode import G from material import init_material from utility import nomad_header, CNC_TRAVEL_Z, GContext, calc_steps, run_3_stages from drill import drill import argparse import math # Assume we are at (x, y, 0) # Accounts for tool size # 'r' radius # 'd' diameter # 'di' inner diameter to reserve (if fill) # 'offset' = 'inside', 'outside', 'middle' # 'fill' = True # 'z' if specified, the z move to issue before cutting # 'return_center' = True, returns to center at the end # def hole(g, mat, cut_depth, **kwargs): radius = 0 offset = "inside" fill = True di = None if 'r' in kwargs: radius = kwargs['r'] if 'd' in kwargs: radius = kwargs['d'] / 2 if 'offset' in kwargs: offset = kwargs['offset'] if 'fill' in kwargs: fill = kwargs['fill'] if 'di' in kwargs: di = kwargs['di'] tool_size = mat['tool_size'] half_tool = tool_size / 2 if offset == 'inside': radius_inner = radius - half_tool elif offset == 'outside': radius_inner = radius + half_tool elif offset == 'middle': radius_inner = radius else: raise RuntimeError("offset not correctly specified") if radius_inner < 0.2: raise RuntimeError(f"Radius too small. Consider a drill. Radius={radius} Inner={radius_inner} (must be 0.2 or greater)") if cut_depth >= 0: raise RuntimeError('Cut depth must be less than zero.') if mat["tool_size"] < 0: raise RuntimeError('Tool size must be zero or greater.') was_relative = g.is_relative with GContext(g): g.relative() g.comment("hole") g.comment("depth=" + str(cut_depth)) g.comment("tool size=" + str(mat['tool_size'])) g.comment("radius=" + str(radius)) g.comment("pass depth=" + str(mat['pass_depth'])) g.comment("feed rate=" + str(mat['feed_rate'])) g.comment("plunge rate=" + str(mat['plunge_rate'])) # The trick is to neither exceed the plunge or the depth-of-cut/pass_depth. # Approaches below. feed_rate = mat['feed_rate'] path_len_mm = 2.0 * math.pi * radius_inner path_time_min = path_len_mm / feed_rate plunge_from_path = mat['pass_depth'] / path_time_min depth_of_cut = mat['pass_depth'] # Both 1) fast little holes and 2) too fast plunge are bad. # Therefore, apply corrections to both. (If for some reason # alternate approaches need to be reviewed, they are in # source control.) if plunge_from_path > mat['plunge_rate']: factor = mat['plunge_rate'] / plunge_from_path if factor < 0.3: factor = 0.3 # slowing down to less than 10% (factor * factor) seems excessive depth_of_cut = mat['pass_depth'] * factor feed_rate = mat['feed_rate'] * factor g.comment('adjusted pass depth=' + str(depth_of_cut)) g.comment('adjusted feed rate =' + str(feed_rate)) g.spindle('CW', mat['spindle_speed']) g.feed(mat['travel_plunge']) g.move(x=radius_inner) if 'z' in kwargs: if was_relative: g.move(z=kwargs['z']) else: g.abs_move(z=kwargs['z']) g.feed(feed_rate) def path(g, plunge, total_plunge): g.arc2(x=-radius_inner, y=radius_inner, i=-radius_inner, j=0, direction='CCW', helix_dim='z', helix_len=plunge / 4) g.arc2(x=-radius_inner, y=-radius_inner, i=0, j=-radius_inner, direction='CCW', helix_dim='z', helix_len=plunge / 4) g.arc2(x=radius_inner, y=-radius_inner, i=radius_inner, j=0, direction='CCW', helix_dim='z', helix_len=plunge / 4) g.arc2(x=radius_inner, y=radius_inner, i=0, j=radius_inner, direction='CCW', helix_dim='z', helix_len=plunge / 4) if fill and radius_inner > half_tool: r = radius_inner dr = 0 step = tool_size * 0.8 min_rad = half_tool * 0.8 if di: min_rad = di / 2 while r > min_rad: if r - step < min_rad: step = r - min_rad r -= step #print("r={} step={}".format(r, step)) dr += step g.move(x=-step) g.arc2(x=-r, y=r, i=-r, j=0, direction='CCW') g.arc2(x=-r, y=-r, i=0, j=-r, direction='CCW') g.arc2(x=r, y=-r, i=r, j=0, direction='CCW') g.arc2(x=r, y=r, i=0, j=r, direction='CCW') g.move(x=dr) steps = calc_steps(cut_depth, -depth_of_cut) run_3_stages(path, g, steps) g.move(z=-cut_depth) # up to the starting point g.feed(mat['travel_plunge']) # go fast again...else. wow. boring. g.move(z=1.0) return_center = True if 'return_center' in kwargs: return_center = kwargs['return_center'] if return_center: g.move(x=-radius_inner) # back to center of the circle def hole_abs(g, mat, cut_depth, radius, x, y): with GContext(g): g.absolute() g.feed(mat['travel_feed']) g.move(z=CNC_TRAVEL_Z) g.move(x=x, y=y) hole(g, mat, cut_depth, r=radius) g.absolute() # assume we are at (x, y, CNC_TRAVEL_Z) def hole_or_drill(g, mat, cut_depth, radius): if radius == 0: return "mark" elif mat['tool_size'] + 0.1 < radius * 2: if g: hole(g, mat, cut_depth, r=radius) return "hole" else: if g: drill(g, mat, cut_depth) return "drill" def main(): parser = argparse.ArgumentParser( description='Cut a hole at given radius and depth. Implemented with helical arcs,' + 'and avoids plunging.') parser.add_argument('material', help='The material to cut in standard machine-material-size format.', type=str) parser.add_argument('depth', help='Depth of the cut. Must be negative.', type=float) parser.add_argument('radius', help='Radius of the hole.', type=float) parser.add_argument('offset', help="inside, outside, middle", type=str) args = parser.parse_args() mat = init_material(args.material) g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) nomad_header(g, mat, CNC_TRAVEL_Z) g.spindle('CW', mat['spindle_speed']) g.move(z=0) hole(g, mat, args.depth, r=args.radius, offset=args.offset) g.spindle() if __name__ == "__main__": main() <file_sep>import math import sys from mecode import G from material import init_material from utility import calc_steps, run_3_stages, GContext, CNC_TRAVEL_Z, nomad_header import argparse OVERLAP = 0.80 def square(g, mat, dx, dy, fill : bool): with GContext(g): g.relative() if fill: num_lines = int(math.ceil(abs(dy) / (mat['tool_size'] * OVERLAP))) + 1 line_step = 0 if num_lines > 1: line_step = dy / (num_lines - 1) g.comment("Square fill={0}".format(fill)) is_out = False for i in range(0, num_lines): if is_out: g.move(x=-dx) else: g.move(x=dx) is_out = not is_out if i < num_lines - 1: g.move(y=line_step) if is_out: g.move(x=-dx) g.move(y=-dy) else: g.move(x=dx) g.move(y=dy) g.move(x=-dx) g.move(y=-dy) def plane(g, mat, depth, x0, y0, x1, y1): dx = x1 - x0 dy = y1 - y0 # print("plane", dx, dy) with GContext(g): g.comment("Plane depth = {} size = {}, {}".format(depth, dx, dy)) g.relative() g.spindle('CW', mat['spindle_speed']) g.feed(mat['feed_rate']) g.move(x=x0, y=y0) z = 0 while(z > depth): dz = -mat['pass_depth'] if z + dz < depth: dz = depth - z z = depth else: z = z + dz # first line to distribute depth cut. g.move(x=dx, z=dz/2) g.move(x=-dx, z=dz/2) # nice edges g.move(x=dx) g.move(y=dy) g.move(x=-dx) g.move(y=-dy) # now the business of cutting. square(g, mat, dx, dy, True) g.move(z=-depth) g.move(x=-x0, y=-y0) def main(): parser = argparse.ArgumentParser( description='Cut a plane. Origin of the plane is the current location. ' + 'Does not account for tool thickness, so the dx, dy will be fully cut and ' + 'on the tool center. dx/dy can be positive or negative.') parser.add_argument('material', help='The material to cut in standard machine-material-size format.', type=str) parser.add_argument('depth', help='Depth of the cut. Must be negative.', type=float) parser.add_argument('dx', help="Size in x.", type=float) parser.add_argument('dy', help="Size in y.", type=float) args = parser.parse_args() mat = init_material(args.material) g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) nomad_header(g, mat, CNC_TRAVEL_Z) g.spindle('CW', mat['spindle_speed']) g.feed(mat['feed_rate']) g.move(z=0) plane(g, mat, args.depth, 0, 0, args.dx, args.dy) g.abs_move(z=CNC_TRAVEL_Z) g.spindle() if __name__ == "__main__": main() <file_sep>import sys from mecode import G from material import init_material from utility import calc_steps, run_3_stages, GContext, CNC_TRAVEL_Z, nomad_header, read_DRL, sort_shortest_path # assume we are at (x, y) def drill(g, mat, cut_depth): if cut_depth >= 0: raise RuntimeError('Cut depth must be less than zero.') with GContext(g): g.relative() num_plunge = 1 + int(-cut_depth / (0.05 * mat['plunge_rate'])) dz = cut_depth / num_plunge g.comment("Drill depth={} num_taps={}".format(cut_depth, num_plunge)) g.spindle('CW', mat['spindle_speed']) g.feed(mat['plunge_rate']) if num_plunge > 1: # move up and down in stages. for i in range(0, num_plunge): g.move(z=dz) g.move(z=-dz) g.move(z=dz) else: g.move(z=cut_depth) g.move(z=-cut_depth) def drill_points(g, mat, cut_depth, points): with GContext(g): g.absolute() sort_shortest_path(points) for p in points: g.feed(mat['travel_feed']) g.move(z=CNC_TRAVEL_Z) g.move(x=p['x'], y=p['y']) g.move(z=0) drill(g, mat, cut_depth) # Leaves the head at CNC_TRAVEL_Z) g.move(z=CNC_TRAVEL_Z) g.move(x=0, y=0) def main(): try: float(sys.argv[3]) is_number_pairs = True except: is_number_pairs = len(sys.argv) > 3 and (sys.argv[3].find(',') >= 0) if len(sys.argv) < 4: print('Drill a set of holes.') print('Usage:') print(' drill material depth file') print(' drill material depth x0,y0 x1,y1 (etc)') print(' drill material depth x0 y0 x1 y1 (etc)') print('Notes:') print(' Runs in absolute coordinates.') print(' Travel Z={}'.format(CNC_TRAVEL_Z)) sys.exit(1) mat = init_material(sys.argv[1]) cut_depth = float(sys.argv[2]) points = [] g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) nomad_header(g, mat, CNC_TRAVEL_Z) if not is_number_pairs: filename = sys.argv[3] points = read_DRL(filename) else: # Comma separated or not? if sys.argv[3].find(',') > 0: for i in range(3, len(sys.argv)): comma = sys.argv[i].find(',') x = float(sys.argv[i][0:comma]) y = float(sys.argv[i][comma + 1:]) points.append({'x': x, 'y': y}) else: for i in range(3, len(sys.argv), 2): points.append({'x': float(sys.argv[i + 0]), 'y': float(sys.argv[i + 1])}) drill_points(g, mat, cut_depth, points) g.spindle() if __name__ == "__main__": main() <file_sep># turn ascii art into a pcb. for real. from mecode import G from material import init_material from utility import CNC_TRAVEL_Z from drill import drill_points from hole import hole_or_drill from rectangle import rectangle import argparse import sys import math import re SCALE = 2.54 / 2 NOT_INIT = 0 COPPER = 1 ISOLATE = -1 class Point: def __init__(self, x: float = 0, y: float = 0): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return self.x != other.x or self.y != other.y def __getitem__(self, item): if item == 'x': return self.x if item == 'y': return self.y return None class PtPair: def __init__(self, x0: float, y0: float, x1: float, y1: float): self.x0 = x0 self.y0 = y0 self.x1 = x1 self.y1 = y1 def swap_points(self): self.x0, self.x1 = self.x1, self.x0 self.y0, self.y1 = self.y1, self.y0 def do_order(self): if self.x0 > self.x1: self.x0, self.x1 = self.x1, self.x0 if self.y0 > self.y1: self.y0, self.y1 = self.y1, self.y0 def add(self, x, y): self.x0 += x self.y0 += y self.x1 += x self.y1 += y def flip(self, w): self.y0 = h - self.y0 self.y1 = h - self.y1 def dx(self): return abs(self.x1 - self.x0) def dy(self): return abs(self.y1 - self.y0) def sign(x): if x > 0: return 1 if x < 0: return -1 return 0 def distance(p0, p1): return math.sqrt((p0.x - p1.x) ** 2 + (p0.y - p1.y) ** 2) def bounds_of_points(arr): pmin = Point(arr[0].x, arr[0].y) pmax = Point(arr[0].x, arr[0].y) for p in arr: pmin.x = min(pmin.x, p.x) pmin.y = min(pmin.y, p.y) pmax.x = max(pmax.x, p.x) pmax.y = max(pmax.y, p.y) return pmin, pmax def pop_closest_pt_pair(x: PtPair, y: PtPair, arr): error = 1000.0 * 1000.0 index = 0 for i in range(0, len(arr)): p = arr[i] err = (p.x0 - x) ** 2 + (p.y0 - y) ** 2 if err == 0: return arr.pop(i) if err < error: index = i error = err err = (p.x1 - x) ** 2 + (p.y1 - y) ** 2 if err == 0: p.swap_points() return arr.pop(i) if err < error: p.swap_points() index = i error = err return arr.pop(index) def scan_isolation(vec): result = [] x0 = 0 while x0 < len(vec): if vec[x0] != ISOLATE: x0 = x0 + 1 continue x1 = x0 while x1 < len(vec) and vec[x1] == ISOLATE: x1 = x1 + 1 if x1 > x0 + 1: result.append(x0) result.append(x1) x0 = x1 return result def scan_file(filename: str): # first get the list of strings that are the lines of the file. ascii_pcb = [] max_char_w = 0 holes = {} offset_cut = Point(0, 0) re_hole_definition = re.compile('[\+\&][a-zA-Z]\s') re_number = re.compile('[\d.-]+') with open(filename, "r") as ins: for line in ins: line = line.rstrip('\n') line = line.replace('\t', ' ') line = line.rstrip(' ') index = line.find('#') if index >= 0: m = re_hole_definition.search(line) offset_x = line.find("+offset_x:") offset_y = line.find("+offset_y:") if m: key = m.group()[1] digit_index = m.end(0) m = re_number.match(line[digit_index:]) diameter = float(m.group()) holes[key] = {"d":diameter, "break":(m[0] == '+')} if offset_x >= 0: offset_cut.x = float(line[offset_x + 10:]) if offset_y >= 0: offset_cut.y = float(line[offset_y + 10:]) else: ascii_pcb.append(line) while len(ascii_pcb) > 0 and len(ascii_pcb[0]) == 0: ascii_pcb.pop(0) while len(ascii_pcb) > 0 and len(ascii_pcb[-1]) == 0: ascii_pcb.pop(-1) for line in ascii_pcb: max_char_w = max(len(line), max_char_w) return ascii_pcb, max_char_w, holes, offset_cut def print_to_console(pcb, mat, n_cols, n_rows, drill_ascii, cut_path_on_center, holes): output_rows = [] for y in range(n_rows): out = "" for x in range(n_cols): c = pcb[y][x] p = {'x': x, 'y': y} if p in drill_ascii: out = out + 'o' elif c == ISOLATE: out = out + '.' elif c == NOT_INIT: out = out + ' ' elif c == COPPER: out = out + '+' output_rows.append(out) for r in output_rows: print(r) half_tool = mat["tool_size"] / 2 for h in holes: diameter = h["diameter"] cut_type = hole_or_drill(None, mat, -1.0, diameter / 2) d_north = cut_path_on_center.y1 - (h['y'] + half_tool) d_south = (h['y'] - half_tool) - cut_path_on_center.y0 d_east = cut_path_on_center.x1 - (h['x'] + half_tool) d_west = (h['x'] - half_tool) - cut_path_on_center.x0 warning = "" pos_x = round(h["x"] - half_tool, 3) pos_y = round(h["y"] - half_tool, 3) if d_north < 1 or d_south < 1 or d_east < 1 or d_west < 1: warning = "Warning: hole within 1mm of edge." print("Hole ({}): d = {} pos = {}, {} pos(no tool) = {}, {} {}".format( cut_type, diameter, pos_x, pos_y, round(h["x"], 3), round(h["y"], 3), warning)) print('Number of drill holes = {}'.format(len(drill_ascii))) print('Rows/Cols = {} x {}'.format(n_cols, n_rows)) print("Cutting offset = {}, {}".format(0.0 - cut_path_on_center.x0, 0.0 - cut_path_on_center.y0)) sx = cut_path_on_center.dx() - mat['tool_size'] sy = cut_path_on_center.dy() - mat['tool_size'] print('Size (after cut) = {} x {} mm ({:.2f} x {:.2f} in)'.format( sx, sy, sx/25.4, sy/25.4)) def print_for_openscad(mat, cut_path_on_center, holes): EDGE_OFFSET = mat["tool_size"] / 2 sx = cut_path_on_center.dx() - mat['tool_size'] # sy = cut_path_on_center.dy() - mat['tool_size'] center_line = sx / 2 print("") print("openscad:") print("[") for h in holes: diameter = h["diameter"] hx = h['x'] - EDGE_OFFSET hy = h['y'] - EDGE_OFFSET cut_type = hole_or_drill(None, mat, -1.0, diameter / 2) if cut_type == "hole": support = "buttress" if (hx > sx / 3) and (hx < 2 * sx / 3): support = "column" print(' [{:.3f}, {:.3f}, "{}" ], // d={}'.format(hx - center_line, hy, support, diameter)) print("]") def rc_to_xy_normal(x: float, y: float, n_cols, n_rows): dx = (n_cols - 1) * SCALE dy = (n_rows - 1) * SCALE return Point(x * SCALE - dx/2, (n_rows - 1 - y) * SCALE - dy/2) def rc_to_xy_flip(x: float, y: float, n_cols, n_rows): dx = (n_cols - 1) * SCALE dy = (n_rows - 1) * SCALE return Point(x * SCALE - dx/2, y * SCALE - dy/2) def nanopcb(filename, g, mat, pcb_depth, drill_depth, do_cutting, info_mode, do_drilling, flip, openscad): if pcb_depth > 0: raise RuntimeError("cut depth must be less than zero.") if drill_depth > 0: raise RuntimeError("drill depth must be less than zero") rc_to_xy = rc_to_xy_normal if flip: rc_to_xy = rc_to_xy_flip ascii_pcb, max_char_w, hole_def, offset_cut = scan_file(filename) PAD = 1 n_cols = max_char_w + PAD * 2 n_rows = len(ascii_pcb) + PAD * 2 # use the C notation # pcb[y][x] pcb = [[NOT_INIT for _ in range(n_cols)] for _ in range(n_rows)] drill_ascii = [] holes = [] # {diameter, x, y} for j in range(len(ascii_pcb)): out = ascii_pcb[j] for i in range(len(out)): c = out[i] x = i + PAD y = j + PAD if c != ' ': # Handle the cutting borders of the board. if c == '[' or c == ']': continue # Handle cutting holes if c in hole_def: diameter = hole_def[c]["d"] point = rc_to_xy(x, y, n_cols, n_rows) holes.append( {'diameter': diameter, 'x': point.x, 'y': point.y}) if hole_def[c]["break"]: continue pcb[y][x] = COPPER for dx in range(-1, 2, 1): for dy in range(-1, 2, 1): x_prime = x + dx y_prime = y + dy if x_prime in range(0, n_cols) and y_prime in range(0, n_rows): if pcb[y_prime][x_prime] == NOT_INIT: pcb[y_prime][x_prime] = ISOLATE if c != '-' and c != '|' and c != '+': drill_ascii.append( {'x': x, 'y': y}) c0 = rc_to_xy(0, 0, n_cols, n_rows) c1 = rc_to_xy(n_cols-1, n_rows-1, n_cols, n_rows) cut_path_on_center = PtPair(c0.x - offset_cut.x, c1.y - offset_cut.y, c1.x + offset_cut.x, c0.y + offset_cut.y) cut_path_on_center.do_order() print_to_console(pcb, mat, n_cols, n_rows, drill_ascii, cut_path_on_center, holes) if openscad: print_for_openscad(mat, cut_path_on_center, holes) if info_mode is True: sys.exit(0) isolation_pairs = [] for y in range(n_rows): pairs = scan_isolation(pcb[y]) while len(pairs) > 0: x0 = pairs.pop(0) x1 = pairs.pop(0) p0 = rc_to_xy(x0, y, n_cols, n_rows) p1 = rc_to_xy(x1 - 1, y, n_cols, n_rows) c = PtPair(p0.x, p0.y, p1.x, p1.y) isolation_pairs.append(c) for x in range(n_cols): vec = [] for y in range(n_rows): vec.append(pcb[y][x]) pairs = scan_isolation(vec) while len(pairs) > 0: y0 = pairs.pop(0) y1 = pairs.pop(0) p0 = rc_to_xy(x, y0, n_cols, n_rows) p1 = rc_to_xy(x, y1 - 1, n_cols, n_rows) c = PtPair(p0.x, p0.y, p1.x, p1.y) isolation_pairs.append(c) g.comment("NanoPCB") g.absolute() g.feed(mat['feed_rate']) g.move(z=CNC_TRAVEL_Z) g.spindle('CW', mat['spindle_speed']) # impossible starting value to force moving to # the cut depth on the first point. c_x = -0.1 c_y = -0.1 while len(isolation_pairs) > 0: cut = pop_closest_pt_pair(c_x, c_y, isolation_pairs) g.comment( '{},{} -> {},{}'.format(cut.x0, cut.y0, cut.x1, cut.y1)) if cut.x0 != c_x or cut.y0 != c_y: g.move(z=CNC_TRAVEL_Z) g.move(x=cut.x0, y=cut.y0) g.move(z=pcb_depth) g.move(x=cut.x1, y=cut.y1) c_x = cut.x1 c_y = cut.y1 g.move(z=CNC_TRAVEL_Z) if do_drilling: drill_pts = [] for da in drill_ascii: drill_pts.append(rc_to_xy(da['x'], da['y'], n_cols, n_rows)) drill_points(g, mat, drill_depth, drill_pts) for hole in holes: diameter = hole["diameter"] g.feed(mat["travel_feed"]) g.move(z=CNC_TRAVEL_Z) g.move(x=hole["x"], y=hole["y"]) g.move(z=0) hole_or_drill(g, mat, drill_depth, diameter / 2) g.move(z=CNC_TRAVEL_Z) if do_cutting: g.move(x=0, y=cut_path_on_center.y0) g.move(z=0) # g.move(x=cut_path_on_center.dx()/2) rectangle(g, mat, drill_depth, cut_path_on_center.dx(), cut_path_on_center.dy(), 1.0, "bottom") g.move(z=CNC_TRAVEL_Z) g.move(z=CNC_TRAVEL_Z) g.spindle() g.move(x=0, y=0) return cut_path_on_center.dx(), cut_path_on_center.dy() def main(): parser = argparse.ArgumentParser( description='Cut a printed circuit board from a text file.') parser.add_argument('filename', help='the source of the ascii art PCB') parser.add_argument( 'material', help='the material to cut (wood, aluminum, etc.)') parser.add_argument( 'pcbDepth', help='depth of the cut. must be negative.', type=float) parser.add_argument( 'drillDepth', help='depth of the drilling and pcb cutting. must be negative.', type=float) parser.add_argument( '-c', '--no-cut', help='disable cut out the final pcb', action='store_true') parser.add_argument( '-i', '--info', help='display info and exit', action='store_true') parser.add_argument( '-d', '--no-drill', help='disable drill holes in the pcb', action='store_true') parser.add_argument( '-f', '--flip', help='flip in the y axis for pcb under and mounting over', action='store_true') parser.add_argument( '-o', '--openscad', help='OpenScad printout.', action='store_true') args = parser.parse_args() mat = init_material(args.material) g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) nanopcb(args.filename, g, mat, args.pcbDepth, args.drillDepth, args.no_cut is False, args.info, args.no_drill is False, args.flip, args.openscad) if __name__ == "__main__": main() <file_sep># saberCNC A collection of CNC code for saber construction. # NanoPCB Nano PCB takes an text-art PCB and creates gcode for sending to a CNC. Basically markdown for printed circuit board cutting. ## Goals: 1. Simple: from a text file to gcode in one step 2. Basic CNC machine. - Isolate circuit, drill, and cut PCB without a bit change. (I use 1.0mm bits, although 0.8mm might be better.) - Account for significant runout. NanoPCB creates straight cuts that are as long as possible. It doesn't use any curves or detail work. Currently it only works single-sided. It would be straightforward to support the flip, the code just needs a way to define the two sides and the flipping axis. It can print the circuit flipped if you want to solder on the down side. ## Legend * ````#```` Starts a comment line. * ````[ ]```` Square brackets define a cutting border. * ````a-z```` Letters define drill holes. * ````# +M 2.2```` Defines a mounting hole, drill hole, etc. Not isolated. If size is zero, then just a mark point. ## Example ```` ################################# # +M 2.2 Mounting # # # # # # # # # # # # # # # # # [ ] M M V o o-r g b | | | | V o o---o o G o o o o | G---o-o---o---o | G o-o o-o o-o o-o M M [ ] ```` <file_sep>import argparse import sys from mecode import G from material import init_material from utility import calc_steps, run_3_stages, GContext def set_feed(g, mat, x, z): if abs(x) < 0.1 or (abs(z) > 0.01 and abs(z) / abs(x) > 1.0): g.feed(mat['plunge_rate']) else: g.feed(mat['feed_rate']) def calc_move_plunge(dx, dy, fillet, pass_plunge): x_move = (dx - fillet * 2) / 2 y_move = (dy - fillet * 2) / 2 plunge = pass_plunge / 4 if (x_move + y_move > 1): x_plunge = plunge * x_move / (x_move + y_move) y_plunge = plunge * y_move / (x_move + y_move) else: x_plunge = y_plunge = plunge / 2 return x_move, y_move, x_plunge, y_plunge def x_segment(g, mat, x_move, x_plunge, cut_depth, total_plunge): set_feed(g, mat, x_move, x_plunge) g.move(x=x_move, z=x_plunge) def y_segment(g, mat, y_move, y_plunge, cut_depth, total_plunge): set_feed(g, mat, y_move, y_plunge) g.move(y=y_move, z=y_plunge) def lower_left(g, mat, dx, dy, fillet, pass_plunge, total_plunge, cut_depth): x_move, y_move, x_plunge, y_plunge = calc_move_plunge(dx, dy, fillet, pass_plunge) y_segment(g, mat, -y_move, y_plunge, cut_depth, total_plunge) if fillet > 0: g.arc2(x=fillet, y=-fillet, i=fillet, j=0, direction="CCW") x_segment(g, mat, x_move, x_plunge, cut_depth, total_plunge) def lower_right(g, mat, dx, dy, fillet, pass_plunge, total_plunge, cut_depth): x_move, y_move, x_plunge, y_plunge = calc_move_plunge(dx, dy, fillet, pass_plunge) x_segment(g, mat, x_move, x_plunge, cut_depth, total_plunge) if fillet > 0: g.arc2(x=fillet, y=fillet, i=0, j=fillet, direction="CCW") y_segment(g, mat, y_move, y_plunge, cut_depth, total_plunge) def upper_right(g, mat, dx, dy, fillet, pass_plunge, total_plunge, cut_depth): x_move, y_move, x_plunge, y_plunge = calc_move_plunge(dx, dy, fillet, pass_plunge) y_segment(g, mat, y_move, y_plunge, cut_depth, total_plunge) if fillet > 0: g.arc2(x=-fillet, y=fillet, i=-fillet, j=0, direction="CCW") x_segment(g, mat, -x_move, x_plunge, cut_depth, total_plunge) def upper_left(g, mat, dx, dy, fillet, pass_plunge, total_plunge, cut_depth): x_move, y_move, x_plunge, y_plunge = calc_move_plunge(dx, dy, fillet, pass_plunge) x_segment(g, mat, -x_move, x_plunge, cut_depth, total_plunge) if fillet > 0: g.arc2(x=-fillet, y=-fillet, i=0, j=-fillet, direction="CCW") y_segment(g, mat, -y_move, y_plunge, cut_depth, total_plunge) # from current location # no accounting for tool size def rectangle(g, mat, cut_depth, dx, dy, fillet, origin, single_pass=False, restore_z=True): if cut_depth > 0: raise RuntimeError('Cut depth must be less than, or equal to, zero.') if dx == 0 and dy == 0: raise RuntimeError('dx and dy may not both be zero') if dx < 0 or dy < 0: raise RuntimeError('dx and dy must be positive') if fillet < 0 or fillet*2 > dx or fillet*2 > dy: raise RuntimeError("Invalid fillet. dx=" + str(dx) + " dy= " + str(dy) + " fillet=" + str(fillet)) corners = [] if origin == "left": corners.append(lower_left) corners.append(lower_right) corners.append(upper_right) corners.append(upper_left) elif origin == "bottom": corners.append(lower_right) corners.append(upper_right) corners.append(upper_left) corners.append(lower_left) elif origin == "right": corners.append(upper_right) corners.append(upper_left) corners.append(lower_left) corners.append(lower_right) elif origin == "top": corners.append(upper_left) corners.append(lower_left) corners.append(lower_right) corners.append(upper_right) else: raise RuntimeError("Origin isn't valid.") with GContext(g): g.comment("Rectangular cut") g.relative() g.spindle('CW', mat['spindle_speed']) g.feed(mat['feed_rate']) def path(g, plunge, total_plunge): corners[0](g, mat, dx, dy, fillet, plunge, total_plunge, cut_depth) corners[1](g, mat, dx, dy, fillet, plunge, total_plunge, cut_depth) corners[2](g, mat, dx, dy, fillet, plunge, total_plunge, cut_depth) corners[3](g, mat, dx, dy, fillet, plunge, total_plunge, cut_depth) if single_pass: path(g, cut_depth, cut_depth) else: steps = calc_steps(cut_depth, -mat['pass_depth']) run_3_stages(path, g, steps) #path(g, 0) if restore_z: g.move(z=-cut_depth) def main(): parser = argparse.ArgumentParser( description='Cut a rectangle. Careful to return to original position so it can be used in other ' + 'calls. Can also cut an axis aligned line. Does not account for tool size. Also ' + 'careful to not travel where it does not cut.') parser.add_argument('material', help='the material to cut (wood, aluminum, etc.)') parser.add_argument('depth', help='depth of the cut. must be negative.', type=float) parser.add_argument('dx', help='x width of the cut.', type=float) parser.add_argument('dy', help='y width of the cut.', type=float) parser.add_argument('-f', '--fillet', help='fillet radius', type=float, default=0) parser.add_argument('-o', '--origin', help="origin. can be 'left', 'bottom', 'right', or 'top'", type=str, default="left") args = parser.parse_args() mat = init_material(args.material) g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) rectangle(g, mat, args.depth, args.dx, args.dy, args.fillet, args.origin) g.spindle() if __name__ == "__main__": main()<file_sep>import argparse import sys from mecode import G from material import init_material from utility import calc_steps, run_3_stages, GContext, CNC_TRAVEL_Z from rectangle import rectangle # from lower left. it's an inner cut, with outer dim x,y def overCut(g, mat, cut_depth, _dx, _dy): g.feed(mat['travel_feed']) g.spindle('CW', mat['spindle_speed']) with GContext(g): g.relative() tool = mat['tool_size'] half = tool / 2 dx = _dx - tool dy = _dy - tool length = dx * 2 + dy * 2 g.move(z=1) g.move(x=half, y=half) g.move(z=-1) def path(g, plunge, total_plunge): g.move(x=dx, z=plunge * dx / length) g.move(x=half) g.move(x=-half, y=-half) g.move(y=half) g.move(y=dy, z=plunge * dy / length) g.move(y=half) g.move(x=half, y=-half) g.move(x=-half) g.move(x=-dx, z=plunge * dx / length) g.move(x=-half) g.move(x=half, y=half) g.move(y=-half) g.move(y=-dy, z=plunge * dy / length) g.move(y=-half) g.move(x=-half, y=half) g.move(x=half) steps = calc_steps(cut_depth, -mat['pass_depth']) run_3_stages(path, g, steps) g.move(z=-cut_depth) g.move(z=1) g.move(x=-half, y=-half) g.move(z=-1) def rectangleTool(g, mat, cut_depth, dx, dy, fillet, origin, align, fill=False, adjust_trim=False): if cut_depth >= 0: raise RuntimeError('Cut depth must be less than zero.') with GContext(g): g.relative() g.feed(mat['travel_feed']) g.spindle('CW', mat['spindle_speed']) tool_size = mat['tool_size'] half_tool = tool_size / 2 x = 0 y = 0 x_sign = 0 y_sign = 0 rect_origin = origin if origin == "left": x_sign = 1 elif origin == "bottom": y_sign = 1 elif origin == "right": x_sign = -1 elif origin == "top": y_sign = -1 elif origin == "center": x_sign = 1 rect_origin = "left" else: raise RuntimeError("unrecognized origin") if origin == "center": g.move(x=-dx/2) if align == 'inner': x = half_tool * x_sign y = half_tool * y_sign dx -= tool_size dy -= tool_size if adjust_trim: fillet -= half_tool if fillet < 0: fillet = 0 elif align == 'outer': x = -half_tool * x_sign y = -half_tool * y_sign dx += tool_size dy += tool_size if adjust_trim: if fillet > 0: fillet += half_tool elif align == "center": pass else: raise RuntimeError("unrecognized align") if dx == 0 and dy == 0: raise RuntimeError('dx and dy may not both be zero') if dx < 0 or dy < 0: raise RuntimeError('dx and dy must be positive') if abs(x) or abs(y): g.move(z=CNC_TRAVEL_Z) g.move(x=x, y=y) g.move(z=-CNC_TRAVEL_Z) if fill == False or dx == 0 or dy == 0: rectangle(g, mat, cut_depth, dx, dy, fillet, rect_origin) else: z_depth = 0 z_step = mat['pass_depth'] single_pass = True # the outer loop walks downward. while z_depth > cut_depth: this_cut = 0 if z_depth - z_step <= cut_depth: this_cut = cut_depth - z_depth single_pass = False z_depth = cut_depth else: this_cut = -z_step z_depth -= z_step dx0 = dx dy0 = dy fillet0 = fillet step = tool_size * 0.7 first = True total_step = 0 #print("dx={} dy={}".format(dx, dy)) # the inner loop walks inward. # note that the cut hasn't happened at the top of the loop; # so only abort when they cross while dx0 > 0 and dy0 > 0: #print(" dx={} dy={} step={}".format(dx0, dy0, step)); if first: first = False rectangle(g, mat, this_cut, dx0, dy0, fillet0, rect_origin, single_pass=single_pass, restore_z=False) else: g.move(x=step * x_sign, y=step * y_sign) total_step += step rectangle(g, mat, 0.0, dx0, dy0, fillet0, rect_origin, single_pass=True) # subtle the last cut doesn't overlap itself. # probably a better algorithm for this if dx0 - step * 2 < 0 or dy0 - step * 2 < 0: dx0 -= step dy0 -= step else: dx0 -= step * 2 dy0 -= step * 2 fillet0 -= step if fillet0 < 0: fillet0 = 0 g.move(x=-total_step * x_sign, y=-total_step * y_sign) # don't need to move down; z is not restored g.move(z=this_cut) g.move(z=-cut_depth) if abs(x) or abs(y): g.move(z=CNC_TRAVEL_Z) g.move(x=-x, y=-y) if origin == "center": g.move(x=dx/2) g.move(z=-CNC_TRAVEL_Z) def main(): parser = argparse.ArgumentParser( description='Cut a rectangle accounting for tool size.') parser.add_argument('material', help='the material to cut (wood, aluminum, etc.)') parser.add_argument('depth', help='depth of the cut. must be negative.', type=float) parser.add_argument('dx', help='x width of the cut.', type=float) parser.add_argument('dy', help='y width of the cut.', type=float) parser.add_argument('-f', '--fillet', help='fillet radius', type=float, default=0) parser.add_argument('-a', '--align', help="'center', 'inner', 'outer'", type=str, default='center') parser.add_argument('-i', '--inside_fill', help="fill inside area", action='store_true') parser.add_argument('-o', '--origin', help="origin, can be 'left', 'bottom', 'right', or 'top'", type=str, default="left") args = parser.parse_args() mat = init_material(args.material) g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) g.feed(mat['feed_rate']) g.absolute() g.move(x=0, y=0, z=0) g.relative() rectangleTool(g, mat, args.depth, args.dx, args.dy, args.fillet, args.origin, args.align, args.inside_fill) g.spindle() if __name__ == "__main__": main()<file_sep>from material import init_material from mecode import G from hole import hole from utility import nomad_header, CNC_TRAVEL_Z, GContext, travel import argparse BASE_OF_HEAD = 6.0 # FIXME D_OF_HEAD = 10.5 # FIXME D_OF_BOLT = 6.2 # FIXME IN_TO_MM = 25.4 def bolt(g, mat, stock_height, x, y): travel(g, mat, x=x*IN_TO_MM, y=y*IN_TO_MM) g.feed(mat['travel_feed']) g.move(z=0) hole(g, mat, -(stock_height - BASE_OF_HEAD), d=D_OF_HEAD) hole(g, mat, -(stock_height - BASE_OF_HEAD) - 2.0, d=D_OF_BOLT) def board(g, mat, stock_height): with GContext(g): g.absolute() bolt(g, mat, stock_height, 0.5, 0.5) bolt(g, mat, stock_height, 0.5, 7.5) bolt(g, mat, stock_height, 7.5, 0.5) bolt(g, mat, stock_height, 7.5, 7.5) bolt(g, mat, stock_height, 4.75, 4.0) # get back to the origin, assuming the next step is a plane travel(g, mat, x=0, y=0) g.move(z=0) def main(): parser = argparse.ArgumentParser( description='Cut holes for wasteboard. Assumes bit at lower left of plate.') parser.add_argument('material', help='the material to cut (wood, aluminum, etc.)') parser.add_argument('stock_height', help='height of stock. z=0 is top of stock.', type=float) args = parser.parse_args() mat = init_material(args.material) g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) nomad_header(g, mat, CNC_TRAVEL_Z) board(g, mat, args.stock_height) g.spindle() if __name__ == "__main__": main() <file_sep>from hole import * from mecode import G from material import * FRONT_PLATE = True BACK_PLATE = False mat = init_material(sys.argv[1]) tool_size = mat['tool_size'] if FRONT_PLATE or BACK_PLATE: inner_d = 5 - tool_size else: inner_d = 11 - tool_size outer_d = 32 + tool_size cut_depth = -2.0 theta0 = math.radians(-20) # theta0 -> 1 is the window to the center theta1 = math.radians(20) theta2 = math.radians(165) # theta2 -> 3 is the inset theta3 = math.radians(245) outer_r = outer_d / 2 inner_r = inner_d / 2 inset_r = outer_r - 5 rod_d = 3.5 rod_x = 0 rod_y = 11 if FRONT_PLATE: channel_d = 4.6 else: channel_d = 5.8 channel_x = -8 channel_y = 8 g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) g.comment("Material: " + mat['name']) g.comment("Tool Size: " + str(mat['tool_size'])) def x_r(theta, r): return math.cos(theta) * r def y_r(theta, r): return math.sin(theta) * r def g_arc(g, theta, r, direction, z=None): x = x_r(theta, r) y = y_r(theta, r) i = -g.current_position['x'] j = -g.current_position['y'] if z is not None: g.arc2(x=x, y=y, i=i, j=j, direction=direction, helix_dim='z', helix_len=z) else: g.arc2(x=x, y=y, i=i, j=j, direction=direction) pass def g_move(g, theta, r, z=None): if z is None: g.abs_move(x=x_r(theta, r), y=y_r(theta, r)) else: g.abs_move(x=x_r(theta, r), y=y_r(theta, r), z=z) def path(g, z, dz): g_move(g, theta0, inner_r, z + dz / 2) g_arc(g, theta1, inner_r, 'CW') g_move(g, theta1, outer_r, z + dz) g_arc(g, theta2, outer_r, 'CCW') g_move(g, theta2, inset_r) g_arc(g, theta3, inset_r, 'CCW') g_move(g, theta3, outer_r) g_arc(g, theta0, outer_r, 'CCW') # rods that hold it together hole_abs(g, mat, cut_depth, rod_d / 2, rod_x, rod_y) hole_abs(g, mat, cut_depth, rod_d / 2, -rod_x, -rod_y) # channel for wires hole_abs(g, mat, cut_depth, channel_d / 2, channel_x, channel_y) g.feed(mat['feed_rate']) g.absolute() g.abs_move(z=CNC_TRAVEL_Z) g_move(g, theta0, inner_r) g.spindle('CW', mat['spindle_speed']) g.abs_move(z=0) steps = calc_steps(cut_depth, -mat['pass_depth']) run_3_stages_abs(path, g, steps) <file_sep>import sys import argparse import pprint pp = pprint.PrettyPrinter() materials = [ { "id": "np883", "machine": "Nomad Pro 883", "travel_feed": 2500, "travel_plunge": 400, "materials": [ {"name": "acrylic", "quality": "Carbide3D test", "tool_size": 3.175, "pass_depth": 0.49, "spindle_speed": 9000, "feed_rate": 1100, "plunge_rate": 355}, {"name": "hdpe", "quality": "Carbide3D test", "tool_size": 3.175, "pass_depth": 0.51, "spindle_speed": 6250, "feed_rate": 2000, "plunge_rate": 500}, {"name": "polycarb", "quality": "Carbide3D test", "tool_size": 3.175, "pass_depth": 0.33, "spindle_speed": 9000, "feed_rate": 1300, "plunge_rate": 450}, {"name": "pine", "quality": "Verified Carbide3D test", "tool_size": 3.175, "pass_depth": 0.76, "spindle_speed": 4500, "feed_rate": 2100, "plunge_rate": 500}, {"name": "pine", "quality": "Test run (success after broken bit)", "tool_size": 2.0, "pass_depth": 0.30, "spindle_speed": 4500, "feed_rate": 800, "plunge_rate": 500}, {"name": "pine", "quality": "Guided guess", "tool_size": 1.0, "pass_depth": 0.20, "spindle_speed": 4500, "feed_rate": 400, "plunge_rate": 300}, {"name": "plywood", "quality": "carbide data tested", "tool_size": 3.175, "pass_depth": 0.86, "spindle_speed": 7800, "feed_rate": 1200, "plunge_rate": 500}, {"name": "hardwood", "quality": "Carbide3D test, experiment", "tool_size": 3.175, "pass_depth": 0.40, "spindle_speed": 9200, "feed_rate": 900, "plunge_rate": 300}, {"name": "hdpe", "quality": "Carbide3D test", "tool_size": 3.175, "pass_depth": 0.50, "spindle_speed": 6250, "feed_rate": 2400, "plunge_rate": 200}, {"name": "hdpe", "quality": "Guess - bantam data", "tool_size": 1.0, "pass_depth": 0.30, "spindle_speed": 6250, "feed_rate": 600, "plunge_rate": 100}, {"name": "evafoam", "quality": "Wild guess", "tool_size": 1.0, "pass_depth": 1.0, "spindle_speed": 6250, "feed_rate": 600, "plunge_rate": 100}, {"name": "copper", "quality": "guess from brass.", "tool_size": 3.175, "pass_depth": 0.30, "spindle_speed": 9200, "feed_rate": 250, "plunge_rate": 25, "comment": "copper"}, {"name": "brass230", "quality": "Guess from 260.", "tool_size": 3.175, "pass_depth": 0.30, "spindle_speed": 9200, "feed_rate": 250, "plunge_rate": 25, "comment": "red brass"}, {"name": "brass260", "quality": "Test and refined. Plunge can lock bit.", "tool_size": 3.175, # there used to be other sizes, but good luck with any other bit. "pass_depth": 0.20, # wrestle with this value. Was 0.25. "spindle_speed": 9200, "feed_rate": 200, "plunge_rate": 25, "comment": "cartridge brass"}, {"name": "brass360", "quality": "From 260 + refined.", "tool_size": 3.175, "pass_depth": 0.10, "spindle_speed": 9200, "feed_rate": 220, "plunge_rate": 25, "comment":"free machining brass"}, {"name": "aluminum", "quality": "Carbide3D test", "tool_size": 3.175, "pass_depth": 0.30, # tried .30 fine with lubricant. aggressive w/o 0.25 more conservative "spindle_speed": 9200, "feed_rate": 120, "plunge_rate": 25}, {"name": "aluminum", "quality": "implied from othermill data", "tool_size": 2.0, "pass_depth": 0.25, "spindle_speed": 9200, "feed_rate": 120, "plunge_rate": 25}, {"name": "aluminum", "quality": "implied from othermill data", "tool_size": 1.0, "pass_depth": 0.15, "spindle_speed": 9200, "feed_rate": 100, "plunge_rate": 10}, # suggested: 55 {"name": "fr", "quality": "othermill data", "tool_size": 3.175, "pass_depth": 0.40, # kicked up from 0.13 the 0.30. "spindle_speed": 12000, "feed_rate": 360, "plunge_rate": 80, # kicked up from 30 (sloww....) "comment": "printed circuit board"}, {"name": "fr", "quality": "othermill data", "tool_size": 1.6, "pass_depth": 0.70, "spindle_speed": 12000, "feed_rate": 360, "plunge_rate": 80, "comment": "printed circuit board"}, {'name': 'fr', 'quality': 'significant testing', 'tool_size': 1.0, 'pass_depth': 0.60, # up 50% so slow before 'spindle_speed': 12000, 'feed_rate': 202.5, 'plunge_rate': 65.0, 'comment': 'printed circuit board' }, {"name": "fr", "quality": "othermill data guess", "tool_size": 0.8, "pass_depth": 0.30, "spindle_speed": 12000, "feed_rate": 150, "plunge_rate": 60, "comment": "printed circuit board"}, ] }, { "id": "em", "machine": "Eleksmill", "travel_feed": 1000, "travel_plunge": 100, "materials": [ {"name": "wood", "tool_size": 3.125, "feed_rate": 1000, "pass_depth": 0.5, "spindle_speed": 1000, "plunge_rate": 100}, {"name": "aluminum", "tool_size": 3.125, "feed_rate": 150, "pass_depth": 0.05, # woh. slow and easy for aluminum "spindle_speed": 1000, "plunge_rate": 12}, {"name": "fr", "tool_size": 1.0, "feed_rate": 200, # was: 280 felt a little fast? "pass_depth": 0.15, "spindle_speed": 1000, "plunge_rate": 30}, {"name": "fr", "tool_size": 0.8, "feed_rate": 160, "pass_depth": 0.15, "spindle_speed": 1000, "plunge_rate": 30}, {"name": "air", "tool_size": 3.125, "feed_rate": 1200, "pass_depth": 2.0, "spindle_speed": 0, "plunge_rate": 150}] } ] def find_machine(machine_ID: str): machine = None for m in materials: if m['id'] == machine_ID: machine = m break return machine def get_quality(m): if 'quality' in m: return m['quality'] return '(not specified)' def preprocess_material(m, machine, tool_size): m['travel_feed'] = machine["travel_feed"] m['travel_plunge'] = machine["travel_plunge"] m['tool_size'] = tool_size for key, value in m.items(): if type(value) is float: m[key] = round(value, 5) return m def material_data(machine_ID: str, material: str, tool_size: float): machine = find_machine(machine_ID) if machine is None: raise RuntimeError("Machine " + machine_ID + " not found.") min_greater_size = 1000.0 min_greater_mat = None max_lesser_size = 0 max_lesser_mat = None print("Machine:", machine_ID, "Material:", material, "Size:", tool_size) for m in machine['materials']: if material == m['name']: if m['tool_size'] == tool_size: return_m = m.copy() return_m['quality'] = 'match: ' + get_quality(m) return preprocess_material(return_m, machine, tool_size) if m['tool_size'] >= tool_size and m['tool_size'] < min_greater_size: min_greater_size = m['tool_size'] min_greater_mat = m if m['tool_size'] <= tool_size and m['tool_size'] > max_lesser_size: max_lesser_size = m['tool_size'] max_lesser_mat = m if (not min_greater_mat) and (not max_lesser_mat): raise RuntimeError("No material found") if min_greater_mat and max_lesser_mat and (min_greater_size != max_lesser_size): # interpolate. cool. fraction = (tool_size - max_lesser_size) / (min_greater_size - max_lesser_size) m = max_lesser_mat.copy() params = ['tool_size', 'feed_rate', 'pass_depth', 'plunge_rate'] for p in params: m[p] = max_lesser_mat[p] + fraction * (min_greater_mat[p] - max_lesser_mat[p]) m['quality'] = '{}%: {} < {}% {}'.format(round((1.0 - fraction) * 100.0, 0), get_quality(max_lesser_mat), round(fraction * 100, 0), get_quality(min_greater_mat)) return preprocess_material(m, machine, tool_size) elif min_greater_mat is not None: m = min_greater_mat.copy() m['quality'] = '{} under: {}'.format(round(m['tool_size'] - tool_size, 2), get_quality(m)) return preprocess_material(m, machine, tool_size) else: m = max_lesser_mat.copy() m['quality'] = '{} over: {}'.format(round(tool_size - m['tool_size'], 2), get_quality(m)) return preprocess_material(m, machine, tool_size) def parse_name(name: str): material = None tool_size = None dash0 = name.find('-') dash1 = name.find('-', dash0 + 1) if dash1 > 0: machine = name[0:dash0] material = name[dash0 + 1:dash1] tool_size = float(name[dash1 + 1:]) elif dash0 > 0: machine = name[0:dash0] material = name[dash0 + 1:] else: machine = name # print("machine= " + machine) # print("material= " + material) # print("tool= " + str(tool_size)) return [machine, material, tool_size] def init_material(name: str): info = parse_name(name) tool_size = 3.125 if info[2] is not None: tool_size = info[2] return material_data(info[0], info[1], tool_size) def main(): if len(sys.argv) == 1: print("""List information about the machines and materials. If not machine is provided, then will list the available machines. Format is the same as used by the command line. Examples: 'material list' 'material em' 'material em-wood' 'material np883-pine-3.0'.""") machine = None info = [None, None] if len(sys.argv) == 2: info = parse_name(sys.argv[1]) # print(info) if info is not None: machine = find_machine(info[0]) if machine and info[1] and info[2]: data = material_data(info[0], info[1], info[2]) print("*** Millimeters ***") pp.pprint(data) # Conversion to inches, when working with grumpy software. data_in = data.copy() data_in['feed_rate'] = round(data_in['feed_rate'] / 25.4, 5) data_in['pass_depth'] = round(data_in['pass_depth'] / 25.4, 5) data_in['plunge_rate'] = round(data_in['plunge_rate'] / 25.4, 5) data_in['tool_size'] = round(data_in['tool_size'] / 25.4, 4) data_in['travel_feed'] = round(data_in['travel_feed'] / 25.4, 2) data_in['travel_plunge'] = round(data_in['travel_plunge'] / 25.4, 2) print("") print("*** Inches ***") pp.pprint(data_in) elif machine and info[1]: for m in machine["materials"]: if m["name"] == info[1]: print(m["name"] + " " + str(m["tool_size"])) elif machine: mat_set = set() for m in machine["materials"]: s = m['name'] if 'comment' in m: s += " (" + m['comment'] + ")" mat_set.add(s) for s in mat_set: print(s) else: for m in materials: print(m["id"] + " " + m["machine"]) if __name__ == "__main__": main() <file_sep># The cut for the "Aquatic" saber. # Center hole - narrow passage - display from hole import * from material import * # start at hole center, # all measurements from the hole center, # origin at hole center CNC_STD_TOOL = 3.175 # 1/8 inch bit TOOLSIZE = CNC_STD_TOOL CYLINDER_DIAMETER = 37 HOLE_DIAMETER = 16 HOLE_DEPTH = -8 BODY_DEPTH = -5 NECK_W = 11 DISPLAY_W = 15 DISPLAY_X0 = 15 DISPLAY_X1 = 35 FILLET = 1 mat = init_material("wood") halfTool = TOOLSIZE / 2 crad = CYLINDER_DIAMETER / 2 g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None) g.abs_move(0, 0, 0) hole(g, mat, HOLE_DEPTH, TOOLSIZE, HOLE_DIAMETER/2) g.abs_move(0, 0, 0) # give ourselves 10 seconds to rest, opportunity to pause the job. g.dwell(10) def path(g, plunge): if plunge > 0: raise RuntimeError("positive plunge:" + str(plunge)) # Really tricky in relative. Had to sketch it all out, and # even then hard to be sure everything added correctly. # Much easier in absolute. Although still needed to sketch it out. # ...of course the plunge logic won't work if absolute. Grr. And # absolute turns out to be tricky as well. zNeck = z_on_cylinder(NECK_W / 2 - halfTool, crad) zDisplay = z_on_cylinder(DISPLAY_W / 2 - halfTool, crad) dy0 = NECK_W/2 - halfTool dx0 = DISPLAY_X0 - FILLET dy1 = DISPLAY_W/2 - NECK_W/2 - FILLET dx1 = DISPLAY_X1 - DISPLAY_X0 - TOOLSIZE g.move(y=dy0, z=zNeck) g.move(x=dx0, z=plunge/2) g.arc(x=FILLET, y=FILLET, direction='CCW', radius=FILLET) # technically there should be a z change here, but close enough. g.move(y=dy1, z=zDisplay - zNeck) g.move(x=dx1) g.arc(y=-(DISPLAY_W - TOOLSIZE), z=0, direction='CCW', radius=crad) g.move(x=-dx1) g.move(y=dy1, z=zNeck - zDisplay) g.arc(x=-FILLET, y=FILLET, direction='CCW', radius=FILLET) g.move(x=-dx0, z=plunge/2) g.move(y=dy0, z=-zNeck) steps = calc_steps(BODY_DEPTH, -mat['pass_depth']) run_3_stages(path, g, steps) g.move(z=-BODY_DEPTH) # up to the starting point g.spindle() g.abs_move(0, 0, 0) <file_sep># The cut for the "Sisters" saber-staff (2nd version). from hole import hole from material import init_material from rectangle import rectangle from utility import CNC_TRAVEL_Z from mecode import G # start at transition line TOOLSIZE = 3.175 Y0 = 27.5 D0 = 16.0 Y1 = 7.5 D1 = 11.0 W = 15 H = 8.5 Y2 = -8.4 - H mat = init_material("np883-aluminum-3.175") HALFTOOL = TOOLSIZE / 2 g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) g.absolute() g.feed(mat['travel_feed']) g.move(z=CNC_TRAVEL_Z) g.move(y=Y0) g.spindle('CW', mat['spindle_speed']) hole(g, mat, -10, D0/2) g.move(y=Y1) hole(g, mat, -10, D1/2) g.move(x=-W/2 + HALFTOOL, y=Y2 + HALFTOOL) g.move(z=0) rectangle(g, mat, -8, W - TOOLSIZE, H - TOOLSIZE) g.move(z=CNC_TRAVEL_Z) g.spindle() g.move(x=0, y=0)<file_sep>import sys from hole import hole from utility import * from material import init_material from mecode import G mat = init_material(sys.argv[1]) g = G(outfile='path.nc', aerotech_include=False, header=None, footer=None, print_lines=False) nomad_header(g, mat, CNC_TRAVEL_Z) # travel(g, mat, x=5, y=5) # hole(g, mat, -5, d=5.0, offset="outside", fill=False, z=-CNC_TRAVEL_Z) g.absolute() travel(g, mat, x=5, y=5) hole(g, mat, -5, d=5.0, offset="outside", fill=False, z=0)
893137e711d8eb2cdd0da25c261cde52f74da311
[ "Markdown", "Python" ]
15
Python
leethomason/saberCNC
f59d429e5abcd97f773a5992ec3bc1bdc5ad5ded
4193c422b6610947175dbb6187910a76de98ad58
refs/heads/master
<file_sep>"use strict"; var app = app || {}; app.hud = { sizeLeft: undefined, draggingSize: undefined, canPlacePlatform: true, text: "", draw : function(ctx, dragPhase) { ctx.save(); if(app.dragPhase) { // Update HUD text this.text = "Drag Stage"; // Draw the amount of platforms the player can still place (based on platform width) if(this.draggingSize*2 > this.sizeLeft) { this.canPlacePlatform = false; ctx.fillStyle = "rgba(255,0,0, .25)"; ctx.fillRect(225, 20, this.sizeLeft, 25); } else { this.canPlacePlatform = true; ctx.fillStyle = "rgba(30,144,255, .25)"; ctx.fillRect(225, 20, this.sizeLeft, 25); ctx.fillStyle = "rgba(30,144,255, .25)"; ctx.fillRect(225, 20, this.sizeLeft - this.draggingSize*2, 25); } ctx.restore(); } else if(app.jumpPhase) { // Update HUD text this.text = "Jump Stage"; } } };<file_sep>"use strict"; var app = app || {}; app.Gate = function(){ function Gate(x,y){ this.x = x; this.y = y; this.width = 50; this.height = 50; this.color = "red"; }; var p = Gate.prototype; p.draw = function(ctx) { var halfW = this.width/2; var halfH = this.height/2; if(!this.image) { ctx.save(); ctx.fillStyle = this.color; ctx.fillRect(this.x - halfW, this.y - halfH, this.width, this.height); ctx.restore(); } else { ctx.drawImage(this.image, this.x-halfW, this.y-halfH); } } return Gate; }();
fb747f97043ecfc310752c94a502240d7f0278b5
[ "JavaScript" ]
2
JavaScript
andrebelanger/DragAndJump
e2dc99672e1637a24611f78bd28c9e865c812bd6
c52e4074b0c3c023bf8224ff5c8aa7c753b359cb
refs/heads/master
<file_sep>import React,{useState} from 'react' import './style.css'; import {Link, useHistory} from 'react-router-dom'; import api from '../../services/api'; import heroesImg from '../../assets/heroes.png'; import logoImg from '../../assets/logo.svg'; import { FiLogIn } from "react-icons/fi"; export default function Login(){ const[id, setID]=useState(''); const historico= useHistory(); async function Logon(e){ e.preventDefault(); try{ const response= await api.post('login', {id}); console.log(response) localStorage.setItem('ongId',id); localStorage.setItem('ongNome',response.data.nome); historico.push('/ong'); }catch(erro){ alert(`Erro ao tentar fazer login. Erro: ${erro}`); } } return(<div className="login-container"> <section className="form"> <img src={logoImg} alt="Seja um Heroi"></img> <form onSubmit={Logon}> <h1>Faça seu Login</h1> <input placeholder="Digite sua ID" value={id} onChange={e=>setID(e.target.value)} /> <button type="submit" className="button">Entrar</button> <Link className="back-link" to="/registro"> <FiLogIn size={16} color="#E02041" /> Quero me registrar </Link> </form> </section> <img src={heroesImg} alt="Herois"></img> </div>); }<file_sep>import React,{useState} from 'react'; import './style.css'; import {FiArrowLeft} from 'react-icons/fi'; import { Link, useHistory } from "react-router-dom"; import logoImg from '../../assets/logo.svg'; import api from '../../services/api'; export default function Caso(){ let ongId=null; ongId= localStorage.getItem('ongId'); const historico= useHistory(); const [titulo, setTitulo]=useState(''); const [descricao, setDescricao]=useState(''); const [valor, setValor]=useState(''); const data={ titulo, descricao, valor } async function addCaso(e){ e.preventDefault(); try{ await api.post('casos',data,{ headers:{ Authorization:ongId } }); historico.push('/ong'); }catch(erro){ alert(`Houve um erro ao tentar cadastrar caso. Erro: ${erro}`); } } return(<div className="caso-container"> <div className="content"> <section> <img src={logoImg} alt="Seja um Heroi"></img> <h1>Registro gratuito</h1> <p>Descreva seu caso, assim mais heróis poderão ajudar.</p> <Link className="back-link" to="/ong"> <FiArrowLeft size={16} color="#E02041" /> Voltar </Link> </section> <form onSubmit={addCaso}> <input type="text" placeholder="Título do caso" value={titulo} onChange={e=>setTitulo(e.target.value)} /> <textarea placeholder="Descrição" value={descricao} onChange={e=>setDescricao(e.target.value)} /> <input placeholder="Valor em R$" value={valor} onChange={e=>setValor(e.target.value)} /> <button className="button">Cadastrar</button> </form> </div> </div>) }
dafa09bf7185fa76303009b6a31d90bb375adfc6
[ "JavaScript" ]
2
JavaScript
cristovao1985/bethehero
769c1e4fb8d6b734eff93aac1a867c70193bf089
b5edbad9d681967d5f7bb96a7033508294727efc
refs/heads/master
<file_sep>import tkinter as tk import windnd from PIL import Image, ImageTk from tkinter import messagebox, ttk from tkinter.filedialog import askopenfilename import matplotlib.pyplot as plt import math import cv2 import numpy as np import requests import os import zipfile from FCRN import predict from MiDaS import run from MegaDepth import demo # 窗口 window = tk.Toplevel() window.title('深度估计') # 定义canvas的height和width width = 400 height = 300 # 输入部分 # “输入”标签 label_in = tk.Label(window, text='输入') label_in.grid(row=1, column=1) # 帆布 canvas_in = tk.Canvas(window, bg='white', width=width, height=height) canvas_in.create_text(200, 150, text='拖拽图片到此处', fill='grey', anchor='center') canvas_in.grid(row=2, column=1, rowspan=2) # 初始化全局变量 """image_in:输入图片; depth:深度图; rec:点""" filepath, image_in, depth, rec_red, line_red, rec_red2 = None, None, None, None, None, None """起点横、纵坐标""" start_x, start_y = 0, 0 """调整系数""" alter_dep_para = 1 alter_plain_para = 1 """距离""" text_dis, plain_dis, dep_dis, max_dep_dis = None, None, None, None """记录序号""" record_index = 1 def show_input(file): global filepath, image_in for item in file: filepath = ''.join(item.decode('gbk')) image_open = Image.open(filepath) image_resize = image_open.resize((width, height)) image = ImageTk.PhotoImage(image_resize) canvas_in.create_image(0, 0, anchor='nw', image=image) canvas_in.image = image image_in = image_open windnd.hook_dropfiles(window, func=show_input) '''输入:下载网址,保存文件路径''' def download_weight(url, path): name = url.split('/')[-1] # 获取文件名 response = requests.get(url, stream=True) # 请求链接后保存到变量respone中,设置为流读取(适用于大文件下载) chunk_size = 1024 # 每次下载数据块大小 content_size = int(response.headers['content-length']) # 下载文件大小 download_window = tk.Tk() # 下载窗口初始化 download_window.title('权重下载') label_download = tk.Label(download_window, text='下载进度:') label_download.grid(row=1, column=1) canvas_download = tk.Canvas(download_window, width=600, height=16, bg='white') canvas_download.grid(row=1, column=2) fill_line = canvas_download.create_rectangle(1.5, 1.5, 0, 23, width=0, fill='green') # 进度条 raise_data = 600/(content_size/chunk_size) # 进度条增量大小 with open(path+'/'+str(name), 'wb') as f: # 将下载的数据写入文件 n = 0 for chunk in response.iter_content(chunk_size=chunk_size): # 以1024个字节为一个数据块进行读取 if chunk: # 如果chunk不为空 f.write(chunk) n = n + raise_data canvas_download.coords(fill_line, (0, 0, n, 60)) # 更新进度条 download_window.update() '''输入:压缩包路径,解压路径''' def unzip_weight(zip_src, dst_dir): weight_zip = zipfile.ZipFile(zip_src, 'r') for file in weight_zip.namelist(): # 获取压缩包里所有文件 weight_zip.extract(file, dst_dir) # 循环解压文件到指定目录 def show_output(): model = askopenfilename() global filepath, depth, max_dep_dis, save if para.get() == 'A': if not os.path.exists('FCRN/NYU_FCRN.ckpt.data-00000-of-00001'): # 如果参数文件不存在 messagebox.showinfo('提示', '第一次使用需要下载相关权重文件,点击确定开始下载') download_weight('http://campar.in.tum.de/files/rupprecht/depthpred/NYU_FCRN-checkpoint.zip', 'FCRN') unzip_weight('FCRN/NYU_FCRN-checkpoint.zip', 'FCRN') # os.remove('FCRN/NYU_FCRN-checkpoint.zip') # Save the file and let the user choose to delete it or not predict.predict(model_data_path=model, image_path=filepath) elif para.get() == 'B': image_in_path = 'MiDaS/input/' + filepath.split('\\')[-1] # 将图片保存到MiDas/input文件夹 image_in.save(image_in_path) # depth, image_result = run.new_run(image_in_path, 'MiDaS/output', 'MiDaS/model.pt') depth, image_result = run.new_run(image_in_path, 'MiDaS/output', model) max_dep_dis = depth.max() - depth.min() plt.imsave('pred.jpg', image_result) elif para.get() == 'C': image_in_path = 'MegaDepth/demo_img/demo.jpg' image_in.save(image_in_path) # 将图片保存到指定文件夹 demo.run() image_result = Image.open('MegaDepth/demo_img/demo1.jpg') plt.imsave('pred.jpg', image_result) else: messagebox.showwarning('警告', '请选择参数') return image_open = Image.open('pred.jpg') image_resize = image_open.resize((width, height)) image = ImageTk.PhotoImage(image_resize) canvas_out.create_image(0, 0, anchor='nw', image=image) canvas_out.image = image save = True # 表示可保存生成图片 img_range = cv2.imread('pred.jpg', 0) # 读取图像 img_range.resize((image_in.size[0], image_in.size[1])) # 将图像放缩为输入框内的大小 depth = np.copy(img_range) # 获得灰度值 def save_output(): if save: filename = filedialog.asksaveasfilename(defaultextension='.jpg', # 默认文件扩展名 filetypes=[('JPG', '*.jpg')], # 设置文件类型下拉菜单里的选项 initialdir='', # 对话框中默认的路径 initialfile='深度估计', # 对话框中初始化显示的文件名 parent=window, title='另存为') if filename != '': im = Image.open('pred.jpg') im.save(filename) else: messagebox.showerror('错误', '未生成输出') # 参数部分 # “参数”标签 label_para = tk.Label(window, text='参数') label_para.grid(row=1, column=2) # 单选框架 frame_para = tk.Frame(window) frame_para.grid(row=2, column=2) """# 复选框 check_para = tk.IntVar() check_pick = tk.Checkbutton(window, text='选择第二点', variable=check_para, height=2, width=20, onvalue=0, offvalue=1) check_pick.grid(row=4, column=2)""" # 单选按钮 para = tk.StringVar() radiobutton1 = tk.Radiobutton(frame_para, text='FCRN', variable=para, value='A') radiobutton1.pack(anchor='w') radiobutton2 = tk.Radiobutton(frame_para, text='MiDaS', variable=para, value='B') radiobutton2.pack(anchor='w') radiobutton3 = tk.Radiobutton(frame_para, text='MegaDepth', variable=para, value='C') radiobutton3.pack(anchor='w') # 焦距输入 label_focal = tk.Label(master=frame_para, text='焦距/mm') label_focal.pack(pady=10) entry_focal = tk.Entry(master=frame_para, width=10) entry_focal.pack() # “确认”按钮 button_para = tk.Button(master=frame_para, text='选择参数', command=show_output) button_para.pack(pady=20) # 按钮框架 frame_button = tk.Frame(window) frame_button.grid(row=3, column=2) # “保存”按钮 button_save = tk.Button(frame_button, text='保存图片', command=save_output) button_save.grid(row=2, column=1) # 调整系数 label_plain_alter = tk.Label(master=frame_para, text='平面系数:' + str(alter_plain_para)) label_plain_alter.pack(pady=0) label_dep_alter = tk.Label(master=frame_para, text='深度系数:' + str(alter_dep_para)) label_dep_alter.pack(pady=0) def check_num1(b): """检测输入是否为数字""" lst = list(entry_plain_alter.get()) for i in range(len(lst)): if lst[i] not in ".0123456789": entry_plain_alter.delete(i, i + 1) if lst.count('.') == 2: entry_plain_alter.delete(len(lst) - 1, len(lst)) def check_num2(a): """检测输入是否为数字""" lst = list(entry_alter.get()) for i in range(len(lst)): if lst[i] not in ".0123456789": entry_alter.delete(i, i + 1) if lst.count('.') == 2: entry_alter.delete(len(lst) - 1, len(lst)) # 调整框架 frame_alter = tk.Frame(window) frame_alter.grid(row=4, column=2) # 调整距离 label_alter_depth = tk.Label(master=frame_alter, text='调整平面距离为(cm):') label_alter_depth.grid(row=1, column=1) entry_plain_alter = tk.Entry(master=frame_alter, width=10) entry_plain_alter.bind('<KeyRelease>', check_num1) entry_plain_alter.grid(row=1, column=2) label_alter_depth = tk.Label(master=frame_alter, text='调整距离为(cm):') label_alter_depth.grid(row=3, column=1) entry_alter = tk.Entry(master=frame_alter, width=10) entry_alter.bind('<KeyRelease>', check_num2) entry_alter.grid(row=3, column=2) # 输出部分 # “输出”标签 label_out = tk.Label(window, text='输出') label_out.grid(row=1, column=3) # 帆布 canvas_out = tk.Canvas(window, bg='white', width=width, height=height) canvas_out.grid(row=2, column=3, rowspan=2) # 选点部分 # 第一点 frame_point1 = tk.Frame(window) label_axis1 = tk.Label(frame_point1, text='坐标:') label_axis1.grid(row=1, column=1) label_axis_content1 = tk.Label(frame_point1, text='') label_axis_content1.grid(row=1, column=2) frame_point1.grid(row=4, column=1) label_depth1 = tk.Label(frame_point1, text='深度:') label_depth1.grid(row=2, column=1) label_depth_content1 = tk.Label(frame_point1, text='') label_depth_content1.grid(row=2, column=2) # 第二点 frame_point2 = tk.Frame(window) label_axis2 = tk.Label(frame_point2, text='坐标:') label_axis2.grid(row=1, column=1) label_axis_content2 = tk.Label(frame_point2, text='') label_axis_content2.grid(row=1, column=2) frame_point2.grid(row=4, column=3) label_depth2 = tk.Label(frame_point2, text='深度:') label_depth2.grid(row=2, column=1) label_depth_content2 = tk.Label(frame_point2, text='') label_depth_content2.grid(row=2, column=2) def click(event): """点击canvas_in,得到所选点的信息""" global rec_red, start_x, start_y try: start_x, start_y = event.x, event.y x = round(event.x * image_in.size[0] / width) y = round(event.y * image_in.size[1] / height) """限定x,y的范围""" x = max(x, 0) x = min(x, image_in.size[0] - 1) y = max(y, 0) y = min(y, image_in.size[1] - 1) except: return try: canvas_in.delete(rec_red, rec_red2, line_red) canvas_in.delete(text_dis) except: return rec_red = canvas_in.create_rectangle(event.x - 2, event.y - 2, event.x + 2, event.y + 2, outline='red', fill='red') label_axis_content1.config(text='({0}, {1})'.format(x, y)) if depth is not None: label_depth_content1.config(text='{0}'.format(depth[y, x])) else: return def move(event): """移动canvas_in,得到所选点的信息""" global line_red, start_x, start_y, rec_red2, text_dis try: x1 = round(start_x * image_in.size[0] / width) y1 = round(start_y * image_in.size[1] / height) x2 = round(event.x * image_in.size[0] / width) y2 = round(event.y * image_in.size[1] / height) """限定x,y的范围""" x1 = min(max(x1, 0), image_in.size[0] - 1) y1 = min(max(y1, 0), image_in.size[1] - 1) x2 = min(max(x2, 0), image_in.size[0] - 1) y2 = min(max(y2, 0), image_in.size[1] - 1) except: return try: canvas_in.delete(line_red) canvas_in.delete(rec_red2) canvas_in.delete(text_dis) except: return line_red = canvas_in.create_line(start_x, start_y, event.x, event.y, fill='red', width=2) rec_red2 = canvas_in.create_rectangle(event.x - 2, event.y - 2, event.x + 2, event.y + 2, outline='red', fill='red') label_axis_content2.config(text='({0}, {1})'.format(x2, y2)) if depth is not None: label_depth_content2.config(text='{0}'.format(depth[y2, x2])) text_x = (start_x + event.x) // 2 text_y = (start_y + event.y) // 2 - 5 str_dis = get_dis(x1, y1, x2, y2) text_dis = canvas_in.create_text(text_x, text_y, text=str_dis, fill='red', font=('Helvetica', '20', 'bold')) # 显示距离 else: return return def release(event): global start_x, start_y, record_index try: x1 = round(start_x * image_in.size[0] / width) y1 = round(start_y * image_in.size[1] / height) x2 = round(event.x * image_in.size[0] / width) y2 = round(event.y * image_in.size[1] / height) """限定x,y的范围""" x1 = min(max(x1, 0), image_in.size[0] - 1) y1 = min(max(y1, 0), image_in.size[1] - 1) x2 = min(max(x2, 0), image_in.size[0] - 1) y2 = min(max(y2, 0), image_in.size[1] - 1) except: return if depth is not None: str_dis = get_dis(x1, y1, x2, y2) tree_view.insert('', 0, values=(str(record_index), '(' + str(x1) + ', ' + str(y1) + ')', '(' + str(x2) + ', ' + str(y2) + ')', str_dis)) record_index += 1 else: return def get_dis(x1, y1, x2, y2): """计算距离""" global alter_dep_para, alter_plain_para, plain_dis, dep_dis plain_dis = (x1 - x2)**2 + (y1 - y2)**2 dep_dis = abs(depth[y2, x2] - depth[y1, x1]) dis = math.sqrt(plain_dis * alter_plain_para + dep_dis * alter_dep_para) # 平面距离乘参数 + 深度差乘参数 if dis < 100: str_dis = str(round(dis, 2)) + 'cm' else: str_dis = str(round(dis / 100, 2)) + 'm' return str_dis def alter_plain_dis(): """修改平面距离""" global alter_plain_para, plain_dis, dep_dis, max_dep_dis get_plain_dis = entry_plain_alter.get() if get_plain_dis and plain_dis: get_plain_dis = float(get_plain_dis) if math.sqrt(dep_dis) / max_dep_dis < 0.02: alter_plain_para = (get_plain_dis**2) / plain_dis label_plain_alter.config(text='平面系数:' + str(alter_plain_para)) else: messagebox.showwarning('限制', '请选择同一平面上的两点进行调整') def alter_dis(): """修改距离""" global alter_dep_para, alter_plain_para, plain_dis, dep_dis get_real_dis = entry_alter.get() if get_real_dis and dep_dis: get_real_dis = float(get_real_dis) alter_dep_para = max((get_real_dis**2 - plain_dis * alter_plain_para) / dep_dis, 0) label_dep_alter.config(text='深度系数:' + str(alter_dep_para)) # 测距部分 # 调整距离按钮 button_para = tk.Button(master=frame_alter, text='确认调整', command=alter_plain_dis) button_para.grid(row=2, column=2) button_para = tk.Button(master=frame_alter, text='确认调整', command=alter_dis) button_para.grid(row=4, column=2) # 测距记录 record_frame = tk.Frame(window) record_frame.grid(row=5, column=1, columnspan=3) sbar = tk.Scrollbar(record_frame) tree_view = ttk.Treeview(record_frame, height=6) sbar.pack(side=tk.RIGHT, fill=tk.Y) tree_view.pack(pady=10, side=tk.LEFT, fill=tk.Y) sbar.config(command=tree_view.yview) tree_view.config(yscrollcommand=sbar.set) # 数据列的定义 tree_view["columns"] = ("#0", "one", "two", "three") tree_view.column("#0", width=50, minwidth=50, stretch=tk.NO) tree_view.column("one", width=200, minwidth=200, stretch=tk.NO) tree_view.column("two", width=200, minwidth=200, stretch=tk.NO) tree_view.column("three", width=150, minwidth=150, stretch=tk.NO) tree_view.heading("#0", text="序号", anchor='center') tree_view.heading("one", text="第一点坐标", anchor='center') tree_view.heading("two", text="第二点坐标", anchor='center') tree_view.heading("three", text="距离", anchor='center') canvas_in.bind('<Button-1>', click) canvas_in.bind("<B1-Motion>", move) canvas_in.bind("<ButtonRelease-1>", release) window.mainloop() <file_sep># Distance-measure-based-on-depth-estimation 2.0 ## 更新重点 1. 重写用户界面,其风格类似word,交互逻辑更为清晰,其结构如下 - 菜单栏 menu bar(暂无功能) - 工具栏 tool bar - **深度估计** - **距离测量**(暂无功能), - **可视化效果**(暂无功能) - 工作区 working area - 原图显示区 - 深度图显示区 - 状态栏 status bar - A点:坐标,深度 - B点:坐标,深度 - 两点距离 2. 整理代码,提高可读性,便于维护 - 将函数部分与界面部分分开,每个函数补充注释内容,使函数更容易理解 - 将`show_input`函数中关于打开并加载图片到工作区的部分分离出来单独写一个函数,这样`show_output`函数也可以调用这一部分,减少不必要的代码 - 规范`show_output`函数,识别用户选择的算法后,使用一个函数实现**保存深度图到根目录**、**返回深度值矩阵**两个功能(通过修改对应算法文件中的函数),再将深度图加载到工作区 > 目前仅完成**FCRN**函数的修改,**MiDaS**和**MegaDepth**已经在修改中,将会在后续版本中给出 <file_sep>import tkinter as tk from tkinter import ttk, filedialog, messagebox from PIL import Image, ImageTk import windnd from FCRN import predict from MiDaS import run from MegaDepth import demo # 全局变量 width = 600 # 帆布组件的宽度 height = 450 # 帆布组件的高度 input_path = None # 原图片路径 depth = None # 深度值矩阵 result = False # 生成深度图状态,若已生成深度图,则为True,可以保存 def show_image(image, canvas): """ 将图片加载到帆布中 :param images: 要加载的文件路径 :param canvas: 展示图片的帆布组件 :return: None """ image_open = Image.open(image) # 加载图片 image_resize = image_open.resize((width, height)) # 缩放图片 image_tk = ImageTk.PhotoImage(image_resize) # 利用PIL包将图片转化tkinter兼容的格式 canvas.create_image(0, 0, anchor='nw', image=image_tk) # 在canvas中显示图像 canvas.image = image_tk # 保留对图像对象的引用,使图像持续显示 return def show_input(images): """ 将拖拽的图片加载到原图帆布中 :param images: 拖拽获得的文件列表 :return: None """ global input_path input_path = images[0].decode() # 获取拖拽文件列表中第一个文件的路径(str类型) show_image(input_path, work_input_cv) # 将文件加载到原图帆布中 return def download_weight(): return def unzip_weight(): return def select_weight(*args): """ 选择算法后自动绑定对应的权重选项(暂未实现权重选择功能) :param args: 可变参数,没啥用 :return: None """ if tool_depth_cbb1.get() == 'FCRN': tool_depth_cbb2['value'] = 'NYU_FCRN.ckpt' elif tool_depth_cbb1.get() == 'MiDaS': tool_depth_cbb2['value'] = 'model.pt' elif tool_depth_cbb1.get() == 'MegaDepth': tool_depth_cbb2['value'] = 'best_generalization_net_G.pth' tool_depth_cbb2.current(0) # 设置初始权重选项 return def show_output(): """ 运行对应算法,返回深度值矩阵,将图片保存到根目录;再将图片加载到深度图帆布中;所有功能用一个函数搞定 :return: None """ global result, depth if tool_depth_cbb1.get() == 'FCRN': depth = predict.predict(model_data_path='FCRN/NYU_FCRN.ckpt', image_path=input_path) elif tool_depth_cbb1.get() == 'MiDaS': # 函数修改中:depth, _ = run.new_run(input_path=input_path, output_path='/', model_path='MiDaS/model.pt') return elif tool_depth_cbb1.get() == 'MegaDepth': # 函数修改中 return show_image('pred.jpg', work_output_cv) # 将生成图加载到深度图帆布中 result = True # 深度图已生成,可以保存 return def save_output(): """ 保存生成的深度图 :return: None """ if result: filename = filedialog.asksaveasfilename(defaultextension='.jpg', # 默认文件拓展名 filetypes=[('JPG', '*.jpg')], # 设置文件类型选项 initialdir='', # 默认路径 initialfile='深度估计', # 默认文件名 parent=window, # 父对话框 title='保存') if filename != '': # 取消保存时返回空字符 image = Image.open('pred.jpg') image.save(filename) else: messagebox.showerror('错误', '未生成深度估计图') return def measure_dist(): return # 窗口界面 window = tk.Tk() window.title('深度估计') # 菜单栏 menu bar menu = tk.Menu(window) window.config(menu=menu) menu_file = tk.Menu(menu) # 文件菜单 menu_file.add_command(label='打开') # 打开图片 menu_file.add_command(label='保存') # 保存图片 menu.add_cascade(label='文件', menu=menu_file) menu_help = tk.Menu(menu) # 帮助菜单 menu_help.add_command(label='说明') menu.add_cascade(label='帮助', menu=menu_help) # 工具栏 tool bar tool = tk.Frame(window) tool.pack(anchor='w') tool_depth = tk.LabelFrame(tool, text='深度估计', labelanchor='s') # 深度估计方法框架 tool_depth.pack(side='left', fill='y') tool_depth_lb1 = tk.Label(tool_depth, text='算法') # 算法 tool_depth_lb1.grid(row=1, column=1) tool_depth_cbb1 = ttk.Combobox(tool_depth, state='readonly') tool_depth_cbb1.grid(row=1, column=2) tool_depth_cbb1.bind('<<ComboboxSelected>>', select_weight) # 选择算法后自动绑定对应权重 tool_depth_cbb1['values'] = ('FCRN', 'MiDaS', 'MegaDepth') tool_depth_lb2 = tk.Label(tool_depth, text='权重') # 权重 tool_depth_lb2.grid(row=2, column=1) tool_depth_cbb2 = ttk.Combobox(tool_depth, state='readonly') tool_depth_cbb2.grid(row=2, column=2) tool_depth_bt = tk.Button(tool_depth, text='生成', command=show_output) tool_depth_bt.grid(row=1, column=3, rowspan=2) tool_dist = tk.LabelFrame(tool, text='距离测量', labelanchor='s') # 距离测量框架 tool_dist.pack(side='left', fill='y') tool_dist_lb1 = tk.Label(tool_dist, text='焦距') # 焦距 tool_dist_lb1.grid(row=1, column=1) tool_dist_etr = tk.Entry(tool_dist) tool_dist_etr.grid(row=1, column=2) tool_dist_lb10 = tk.Label(tool_dist, text='(cm)') tool_dist_lb10.grid(row=1, column=3) tool_dist_lb2 = tk.Label(tool_dist, text='比例尺') # 比例尺 tool_dist_lb2.grid(row=2, column=1) tool_dist_etr = tk.Entry(tool_dist) tool_dist_etr.grid(row=2, column=2) tool_visual = tk.LabelFrame(tool, text='可视化效果', labelanchor='s') # 可视化效果 tool_visual.pack(side='left', fill='y') tool_visual_lb = tk.Label(tool_visual, text='颜色') # 颜色 tool_visual_lb.grid(row=1, column=1) tool_visual_cbb = ttk.Combobox(tool_visual) tool_visual_cbb.grid(row=1, column=2) # 工作区域(主界面) working area work = tk.Frame(window) work.pack() work_input_cv = tk.Canvas(work, width=width, height=height, bg='white') # 原图帆布 work_input_cv.create_text(width / 2, height / 2, text='拖拽图片到此处', fill='grey', anchor='center') work_input_cv.pack(side='left') windnd.hook_dropfiles(work_input_cv, func=show_input) # 将拖拽图片与wa_input_cv组件挂钩 work_output_cv = tk.Canvas(work, width=width, height=height, bg='white') # 深度图帆布 work_output_cv.pack(side='right') # 状态栏 status bar status = tk.Frame(window) status.pack(anchor='e') status_message_lb1 = tk.Label(status, text='A点:') # A点信息 status_message_lb1.pack(side='left') status_message_lb11 = tk.Label(status, text='坐标:') status_message_lb11.pack(side='left') status_message_lb12 = tk.Label(status, text='深度:') status_message_lb12.pack(side='left') status_message_lb01 = tk.Label(status, text=' ') # 间隔 status_message_lb01.pack(side='left') status_message_lb2 = tk.Label(status, text='B点:') # B点信息 status_message_lb2.pack(side='left') status_message_lb21 = tk.Label(status, text='坐标:') status_message_lb21.pack(side='left') status_message_lb22 = tk.Label(status, text='深度:') status_message_lb22.pack(side='left') status_message_lb02 = tk.Label(status, text=' ') # 间隔 status_message_lb02.pack(side='left') status_message_lb3 = tk.Label(status, text='距离:') # 距离 status_message_lb3.pack(side='left') window.mainloop() <file_sep># Distance-measure-based-on-depth-estimation This is a repository of SRP2020 for bears. Here we make a software to measure the distance between any two points on any images based on some depth estimation algorithms. ## TODO list - [ ] A better UI - [ ] Use focal length into the calculating of distances ## parameter files: - put in MiDaS_master: [model.pt](https://drive.google.com/file/d/1zQAV1YODL9uaalPBOZGVGevctCYiY8-l/view?usp=sharing) - put in FRCN_master: - [NYU_FCRN.ckpt.data-00000-of-00001](https://drive.google.com/file/d/1TTDdFT3LcKoVTDCFEFTYarhOKpISmHPN/view?usp=sharing) - [NYU_FCRN.ckpt.meta](https://drive.google.com/file/d/1wdUh-22jxhBHLKHK8qvFsHXHncCoMsFO/view?usp=sharing) ## References [1] Ranftl, René, <NAME>, <NAME>, <NAME>, and <NAME>. “Towards Robust Monocular Depth Estimation: Mixing Datasets for Zero-Shot Cross-Dataset Transfer.” ArXiv:1907.01341 [Cs], December 6, 2019. http://arxiv.org/abs/1907.01341. [2] Laina, Iro, <NAME>, <NAME>, <NAME>, and <NAME>. “Deeper Depth Prediction with Fully Convolutional Residual Networks.” ArXiv:1606.00373 [Cs], September 19, 2016. http://arxiv.org/abs/1606.00373.
06f90551e27c6bbf39ed5930260e8d1eac5993d7
[ "Markdown", "Python" ]
4
Python
long-yy/Distance-measure-based-on-depth-estimation-1
8a36563058508b05d93a5d0fd3899461e28c079a
7cdfc70d1c4dcd9532ce97f4e0a6800b9a232446
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oriz { public abstract class CombiningAlgorithm : ICombiningAlgorithm { public abstract Decision Evaluate(IEnumerable<IDecisionEvaluator> evaluators, AuthorizationContext context); } } <file_sep>using System.Collections.Generic; namespace Oriz { public interface IPolicy : IDecisionEvaluator { string Id { get; } IEnumerable<IRule> Rules { get; } ITarget Target { get; } ICombiningAlgorithm CombiningAlgorithm { get; } } }<file_sep>namespace Oriz { public enum RuleEffect { Permit, Deny } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oriz { /// <summary> /// <see cref="http://docs.oasis-open.org/xacml/3.0/xacml-3.0-core-spec-os-en.html#_Toc297001161"/> /// </summary> public class Rule : IRule { public string Id { get; private set; } public RuleEffect Effect { get; private set; } public Target Target { get; private set; } public Rule(string id, RuleEffect effect, Target target) { Id = id; Effect = effect; Target = target; } /// <summary> /// <see cref="http://docs.oasis-open.org/xacml/3.0/xacml-3.0-core-spec-os-en.html#_Toc325047188">Rule evaluation</see> /// </summary> /// <param name="authorizationContext"></param> /// <returns></returns> public Decision Evaluate(AuthorizationContext authorizationContext) { // not using conditions right now, so the rule table will always be // true for the condition column var matchResult = Target != null ? Target.Evaluate(authorizationContext) : MatchResult.True; switch (matchResult) { case MatchResult.True: if (Effect == RuleEffect.Permit) return Decision.Permit; return Decision.Deny; case MatchResult.False: return Decision.NotApplicable; case MatchResult.Indeterminate: if (Effect == RuleEffect.Permit) return Decision.Indeterminate | Decision.Permit; return Decision.Indeterminate | Decision.Deny; } throw new Exception("Invalid match result detected."); } } } <file_sep>using System; using System.Collections.Generic; namespace Oriz.Algorithms { /// <summary> /// <see cref="http://docs.oasis-open.org/xacml/3.0/xacml-3.0-core-spec-os-en.html#_Toc297001241"/> /// </summary> public class DenyOverridesCombiningAlgorithm : CombiningAlgorithm { public override Decision Evaluate(IEnumerable<IDecisionEvaluator> evaluators, AuthorizationContext context) { bool atLeastOneErrorD = false; bool atLeastOneErrorP = false; bool atLeastOneErrorDP = false; bool atLeastOnePermit = false; foreach (var decisionEvaluator in evaluators) { var decision = decisionEvaluator.Evaluate(context); switch (decision) { case Decision.Deny: return Decision.Deny; case Decision.Permit: atLeastOnePermit = true; continue; case Decision.NotApplicable: continue; case Decision.Indeterminate | Decision.Deny: atLeastOneErrorD = true; continue; case Decision.Indeterminate | Decision.Permit: atLeastOneErrorP = true; continue; case Decision.Indeterminate | Decision.Permit | Decision.Deny: atLeastOneErrorDP = true; continue; } } if (atLeastOneErrorDP) return Decision.Indeterminate | Decision.Permit; if (atLeastOneErrorD && (atLeastOneErrorP || atLeastOnePermit)) return Decision.Indeterminate | Decision.Permit | Decision.Deny; if (atLeastOneErrorD) return Decision.Indeterminate | Decision.Deny; if (atLeastOnePermit) return Decision.Permit; if (atLeastOneErrorP) return Decision.Indeterminate | Decision.Permit; return Decision.NotApplicable; } } } <file_sep>using System.Collections.Generic; namespace Oriz { public abstract class Match { public AttributeValue AttributeValue { get; private set; } public AttributeDesignator AttributeDesignator { get; private set; } public string Id { get; private set; } protected Match(string id, AttributeDesignator designator, AttributeValue value) { Id = id; AttributeDesignator = designator; AttributeValue = value; } public MatchResult Evaluate(AuthorizationContext authorizationContext) { foreach (var attributeCategory in authorizationContext.AttributeCategories) if (Evaluate(attributeCategory) == MatchResult.True) return MatchResult.True; return MatchResult.False; } private MatchResult Evaluate( AttributeCategory attributeCategory) { if (attributeCategory.Id != AttributeDesignator.Category) return MatchResult.False; foreach (var attribute in attributeCategory.Attributes) { if (attribute.Id == AttributeDesignator.AttributeId) return Evaluate(attribute); } return MatchResult.False; } protected abstract MatchResult Evaluate(Attribute attribute); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oriz { public class Attribute { public string Id { get; set; } public ICollection<AttributeValue> Values { get; set; } public Attribute() { } public Attribute(string id, params AttributeValue[] values) { Id = id; Values = new List<AttributeValue>(values); } } } <file_sep>using System.Collections.Generic; namespace Oriz { public interface ICombiningAlgorithm { Decision Evaluate(IEnumerable<IDecisionEvaluator> evaluators, AuthorizationContext context); } }<file_sep>namespace Oriz { public class AttributeValue { public string DataType { get; private set; } public string Value { get; private set; } public AttributeValue(string dataType, string value) { DataType = dataType; Value = value; } } }<file_sep>using System; using System.Collections.Generic; namespace Oriz { public class Policy : IPolicy { public string Id { get; private set; } public ITarget Target { get; private set; } public ICombiningAlgorithm CombiningAlgorithm { get; private set; } public IEnumerable<IRule> Rules { get; private set; } public Policy(string id, ITarget target, ICombiningAlgorithm combiningAlgorithm, IEnumerable<IRule> rules) { Id = id; Target = target; CombiningAlgorithm = combiningAlgorithm; Rules = rules; } public Decision Evaluate(AuthorizationContext authorizationContext) { return CombiningAlgorithm.Evaluate(Rules, authorizationContext); } } } <file_sep>using System; using System.Collections.Generic; namespace Oriz.Algorithms { /// <summary> /// <see cref="http://docs.oasis-open.org/xacml/3.0/xacml-3.0-core-spec-os-en.html#_Toc297001243"/> /// </summary> public class PermitOverridesCombiningAlgorithm : CombiningAlgorithm { public override Decision Evaluate(IEnumerable<IDecisionEvaluator> evaluators, AuthorizationContext context) { var atLeastOneErrorD = false; var atLeastOneErrorP = false; var atLeastOneErrorDP = false; var atLeastOneDeny = false; foreach (var evaluator in evaluators) { Decision decision = evaluator.Evaluate(context); switch (decision) { case Decision.Deny: atLeastOneDeny = true; continue; case Decision.Permit: return Decision.Permit; case Decision.NotApplicable: continue; case Decision.Indeterminate | Decision.Deny: atLeastOneErrorD = true; continue; case Decision.Indeterminate | Decision.Permit: atLeastOneErrorP = true; continue; case Decision.Indeterminate | Decision.Permit | Decision.Deny: atLeastOneErrorDP = true; continue; } } if (atLeastOneErrorDP) return Decision.Indeterminate | Decision.Deny | Decision.Permit; if (atLeastOneErrorP && (atLeastOneErrorD || atLeastOneDeny)) return Decision.Indeterminate | Decision.Deny | Decision.Permit; if (atLeastOneErrorP) return Decision.Indeterminate | Decision.Permit; if (atLeastOneDeny) return Decision.Deny; if (atLeastOneErrorD) return Decision.Indeterminate | Decision.Deny; return Decision.NotApplicable; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oriz { public class PolicyDecisionPoint { public PolicyManagementPoint PolicyManagementPoint { get; private set; } public PolicyDecisionPoint(PolicyManagementPoint policyManagementPoint) { PolicyManagementPoint = policyManagementPoint; } public AuthorizationResponse Authorize(AuthorizationRequest request) { var policies = PolicyManagementPoint.GetApplicablePolicies(request.AuthorizationContext); var policySets = PolicyManagementPoint.GetApplicablePolicySets(request.AuthorizationContext); var results = new List<Result>(); foreach (var policySet in policySets) results.Add(new Result { Decision = policySet.Evaluate(request.AuthorizationContext) }); foreach (var policy in policies) results.Add(new Result { Decision = policy.Evaluate(request.AuthorizationContext) }); return new AuthorizationResponse { Results = results }; } } } <file_sep>using System; using System.Collections.Generic; namespace Oriz { public class PolicyManagementPoint { public IList<Policy> Policies { get; private set; } public IList<PolicySet> PolicySets { get; private set; } public PolicyManagementPoint(IList<Policy> policies, IList<PolicySet> policySets) { Policies = new List<Policy>(policies); PolicySets = new List<PolicySet>(policySets); } public PolicyManagementPoint() { Policies = new List<Policy>(); PolicySets = new List<PolicySet>(); } public ICollection<Policy> GetApplicablePolicies(AuthorizationContext authorizationContext) { var applicablePolicies = new List<Policy>(); foreach (var policy in Policies) if (policy.Target.Evaluate(authorizationContext) == MatchResult.True) applicablePolicies.Add(policy); return applicablePolicies; } public ICollection<PolicySet> GetApplicablePolicySets(AuthorizationContext authorizationContext) { var applicablePolicySets = new List<PolicySet>(); foreach (var policySet in PolicySets) if (policySet.Target.Evaluate(authorizationContext) == MatchResult.True) applicablePolicySets.Add(policySet); return applicablePolicySets; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oriz { public class AuthorizationContext { public ICollection<AttributeCategory> AttributeCategories { get; set; } public AuthorizationContext() { } public AuthorizationContext(params AttributeCategory[] attributeCategories) { AttributeCategories = new List<AttributeCategory>(attributeCategories); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Oriz { public interface IRule : IDecisionEvaluator { string Id { get; } RuleEffect Effect { get; } Target Target { get; } } } <file_sep>using System; using System.Collections.Generic; namespace Oriz { public class PolicySet : IDecisionEvaluator { public Target Target { get; set; } public ICollection<PolicySet> PolicySets { get; set; } public ICollection<Policy> Policies { get; set; } public ICombiningAlgorithm CombiningAlgorithm { get; set; } public Decision Evaluate(AuthorizationContext authorizationContext) { return CombiningAlgorithm.Evaluate(GetEvaluators(), authorizationContext); } private IEnumerable<IDecisionEvaluator> GetEvaluators() { foreach (var policy in Policies) yield return policy; foreach (var policySet in PolicySets) yield return policySet; } } }<file_sep>Oriz =========== Overview -------- Implements a stripped down version of xcaml in .NET Purpose ------- Large enterprises have complex authorization needs which opens the door to look at standards compliant authorization standards, to achieve these needs they also have large budgets. There are no really 'easy' ways to achieve complex authorization in a simple .NET application without using a large vendor product. So, to fulfill the need and as a learning project, the Oriz implementation was created. <file_sep>namespace Oriz { public class AttributeDesignator { public string Category { get; private set; } public string AttributeId { get; private set; } public string DataType { get; private set; } public AttributeDesignator(string category, string attributeId, string dataType) { Category = category; AttributeId = attributeId; DataType = dataType; } } }<file_sep>using System.Collections.Generic; namespace Oriz { public class AttributeCategory { public string Id { get; set; } public ICollection<Attribute> Attributes { get; set; } public AttributeCategory() { } public AttributeCategory(string id, params Attribute[] attributes) { Id = id; Attributes = attributes; } } } <file_sep>namespace Oriz { public class Result { public Decision Decision { get; set; } } }<file_sep>using System; namespace Oriz { [Flags] public enum Decision { Permit = 1, Deny = 2, Indeterminate = 4, NotApplicable = 0 } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oriz { public class AuthorizationResponse { public IEnumerable<Result> Results { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Oriz.Functions { public class StringEqualFunction { public string Id { get; private set; } public AttributeValue AttributeValue { get; private set; } public StringEqualFunction( AttributeValue attributeValue) { AttributeValue = attributeValue; Id = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; } public bool Evaulate(Attribute attribute ) { // perf: avoid linq to avoid lambda allocation foreach (var attributeValue in attribute.Values) { if (attributeValue.DataType == AttributeValue.DataType) return (attributeValue.Value == AttributeValue.Value); return false; } return false; } } } <file_sep>using System.Collections.Generic; namespace Oriz { public class AuthorizationRequest { public AuthorizationContext AuthorizationContext { get; set; } public AuthorizationRequest(AuthorizationContext authorizationContext) { AuthorizationContext = authorizationContext; } public AuthorizationRequest() { } } }<file_sep>using System; namespace Oriz.Matches { public class StringEqualIgnoreCaseMatch : Match { public StringEqualIgnoreCaseMatch( AttributeDesignator designator, AttributeValue value) : base("urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case", designator, value) { } protected override MatchResult Evaluate(Attribute attribute) { foreach (var value in attribute.Values) if (value.DataType == AttributeDesignator.DataType) return (AttributeValue.Value.Equals(value.Value, StringComparison.InvariantCultureIgnoreCase)) ? MatchResult.True : MatchResult.False; return MatchResult.False; } } } <file_sep>using System.Collections.Generic; namespace Oriz { public class AllOf { public IEnumerable<Match> Matches { get; private set; } public AllOf(IEnumerable<Match> matches) { Matches = matches; } public AllOf(params Match[] matches) : this(matches as IEnumerable<Match>) { } public MatchResult Evaluate(AuthorizationContext authorizationContext) { foreach (var match in Matches) if (match.Evaluate(authorizationContext) == MatchResult.False) return MatchResult.False; return MatchResult.True; } } } <file_sep>using System.Collections.Generic; namespace Oriz { public interface IDecisionEvaluator { Decision Evaluate(AuthorizationContext authorizationContext); } }<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using Oriz.Algorithms; using Oriz.Matches; namespace Oriz.Tests { [TestClass] public class PolicyDecisionPointTests { [TestMethod] public void PolicyDecisionPointShouldAllowReadForAllMedicalRecords() { var policyManagementPoint = new PolicyManagementPoint(); policyManagementPoint.Policies.Add( new Policy( id: "urn:oasis:names:tc:xacml:3.0:example:policyid:1", target: new Target( new AnyOf( new AllOf( new StringEqualMatch( new AttributeDesignator( Constants.Category.Resource, Resource.TargetNamespace, DataType.AnyUri), new AttributeValue( DataType.AnyUri, ""))))), combiningAlgorithm: new DenyOverridesCombiningAlgorithm(), rules: new IRule[] { })); var policyDecisionPoint = new PolicyDecisionPoint(policyManagementPoint); var authorizationResponse = policyDecisionPoint.Authorize( new AuthorizationRequest( new AuthorizationContext( new AttributeCategory( Constants.Category.AccessSubject, new Attribute( Constants.Attribute.SubjectId, new AttributeValue( dataType: DataType.Rfc822Name, value: "<EMAIL>"))), new AttributeCategory( Constants.Category.Resource, new Attribute( Constants.Attribute.ResourceId, new AttributeValue( dataType: DataType.AnyUri, value: "urn:simple:medical:record:12345"))), new AttributeCategory( Constants.Category.Action, new Attribute( Constants.Attribute.ActionId, new AttributeValue( dataType: DataType.String, value: "read")))))); Assert.IsNotNull(authorizationResponse); Assert.AreEqual(1, authorizationResponse.Results.Count()); Assert.AreEqual(authorizationResponse.Results.First().Decision, Decision.Permit); } } } <file_sep>using System.Collections.Generic; namespace Oriz { public interface ITarget { IEnumerable<AnyOf> AnyOf { get; } MatchResult Evaluate(AuthorizationContext authorizationContext); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Oriz { public static class Constants { public static class Category { public static readonly string AccessSubject = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; public static readonly string Resource = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; public static readonly string Action = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; } public static class Attribute { public static readonly string SubjectId = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; public static readonly string ResourceId = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; public static readonly string ActionId = "urn:oasis:names:tc:xacml:1.0:action:action-id"; } } public static class DataType { public static readonly string Rfc822Name = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"; public static readonly string AnyUri = "http://www.w3.org/2001/XMLSchema#anyURI"; public static readonly string String = "http://www.w3.org/2001/XMLSchema#string"; } public static class Resource { public static readonly string Id = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; public static readonly string TargetNamespace = "urn:oasis:names:tc:xacml:2.0:resource:target-namespace"; } public static class Action { public static readonly string Id = "urn:oasis:names:tc:xacml:1.0:action:action-id"; public static readonly string ImpliedAction = "urn:oasis:names:tc:xacml:1.0:action:implied-action"; public static readonly string Namespace = "urn:oasis:names:tc:xacml:1.0:action:action-namespace"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oriz { public class AnyOf { public IEnumerable<AllOf> AllOf { get; private set; } public AnyOf(IEnumerable<AllOf> allOf) { AllOf = allOf; } public AnyOf(params AllOf[] allOf) : this(allOf as IEnumerable<AllOf>) { } public MatchResult Evaluate(AuthorizationContext authorizationContext) { foreach (var allOf in AllOf) if (allOf.Evaluate(authorizationContext) == MatchResult.True) return MatchResult.True; return MatchResult.False; } } } <file_sep>namespace Oriz.Matches { public class StringEqualMatch : Match { public StringEqualMatch(AttributeDesignator designator, AttributeValue value) : base("urn:oasis:names:tc:xacml:1.0:function:string-equal", designator, value) { } protected override MatchResult Evaluate(Attribute attribute) { foreach (var attributeValue in attribute.Values) if (attributeValue.DataType == AttributeValue.DataType) return (attributeValue.Value == AttributeValue.Value) ? MatchResult.True : MatchResult.False; return MatchResult.False; } } } <file_sep>using System.Collections.Generic; namespace Oriz { public class Target : ITarget { public IEnumerable<AnyOf> AnyOf { get; private set; } public Target(IEnumerable<AnyOf> anyOf) { AnyOf = anyOf; } public Target(params AnyOf[] anyOf) : this(anyOf as IEnumerable<AnyOf>) { } public MatchResult Evaluate(AuthorizationContext authorizationContext) { foreach (var anyOf in AnyOf) if (anyOf.Evaluate(authorizationContext) == MatchResult.False) return MatchResult.False; return MatchResult.True; } } }
f99ddb4a955e712ec4db4bb0211cfd61e4651c01
[ "Markdown", "C#" ]
33
C#
patrickhuber/Oriz
61ff19d8d101425179acfd2cde853a93b251471c
b787570c9a908b48b67842a97595e5c66179576b