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/develop
|
<file_sep>import {
PrimaryGeneratedColumn,
Column,
Entity,
CreateDateColumn,
UpdateDateColumn,
ManyToMany,
JoinTable
} from 'typeorm'
import { Course } from '@models/course'
@Entity()
export class Student {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
email: string;
@Column()
age: number;
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date;
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date;
@ManyToMany((type) => Course, (course) => course.students, { cascade: true })
@JoinTable()
courses: Course[];
}
<file_sep>import {
PrimaryGeneratedColumn,
Column,
Entity,
CreateDateColumn,
UpdateDateColumn,
ManyToMany
} from 'typeorm'
import { Student } from '@models/student'
@Entity()
export class Course {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column()
hours: number;
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date;
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date;
@ManyToMany(
(type) => Student,
(student) => student.courses,
{ onDelete: 'CASCADE' }
)
students: Student[];
}
<file_sep>import { Request, Response } from 'express'
import { getRepository } from 'typeorm'
import { Student } from '@models/student'
class StudentController {
async index (req: Request, res: Response): Promise<Response> {
try {
const students = await getRepository(Student).find(
{ relations: ['courses'] }
)
return res.status(200).json(students)
} catch (error) {
return res.status(400).json(error)
}
}
async create (req: Request, res: Response): Promise<Response> {
try {
const { firstName, lastName, email, age } = req.body
const student = getRepository(Student).create(
{ firstName, lastName, email, age }
)
await getRepository(Student).save(student)
return res.status(200).json(student)
} catch (error) {
return res.status(400).json(error)
}
}
}
export default new StudentController()
<file_sep>import 'reflect-metadata'
import express, { json } from 'express'
import { createConnection } from 'typeorm'
import cors from 'cors'
import routes from './routes'
import { errors } from 'celebrate'
createConnection()
const app = express()
app.use(cors())
app.use(json())
app.use('/api/v1', routes)
app.use(errors())
export default app
<file_sep>import { celebrate, Segments, Joi } from 'celebrate'
export const validate = celebrate({
[Segments.BODY]: Joi.object({
firstName: Joi.string().trim().required(),
lastName: Joi.string().trim().required(),
email: Joi.string().trim().email(
{ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } }
).required(),
age: Joi.number().integer('age must be an integer')
.positive('age must be positive').required()
})
})
<file_sep>import { Router } from 'express'
import StudentController from '@controllers/student'
import { validate } from '@validators/student'
const router = Router()
router.get('/students', StudentController.index)
router.post('/students', validate, StudentController.create)
export default router
|
148fe4e311ba2e069c0b26df646955d0ff6c2d30
|
[
"TypeScript"
] | 6
|
TypeScript
|
juliocabrera820/courses-api
|
94f5082a2145a2ce84944e8e5924aa575efe89cf
|
8ca36652e2d7c86ff5442c6ca1633f69c3e138ab
|
refs/heads/master
|
<repo_name>omidAien/ionic-barcode-scanner<file_sep>/src/app/shared/product-info-viewer/product-info-viewer.component.ts
import { AfterViewInit, Component, OnInit } from '@angular/core';
import { BarcodeReaderService } from 'src/app/services/barcode-reader.service';
@Component({
selector: 'app-product-info-viewer',
templateUrl: './product-info-viewer.component.html',
styleUrls: ['./product-info-viewer.component.scss'],
})
export class ProductInfoViewerComponent implements OnInit {
constructor(public barcodeReaderService: BarcodeReaderService) { }
ngOnInit() {}
}
<file_sep>/src/app/authenticate/authenticate.page.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { from, noop, Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AuthenticateParameters, AuthenticateResponse, ClientInformation, SystemInformation } from '../general-models/general';
import { GlobalAPIService } from '../services/global-api.service';
import { LoadingService } from '../services/loading.service';
import { FormGroup, FormControl } from '@angular/forms';
import { AlertController, IonCheckbox, ToastController } from '@ionic/angular';
import { CookieService } from 'ngx-cookie-service';
import { Router } from '@angular/router';
import { ManageUserService } from '../services/manage-user.service';
@Component({
selector: 'app-authenticate',
templateUrl: './authenticate.page.html',
styleUrls: ['./authenticate.page.scss'],
})
export class AuthenticatePage implements OnInit {
@ViewChild("remmeberMe") remmeberMe: IonCheckbox;
pageDirection:string;
Caption:string;
appVersion:string;
PoweredBy:string;
ReleaseDate:string;
clientInformation: ClientInformation;
loginForm:FormGroup;
remmeberMeIsChecked:boolean = true;
constructor(private globalAPIService: GlobalAPIService,
public loadingService: LoadingService,
private cookieService: CookieService,
private router: Router,
private managerUser: ManageUserService,
public alertController: AlertController,
public toastController: ToastController) { }
ngOnInit() {
this.clientInformation = JSON.parse(this.cookieService.get("clientInformation"));
// this.remmeberMeIsChecked = JSON.parse(localStorage.getItem("remmeberMe"));
const systemInformation$: Observable<SystemInformation> = this.globalAPIService.getSystemInformation();
const systemInformation: (SystemInformation | null) = JSON.parse(sessionStorage.getItem("SystemInformation"));
if ( systemInformation ) {
this.pageDirection = systemInformation.Direction;
this.Caption = systemInformation.Caption;
this.appVersion = systemInformation.Version;
this.PoweredBy = systemInformation.PoweredBy;
this.ReleaseDate = systemInformation.ReleaseDate;
}
else {
this.loadingService
.loadUntilRequestComplete(systemInformation$)
.subscribe((systemInformation: SystemInformation) => {
if ( !systemInformation.Error.hasError ) {
sessionStorage.setItem("SystemInformation", JSON.stringify(systemInformation));
this.pageDirection = systemInformation.Direction;
this.Caption = systemInformation.Caption;
this.appVersion = systemInformation.Version;
this.PoweredBy = systemInformation.PoweredBy;
this.ReleaseDate = systemInformation.ReleaseDate;
}
else {
const alertController$ = from(this.alertController.create({
cssClass: 'broken-product-alert',
header: 'توجه',
message: systemInformation.Error.Message,
buttons: [
{
text: 'تایید',
role: 'okay',
}
]
}));
alertController$.subscribe((alertController) => alertController.present());
}
});
};
this.loginForm = new FormGroup({
username: new FormControl(localStorage?.getItem("username")),
password: new FormControl(localStorage.getItem("<PASSWORD>")),
});
}
submitLoginForm() {
if ( this.loginForm.valid ) {
const username = this.loginForm.get('username').value;
const password = this.loginForm.get('password').value;
const clientInformation = this.clientInformation;
const authenticateParameters: AuthenticateParameters = {
userID : username,
userPSW : password,
workstationID : 0,
workgroupID : 0,
clientInformation : clientInformation,
};
this.globalAPIService
.loginProcedure(authenticateParameters)
.pipe(
tap((authenticateResponse: AuthenticateResponse) => {
if ( !authenticateResponse.Error.hasError ) {
const token: string = authenticateResponse.Token;
this.cookieService.set("token", JSON.stringify(authenticateResponse.Token));
this.managerUser.setUserRole(+authenticateResponse.DefaultWorkgroupID);
this.saveToSessionStorage("userLogin", JSON.stringify(true));
this.router.navigateByUrl("/main");
}
else {
const errorMessage:string = authenticateResponse.Error.Message;
this.presentToast(errorMessage);
}
})
)
.subscribe(
noop
);
}
}
applyRememberMe(username: string, password: string) {
if ( this.remmeberMe?.checked ) {
localStorage.setItem("username", username);
localStorage.setItem("password", <PASSWORD>);
localStorage.setItem("remmeberMe", JSON.stringify(true));
};
}
async presentToast(msg:string) {
const toast = await this.toastController.create({
message: msg,
duration: 2000,
position: 'top',
color: "dark",
cssClass: 'map-toast-message'
});
toast.present();
}
saveToSessionStorage(key: string, value:any) {
sessionStorage.setItem(key, JSON.stringify(value));
}
}
<file_sep>/src/app/services/manage-user.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ManageUserService {
private userRoleSubject = new BehaviorSubject<number>(null);
public userRole$: Observable<number> = this.userRoleSubject.asObservable();
constructor() { }
setUserRole(defaultWorkgroupID:number) {
this.userRoleSubject.next(defaultWorkgroupID);
sessionStorage.setItem('DefaultWorkgroupID', JSON.stringify(defaultWorkgroupID));
}
}
<file_sep>/src/app/services/is-login.guard.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class IsLoginGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const userLoginStatus = sessionStorage.getItem("userLogin");
const IsUserLogin: boolean | null = userLoginStatus ? JSON.parse(userLoginStatus) : null;
if ( IsUserLogin ) {
this.router.navigateByUrl("/barcode");
return false
}
else {
return true
}
}
}
<file_sep>/src/app/broken-product/broken-product.page.ts
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController, IonInput } from '@ionic/angular';
import { ModalController } from '@ionic/angular';
import { BehaviorSubject, from, noop, of } from 'rxjs';
import { delay, finalize, shareReplay, tap } from 'rxjs/operators';
import { BarcodeTrackerResponse } from '../general-models/general';
import { BarcodeReaderService } from '../services/barcode-reader.service';
import { ProductInfoViewerComponent } from '../shared/product-info-viewer/product-info-viewer.component';
import { BrokrnRegisterComponent } from './modalPages/brokrn-register/brokrn-register.component';
@Component({
selector: 'app-broken-product',
templateUrl: './broken-product.page.html',
styleUrls: ['./broken-product.page.scss'],
})
export class BrokenProductPage implements OnInit, AfterViewInit {
@ViewChild('barcode') barcode: IonInput;
barcodeContainerLabel:string = "بارکد";
title:string;
constructor(private router: Router,
public barcodeReaderService: BarcodeReaderService,
public alertController: AlertController,
public modalController: ModalController) {
try {
this.title = this.router.getCurrentNavigation().extras.state.title;
}
catch (error) {
this.router.navigateByUrl("/main");
}
}
ngOnInit() {}
focusOnBarcodeInputElement() {
setTimeout(() => {
this.barcode.readonly = false;
this.barcode.setFocus()
}, 300);
}
ionViewWillEnter() {
this.focusOnBarcodeInputElement();
this.barcodeReaderService.setBarcode(null);
}
ngAfterViewInit() {
this.barcode.readonly = true;
}
onClickBackButton() {
this.barcodeReaderService.setBarcode(null);
this.barcodeReaderService.resetBarcodeTrackerResponse();
}
changeInputBarcode() {
let barcode:string = "";
if ( this.barcode.value.toString().startsWith('j') ) { barcode = this.barcode.value.toString().replace("j", ""); }
else if ( this.barcode.value.toString().startsWith('s') ) { barcode = this.barcode.value.toString().replace("s", ""); }
else { barcode = this.barcode.value.toString(); }
if ( barcode.length >= 12 ) {
const loading$ = this.barcodeReaderService.getProductInformation(barcode);
loading$.subscribe((loading) => loading.onDidDismiss().then(() => {
this.barcode.value = "";
this.barcode.readonly = true;
this.focusOnBarcodeInputElement();
}));
}
}
async brokenRegisterModal() {
let barcodeIsExistence:boolean = false;
this.barcodeReaderService
.barcodeTrackerResponse$
.pipe(
shareReplay(),
tap((data:BarcodeTrackerResponse) => {
if ( data ) {
if ( data.Barcode ) { barcodeIsExistence = true; }
else { barcodeIsExistence = false; }
}
else { barcodeIsExistence = false; }
})
)
.subscribe(noop);
if ( !barcodeIsExistence ) {
const alert = await this.alertController.create({
cssClass: 'broken-product-alert',
header: 'توجه',
message: 'لطفا بارکد را به درستی اسکن نمایید',
buttons: [
{
text: 'تایید',
role: 'okay',
handler: () => {
this.barcode.readonly = true;
this.focusOnBarcodeInputElement();
}
}
]
});
await alert.present();
}
else {
const modal = await this.modalController.create({
component: BrokrnRegisterComponent,
componentProps: {
'title': 'ثبت عملیات',
}
});
await modal.present();
const { data } = await modal.onWillDismiss();
if (data) {
this.barcode.readonly = true;
this.focusOnBarcodeInputElement();
};
}
}
}
<file_sep>/src/app/services/client-information.service.ts
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { DeviceDetectorService } from 'ngx-device-detector';
import { ClientInformation } from '../general-models/general';
@Injectable({
providedIn: 'root'
})
export class ClientInformationService {
constructor(private deviceService: DeviceDetectorService,
private cookieService: CookieService) {
this.getDeviceInfo();
}
getDeviceInfo() {
const clientDeviceInformation: ClientInformation = {
browser: this.deviceService.browser,
browserVersion : this.deviceService.browser_version,
device : this.deviceService.device,
deviceType : this.deviceService.deviceType,
orientation : this.deviceService.orientation,
os : this.deviceService.os,
osVersion : this.deviceService.os_version,
ip : "",
mac: "",
agent : this.deviceService.userAgent,
longitude: 0,
latitude: 0
};
this.cookieService.set("clientInformation", JSON.stringify(clientDeviceInformation));
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
API_URL_INTERNAL : "http://192.168.1.5:8084/map/v1/",
API_URL_EXTERNAL : "http://172.16.17.32:18831/map/v1/"
};<file_sep>/src/app/broken-product/broken-product.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { BrokenProductPageRoutingModule } from './broken-product-routing.module';
import { BrokenProductPage } from './broken-product.page';
import { SharedModule } from '../shared/shared.module';
import { BrokrnRegisterComponent } from './modalPages/brokrn-register/brokrn-register.component';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
SharedModule,
BrokenProductPageRoutingModule,
],
declarations: [BrokenProductPage, BrokrnRegisterComponent],
entryComponents:[
BrokrnRegisterComponent
]
})
export class BrokenProductPageModule {}
<file_sep>/src/app/print-label/print-label.page.ts
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController, IonInput, LoadingController } from '@ionic/angular';
import { CookieService } from 'ngx-cookie-service';
import { from, noop, Observable, of, throwError } from 'rxjs';
import { catchError, concatMap, delay, finalize, tap } from 'rxjs/operators';
import { BarcodeTrackerResponse, QCPrint } from '../general-models/general';
import { BarcodeReaderService } from '../services/barcode-reader.service';
import { GlobalAPIService } from '../services/global-api.service';
@Component({
selector: 'app-print-label',
templateUrl: './print-label.page.html',
styleUrls: ['./print-label.page.scss'],
})
export class PrintLabelPage implements OnInit, AfterViewInit {
@ViewChild('barcode') barcode: IonInput;
@ViewChild('numberOfLabel') numberOfLabel:IonInput;
title:string;
barcodeContainerLabel:string = "بارکد";
constructor(private router: Router,
private alertController: AlertController,
private globalService: GlobalAPIService,
public loadingController: LoadingController,
private cookieService: CookieService,
public barcodeReaderService: BarcodeReaderService,) {
try {
this.title = this.router.getCurrentNavigation().extras.state.title;
} catch (error) {
this.router.navigateByUrl("/main");
}
}
ngOnInit() {}
focusOnBarcodeInputElement() {
setTimeout(() => {
this.barcode.readonly = false;
this.barcode.setFocus();
}, 300);
}
ionViewWillEnter() {
this.focusOnBarcodeInputElement();
this.barcodeReaderService.setBarcode(null);
}
ngAfterViewInit() {
this.barcode.readonly = true;
}
changeInputBarcode() {
let barcode:string = "";
if ( this.barcode.value.toString().startsWith('j') ) { barcode = this.barcode.value.toString().replace("j", ""); }
else if ( this.barcode.value.toString().startsWith('s') ) { barcode = this.barcode.value.toString().replace("s", ""); }
else { barcode = this.barcode.value.toString(); };
if ( barcode.length >= 12 ) {
const loading$ = this.barcodeReaderService.getProductInformation(barcode);
loading$.subscribe((loading) => loading.onDidDismiss().then(() => {
this.barcode.value = "";
this.barcode.readonly = true;
this.focusOnBarcodeInputElement();
}));
}
}
onClickBackButton() {
this.barcodeReaderService.setBarcode(null);
this.barcodeReaderService.resetBarcodeTrackerResponse();
}
registerPrintLabel() {
const barcode:string = this.barcodeReaderService.getBarcode();
const numberOfLabel:number = +this.numberOfLabel.value;
const loading$ = this.generateLodingController();
const token = "bearer ".concat(JSON.parse(this.cookieService.get("token")));
if ( barcode && numberOfLabel ) {
const qcPrintRequest: QCPrint = {
barcode: barcode,
number: numberOfLabel
};
const QCPrintRequest$: Observable<BarcodeTrackerResponse> = this.globalService.mapQCPrint(token, qcPrintRequest);
of(null)
.pipe(
catchError((error) => {
sessionStorage.removeItem("userLogin");
this.router.navigateByUrl("/login").then(() => window.location.reload());
return throwError(error);
}),
tap(() => loading$.subscribe((loading) => loading.present())),
delay(500),
concatMap(() => QCPrintRequest$),
tap((response: BarcodeTrackerResponse) => {
if ( !response.Error.hasError ) {
this.barcodeReaderService.updateBarcodeTrackerResponse(response);
}
else {
const alertController$ = this.generateAlertController(response.Error.Message);
alertController$.subscribe((alertController) => alertController.present());
}
}),
finalize(() => loading$.subscribe((loading) => {
loading.dismiss().then(() => {
this.numberOfLabel.value = null;
this.numberOfLabel.setBlur;
this.barcode.readonly = true;
this.focusOnBarcodeInputElement();
});
}))
)
.subscribe(noop);
}
else {
let errorMessage:string = "";
const notExistenceBarcode:string = "بارکد به درستی اسکن نشده است";
const notExistenceNumberOfLabel:string = "تعداد لیبل ها مشخص نشده است";
const notExistenceBoth:string = "بارکد به درستی اسکن نشده و تعداد لیبل ها مشخص نشده است";
if ( !barcode && !numberOfLabel ) { errorMessage = notExistenceBoth; }
else if ( !barcode ) { errorMessage = notExistenceBarcode; }
else if ( !numberOfLabel ) { errorMessage = notExistenceNumberOfLabel; };
const alertController$ = this.generateAlertController(errorMessage);
alertController$.subscribe((alertController) => alertController.present());
}
}
generateAlertController(serverSideMessage:string) {
const alertController = this.alertController.create({
cssClass: 'broken-product-alert',
header: 'توجه',
message: serverSideMessage,
buttons: [
{
text: 'تایید',
role: 'okay',
handler: () => {
this.barcode.readonly = true;
this.focusOnBarcodeInputElement();
}
}
]
});
const alertController$ = from(alertController);
return alertController$
}
generateLodingController() {
const loadingPromise = this.loadingController.create({
message: '... لطفا چند صبر کنید',
});
const loading$ = from(loadingPromise);
return loading$
}
}
<file_sep>/src/app/shared/preloader/preloader.component.ts
import { Component, OnInit } from '@angular/core';
import { LoadingService } from 'src/app/services/loading.service';
@Component({
selector: 'app-preloader',
templateUrl: './preloader.component.html',
styleUrls: ['./preloader.component.scss'],
})
export class PreloaderComponent implements OnInit {
constructor(public loadingService: LoadingService) { }
ngOnInit() {}
}
<file_sep>/src/app/services/auth.guard.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const userLoginStatus = sessionStorage.getItem("userLogin");
const IsUserLogin: boolean | null = userLoginStatus ? JSON.parse(userLoginStatus) : null;
if ( IsUserLogin ) {
return true
}
else {
this.router.navigateByUrl("/");
return false
}
}
}
<file_sep>/src/app/broken-product/modalPages/brokrn-register/brokrn-register.component.ts
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { AlertController, IonInput, IonSelect, IonSelectOption, LoadingController, ModalController } from '@ionic/angular';
import { CookieService } from 'ngx-cookie-service';
import { from, noop, of, throwError } from 'rxjs';
import { catchError, concatMap, finalize, tap } from 'rxjs/operators';
import { BarcodeTracker, ErrorModel, GetBreak, SetBreak } from 'src/app/general-models/general';
import { BarcodeReaderService } from 'src/app/services/barcode-reader.service';
import { GlobalAPIService } from 'src/app/services/global-api.service';
@Component({
selector: 'app-brokrn-register',
templateUrl: './brokrn-register.component.html',
styleUrls: ['./brokrn-register.component.scss'],
})
export class BrokrnRegisterComponent implements OnInit {
@Input() title: string;
@ViewChild('numberOfBreak') numberOfBreak:IonInput;
breakFormData: { ID:number; Caption:string; DefaultValue:string; Items: null | string; ObjectType:number }[] = null;
registerValue: { fieldID:number; fieldValue:string; }[] = [];
constructor(public modalController: ModalController,
private globalAPIService: GlobalAPIService,
private cookieService: CookieService,
private router: Router,
public alertController: AlertController,
public loadingController: LoadingController,
public barcodeReaderService: BarcodeReaderService,) { }
ngOnInit() {}
dismiss() {
this.modalController.dismiss({
'dismissed': true
}).then(() => {
this.barcodeReaderService.setBarcode(null);
this.barcodeReaderService.resetBarcodeTrackerResponse();
});
}
ionViewWillEnter() {
const barcode:string = this.barcodeReaderService.getBarcode();
const token = "bearer ".concat(JSON.parse(this.cookieService.get("token")));
const mapGetBreakRequest: BarcodeTracker = {
barcode: barcode
};
const mapGetBreak$ = this.globalAPIService
.mapGetBreak(token, mapGetBreakRequest)
.pipe(
catchError((error) => {
sessionStorage.removeItem("userLogin");
this.router.navigateByUrl("/login").then(() => window.location.reload());
return throwError(error);
}),
);
const loading$ = this.generateLodingController();
of(null)
.pipe(
tap(() => loading$.subscribe((loading) => loading.present())),
concatMap(() => mapGetBreak$),
tap((data: GetBreak) => {
if ( !data.Error.hasError ) {
data.Break
.map((item) => {
const _id:number = item.ID;
if ( item.DefaultValue && item.Items ) {
const _Items:{ Code:string; Value:string;}[] = JSON.parse(item.Items);
let _code:string = null;
_Items.map((op:{ Code:string; Value:string;}) => {
if ( op.Value === item.DefaultValue ) {
_code = op.Code;
}
});
setTimeout(() => this.registerValue.push({ fieldID: _id, fieldValue: _code }), 100);
}
else if ( item.DefaultValue && !item.Items ) {
this.registerValue.push({ fieldID: _id, fieldValue: item.DefaultValue });
}
else if ( !item.DefaultValue ) {
this.registerValue.push({ fieldID: _id, fieldValue: null });
}
});
setTimeout(() => {
this.breakFormData = data.Break;
}, 200);
}
}),
finalize(() => loading$.subscribe((loading) => loading.dismiss()))
)
.subscribe(noop);
}
selectOptions(event:any, id:number) {
this.registerValue
.map((item:{ fieldID:number; fieldValue:string; }) => {
if ( item.fieldID === id ) {
item.fieldValue = event.detail.value;
}
});
}
generateLodingController() {
const loadingPromise = this.loadingController.create({
message: '... لطفا چند صبر کنید',
});
const loading$ = from(loadingPromise);
return loading$
}
convertToJson(value:string) {
return JSON.parse(value);
}
sendDataToSever() {
const token = "bearer ".concat(JSON.parse(this.cookieService.get("token")));
const mapSetBreakRequest: SetBreak[] = this.registerValue;
const mapSetBreak$ = this.globalAPIService
.mapSetBreak(token, mapSetBreakRequest)
.pipe(
catchError((error) => {
sessionStorage.removeItem("userLogin");
this.router.navigateByUrl("/login").then(() => window.location.reload());
return throwError(error);
}),
);
const loading$ = this.generateLodingController();
of(null)
.pipe(
tap(() => loading$.subscribe((loading) => loading.present())),
concatMap(() => mapSetBreak$),
tap((data:ErrorModel) => {
if ( !data.hasError ) {
const alertController$ = from(this.alertController.create({
cssClass: 'broken-product-alert',
header: 'توجه',
message: 'ثبت با موفقیت انجام شد',
buttons: [
{
text: 'تایید',
role: 'okay',
handler: () => {
this.dismiss();
}
}
]
}));
alertController$.subscribe((alertController) => alertController.present());
}
else {
const alertController$ = from(this.alertController.create({
cssClass: 'broken-product-alert',
header: 'توجه',
message: 'خطایی رخ داد',
buttons: [
{
text: 'تایید',
role: 'okay'
}
]
}));
alertController$.subscribe((alertController) => alertController.present());
}
}),
finalize(() => loading$.subscribe((loading) => loading.dismiss()))
)
.subscribe(noop);
}
setIonSelectValue(event:IonSelect, defaultValue:string) {
event.value = defaultValue;
}
}
<file_sep>/src/app/services/barcode-reader.service.ts
import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController, LoadingController } from '@ionic/angular';
import { CookieService } from 'ngx-cookie-service';
import { BehaviorSubject, from, noop, Observable, of, throwError } from 'rxjs';
import { catchError, concatMap, delay, finalize, tap } from 'rxjs/operators';
import { BarcodeTracker, BarcodeTrackerResponse } from '../general-models/general';
import { GlobalAPIService } from './global-api.service';
@Injectable({
providedIn: 'root'
})
export class BarcodeReaderService {
private barcodeSubject = new BehaviorSubject<string>(null);
private barcodeTrackerResponseSubject = new BehaviorSubject<BarcodeTrackerResponse>(null);
public barcodeTrackerResponse$: Observable<BarcodeTrackerResponse> = this.barcodeTrackerResponseSubject.asObservable();
constructor(public loadingController: LoadingController,
private globalService: GlobalAPIService,
private alertController: AlertController,
private router: Router,
private cookieService: CookieService) { }
getProductInformation(barcode:string) {
// 1. save barcode in memory
this.barcodeSubject.next(barcode);
// 2. create loadingController Promise by menas of ionic's loadingController
const loadingPromise = this.loadingController.create({
message: '... لطفا چند صبر کنید',
});
// 3. convert loadingController Promise to Observeable
const loading$ = from(loadingPromise);
// 4. send barcode has been read to sever in order to get information of product
const token = "bearer ".concat(JSON.parse(this.cookieService.get("token")));
const bodyRequest: BarcodeTracker = {
barcode: barcode
};
const barcodeTracker$:Observable<BarcodeTrackerResponse> = this.globalService
.mapTracking(token, bodyRequest)
.pipe(
catchError((error:HttpErrorResponse) => {
sessionStorage.removeItem("userLogin");
this.router.navigateByUrl("/login").then(() => window.location.reload());
return throwError(error);
}),
);
of(true)
.pipe(
tap(() => loading$.subscribe((loading) => loading.present())),
delay(2000),
concatMap(() => barcodeTracker$),
tap((barcodeTrackerResponse:BarcodeTrackerResponse) => {
this.barcodeTrackerResponseSubject.next(barcodeTrackerResponse);
if ( barcodeTrackerResponse.Error.LogData && this.router.url === '/broken-product' ) {
const logData = JSON.parse(barcodeTrackerResponse.Error.LogData);
const alertController$ = from(this.alertController.create({
cssClass: 'broken-product-alert',
header: 'توجه',
message: logData.Status,
buttons: [
{
text: 'تایید',
role: 'okay'
}
]
})
);
alertController$.subscribe((alertController) => alertController.present());
}
}),
finalize(() => loading$.subscribe((loading) => loading.dismiss()))
)
.subscribe(noop);
return loading$
}
setBarcode(value:string) {
this.barcodeSubject.next(value);
}
getBarcode() {
return this.barcodeSubject.getValue();
}
resetBarcodeTrackerResponse() {
this.barcodeTrackerResponseSubject.next(null);
}
updateBarcodeTrackerResponse(value:BarcodeTrackerResponse) {
this.barcodeTrackerResponseSubject.next(value);
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './services/auth.guard';
import { IsLoginGuard } from './services/is-login.guard';
const routes: Routes = [
{
path: 'login',
loadChildren: () => import('./authenticate/authenticate.module').then( m => m.AuthenticatePageModule),
canActivate: [IsLoginGuard]
},
{
path: 'main',
loadChildren: () => import('./main/main.module').then( m => m.MainPageModule),
canActivate: [AuthGuard]
},
{
path: 'product-tracker',
loadChildren: () => import('./product-tracker/product-tracker.module').then( m => m.ProductTrackerPageModule),
canActivate: [AuthGuard]
},
{
path: 'broken-product',
loadChildren: () => import('./broken-product/broken-product.module').then( m => m.BrokenProductPageModule),
canActivate: [AuthGuard]
},
{
path: 'print-label',
loadChildren: () => import('./print-label/print-label.module').then( m => m.PrintLabelPageModule),
canActivate: [AuthGuard]
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/main/main.page.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { noop, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { BarcodeReaderService } from '../services/barcode-reader.service';
import { ManageUserService } from '../services/manage-user.service';
@Component({
selector: 'app-main',
templateUrl: './main.page.html',
styleUrls: ['./main.page.scss'],
})
export class MainPage implements OnInit {
mainPageTitle:string = "";
defaultWorkGroupId:number;
constructor(private cookieService: CookieService,
private manageUserService:ManageUserService,
public barcodeReaderService:BarcodeReaderService,
private router: Router) { }
ngOnInit() {
}
ionViewWillEnter() {
this.manageUserService
.userRole$
.pipe(
tap((_defaultWorkGroupId:number) => {
if ( _defaultWorkGroupId ) {
this.defaultWorkGroupId = _defaultWorkGroupId;
}
else {
this.defaultWorkGroupId = JSON.parse(sessionStorage.getItem("DefaultWorkgroupID"))
}
this.determineMainPageTitleBasedOnDefaultWorkGroupId(this.defaultWorkGroupId);
})
)
.subscribe(noop)
this.barcodeReaderService.resetBarcodeTrackerResponse();
}
goTospecificPage(moduleName:string) {
switch (moduleName) {
case 'productTracking':
this.router.navigateByUrl('/product-tracker', { state : { title: 'ردیابی محصول' } })
break;
case 'brokenProduct':
this.router.navigateByUrl('/broken-product', { state : { title: 'ثبت شکست' } });
break;
case 'printLabel':
this.router.navigateByUrl('/print-label', { state : { title: 'چاپ لیبل پای سکو' } });
break;
}
}
logOut() {
sessionStorage.clear();
this.cookieService.delete("token");
this.router.navigateByUrl("/");
}
determineMainPageTitleBasedOnDefaultWorkGroupId(id:number) {
switch (id) {
case 3:
this.mainPageTitle = "انبار";
break;
case 9:
this.mainPageTitle = "کنترل کیفی";
break;
}
}
}
<file_sep>/src/app/services/global-api.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { throwError } from 'rxjs';
import { catchError, shareReplay } from 'rxjs/operators'
import { environment } from "../../environments/environment";
import { AuthenticateParameters, AuthenticateResponse, BarcodeTracker, BarcodeTrackerResponse, QCPrint, SetBreak, SystemInformation } from '../general-models/general';
@Injectable({
providedIn: 'root'
})
export class GlobalAPIService {
private origin:Required<string> = window.location.origin;
private originExternal = "http://192.168.127.12:18830";
private baseURL:Required<string>;
constructor(private httpClient: HttpClient) {
if ( this.origin === this.originExternal ) {
this.baseURL = environment.API_URL_EXTERNAL;
}
else {
this.baseURL = environment.API_URL_INTERNAL;
};
}
private setHeaders(token:Required<string>) {
const headres = new HttpHeaders({
"Authorization" : token,
"Content-Type" : "application/json; charset=utf-8",
});
return headres
}
getSystemInformation(): Observable<SystemInformation> {
const requestURL:Required<string> = this.baseURL.concat("mapSystemInformation");
return this.httpClient.get<SystemInformation>(requestURL)
.pipe(
catchError((error) => {
return throwError(error);
}),
shareReplay()
);
}
loginProcedure(authenticateParameters:AuthenticateParameters): Observable<AuthenticateResponse> {
const headers = { 'content-type': 'application/json'};
const requestURL:Required<string> = this.baseURL.concat("Login/athenticate");
const body:Required<string> = JSON.stringify(authenticateParameters);
return this.httpClient.post<AuthenticateResponse>(requestURL, body, {headers:headers})
.pipe(
catchError((error) => {
console.log(error);
return throwError(error)
}),
shareReplay()
);
}
mapTracking(token:string, barcodeTracker:BarcodeTracker):Observable<BarcodeTrackerResponse> {
const requestURL:Required<string> = this.baseURL.concat("mapTracking");
const body:Required<string> = JSON.stringify(barcodeTracker);
return this.httpClient.post<BarcodeTrackerResponse>(requestURL, body, {headers:this.setHeaders(token)});
}
mapQCPrint(token:string, qcPrint: QCPrint):Observable<BarcodeTrackerResponse> {
const requestURL:Required<string> = this.baseURL.concat("mapQCPrint");
const body:Required<string> = JSON.stringify(qcPrint);
return this.httpClient.post<BarcodeTrackerResponse>(requestURL, body, {headers:this.setHeaders(token)});
}
mapGetBreak(token:string, barcodeTracker:BarcodeTracker) {
const requestURL:Required<string> = this.baseURL.concat("mapGetBreak");
const body:Required<string> = JSON.stringify(barcodeTracker);
return this.httpClient.post(requestURL, body, {headers:this.setHeaders(token)});
}
mapSetBreak(token:string, setBreak:SetBreak[]) {
const requestURL:Required<string> = this.baseURL.concat("mapSetBreak");
const body:Required<string> = JSON.stringify(setBreak);
return this.httpClient.post(requestURL, body, {headers:this.setHeaders(token)});
}
}
<file_sep>/src/app/product-tracker/product-tracker.page.ts
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { IonInput } from '@ionic/angular';
import { BarcodeReaderService } from '../services/barcode-reader.service';
@Component({
selector: 'app-product-tracker',
templateUrl: './product-tracker.page.html',
styleUrls: ['./product-tracker.page.scss'],
})
export class ProductTrackerPage implements OnInit {
@ViewChild('barcode') barcode: IonInput;
barcodeContainerLabel:string = "بارکد";
title:string;
constructor(private router: Router,
public barcodeReaderService: BarcodeReaderService) {
try {
this.title = this.router.getCurrentNavigation().extras.state.title;
}
catch (error) {
this.router.navigateByUrl("/main");
};
}
ngOnInit() {}
focusOnBarcodeInputElement() {
setTimeout(() => {
this.barcode.readonly = false;
this.barcode.setFocus()
}, 300);
}
ionViewWillEnter() {
this.focusOnBarcodeInputElement();
this.barcodeReaderService.setBarcode(null);
}
changeInputBarcode() {
let barcode:string = "";
if ( this.barcode.value.toString().startsWith('j') ) {
barcode = this.barcode.value.toString().replace("j", "");
}
else if ( this.barcode.value.toString().startsWith('s') ) {
barcode = this.barcode.value.toString().replace("s", "");
}
else {
barcode = this.barcode.value.toString();
}
if ( barcode.length >= 12 ) {
const loading$ = this.barcodeReaderService.getProductInformation(barcode);
loading$.subscribe((loading) => loading.onDidDismiss().then(() => {
this.barcode.value = "";
this.barcode.readonly = true;
this.focusOnBarcodeInputElement();
}));
}
}
ngAfterViewInit() {
this.barcode.readonly = true;
}
onClickBackButton() {
this.barcodeReaderService.setBarcode(null);
this.barcodeReaderService.resetBarcodeTrackerResponse();
}
}
<file_sep>/src/app/general-models/general.ts
export interface ErrorModel {
hasError: boolean,
Code: number;
Message: string;
MessageViewType: number;
LogData:any;
LogID:number;
}
export interface Workstation {
PK_ObjectID:number;
Caption: string;
}
export interface UserWorkgroup {
PK_WorkgroupID: number;
Workgroup: string;
}
export interface UserProject {
PK_ProjectID: number;
Project: string;
isDefault: boolean;
}
export interface SystemInformation {
Error: ErrorModel | null;
Direction:string;
Caption:string;
Remark:string;
Version:string;
ReleaseDate:string;
PoweredBy:string;
Culture:string;
}
export interface AuthenticateParameters {
userID:string;
userPSW:string;
workstationID:number;
workgroupID:number;
clientInformation:ClientInformation;
}
export interface ClientInformation {
browser: string;
browserVersion: string;
device: string;
deviceType: string;
orientation: string;
os: string;
osVersion: string;
ip: string;
mac: string;
agent: string;
latitude: number;
longitude: number;
}
export interface AuthenticateResponse {
Error: ErrorModel;
Token: string | null;
UserName: string;
Workstations: Workstation[];
Workgroups: UserWorkgroup[] | null;
DefaultWorkgroupID: number | UserWorkgroup;
Projects: UserProject[];
}
export interface BarcodeTracker {
barcode:string;
}
export interface BarcodeInformation {
Caption:string;
Value:string;
}
export interface BarcodeTrackerResponse {
Error: ErrorModel;
Barcode: BarcodeInformation[];
}
export interface QCPrint {
barcode:string;
number:number;
}
export interface GetBreak {
Break: {ID:number; Caption:string; DefaultValue:string; Items: null | string; ObjectType:number}[];
Error: ErrorModel;
}
export interface SetBreak {
fieldID: number;
fieldValue: string;
}
|
d21afe9e2f7c4bdb296d4a104ea6889081e8bbde
|
[
"TypeScript"
] | 18
|
TypeScript
|
omidAien/ionic-barcode-scanner
|
b6889b53886c27d752bb9cd014acb6df0f4791d4
|
740ba217a5c993ea41d28ef232c8ebb5b173ef9d
|
refs/heads/master
|
<file_sep>package auth
import (
"time"
)
const sessionName = "session-id"
type Session struct {
SessionID string
UserID int
CreatedAt time.Time
ExpiresAt time.Time
DeletedAt *time.Time
}
<file_sep>package users
import (
"database/sql"
"fmt"
"net/http/httptest"
"testing"
"github.com/Pashakrut94/SwiftChat/utility"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)
// func RouterCreate(db *sql.DB) *mux.Router {
// r := mux.NewRouter()
// r.HandleFunc("/api/users", CreateUser(*NewUserRepo(db)))
// return r
// }
//dont need test for unnecessary handler(delete CreateUser handler)
// func TestCreateUser(t *testing.T) {
// db, dropschema := utility.SetupSchema(t)
// defer dropschema()
// testUser := User{Name: "Pasha", Password: "<PASSWORD>", Phone: "375291112233"}
// data, err := json.Marshal(testUser)
// require.NoError(t, err)
// body := bytes.NewReader(data)
// req := httptest.NewRequest("POST", "/api/signin", body)
// req.Header.Add("Content-Type", "application/json")
// rec := httptest.NewRecorder()
// RouterCreate(db).ServeHTTP(rec, req)
// var user User
// err = json.Unmarshal(rec.Body.Bytes(), &user)
// require.NoError(t, err)
// assert.Equal(t, http.StatusOK, rec.Code)
// AssertUsers(t, testUser, user)
// }
// repo := *NewUserRepo(db)
// testUsers := []User{
// {Name: "Pasha", Password: "<PASSWORD>", Phone: "375291112233"},
// {Name: "Roman", Password: "<PASSWORD>", Phone: "37533<PASSWORD>"},
// {Name: "Denis", Password: "<PASSWORD>", Phone: "375441112233"},
// }
// for i := 0; i < len(testUsers); i++ {
// err = repo.Create(&testUsers[i])
// assert.NoError(t, err)
// }
func Router(db *sql.DB) *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/api/users/{UserID:[0-9]+}", GetUser(*NewUserRepo(db)))
return r
}
func GetUserCase(t *testing.T) {
db, dropSchema := utility.SetupSchema(t)
defer dropSchema()
testCases := []struct {
Name string
ID int
Want []byte
}{
{Name: "first", ID: 1, Want: []byte(`{"data":{"id":1,"name":"Pasha","password":"<PASSWORD>","phone":"123456789012"}}`)},
{Name: "second", ID: 2, Want: []byte(`{"data":{"id":2,"name":"Masha","password":"<PASSWORD>","phone":"09876543212"}}`)},
{Name: "third", ID: 3, Want: []byte(`{"data":{"id":3,"name":"Nikolay","password":"<PASSWORD>","phone":"375291234599"}}`)},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", fmt.Sprintf("/api/users/%d", tc.ID), nil)
// assert.NoError(t, err)
// handler.ServeHTTP(rec, req)
Router(db).ServeHTTP(rec, req)
assert.Equal(t, tc.Want, rec.Body.Bytes())
})
}
}
<file_sep>CREATE TABLE IF NOT EXISTS sessions (
session_id text PRIMARY KEY,
user_id INTEGER REFERENCES users (id),
created_at timestamp NOT NULL,
expires_at timestamp NOT NULL
)
<file_sep>CREATE TABLE IF NOT EXISTS rooms (
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
name VARCHAR(20) UNIQUE
)
<file_sep>ALTER TABLE sessions
ADD deleted_at timestamp;
<file_sep>package chat
import (
"database/sql"
"fmt"
"github.com/pkg/errors"
)
func validateCreateRoom(repo RoomRepo, room Room) error {
_, err := repo.Get(room.ID)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return errors.Wrap(err, "error getting room from DB")
}
return nil
}
func HandleCreateRoom(repo RoomRepo, room Room) (Room, error) {
if err := validateCreateRoom(repo, room); err != nil {
return Room{}, err
}
if err := repo.Create(&room); err != nil {
fmt.Println(err)
return Room{}, err
}
return room, nil
}
func HandleListRooms(repo RoomRepo) ([]Room, error) {
rooms, err := repo.List()
if err == sql.ErrNoRows {
return []Room{}, nil
}
if err != nil {
return nil, err
}
return rooms, nil
}
func HandleGetRoom(repo RoomRepo, roomID int) (Room, error) {
room, err := repo.Get(roomID)
if err == sql.ErrNoRows {
return Room{}, ErrNotFound
}
if err != nil {
return Room{}, err
}
return *room, nil
}
func HandleCreateMessage(repo MsgRepo, text string, userID, roomID int) (Message, error) {
msg := Message{Text: text, UserID: userID, RoomID: roomID}
if err := repo.Create(&msg); err != nil {
return Message{}, errors.New("error creating message")
}
return msg, nil
}
func HandleListMessages(repo MsgRepo, roomID int) ([]Message, error) {
msgs, err := repo.ListByRoomID(roomID)
if err != nil {
return nil, errors.Wrap(err, "error getting messages from DB")
}
return msgs, nil
}
<file_sep>package main
import (
"database/sql"
"flag"
"fmt"
"net/http"
"github.com/Pashakrut94/SwiftChat/auth"
"github.com/Pashakrut94/SwiftChat/chat"
"github.com/Pashakrut94/SwiftChat/users"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
var (
pgUser = flag.String("pg_user", "Pasha", "PostgreSQL name")
pgPwd = flag.String("pg_pwd", "<PASSWORD>", "PostgreSQL password")
pgHost = flag.String("pg_host", "localhost", "PostgreSQL host")
pgPort = flag.String("pg_port", "54320", "PostgreSQL port")
pgDBname = flag.String("pg_dbname", "mydb", "PostgreSQL name of DB")
)
func main() {
flag.Parse()
connectionString := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s?sslmode=disable", *pgUser, *pgPwd, *pgHost, *pgPort, *pgDBname)
db, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
defer db.Close()
roomRepo := chat.NewRoomRepo(db)
userRepo := users.NewUserRepo(db)
msgRepo := chat.NewMsgRepo(db)
sessRepo := auth.NewSessionRepo(db)
authMiddleware := auth.RequireAuthentication(*sessRepo)
router := mux.NewRouter()
router.HandleFunc("/api/signup", auth.SignUp(userRepo, *sessRepo)).Methods("POST")
router.HandleFunc("/api/signin", auth.SignIn(userRepo, *sessRepo)).Methods("POST")
router.HandleFunc("/api/logout", auth.Logout(*userRepo, *sessRepo)).Methods("POST")
router.Handle("/api/rooms", authMiddleware(chat.CreateRoom(*roomRepo))).Methods("POST")
router.Handle("/api/rooms", authMiddleware(chat.ListRooms(*roomRepo))).Methods("GET")
router.Handle("/api/rooms/{RoomID:[0-9]+}", authMiddleware(chat.GetRoom(*roomRepo))).Methods("GET")
router.Handle("/api/users", authMiddleware(users.ListUsers(*userRepo))).Methods("GET")
router.Handle("/api/users/{UserID:[0-9]+}", authMiddleware(users.GetUser(*userRepo))).Methods("GET")
router.Handle("/api/rooms/{RoomID:[0-9]+}/messages", authMiddleware(chat.CreateMessage(*msgRepo))).Methods("POST")
router.Handle("/api/rooms/{RoomID:[0-9]+}/messages", authMiddleware(chat.ListMessages(*msgRepo))).Methods("GET")
http.Handle("/", router)
fmt.Println("Server starts at :8080")
http.ListenAndServe(":8080", nil)
}
<file_sep>package auth
import (
"net/http"
"github.com/Pashakrut94/SwiftChat/handlers"
"github.com/pkg/errors"
)
func RequireAuthentication(sessRepo SessionRepo) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(sessionName)
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "error getting cookie from request").Error(), http.StatusUnauthorized)
return
}
session, err := HandleAuthentication(sessRepo, cookie.Value)
if err != nil {
switch errors.Cause(err) {
case ErrUnauthorized:
handlers.HandleResponseError(w, err.Error(), http.StatusUnauthorized)
return
default:
handlers.HandleResponseError(w, err.Error(), http.StatusInternalServerError)
return
}
}
ctx := WithSession(r.Context(), &session)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
<file_sep>package auth
import (
"database/sql"
"time"
)
type SessionRepo struct {
db *sql.DB
}
func NewSessionRepo(db *sql.DB) *SessionRepo {
return &SessionRepo{db: db}
}
func (repo *SessionRepo) Create(sessionID string, userID int, expires time.Time) error {
q := "insert into sessions (session_id, user_id, created_at, expires_at) values ($1,$2,$3,$4)"
now := time.Now()
_, err := repo.db.Exec(q, sessionID, userID, now, expires)
if err != nil {
return err
}
return nil
}
func (repo *SessionRepo) Delete(sessionID string) error {
q := "update sessions set deleted_at = $1 where session_id = $2"
now := time.Now()
_, err := repo.db.Exec(q, now, sessionID)
if err != nil {
return err
}
return nil
}
func (repo *SessionRepo) get(q string, args ...interface{}) (*Session, error) {
var s Session
if err := repo.db.QueryRow(q, args...).Scan(
&s.SessionID,
&s.UserID,
&s.CreatedAt,
&s.ExpiresAt,
&s.DeletedAt); err != nil {
return nil, err
}
return &s, nil
}
func (repo *SessionRepo) Get(sessionID string) (*Session, error) {
return repo.get("select session_id, user_id, created_at, expires_at, deleted_at from sessions where session_id = $1 and deleted_at is null", sessionID)
}
<file_sep>package auth
import (
"github.com/pkg/errors"
)
var (
ErrUserAlreadyExists = errors.New("user already exists")
ErrValidationError = errors.New("validation error")
ErrUnauthorized = errors.New("unauthorized error")
)
<file_sep>package chat
import (
"github.com/pkg/errors"
)
var (
ErrNotFound = errors.New("can't find credentials")
ErrRoomAlreadyExists = errors.New("room already exists")
)
<file_sep>package auth
import (
"context"
)
const key = "session"
func WithSession(parent context.Context, sess *Session) context.Context {
return context.WithValue(parent, key, sess)
}
func SessionValue(ctx context.Context) *Session {
v := ctx.Value(key)
session := v.(*Session)
return session
}
<file_sep>package chat
import (
"encoding/json"
"net/http"
"strconv"
"github.com/Pashakrut94/SwiftChat/auth"
"github.com/Pashakrut94/SwiftChat/handlers"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
"github.com/pkg/errors"
)
//уникальное имя, добавь кейс в ошибках для этого, добавь ошибку в этом пакете отдельную и обрабатывай через нее
func CreateRoom(repo RoomRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, pretty := r.URL.Query()["pretty"]
var room Room
if err := json.NewDecoder(r.Body).Decode(&room); err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "error parsing signup request").Error(), http.StatusBadRequest)
return
}
room, err := HandleCreateRoom(repo, room)
if err != nil {
switch errors.Cause(err) {
case ErrRoomAlreadyExists:
handlers.HandleResponseError(w, errors.Wrap(err, "room already exists").Error(), http.StatusBadRequest)
return
default:
handlers.HandleResponseError(w, errors.Wrap(err, "error creating room").Error(), http.StatusInternalServerError)
return
}
}
handlers.HandleResponse(w, room, pretty)
}
}
func ListRooms(repo RoomRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, pretty := r.URL.Query()["pretty"]
rooms, err := HandleListRooms(repo)
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "error listing of rooms").Error(), http.StatusInternalServerError)
return
}
handlers.HandleResponse(w, rooms, pretty)
}
}
func GetRoom(repo RoomRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
variables := mux.Vars(r)
roomID, err := strconv.Atoi(variables["RoomID"])
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "incorrect enter of RoomID").Error(), http.StatusBadRequest)
return
}
room, err := HandleGetRoom(repo, roomID)
if err != nil {
switch errors.Cause(err) {
case ErrNotFound:
handlers.HandleResponseError(w, errors.Wrap(err, err.Error()).Error(), http.StatusNotFound)
return
default:
handlers.HandleResponseError(w, errors.Wrap(err, "error no rows").Error(), http.StatusInternalServerError)
return
}
}
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, room, pretty)
}
}
type CreateMessageRequest struct {
Text string `json:"text"`
}
func CreateMessage(repo MsgRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := auth.SessionValue(ctx)
variables := mux.Vars(r)
roomID, err := strconv.Atoi(variables["RoomID"])
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "incorrect enter of RoomID").Error(), http.StatusBadRequest)
return
}
var req CreateMessageRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "error parsing signup request").Error(), http.StatusBadRequest)
return
}
msg, err := HandleCreateMessage(repo, req.Text, session.UserID, roomID)
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, err.Error()).Error(), http.StatusInternalServerError)
return
}
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, msg, pretty)
}
}
func ListMessages(repo MsgRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
roomID, err := strconv.Atoi(vars["RoomID"])
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "incorrect enter of RoomID").Error(), http.StatusBadRequest)
return
}
msgs, err := HandleListMessages(repo, roomID)
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "error getting messages").Error(), http.StatusBadRequest)
return
}
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, msgs, pretty)
}
}
<file_sep>package utility
import (
"database/sql"
"flag"
"fmt"
"math/rand"
"strconv"
"testing"
"time"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
_ "github.com/lib/pq"
"github.com/stretchr/testify/require"
)
var (
testPGUser = flag.String("pg_user", "Pasha", "PostgreSQL name")
testPGPwd = flag.String("pg_pwd", "<PASSWORD>", "PostgreSQL password")
testPGHost = flag.String("pg_host", "localhost", "PostgreSQL host")
testPGPort = flag.String("pg_port", "54320", "PostgreSQL port")
testPGDBname = flag.String("pg_dbname", "test_mydb", "PostgreSQL name of DB")
migrationsSource = flag.String("migration_source", "file:///home/anduser/Documents/SwiftChat/migrations", "The path to migrations directory") //"file:///home/anduser/Documents/SwiftChat/migrations"
)
func SetupSchema(t *testing.T) (*sql.DB, func()) {
flag.Parse()
rand.Seed(time.Now().UnixNano())
schemaName := "test" + strconv.FormatInt(rand.Int63(), 10)
connectionString := fmt.Sprintf("host=%s port=%s dbname=%s user=%s password='%s' sslmode=disable search_path=%s", *testPGHost, *testPGPort, *testPGDBname, *testPGUser, *testPGPwd, schemaName)
db, err := sql.Open("postgres", connectionString)
require.NoError(t, err)
_, err = db.Exec("CREATE SCHEMA " + schemaName)
require.NoError(t, err)
driver, err := postgres.WithInstance(db, &postgres.Config{})
require.NoError(t, err)
m, err := migrate.NewWithDatabaseInstance(*migrationsSource, "postgres", driver)
require.NoError(t, err)
err = m.Up()
require.NoError(t, err)
return db, func() {
_, err := db.Exec("DROP SCHEMA " + schemaName + " CASCADE")
require.NoError(t, err)
db.Close()
}
}
<file_sep>module github.com/Pashakrut94/SwiftChat
go 1.13
require (
github.com/go-pg/migrations/v7 v7.1.9 // indirect
github.com/golang-migrate/migrate v3.5.4+incompatible
github.com/golang-migrate/migrate/v4 v4.7.1
github.com/gorilla/mux v1.7.3
github.com/lib/pq v1.2.0
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d
github.com/pkg/errors v0.9.0
github.com/stretchr/testify v1.4.0
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413
)
<file_sep>package users
import (
"net/http"
_ "github.com/lib/pq"
"github.com/pkg/errors"
"strconv"
"github.com/Pashakrut94/SwiftChat/handlers"
"github.com/gorilla/mux"
)
func GetUser(repo UserRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userID, err := strconv.Atoi(vars["UserID"])
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "incorrect enter of userID").Error(), http.StatusBadRequest)
return
}
user, err := HandleGetUSer(repo, userID)
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, err.Error()).Error(), http.StatusBadRequest)
return
}
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, user, pretty)
}
}
func ListUsers(repo UserRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
allUsers, err := HandleListUSer(repo)
if err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, err.Error()).Error(), http.StatusInternalServerError)
return
}
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, allUsers, pretty)
}
}
<file_sep>CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
name VARCHAR(50),
phone VARCHAR(12) UNIQUE,
password VARCHAR(150)
)
<file_sep>CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
text TEXT,
room_id INTEGER REFERENCES rooms (id),
user_id INTEGER REFERENCES users (id)
)
<file_sep>package chat
import (
"database/sql"
)
type MsgRepo struct {
db *sql.DB
}
func NewMsgRepo(db *sql.DB) *MsgRepo {
return &MsgRepo{db: db}
}
func (repo *MsgRepo) Create(msg *Message) error {
q := "insert into messages (text, user_id, room_id) values ($1, $2, $3) returning id"
err := repo.db.QueryRow(q, msg.Text, msg.UserID, msg.RoomID).Scan(&msg.ID)
if err != nil {
return err
}
return nil
}
func (repo *MsgRepo) ListByRoomID(roomID int) ([]Message, error) {
q := "select id, text, user_id, room_id from messages where room_id = $1"
rows, err := repo.db.Query(q, roomID)
if err != nil {
return nil, err
}
defer rows.Close()
var msgs []Message
for rows.Next() {
var msg Message
err := rows.Scan(&msg.ID, &msg.Text, &msg.UserID, &msg.RoomID)
if err != nil {
continue
}
if msg.RoomID == roomID {
msgs = append(msgs, msg)
}
}
return msgs, nil
}
type RoomRepo struct {
db *sql.DB
}
func NewRoomRepo(db *sql.DB) *RoomRepo {
return &RoomRepo{db: db}
}
func (repo *RoomRepo) Create(room *Room) error {
q := "insert into rooms (name) values ($1) returning id"
err := repo.db.QueryRow(q, room.Name).Scan(&room.ID)
if err != nil {
return err
}
return nil
}
func (repo *RoomRepo) List() ([]Room, error) {
q := "select id , name from rooms"
rows, err := repo.db.Query(q)
if err == sql.ErrNoRows {
return []Room{}, nil
}
if err != nil {
return nil, err
}
defer rows.Close()
var rooms []Room
for rows.Next() {
var room Room
err := rows.Scan(&room.ID, &room.Name)
if err != nil {
continue
}
rooms = append(rooms, room)
}
return rooms, nil
}
func (repo *RoomRepo) Get(id int) (*Room, error) {
row := repo.db.QueryRow("select id , name from rooms where id = $1", id)
var room Room
err := row.Scan(&room.ID, &room.Name)
if err == sql.ErrNoRows {
return nil, err
}
if err != nil {
return nil, err
}
return &room, nil
}
<file_sep>package users
import (
"database/sql"
"fmt"
)
type UserRepo struct {
db *sql.DB
}
func NewUserRepo(db *sql.DB) *UserRepo {
return &UserRepo{db: db}
}
func (repo *UserRepo) get(q string, args ...interface{}) (*User, error) {
var u User
if err := repo.db.QueryRow(q, args...).Scan(
&u.ID,
&u.Name,
&u.Phone,
&u.Password); err != nil {
return nil, err
}
return &u, nil
}
func (repo *UserRepo) Get(id int) (*User, error) {
return repo.get("select * from users where id = $1", id)
}
func (repo *UserRepo) GetByPhone(phone string) (*User, error) {
return repo.get("select * from users where phone = $1", phone)
}
func (repo *UserRepo) List() ([]User, error) {
rows, err := repo.db.Query("select * from users")
if err != nil {
return nil, err
}
defer rows.Close()
users := []User{}
for rows.Next() {
user := User{}
err := rows.Scan(&user.ID, &user.Name, &user.Phone, &user.Password)
if err != nil {
fmt.Println(err)
continue
}
users = append(users, user)
}
return users, nil
}
func (repo *UserRepo) Create(user *User) error {
err := repo.db.QueryRow("insert into users (name, phone, password) values ($1,$2,$3) returning id", user.Name, user.Phone, user.Password).Scan(&user.ID)
if err != nil {
return err
}
return nil
}
<file_sep>package chat
type Message struct {
ID int `json:"id"`
Text string `json:"text"`
UserID int `json:"user_id"`
RoomID int `json:"room_id"`
}
type Room struct {
ID int `json:"id"`
Name string `json:"name"`
}
<file_sep>package auth
import (
"bytes"
"database/sql"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Pashakrut94/SwiftChat/users"
"github.com/Pashakrut94/SwiftChat/utility"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Router(db *sql.DB) *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/api/signup", SignUp(users.NewUserRepo(db), *NewSessionRepo(db)))
r.HandleFunc("/api/signin", SignIn(users.NewUserRepo(db), *NewSessionRepo(db)))
r.HandleFunc("/api/logout", Logout(*users.NewUserRepo(db), *NewSessionRepo(db)))
return r
}
func TestSignUp(t *testing.T) {
db, dropschema := utility.SetupSchema(t)
defer dropschema()
signUpRequest := SignUpRequest{Username: "Pasha", Password: "<PASSWORD>", Phone: "375291112233"}
data, err := json.Marshal(signUpRequest)
require.NoError(t, err)
body := bytes.NewReader(data)
req := httptest.NewRequest("POST", "/api/signup", body)
req.Header.Add("Content-Type", "application/json")
rec := httptest.NewRecorder()
Router(db).ServeHTTP(rec, req)
var resp struct {
Data users.User `json:"data"`
}
err = json.Unmarshal(rec.Body.Bytes(), &resp)
require.NoError(t, err)
// User data exists in signup responses
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, 1, resp.Data.ID)
assert.NotEqual(t, signUpRequest.Password, resp.Data.Password)
// Signed up user exists in db
repo := users.NewUserRepo(db)
userByID, err := repo.Get(resp.Data.ID)
require.NoError(t, err)
assert.Equal(t, userByID.Name, resp.Data.Name)
assert.Equal(t, userByID.Phone, resp.Data.Phone)
assert.Equal(t, userByID.Password, resp.Data.Password)
// Valid session created
sid := rec.Result().Cookies()[0].Value
sessRepo := NewSessionRepo(db)
sess, err := sessRepo.Get(sid)
assert.NoError(t, err)
assert.Equal(t, resp.Data.ID, sess.UserID)
assert.Nil(t, sess.DeletedAt)
rec = httptest.NewRecorder()
body.Seek(0, 0)
Router(db).ServeHTTP(rec, req)
var errResp struct {
Error string `json:"error"`
}
err = json.Unmarshal(rec.Body.Bytes(), &errResp)
require.NoError(t, err)
// User already exists
assert.Equal(t, http.StatusBadRequest, rec.Code)
assert.Equal(t, "user already exists", errResp.Error)
}
func TestSignIn(t *testing.T) {
db, dropschema := utility.SetupSchema(t)
defer dropschema()
signInRequest := users.User{Phone: "375441235588", Password: "<PASSWORD>", Name: "Pasha"}
repo := users.NewUserRepo(db)
user, err := HandleSignUp(repo, signInRequest.Name, signInRequest.Password, signInRequest.Phone)
require.NoError(t, err)
data, err := json.Marshal(signInRequest)
require.NoError(t, err)
body := bytes.NewReader(data)
req := httptest.NewRequest("POST", "/api/signin", body)
req.Header.Add("Content-Type", "application/json")
rec := httptest.NewRecorder()
Router(db).ServeHTTP(rec, req)
var resp struct {
Data users.User `json:"data"`
}
err = json.Unmarshal(rec.Body.Bytes(), &resp)
require.NoError(t, err)
// User data exists in signin response
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, user.ID, resp.Data.ID)
assert.Equal(t, user.Password, resp.Data.Password)
assert.Equal(t, user.Phone, resp.Data.Phone)
// Signen in user exists in db
userByID, err := repo.Get(resp.Data.ID)
require.NoError(t, err)
assert.Equal(t, userByID.Name, resp.Data.Name)
assert.Equal(t, userByID.Phone, resp.Data.Phone)
assert.Equal(t, userByID.Password, resp.Data.Password)
// Valid session created
sid := rec.Result().Cookies()[0].Value
sessRepo := NewSessionRepo(db)
sess, err := sessRepo.Get(sid)
assert.NoError(t, err)
assert.Equal(t, resp.Data.ID, sess.UserID)
assert.Nil(t, sess.DeletedAt)
}
func TestLogout(t *testing.T) {
// Going to signup handler for seed user and set cookies
db, dropschema := utility.SetupSchema(t)
defer dropschema()
signUpRequest := SignUpRequest{Username: "Pasha", Password: "<PASSWORD>", Phone: "375291112233"}
data, err := json.Marshal(signUpRequest)
require.NoError(t, err)
body := bytes.NewReader(data)
req := httptest.NewRequest("POST", "/api/signup", body)
req.Header.Add("Content-Type", "application/json")
rec := httptest.NewRecorder()
Router(db).ServeHTTP(rec, req)
sid := rec.Result().Cookies()[0].Value
sessRepo := NewSessionRepo(db)
sess, err := sessRepo.Get(sid)
assert.NoError(t, err)
assert.Nil(t, sess.DeletedAt)
rec = httptest.NewRecorder()
req = httptest.NewRequest("POST", "/api/logout", nil)
req.AddCookie(&http.Cookie{Name: sessionName, Value: sid})
req.Header.Add("Content-Type", "application/json")
Router(db).ServeHTTP(rec, req)
sess, err = sessRepo.Get(sid)
assert.Error(t, err)
cookie := rec.Result().Cookies()[0]
assert.Empty(t, cookie.Value)
assert.Equal(t, time.Unix(0, 0).UTC(), cookie.Expires)
}
<file_sep>package auth
import (
"encoding/json"
"net/http"
"time"
"github.com/Pashakrut94/SwiftChat/handlers"
"github.com/Pashakrut94/SwiftChat/users"
"github.com/pkg/errors"
)
type SignUpRequest struct {
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
Phone string `json:"phone"`
}
func SignUp(userRepo *users.UserRepo, sessRepo SessionRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, err := r.Cookie(sessionName)
if err == nil {
handlers.HandleResponseError(w, errors.Wrap(err, "this user already has a session").Error(), http.StatusInternalServerError)
return
}
var req SignUpRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "error parsing signup request").Error(), http.StatusBadRequest)
return
}
user, err := HandleSignUp(userRepo, req.Username, req.Password, req.Phone)
if err != nil {
switch errors.Cause(err) {
case ErrValidationError, ErrUserAlreadyExists:
handlers.HandleResponseError(w, err.Error(), http.StatusBadRequest)
return
default:
handlers.HandleResponseError(w, err.Error(), http.StatusInternalServerError)
return
}
}
sid, expires, err := SetNewSession(sessRepo, user.ID)
if err != nil {
handlers.HandleResponseError(w, err.Error(), http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{Name: sessionName, Value: sid, HttpOnly: true, Expires: expires})
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, user, pretty)
}
}
type SignInRequest struct {
Phone string `json:"phone"`
Password string `json:"<PASSWORD>"`
}
func SignIn(userRepo *users.UserRepo, sessRepo SessionRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, err := r.Cookie(sessionName)
if err == nil {
handlers.HandleResponseError(w, errors.Wrap(err, "this user already has a session").Error(), http.StatusInternalServerError)
return
}
var req SignInRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
handlers.HandleResponseError(w, errors.Wrap(err, "wrong structure of the body in decoding").Error(), http.StatusBadRequest)
return
}
user, err := HandleSignIn(userRepo, req.Phone, req.Password)
if err != nil {
switch errors.Cause(err) {
case ErrValidationError:
handlers.HandleResponseError(w, err.Error(), http.StatusBadRequest)
return
default:
handlers.HandleResponseError(w, err.Error(), http.StatusInternalServerError)
return
}
}
sid, expires, err := SetNewSession(sessRepo, user.ID)
if err != nil {
handlers.HandleResponseError(w, err.Error(), http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{Name: sessionName, Value: sid, HttpOnly: true, Expires: expires})
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, user, pretty)
}
}
func Logout(userRepo users.UserRepo, sessRepo SessionRepo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie(sessionName)
if err != nil {
handlers.HandleResponseError(w, err.Error(), http.StatusUnauthorized)
return
}
if err := sessRepo.Delete(c.Value); err != nil {
handlers.HandleResponseError(w, err.Error(), http.StatusInternalServerError)
return
}
c = &http.Cookie{
Name: sessionName,
Value: "",
Expires: time.Unix(0, 0).UTC(),
HttpOnly: true,
}
http.SetCookie(w, c)
_, pretty := r.URL.Query()["pretty"]
handlers.HandleResponse(w, nil, pretty)
}
}
<file_sep>package auth
import (
"database/sql"
"time"
"github.com/Pashakrut94/SwiftChat/users"
uuid "github.com/nu7hatch/gouuid"
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
)
func validateSignUpRequest(username, password, phone string) error {
if len(username) < 2 {
return errors.Wrap(ErrValidationError, "username is too short")
}
if len(password) < 8 {
return errors.Wrap(ErrValidationError, "password can't be shorter then 8 symbols")
}
if len(phone) < 12 {
return errors.Wrap(ErrValidationError, "incorrect phone number")
}
return nil
}
func HandleSignUp(userRepo *users.UserRepo, username, password, phone string) (*users.User, error) {
if err := validateSignUpRequest(username, password, phone); err != nil {
return nil, err
}
_, err := userRepo.GetByPhone(phone)
if err == nil {
return nil, ErrUserAlreadyExists
}
if err != sql.ErrNoRows {
return nil, errors.Wrap(err, "error getting user by phone")
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, errors.Wrap(err, "unable to generate password hash")
}
user := users.User{Name: username, Phone: phone, Password: string(hashedPassword)}
if err := userRepo.Create(&user); err != nil {
return nil, errors.Wrap(err, "unable to create user")
}
return &user, nil
}
func validateSignIn(phone, password string) error {
if len(phone) < 12 {
return errors.Wrap(ErrValidationError, "incorrect input of phone number")
}
if len(password) < 8 {
return errors.Wrap(ErrValidationError, "password can't be shorter then 8 symbols")
}
return nil
}
func HandleSignIn(userRepo *users.UserRepo, phone, password string) (*users.User, error) {
if err := validateSignIn(phone, password); err != nil {
return nil, err
}
user, err := userRepo.GetByPhone(phone)
if err != nil {
return nil, errors.Wrap(err, "error getting user by phone from DB")
}
if err == sql.ErrNoRows {
return nil, errors.Wrap(err, "error getting user from DB")
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil {
return nil, errors.Wrap(err, "mismatch converted password and hash")
}
return user, nil
}
func HandleAuthentication(sessRepo SessionRepo, cookieValue string) (Session, error) {
session, err := sessRepo.Get(cookieValue)
if err == sql.ErrNoRows {
return Session{}, errors.Wrap(err, "error session not found")
}
if err != nil {
return Session{}, errors.Wrap(err, "error getting session from DB")
}
if time.Now().After(session.ExpiresAt) {
if err := sessRepo.Delete(cookieValue); err != nil {
return Session{}, errors.Wrap(err, "error updating deleted_at field")
}
return Session{}, errors.Wrap(err, "session expired")
}
return *session, nil
}
func SetNewSession(sessRepo SessionRepo, userID int) (sid string, expires time.Time, err error) {
sessID, err := uuid.NewV4()
if err != nil {
return "", time.Time{}, errors.Wrap(err, "error getting hash of the session")
}
sid = sessID.String()
expires = time.Now().Add(time.Minute * 72000)
if err = sessRepo.Create(sid, userID, expires); err != nil {
return sid, expires, errors.Wrap(err, "error creating new session")
}
return
}
<file_sep>package users
import "github.com/pkg/errors"
func HandleGetUSer(repo UserRepo, userID int) (User, error) {
user, err := repo.Get(userID)
if err != nil {
return User{}, errors.Wrap(err, "error getting user by ID")
}
return *user, nil
}
func HandleListUSer(repo UserRepo) ([]User, error) {
allUsers, err := repo.List()
if err != nil {
return nil, errors.Wrap(err, "error getting list of users")
}
return allUsers, nil
}
<file_sep>package users
import (
"testing"
"github.com/Pashakrut94/SwiftChat/utility"
_ "github.com/golang-migrate/migrate/v4/source/file"
_ "github.com/lib/pq"
"github.com/stretchr/testify/assert"
)
func AssertUsers(t *testing.T, u1, u2 User) {
assert.Equal(t, u1.Name, u2.Name)
assert.Equal(t, u1.Password, u2.Password)
assert.Equal(t, u1.Phone, u2.Phone)
}
func TestRepo(t *testing.T) {
db, dropSchema := utility.SetupSchema(t)
defer dropSchema()
repo := NewUserRepo(db)
testUsers := []User{
{Name: "Pasha", Password: "<PASSWORD>", Phone: "375291112233"},
{Name: "Roman", Password: "<PASSWORD>", Phone: "375331112233"},
{Name: "Denis", Password: "<PASSWORD>", Phone: "375441112233"},
}
for i := 0; i < len(testUsers); i++ {
err := repo.Create(&testUsers[i])
assert.NoError(t, err)
}
userByID, err := repo.Get(1)
assert.NoError(t, err)
AssertUsers(t, testUsers[0], *userByID)
userByPhone, err := repo.GetByPhone(testUsers[0].Phone)
assert.NoError(t, err)
AssertUsers(t, testUsers[0], *userByPhone)
users, err := repo.List()
assert.NoError(t, err)
for i, user := range users {
AssertUsers(t, testUsers[i], user)
}
}
|
9926182b708162ccd0d2fe5099fc73e255a346fe
|
[
"SQL",
"Go Module",
"Go"
] | 26
|
Go
|
Pashakrut94/SwiftChat
|
a4f2fae48d919745b8e8c31aa60851b610f3b330
|
4e57764227a4e99ed183c12e0e9c8a64a1bea631
|
refs/heads/master
|
<repo_name>BokarevDmitry/lab2<file_sep>/src/main/java/bokarev/FlightMapper.java
package bokarev;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class FlightMapper extends Mapper<LongWritable, Text, TextPair, Text> {
private static String DESCRIPTION_LINE = "ARR_DELAY_NEW";
@Override
protected void map(LongWritable key, Text value, Mapper.Context context) throws IOException, InterruptedException {
String[] columns = CSVParser.parseFlights(value);
String delayTime = CSVParser.getDelayTime(columns);
if (!delayTime.contains(DESCRIPTION_LINE) && delayTime.length()>0 && Float.parseFloat(delayTime)>0) {
context.write(new TextPair(CSVParser.getAirportCode(columns), "1"), new Text(delayTime));
}
}
}<file_sep>/src/main/java/bokarev/CSVParser.java
package bokarev;
import org.apache.hadoop.io.Text;
public class CSVParser {
public static String[] parseFlights(Text s) {
return s.toString().split(",");
}
public static String[] parseAirports (Text s) {
return s.toString().split("\",\"");
}
public static String removeQuotes (String s) {return s.replaceAll("[\"]", "");}
public static String getAirCode (String[] s) {return s[0];}
public static String getAirportName (String[] s) { return s[1];}
public static String getAirportCode (String[] s) {return s[14];}
public static String getDelayTime (String[] s) {return s[18];}
}<file_sep>/src/main/java/bokarev/AirportMapper.java
package bokarev;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class AirportMapper extends Mapper<LongWritable, Text, TextPair, Text> {
private static String DESCRIPTION_LINE = "Code";
@Override
protected void map(LongWritable key, Text value, Mapper.Context context) throws IOException, InterruptedException {
String[] columns = CSVParser.parseAirports(value);
String airportCode = CSVParser.getAirCode(columns);
if (!airportCode.contains(DESCRIPTION_LINE)) {
String airportName = CSVParser.getAirportName(columns);
context.write(new TextPair(CSVParser.removeQuotes(airportCode), "0"), new Text(CSVParser.removeQuotes(airportName)));
}
}
}<file_sep>/src/main/java/bokarev/ReduceJoiner.java
package bokarev;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.io.Text;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
public class ReduceJoiner extends Reducer<TextPair, Text, Text, Text> {
@Override
protected void reduce(TextPair key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int count = 0;
Double time = 0.00;
Double minTime = Double.MAX_VALUE;
Double maxTime = 0.00;
DecimalFormat f = new DecimalFormat("#.#");
Iterator<Text> iter = values.iterator();
Text airportName = new Text(iter.next());
while (iter.hasNext()) {
String timeDelayInfo = iter.next().toString();
double timeDelay = Float.parseFloat(timeDelayInfo);
count++;
time += timeDelay;
if (timeDelay<minTime) minTime=timeDelay;
if (timeDelay>maxTime) maxTime=timeDelay;
}
if (count>0) {
String delayLine = "Average = " + f.format(time/count) + " Min = " + minTime + " Max = " + maxTime;
context.write(airportName, new Text(delayLine));
}
}
}<file_sep>/src/main/java/bokarev/FlightComparator.java
package bokarev;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.io.WritableComparable;
public class FlightComparator extends WritableComparator{
public FlightComparator() {
super(TextPair.class, true);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
TextPair a1 = (TextPair) a;
TextPair b1 = (TextPair) b;
return a1.getCode().compareTo(b1.getCode());
}
}
|
0e306c8f18ae3179c04bd79f90ac1f823ddad749
|
[
"Java"
] | 5
|
Java
|
BokarevDmitry/lab2
|
f6e09875955d9bc404b92b6482acd7b3ad7021ec
|
cdc2920bf85eba5d2ba928a9d6a5168209e9c53d
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "private, max-age=86400, stale-while-revalidate=604800")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
<file_sep>var MAIN = (function() {
var pizzaFlavors = 100,
movingPizza = document.querySelector("#movingPizzas1"),
container,
randomPizzas = document.querySelector("#randomPizzas"),
pizzaSizeSelector = document.querySelector("#pizzaSize"),
moverSelector = [];
var getContainer = function() {
if(!container) container = document.querySelectorAll(".randomPizzaContainer");
return container;
};
var createAllPizzas = function() {
for (var i = pizzaFlavors; i > 2; i--) {
randomPizzas.appendChild(PIZZA_FACTORY.createPizza(i));
}
};
var generateSlidingPizzas = function() {
var cols = 6;
var lineHeight = 256;
var backgroundPizzas = Math.ceil(window.innerHeight / lineHeight) * cols * 3;
for (var i = 0; i < backgroundPizzas; i++) {
var l = (i % cols) * lineHeight;
var t = (Math.floor(i / cols) * lineHeight) + 'px';
moverSelector[i] = PIZZA_FACTORY.createPizzaImg(l, t);
movingPizza.appendChild(moverSelector[i]);
}
};
var updatePositions = function() {
var top = document.body.scrollTop / 1250;
var j = 0;
for (var i = 0, max = moverSelector.length; i < max; i++) {
var selector = moverSelector[i];
var left = selector.basicLeft + 100 * Math.sin(top + j);
selector.style.left = left + 'px';
j = j == 4 ? 0 : j++;
}
};
var resizePizzas = function(size) {
var pizzaSize = PIZZA_FACTORY.pizzaSize(size);
if(pizzaSize) {
pizzaSizeSelector.innerHTML = pizzaSize.label;
PIZZA_FACTORY.changePizzaSize(getContainer(), pizzaSize.size);
}
};
return {
"createAllPizzas": createAllPizzas,
"generateSlidingPizzas": generateSlidingPizzas,
"updatePositions": updatePositions,
"resizePizzas": resizePizzas
};
}());
var resizePizzas = function (size) {
LOG_HELPER.measureTime(
"mark_start_resize",
"mark_end_resize",
"measure_pizza_resize",
function() { MAIN.resizePizzas(size); },
function(time) {
console.log("Time to resize pizzas: " + time[time.length - 1].duration + "ms")
});
};
var updatePositions = function() {
LOG_HELPER.measureTime(
"mark_start_frame",
"mark_end_frame",
"measure_frame_duration",
function() {
LOG_HELPER.incFrame();
MAIN.updatePositions();
},
function(time) { LOG_HELPER.logAverageFrame(time); });
};
window.addEventListener('scroll', updatePositions);
document.addEventListener('DOMContentLoaded', function () {
LOG_HELPER.measureTime(
"mark_start_generating",
"mark_end_generating",
"measure_pizza_generation",
MAIN.createAllPizzas,
function(time) {
console.log("Time to generate pizzas on load: " + time[0].duration + "ms");
});
MAIN.generateSlidingPizzas();
updatePositions();
});
|
76fc02fedc181e018f7680a5c60a87b646543ecf
|
[
"JavaScript",
"Python"
] | 2
|
Python
|
AlanPrado/udportfolio
|
abd93e203e7aba108e1e5855e41692d5dc50217d
|
21692f85411814c00a9100367c12a7a0677edfd9
|
refs/heads/master
|
<file_sep>import Vue from 'vue';
import Router from 'vue-router';
import PL from './views/pl.vue';
import EN from './views/en.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'pl',
component: PL,
},
{
path: '/EN',
name: 'en',
component: EN,
// component: () => import(/* webpackChunkName: "about" */ './views/en.vue'),
},
],
});
|
f47f383a5d94a9fa584441f5a5c0a96cac5b028e
|
[
"JavaScript"
] | 1
|
JavaScript
|
Kordrad/cv-vue.js
|
b64b5a1f8aeca00bbe871c2f02434d8612639be0
|
4d7675cc9d680f5593ebfd15a2c544e632e4b595
|
refs/heads/master
|
<file_sep># SetParser
Program that takes a set and determines if it's written in the correct format. Example: {1,{2,3}}
Uses a pattern to check for any kind of value that doesn't work with the program.
If an error is detected then the console with have an error outputted to it.
<file_sep>import java.util.Scanner;
public class MyParser {
public static void main(String[] args) {
int num = 1; int count = 0;
while (count < 10) {
System.out.print(num++ + ". Input a set to test if its format is correct: ");
String in = new Scanner(System.in).nextLine();
boolean state = true; //Turns false when the set is invalid
int bracketCount = 0; //Keeps track of bracket pairs
int i = 0; //int to count tokens from the string
if (in.startsWith("{") && in.endsWith("}")) {
scan:
for (; i < in.length(); i++) {
switch (in.charAt(i)) {
case '{': //Tallies start brackets
bracketCount++;
break;
case '}': //Removes a tally for every end bracket to make pairs
bracketCount--;
if (bracketCount == 0) //If the first bracket is used prematurely end the loop
break scan;
if(i < in.length()-1)
if(in.charAt(i+1) == '{' || in.charAt(i+1) == 'n')
state = false;
break;
case ',': //Validates that the char before/after the comma is the correct bracket or a 'n'
if (!(in.charAt(i - 1) == '}' && in.charAt(i + 1) == 'n' || in.charAt(i - 1) == 'n' && in.charAt(i + 1) == 'n' ||
in.charAt(i - 1) == 'n' && in.charAt(i + 1) == '{' || in.charAt(i - 1) == '}' && in.charAt(i + 1) == '{'))
state = false;
break;
case 'n': //Checks to validate that the chars around the 'n' are correct
if (in.charAt(i - 1) == 'n' || in.charAt(i + 1) == 'n' || in.charAt(i + 1) == '{')
state = false;
break;
default:
state = false;
break;
}
}
if (bracketCount == 0 && i != in.length() - 1) //If the loop ends prematurely the set is invalid
state = false;
} else
state = false;
if (state && bracketCount == 0) //Outputs the validation
System.out.println("Correct\n");
else
System.out.println("Incorrect Set Form . . . \n");
count++;
}
}
}
|
8fd940ca5df88f30db59ee11a19ec69e39a848ba
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
AidanWes/SetParser
|
b00c12a50bce004e6433d3df35c0ec5e7cb9bbfc
|
d42724b5c626971891e07b26250ec7b8d0029b6e
|
refs/heads/master
|
<repo_name>mittwald/salt-microservices<file_sep>/README.md
Deploying microservice architectures with Salt
==============================================
[](https://travis-ci.org/mittwald/salt-microservices)
Author and copyright
--------------------
<NAME>
Mittwald CM Service GmbH & Co. KG
This code is [MIT-licensed](LICENCE.txt).
Synopsis
--------
This repository contains [Salt](http://saltstack.com) formulas for easily
deploying a small, Docker-based [microservice](http://martinfowler.com/articles/microservices.html)
architecture, implementing the following features:
- Container-based deployment
- Using [Consul][consul] for service discovery
- Using [NGINX][nginx] for load balancing and service routing
- Using [Prometheus][prom] and [Grafana][grafana] for monitoring and alerting
- Zero-downtime (re)deployment of services using a few custom Salt modules
```
HTTP (Port 80, 443) │ │ HTTP (Port 80, 443)
identity.services.acme.co │ │ finances.services.acme.co
▼ ▼
┌───────────────────────────────────────┐ ┌────────┐
│ NGINX ├──────────────────────►│ │
└────────────┬─────────────────────┬────┘ │ │
│ │ │ │
HTTP (Port 10000) ┌──────┴───────┐ │ HTTP (Port 10010) │ │
identity.services.consul │ │ │ finances.service.consul │ │
▼ ▼ ▼ │ │
┌──────────┐ ┌──────────┐ ┌─────────┐ │ Consul │
│ Identity │ │ Identity │ │ Finance │ │ │
│ Service │ │ Service │ │ Service │ │ │
└──────────┘ └──────────┘ └─────────┘ │ │
│ │
┌───────────────────────────────────────┐ │ │
│ Docker │ │ │
└───────────────────────────────────────┘ └────────┘
```
Motivation
----------
The movitation of this project was to be able to host a small (!) microservice
infrastructure without adding the complexity of additional solutions like Mesos
or Kubernetes.
This probably does not scale beyond a few nodes, but sometimes that's all you
need.
Requirements
------------
- This formula was tested on Debian Linux. With a bit of luck, it should work
on recent Ubuntu versions, as well.
- You need to have [Docker](https://www.docker.com) installed. Since there are
a number of ways to install Docker, installing Docker is out of scope for
this formula. If you want to get up and running quickly, use the following
Salt states for installing Docker:
```yaml
docker-repo:
repo.managed:
- name: deb https://apt.dockerproject.org/repo debian-jessie main
- dist: debian-jessie
- file: /etc/apt/sources.list.d/docker.list
- gpgcheck: 1
- key_url: https://get.docker.com/gpg
docker-engine:
pkg.installed:
- require:
- repo: docker-repo
docker:
service.running:
- require:
- pkg: docker-engine
```
Remember to change the *distribution* above from `debian-jessie` to whatever
you happen to be running.
- You need the [docker-py](https://github.com/docker/docker-py) Python library.
The Docker states in this repository require at least version 1.3 of this
library (tested with 1.3.1). The easiest way to install this package is
using *pip*:
```shellsession
$ pip install "docker-py>=1.3.0,<1.4.0"
```
Alternatively, use the following Salt states to install docker-py:
```yaml
pip:
pkg.installed: []
docker-py:
pip.installed:
- name: docker-py>=1.3.0,<1.4.0
- require:
- pkg: pip
```
Installation
------------
See the [official documentation][salt-formulas] on how to use formulas in your
Salt setup. Assuming you have *GitFS* set up and configured on your Salt master,
simply configure this repository as a GitFS remote in your Salt configuration
file (typically `/etc/salt/master`):
```yaml
gitfs_remotes:
- https://github.com/mittwald/salt-microservices
```
To quote a very important warning from the official documentation:
>**We strongly recommend forking a formula repository** into your own GitHub
>account to avoid unexpected changes to your infrastructure.
>Many Salt Formulas are highly active repositories so pull new changes with care.
>Plus any additions you make to your fork can be easily sent back upstream with
>a quick pull request!
Using the microservice states
-----------------------------
### Setting up the Salt mine
This formula uses the [Salt mine][salt-mine] feature to discover servers in the
infrastructure. Specifically, the `network.ip_addrs` function needs to be
callable as a mine function. For this, ensure that the following pillar is set
for all servers of your infrastructure:
```yaml
mine_functions:
network.ip_addrs:
- eth0
```
### Setting up the Consul server(s)
You need at least one Consul server in your cluster (althoug a number of three
or five should be used in production for a high-availability setup).
First of all, you need to configure a [targeting expression][salt-targeting]
(and optionally a targeting mode) that can be used to match your consul servers.
The default expression will simply match the minion ID against the pattern
`consul-server*`. Use the pillar `consul:server_pattern` for this:
```yaml
consul:
server_pattern: "<your-consul-server-pattern>"
server_target_mode: "<glob|pcre|...>"
```
You can install these servers by using the `mwms.consul.server` state in your
`top.sls` file:
```yaml
'consul-server*':
- mwms.consul.server
```
During the next highstate call, Salt will install a Consul server on each of
these nodes and configure them to run in a cluster. The servers will also be
installed with the Consul UI. You should be able to access the UI by opening
any of your Consul servers on port 8500 in your browser.
### Setting up the Docker nodes
On the Docker nodes, a Consul agent has to be installed (or a Consul server).
You can use the `mwms.consul.agent` state for this. Furthermore, use the
`mwms.services` state to deploy the actual services:
```yaml
'service-node*':
- mwms.consul.agent
- mwms.services
```
### Setting up monitoring
For monitoring services, you can use the `mwms.monitoring` state for every node:
```yaml
'service-node*':
- mwms.monitoring
```
To install a Prometheus server to actually gather metrics, use the
`mwms.prometheus` state on one of your nodes:
```yaml
'service-node-monitoring':
- mwms.prometheus
```
# Deploying services
## Defining services
Services that should be deployed in your infrastructure are defined using
Salt pillars.
```yaml
#!jinja|yaml|gpg
microservices:
example:
hostname: example.services.acme.co
ssl_certificate: /etc/ssl/certs/your-domain.pem
ssl_key: /etc/ssl/private/your-domain.key
ssl_force: True
containers:
web:
instances: 2
docker_image: docker-registry.acme.co/services/example:latest
stateful: False
http: True
http_internal_port: 8000
base_port: 10000
links:
database: db
volumes:
- ["persistent", "/var/lib/persistent-app-data", "rw"]
environment:
DATABASE_PASSWORD: |
-----BEGIN PGP MESSAGE-----
...
db:
instances: 1
docker_image: mariadb:10
stateful: True
volumes:
- ["database", "/var/lib/mysql", "rw"]
```
Supposing that each service pillar resides in it's own file (like for example,
`<pillar-root>/services/example.sls`), you can manually distribute your services
on your hosts in your top file:
```yaml
service-node*:
- services.identity
service-node-001:
- services.finance
service-node-002:
- services.mailing
```
**Note**: Yes, you need to distribute services manually to your hosts. Yes, this
is done on purpose to offer a low-complexity solution for small-scale
architectures. If you want more, use [Kubernetes][kubernetes] or
[Marathon][marathon].
## Updating existing services
For updating existing services, you can use the `microservice.redeploy` Salt
module. This module will try to pull a newer version of the image that the
application containers were created from. If a newer image exists, this module
will delete and re-create the containers from the newer image:
```shellsession
$ salt-call microservice.redeploy example
```
This is done sequentially and with a grace time of 60 seconds. If your service
consists of more than one instance of the same container, the deployment will
not cause ~~any~~ significant downtime.
# Reference
## Configuration reference
All deployed microservices are configured using Salt pillars. The root pillar
is the `microservices` pillar. The `microservices` pillar is a map of *service
definitions*. Each key of this map will be used as service name.
### Service definition
A service definition is a YAML object consisting of the following properties:
* `hostname` (**required**): Describes the public hostname used to address
this service. This especially important when the service exposes a HTTP API
or GUI; in this case NGINX will be configured to use this hostname to route
requests to respective containers.
* `containers` (**required**): A map of *container definitions*. Each key of
this map will be as container name.
* `ssl_certificate` and `ssl_key` (*optional*): The path to a SSL certificate
and the associated private key to use to encrypt the connections to the
respective service.
* `ssl_force` (*optional*): When a `ssl_certificate` is defined, by default
all unencrypted HTTP traffic will be redirected to SSL. Set this value to
`False` to still allow unencrypted HTTP traffic.
* `checks` (*optional*): Can contain additional health checks for
[Consul][consul]. See the [Consul documentation on health checks][consul-checks]
for more information.
* `check_url` (*optional*): The URL to use for the Consul health check. This
option will only be used when the service is accessibly via HTTP. If not
specified, the service's `hostname` property will be used as URL.
### Container definition
A container definition is a YAML object consisting of the properties defined
below. Each container definition may result in *one or more* actual Docker
containers being created (the exact number of containers depends on the
`instances` property). Each container will follow the naming pattern
`<service-name>-<container-name>-<instance-number>`. This means that the example
from above would create three containers:
1. `example-web-0`
2. `example-web-1`
3. `example-db-0`
You can use the following configuration options for each container:
* `instances` (*default:* `1`): How many instances of this container to spawn.
* `docker_image` (**required**): The Docker image to use for building this
container. If the image is not present on the host, the `mwdocker` Salt
states will try to pull this image.
* `stateful` (*default:* `False`): You can set this property to `True` if any
kind of persistent data is stored inside the container (usually, you should
try to avoid this, for example by using host directories mounted as
volumes). If a container is as *stateful*, the Salt states will not delete
and re-create this when a newer version of the image is present.
* `http` (*default:* `False`): Set to `True` when this container exposes a
HTTP service. This will cause a respective NGINX configuration to be created
to make the service be accessible by the public.
* `http_internal_port` (*default:* `80`): Set this property to the port that
the HTTP service listens on *inside the container*!
* `base_port` (**required**): Port that container ports should be mapped on
on the host. Note that this property does not configure one port, but rather
the beginning of a port range of `instances` length.
* `links`: A map of other containers (of the same service) that should be
linked into this container. The format is `<container-name>: <alias>`.
Example:
```yaml
links:
database: db
storage: data
```
* `volumes`: A list of volumes that should be created for this container. Each
volume is a list of three items:
1. The volume name on the host side. **Do not specify an absolute path
here!** The Salt states will automatically create a new host directory in
`/var/lib/services/<service-name>/<path>` for you.
2. The volume path inside the container.
3. `ro` or `rw` to denote read-only or read&write access.
Example:
```yaml
volumes:
- ["database", "/var/lib/mysql", "rw"]
- ["files", "/opt/service-resources", "ro"]
```
* `volumes_from`: A list of *containers* from which volumes should be used.
Use the service-local container name, here. Containers should be specified
as a simple list.
Example:
```yaml
volumes_from:
- database
```
* `environment`: A map of environment variables to set for this container.
**Note:** When using this feature for setting confidential data like API
tokens or passwords, consider using [Salt's GPG encryption features][salt-gpg].
## SLS reference
### `mwms.consul.server` and `mwms.consul.agent`
These states install a Consul server or agent on a node. The Consul version that
is installed is shipped statically with this formula. The Consul agent will be
run using the [Supervisor process manager][supervisor]
### `mwms.consul.dns`
Configures a node to use the Consul servers as DNS server. This is done by
placing a custom `resolv.conf` file.
### `mwms.services`
This states read the `microservice` pillar (see above) and defines the necessary
states for operating the application containers for these services. This will
include the following:
1. Creating as many Docker containers as defined in the pillar
2. Adjusting the NGINX configuration to make your services accessible to the
world.
3. Configure maintenance cron jobs for each service as defined in the pillar.
These will be run in temporary docker containers.
### `mwms.monitoring`
Installs cAdvisor on your host that gathers host and container metrics. This is
probably most useful when you're also using the `mwms.prometheus` state on one
or more of your nodes.
Note that due to Docker issue [#17902](https://github.com/docker/docker/issues/17902),
cAdvisor is started directly on the host, not within a Docker container.
### `mwms.prometheus`
Sets up a Prometheus server for gathering metrics and alerting. The setup
consists of the actual Prometheus service, the Alertmanager and a Grafana
frontend.
## State reference
### `consul.node`
This state registers a new external node using the Consul REST API. This state
requires Consul to be already installed on the node (use one of the
`mwms.consul.*` SLSes for that) and requires the Python [requests][py-requests]
package.
Example:
```yaml
external-node:
consul.node:
- address: url-to-external.service.acme.com
- datacenter: dc1
- service:
ID: example
Port: 80
Tags:
- master
- v1
```
## Module reference
### `microservice.redeploy`
This module will re-deploy a microservice. This module will try to pull a newer
version of the image that the application containers were created from. If a
newer image exists, this module will delete and re-create the containers from
the newer image.
This is done sequentially and with a grace time of 60 seconds. If your service
consists of more than one instance of the same container, the deployment will
not cause ~~any~~ significant downtime.
[cadvisor]: https://github.com/google/cadvisor
[consul]: http://consul.io
[consul-checks]: https://www.consul.io/docs/agent/checks.html
[grafana]: http://grafana.org
[kubernetes]: http://kubernetes.io/
[marathon]: https://mesosphere.github.io/marathon/
[nginx]: http://nginx.org
[prom]: http://prometheus.io
[py-requests]: http://www.python-requests.org/en/latest/
[salt-formulas]: https://docs.saltstack.com/en/latest/topics/development/conventions/formulas.html
[salt-gpg]: https://docs.saltstack.com/en/stage/ref/renderers/all/salt.renderers.gpg.html
[salt-mine]: https://docs.saltstack.com/en/stage/topics/mine/index.html
[salt-targeting]: https://docs.saltstack.com/en/latest/topics/targeting/index.html
[supervisor]: http://supervisord.org/
<file_sep>/_states/consul.py
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Mittwald CM Service GmbH & Co. KG
#
# Docker-based microservice deployment with service discovery
# This code is MIT-licensed. See the LICENSE.txt for more information
import requests
import json
import salt.states.file
def node(name, address, datacenter=None, service=None):
"""
This state registers a new external node using the Consul REST API.
[1] https://www.consul.io/docs/agent/http/catalog.html#catalog_register
:param name: The node name
:param address: A resolvable address (IP address or hostname) under which the node can be reached
:param datacenter: The data center name
:param service: A Consul service definition (see [1] for more information)
"""
r = requests.get('http://localhost:8500/v1/catalog/node/%s' % name)
repr = {
"Node": name,
"Address": address
}
if datacenter is not None:
repr["Datacenter"] = datacenter
if service is not None:
repr["Service"] = service
repr["Service"]["Address"] = ""
if "Tags" not in repr["Service"]:
repr["Service"]["Tags"] = None
changed = False
if r.status_code == 200:
existing = r.json()
if existing is not None:
if existing["Node"]["Address"] != repr["Address"]:
changed = True
if datacenter is not None and existing["Datacenter"] != repr["Datacenter"]:
changed = True
if service is not None and existing["Services"][repr["Service"]["ID"]] != repr["Service"]:
changed = True
else:
changed = True
if r.status_code == 404 or changed:
ret = {
'name': name,
'result': True,
'changes': {"service": {"old": r.json(), "new": repr}},
'comment': 'Registered node'
}
if not __opts__['test']:
r = requests.put('http://localhost:8500/v1/catalog/register', data=json.dumps(repr))
if r.status_code != 200:
print(r.text)
raise Exception('Unexected status: %d' % r.status_code)
else:
ret = {
'name': name,
'result': True,
'changes': {},
'comment': 'Node is up to spec'
}
return ret
def service(name, config_dir='/etc/consul', port=80, check_type=None, check_url=None, check_script=None,
check_interval="1m", check_name='default health check'):
"""
This state registers a new service in Consul. This is done by placing a
static configuration file into Consul's `config-dir`.
:param name: The service name
:param config_dir: The consul configuration directory
:param port: The port that the service is available on
:param check_type: The type to use for the health check (either "http", "script" or `None`)
:param check_url: The URL to use for the HTTP health check
:param check_script: The script to use for the script health check
:param check_interval: The check interval in a time interval format parseable by Go
:param check_name: The health check's name
:return:
"""
service_definition = {
'service': {
'name': name,
'port': port
}
}
if check_type == "http":
if check_url is None:
raise Exception('When check_type is "http", a check_url must be specified!')
if check_script is not None:
raise Exception('When check_type is "http", no check_script must be specified!')
service_definition['checks'] = [
{
'interval': check_interval,
'http': check_url,
'name': 'HTTP connectivity'
}
]
elif check_type == 'script':
if check_url is not None:
raise Exception('When check_type is "script", no check_url must be specified!')
if check_script is not None:
raise Exception('When check_type is "script", a check_script must be specified!')
service_definition['checks'] = [
{
'interval': check_interval,
'script': check_script,
'name': check_name
}
]
elif check_type is None:
pass
else:
raise Exception('bad check_type: "%s". Allowed are "http" and "script".' % check_type)
service_json = json.dumps(service_definition)
service_file = '%s/service-%s.json' % (config_dir, name)
return salt.states.file.managed(name=service_file, contents=service_json)
<file_sep>/_states/mwdocker.py
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Mittwald CM Service GmbH & Co. KG
#
# Docker-based microservice deployment with service discovery
# This code is MIT-licensed. See the LICENSE.txt for more information
import docker.errors
import docker
import logging
log = logging.getLogger(__name__)
if not '__opts__' in globals():
log.fatal("Whoops! __opts__ not set!?")
__opts__ = {}
if not '__salt__' in globals():
log.fatal("Whoops! __salt__ not set!?")
__salt__ = {}
def running(name, image, volumes=(), restart=True, tcp_ports=(), udp_ports=(), environment=None, command=None, dns=None,
domain=None, volumes_from=None, links=None, user=None, warmup_wait=60, stateful=False, labels=None):
"""
Asserts that a container matching the provided specification is up and
running.
:param str name : The container name
:param str image : The image from which to create the container
:param list volumes : A list of volumes. Each volume definition is a string of the format "<host-directory>:<container-directory>:<rw|ro>"
:param bool restart : `True` to restart the container when it stops
:param list tcp_ports : TCP ports to expose. This is a list of dictionaries that must provide a "port" and an "address" key
:param list udp_ports : UDP ports to expose. This is a list of dictionaries that must provide a "port" and an "address" key
:param dict environment : A dictionary of environment variables to pass into the container
:param str|list command : The command to use for the container
:param str dns : DNS server address to use
:param str domain : The DNS search domain
:param list volumes_from: A list of container names from which to use the volumes
:param dict links : A dictionary of containers to link (using the container name as index and the alias as value)
:param str user : The user under which to start the container
:param int warmup_wait : The amount of time to wait for the container to start
:param bool stateful : Set to `True` to prevent this container from automatic deletion
:param dict labels : A dictionary of labels that should be attached to the container
"""
ret = {
'name': name,
'result': True,
'changes': {},
'comment': ''
}
client = docker.Client(base_url='unix://var/run/docker.sock')
if ':' not in image:
image += ":latest"
# noinspection PyCallingNonCallable
__salt__['mwdocker.pull_image'](image, force=False, test=__opts__['test'])
try:
existing = client.inspect_container(name)
except docker.errors.NotFound:
existing = None
if existing is not None:
matches_spec = __does_existing_container_matches_spec(client, ret, existing, name, image, tcp_ports=tcp_ports,
volumes=volumes, udp_ports=udp_ports,
environment=environment, command=command, dns=dns,
volumes_from=volumes_from, links=links, domain=domain,
labels=labels)
if not matches_spec and stateful:
ret['comment'] += "Deleting old version of container %s with gracious timeout, keeping volumes\n" % name
if not __opts__['test']:
# noinspection PyCallingNonCallable
__salt__['mwdocker.delete_container'](name, timeout=60, with_volumes=False)
return ret
elif not matches_spec:
ret['comment'] += "Deleting old version of container %s\n" % name
if not __opts__['test']:
# noinspection PyCallingNonCallable
__salt__['mwdocker.delete_container'](name, with_volumes=True)
else:
ret['comment'] += 'Container exists and is up to spec.\n'
return ret
if not __opts__['test']:
# noinspection PyCallingNonCallable
container_id = __salt__['mwdocker.create_container'](
name=name,
image=image,
command=command,
environment=environment,
links=links,
volumes=volumes,
volumes_from=volumes_from,
udp_ports=udp_ports,
tcp_ports=tcp_ports,
restart=restart,
dns=dns,
domain=domain,
user=user,
labels=labels,
test=__opts__['test']
)
ret['changes']['container'] = {'new': container_id}
ret['changes']['running'] = {'old': False, 'new': True}
__salt__['mwdocker.start_container'](name, warmup_wait=warmup_wait)
else:
ret['changes']['container'] = {'new': '<NEW-CONTAINER-ID>'}
ret['changes']['running'] = {'old': False, 'new': True}
return ret
def __does_existing_container_matches_spec(client, ret, existing, name, image, volumes=(), restart=True, tcp_ports=(),
udp_ports=(), environment=None, command=None, dns=None, volumes_from=None,
links=None, domain=None, labels=None):
up_to_spec = True
image_id = __salt__['mwdocker.image_id'](image)
if labels is None:
labels = {}
if existing['Image'] != image_id:
ret['changes']['image'] = {'old': existing['Image'], 'new': image_id}
up_to_spec = False
for volume in volumes:
try:
source_dir, mount, mode = volume.split(':')
except ValueError:
source_dir, mount = volume.split(':')
if mount not in existing['Volumes']:
ret['changes']['volumes/%s' % mount] = {'new': volume, 'old': None}
up_to_spec = False
elif existing['Volumes'][mount] != source_dir:
ret['changes']['volumes/%s' % mount] = {'new': volume,
'old': "%s:%s:%s" % (existing['Volumes'][mount], mount, '??')}
up_to_spec = False
if restart and existing['HostConfig']['RestartPolicy']['Name'] != 'always':
ret['changes']['restart'] = {'old': False, 'new': True}
up_to_spec = False
if not restart and existing['HostConfig']['RestartPolicy']['Name'] == 'always':
ret['changes']['restart'] = {'old': True, 'new': False}
up_to_spec = False
for port in tcp_ports:
port_name = "%d/tcp" % port['port']
host_port = port['host_port'] if 'host_port' in port else port['port']
should = [{"HostIp": port["address"], "HostPort": str(host_port)}]
if existing['NetworkSettings']['Ports'] is None or not port_name in existing['NetworkSettings']['Ports']:
ret['changes']['ports/tcp/%d' % port['port']] = {'old': False, 'new': port}
up_to_spec = False
elif existing['NetworkSettings']['Ports'][port_name] != should:
ret['changes']['ports/tcp/%d' % port['port']] = {'old': existing['NetworkSettings']['Ports'][port_name],
'new': should}
up_to_spec = False
for port in udp_ports:
port_name = "%d/udp" % port['port']
host_port = port['host_port'] if 'host_port' in port else port['port']
should = {"HostIp": port["address"], "HostPort": str(host_port)}
if existing['NetworkSettings']['Ports'] is None or not port_name in existing['NetworkSettings']['Ports']:
ret['changes']['ports/udp/%d' % port['port']] = {'old': False, 'new': port}
up_to_spec = False
elif existing['NetworkSettings']['Ports'][port_name] != should:
ret['changes']['ports/udp/%d' % port['port']] = {'old': existing['NetworkSettings']['Ports'][port_name],
'new': should}
up_to_spec = False
if environment is not None:
for key, value in environment.items():
if ("%s=%s" % (key, value)) not in existing['Config']['Env']:
ret['changes']['env/%s' % key] = {'old': None, 'new': "%s=%s" % (key, value)}
up_to_spec = False
if command is not None:
joined_command = command
if type(command) is list:
joined_command = " ".join(command)
if " ".join(existing['Config']['Cmd']) != joined_command:
ret['changes']['command'] = {'old': " ".join(existing['Config']['Cmd']), 'new': joined_command}
up_to_spec = False
if dns is not None and existing['HostConfig']['Dns'] != dns:
ret['changes']['dns'] = {'old': existing['HostConfig']['Dns'], 'new': dns}
up_to_spec = False
if volumes_from is not None and existing['HostConfig']['VolumesFrom'] != volumes_from:
ret['changes']['volumes_from'] = {'old': existing['HostConfig']['VolumesFrom'], 'new': volumes_from}
up_to_spec = False
if links is not None:
docker_format = ["/%s:%s/%s" % (a, existing["Name"], b) for a, b in links.items()]
if existing['HostConfig']['Links'] != docker_format:
ret['changes']['links'] = {'old': existing['HostConfig']['Links'], 'new': docker_format}
up_to_spec = False
if domain is not None:
if existing['HostConfig']['DnsSearch'] != [domain]:
ret['changes']['domain'] = {'old': existing['HostConfig']['DnsSearch'], 'new': [domain]}
up_to_spec = False
if existing['Config']['Labels'] != labels:
ret['changes']['labels'] = {'old': existing['Config']['Labels'], 'new': labels}
up_to_spec = False
return up_to_spec
<file_sep>/_modules/consul.py
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Mittwald CM Service GmbH & Co. KG
#
# Docker-based microservice deployment with service discovery
# This code is MIT-licensed. See the LICENSE.txt for more information
def reload():
"""
Reloads the consul configuration. This command requires the Consul
executable to be installed on the node.
"""
__salt__['cmd.run']('consul reload')
<file_sep>/_modules/mwdocker.py
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Mittwald CM Service GmbH & Co. KG
#
# Docker-based microservice deployment with service discovery
# This code is MIT-licensed. See the LICENSE.txt for more information
try:
import docker
import docker.utils
import docker.errors
except ImportError:
def __virtual__():
return False, ["The docker-py package is not installed"]
import json
import logging
import time
log = logging.getLogger(__name__)
def container_ip(name):
"""
Determines the internal IP address of a Docker container.
:param name: The container name
:return: The container's internal IP address
"""
client = docker.Client(base_url='unix://var/run/docker.sock')
info = client.inspect_container(name)
return info['NetworkSettings']['IPAddress']
def container_published_port(name, container_port):
"""
Gets the port number of a publicly exposed container port.
:param name: The container name
:param int: The internal container port
:return: The host port that the container port is mapped on
"""
client = docker.Client(base_url='unix://var/run/docker.sock')
info = client.inspect_container(name)
return info['NetworkSettings']['Ports'][container_port]['HostPort']
def start_container(name, warmup_wait=60):
"""
Starts a Docker container. This function will wait for a defined amount of
time to check if the container actually stays up after being started. If the
container status is not "up" after the `warmup_wait` has expired, this
function will raise an exception.
:param name: The container name
:param int: How long this function should wait to check the container status
"""
log.info("Starting container %s" % name)
client = docker.Client(base_url='unix://var/run/docker.sock')
client.start(name)
# We need to sleep to prevent race conditions on application startup.
# For example, Flow applications that do a doctrine:migrate on startup.
log.info("Waiting %d seconds for container to start" % warmup_wait)
time.sleep(warmup_wait)
container_status = client.inspect_container(name)
if not container_status["State"]["Running"] or container_status["State"]["Restarting"]:
raise Exception('Container %s is not running after %d seconds. Status is: %s' % (
name, warmup_wait, container_status["State"]))
def image_id(image):
"""
Gets the image ID for a specified image name.
:param image: The image name
:return: The image ID
"""
if ':' not in image:
image += ":latest"
client = docker.Client(base_url='unix://var/run/docker.sock')
images = client.images()
for existing_image in images:
if image in existing_image['RepoTags']:
return existing_image['Id']
return None
def delete_container(name, timeout=10, with_volumes=False):
"""
Stops and deletes a container.
:param str name: Name of the container to delete
:param int timeout: Time in seconds to wait for the container to start
:param bool with_volumes: TRUE to also delete volumes
"""
log.info("Deleting container %s" % name)
client = docker.Client(base_url='unix://var/run/docker.sock')
try:
client.inspect_container(name)
except docker.errors.NotFound:
log.info("Container %s was not present in the first place." % name)
return
client.stop(name, timeout=timeout)
client.remove_container(name, v=with_volumes)
def create_container(name, image, command=None, environment=None, volumes=(), udp_ports=None, tcp_ports=None,
restart=True, dns=None, domain=None, volumes_from=None, links=None, user=None, labels=None, test=False):
"""
Creates a new container.
:param name: The container name
:param image: The image from which to create the container
:param command: The command to use for the container
:param environment: A dictionary of environment variables to pass into the
container
:param volumes: A list of volumes. Each volume definition is a string of the
format "<host-directory>:<container-directory>:<rw|ro>"
:param udp_ports: UDP ports to expose. This is a list of dictionaries that
must provide a "port" and an "address" key.
:param tcp_ports: TCP ports to expose. This is a list of dictionaries that
must provide a "port" and an "address" key.
:param restart: `True` to restart the container when it stops
:param dns: A list of DNS server addresses to use
:param domain: The DNS search domain
:param volumes_from: A list of container names from which to use the volumes
:param links: A dictionary of containers to link (using the container name
as index and the alias as value)
:param user: The user under which to start the container
:param dict labels: A dictionary of labels to attach to this container
:param test: Set to `True` to not actually do anything
"""
client = docker.Client(base_url='unix://var/run/docker.sock')
pull_image(image, force=False, test=test)
hostconfig_ports, ports = _create_port_definitions(udp_ports, tcp_ports)
hostconfig_binds, binds = _create_volume_definitions(volumes)
restart_policy = None
if restart:
restart_policy = {
"MaximumRetryCount": 0,
"Name": "always"
}
host_config = docker.utils.create_host_config(
binds=hostconfig_binds,
port_bindings=hostconfig_ports,
restart_policy=restart_policy,
dns=dns,
dns_search=[domain],
volumes_from=volumes_from,
links=links
)
if test:
log.info("Would create container %s" % name)
return None
log.info("Creating container %s" % name)
container = client.create_container(
name=name,
image=image,
command=command,
ports=ports,
host_config=host_config,
volumes=binds,
environment=environment,
user=user,
labels=labels
)
return container['Id']
def pull_image(image, force=False, test=False):
"""
Pulls the current version of an image.
:param image: The image name. If no tag is specified, the `latest` tag is assumed
:param force: Set to `True` to pull even when a local image of the same name exists
:param test: Set to `True` to not actually do anything
"""
client = docker.Client(base_url='unix://var/run/docker.sock')
if ':' not in image:
image += ":latest"
images = client.images()
present = False
for existing_image in images:
if image in existing_image['RepoTags']:
present = True
repository, tag = image.split(':')
if not present or force:
if test:
log.info("Would pull image %s:%s" % (repository, tag))
else:
# noinspection PyUnresolvedReferences
log.info("Pulling image %s:%s" % (repository, tag))
pull_stream = client.pull(repository, tag, stream=True)
for line in pull_stream:
j = json.loads(line)
if 'error' in j:
raise Exception("Could not pull image %s:%s: %s" % (repository, tag, j['errorDetail']))
def _create_port_definitions(udp_ports, tcp_ports):
ports = []
port_bindings = {}
def walk_ports(port_definitions, protocol):
for binding in port_definitions:
host_port = binding['host_port'] if 'host_port' in binding else binding['port']
ports.append((binding['port'], protocol))
port_bindings["%d/%s" % (binding['port'], protocol)] = (binding['address'], host_port)
walk_ports(tcp_ports, 'tcp')
walk_ports(udp_ports, 'udp')
return port_bindings, ports
def _create_volume_definitions(volumes):
binds = {}
container_volumes = []
for bind in volumes:
r = bind.split(':')
mode = r[2] if len(r) > 2 else "rw"
container_volumes.append(r[1])
binds[r[0]] = {
"bind": r[1],
"mode": mode
}
return binds, container_volumes
<file_sep>/_modules/microservice.py
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Mittwald CM Service GmbH & Co. KG
#
# Docker-based microservice deployment with service discovery
# This code is MIT-licensed. See the LICENSE.txt for more information
import logging
import docker
import docker.errors
logger = logging.getLogger(__name__)
def redeploy(service_name, tag_override='latest'):
"""
Re-deploys a service. This module tries to pull the Docker image from which
an application container is created. If a newer version of the image could
be pulled, this module will sequentially delete the containers and re-create
them.
:param service_name: The name of the service to re-deploy
:param tag_override: The default tag to use (if no image tag was specified)
in the service definition pillar.
"""
try:
service_definition = __salt__['pillar.get']('microservices:%s' % service_name)
except KeyError:
return {
"result": True,
"changes": {},
"comment": "service is not registered on this host"
}
client = docker.Client(base_url='unix://var/run/docker.sock')
result = {
"container_images": {},
"container_ids": {}
}
for key, container_config in service_definition['containers'].items():
image_name = container_config['docker_image']
if ':' not in image_name:
image_name += ":%s" % tag_override
__salt__['mwdocker.pull_image'](image_name, force=True)
current_image_id = __salt__['mwdocker.image_id'](image_name)
for container_number in range(container_config['instances']):
container_name = "%s-%s-%d" % (service_name, key, container_number)
try:
existing_container_info = client.inspect_container(container_name)
used_image_id = existing_container_info['Image']
result["container_ids"][container_name] = {"old": existing_container_info["Id"]}
except docker.errors.NotFound:
existing_container_info = None
used_image_id = None
result["container_ids"][container_name] = {"old": None}
result["container_images"][container_name] = {
"old": used_image_id,
"new": current_image_id
}
if used_image_id == current_image_id:
result["container_ids"][container_name]["new"] = result["container_ids"][container_name]["old"]
if 'volumes_from' not in container_config:
continue
if existing_container_info is not None:
if 'stateful' in container_config and container_config['stateful']:
logger.warn("Container %s needs to be updates (current image version is %s), but is stateful. Please upgrade yourself." % (container_name, current_image_id))
result["container_ids"][container_name]["new"] = None
continue
logger.info("Deleting container %s" % container_name)
__salt__['mwdocker.delete_container'](container_name)
links = {}
if 'links' in container_config:
for linked_container, alias in sorted(container_config['links'].items()):
linked_container_name = "%s-%s-0" % (service_name, linked_container)
links[linked_container_name] = alias
volumes_from = None
if 'volumes_from' in container_config:
volumes_from = []
for volume_container in container_config['volumes_from']:
volume_container_name = "%s-%s-0" % (service_name, volume_container)
volumes_from.append(volume_container_name)
volumes = []
if "volumes" in container_config:
volumes = []
for dir, mount, mode in container_config["volumes"]:
source_dir = "/var/lib/services/%s/%s" % (service_name, dir)
volumes.append("%s:%s:%s" % (source_dir, mount, mode))
ports = []
if 'http' in container_config and container_config['http']:
base_port = container_config['base_port']
host_port = base_port + container_number
container_http_port = 80
if 'http_internal_port' in container_config:
container_http_port = container_config['http_internal_port']
ports.append({"address": "0.0.0.0", "port": container_http_port, "host_port": host_port})
elif 'ports' in container_config:
ports += container_config['ports']
container_id = __salt__['mwdocker.create_container'](
name=container_name,
image=image_name,
environment=container_config["environment"] if "environment" in container_config else None,
links=links,
volumes=volumes,
volumes_from=volumes_from,
udp_ports=[],
tcp_ports=ports,
restart=container_config["restart"] if "restart" in container_config else True,
user=container_config["user"] if "user" in container_config else None,
command=container_config["command"] if "command" in container_config else None,
dns=[__salt__['grains.get']('ip4_interfaces:eth0')[0]],
domain="consul"
)
result["container_ids"][container_name]["new"] = container_id
__salt__['mwdocker.start_container'](container_name)
logger.info("Created container %s with id %s" % (container_name, container_id))
return result
|
300c855306dcaea263f4e359c63d47b47dfe1a43
|
[
"Markdown",
"Python"
] | 6
|
Markdown
|
mittwald/salt-microservices
|
5a78ba68e7f8ea44e74f0941190ee7b451b8adcf
|
1b940655774ca28a3b812c9a01d4a4eadf8ada85
|
refs/heads/master
|
<repo_name>varnerlab/SBMLToVFFParser<file_sep>/SBMLToVFFConverter/MediatorClient.swift
//
// MediatorClient.swift
// SBMLToVFFConverter
//
// Created by <NAME> on 2/29/16.
// Copyright © 2016 Varnerlab. All rights reserved.
//
import Foundation
class MediatorClient {
var mediator: MessageMediator?
func send(message: String) {
if let local_mediator = mediator {
local_mediator.send(message, client: self)
}
}
func receive(message: String) {
assert(false, "Method should be overriden")
}
}<file_sep>/SBMLToVFFConverter/MessageMediator.swift
//
// MessageMediator.swift
// SBMLToVFFConverter
//
// Created by <NAME> on 2/29/16.
// Copyright © 2016 Varnerlab. All rights reserved.
//
import Foundation
class MessageMediator: Mediator {
// clients -
private var clients: [MediatorClient] = []
// shared instance -
static let sharedInstance = MessageMediator()
private init() {
}
func addColleague(colleague:MediatorClient) {
print(colleague)
clients.append(colleague)
}
func send(message: String, client: MediatorClient?) {
if let local_client = client {
}
else {
// broadcast -
for client in clients {
client.receive(message)
}
}
}
}<file_sep>/SBMLToVFFConverter/VLSBMLViewControllerMediatorDelegate.swift
//
// VLSBMLViewControllerMediatorDelegate.swift
// SBMLToVFFConverter
//
// Created by <NAME> on 2/29/16.
// Copyright © 2016 Varnerlab. All rights reserved.
//
import Foundation
import Cocoa
class VLSBMLViewControllerMediatorDelegate:MediatorClient {
// instance variable
let text_field:NSTextView
init(textField:NSTextView) {
text_field = textField
}
func clearConsole() -> Void {
text_field.string = ""
}
override func receive(message: String) {
// We are updating the main thread -
dispatch_async(dispatch_get_main_queue()) {[weak self]() -> Void in
if let weak_self = self {
// buffer -
var buffer = ""
// get the old string -
let old_text = weak_self.text_field.string!
// append the new line -
buffer+=old_text
buffer+="\n"
buffer+=message
// set the new text -
weak_self.text_field.string = buffer
// scroll -
weak_self.text_field.scrollToEndOfDocument(nil)
}
}
}
}<file_sep>/SBMLToVFFConverter/ConversionDelegateProtocol.swift
//
// ConversionDelegateProtocol.swift
// SBMLToVFFConverter
//
// Created by <NAME> on 12/16/15.
// Copyright © 2015 Varnerlab. All rights reserved.
//
import Foundation
protocol ConversionDelegateProtocol {
func execute(input:NSURL, output:NSURL) -> Void
}
<file_sep>/SBMLToVFFConverter/VLSBMLConverterViewController.swift
//
// VLSBMLConverterViewController.swift
// SBMLToVFFConverter
//
// Created by <NAME> on 12/16/15.
// Copyright © 2015 Varnerlab. All rights reserved.
//
import Cocoa
class VLSBMLConverterViewController: NSViewController {
// instance variables -
// Outlets -
@IBOutlet var myGenerateButton:NSButton?
@IBOutlet var myClearButton:NSButton?
@IBOutlet var myPopulateSBMLPathButton:NSButton?
@IBOutlet var myPopulateVFFPathButton:NSButton?
@IBOutlet var mySBMLFilePathTextField:NSTextField?
@IBOutlet var myVFFFilePathTextField:NSTextField?
@IBOutlet var myGenerateConsoleTextField:NSTextView?
@IBOutlet var myModelTypePopupButton:NSPopUpButton?
// data -
var sbml_file_path:NSURL?
var vff_file_path:NSURL?
var mediator_delegate:VLSBMLViewControllerMediatorDelegate?
// delegates -
var delegate:ConversionDelegateProtocol = SBMLToLFBAFlatFileConversionDelegate()
// build mediator -
let message_mediator:MessageMediator = MessageMediator.sharedInstance;
override func viewDidLoad() {
super.viewDidLoad()
if let local_text_field = myGenerateConsoleTextField {
// user can't edit -
local_text_field.editable = false
// build the mediator delegate -
mediator_delegate = VLSBMLViewControllerMediatorDelegate(textField:local_text_field)
if let local_mediator = mediator_delegate {
// add the client -
message_mediator.addColleague(local_mediator)
}
}
}
// MARK:- IBAction methods -
@IBAction func loadSBMLFilePathAction(sender:NSButton) -> Void {
// Method variables -
let myFileDialog: NSOpenPanel = NSOpenPanel()
myFileDialog.canChooseDirectories = false
myFileDialog.canCreateDirectories = false
// focus on sbml path -
myFileDialog.becomeFirstResponder()
// completion handler -
let myCompletionHandler = {[weak self](user_selection:Int) -> Void in
// check the selection -
if (user_selection == NSFileHandlingPanelOKButton){
// get the URL -
if let local_path_url = myFileDialog.URL {
// get the URL -
self?.sbml_file_path = local_path_url
// display the URL -
let url_string = local_path_url.absoluteString;
self?.mySBMLFilePathTextField?.stringValue = url_string
// activate generate button?
self?.activateMyGenerationButton();
}
}
}
// open as sheet -
myFileDialog.beginSheetModalForWindow(self.view.window!, completionHandler: myCompletionHandler);
}
@IBAction func loadVFFFilePathAction(sender:NSButton) -> Void {
// Method variables -
let myFileDialog: NSOpenPanel = NSOpenPanel()
myFileDialog.canChooseFiles = false
myFileDialog.canCreateDirectories = true
myFileDialog.canChooseDirectories = true
// focus on vff path -
self.myVFFFilePathTextField?.becomeFirstResponder()
// completion handler -
let myCompletionHandler = {[weak self](user_selection:Int) -> Void in
// check the selection -
if (user_selection == NSFileHandlingPanelOKButton){
// get the URL -
if let local_path_url = myFileDialog.URL {
// if we have the URL, grab it for later -
self?.vff_file_path = local_path_url
// display the URL -
let url_string = local_path_url.absoluteString
self?.myVFFFilePathTextField?.stringValue = url_string
// activate generate button?
self?.activateMyGenerationButton();
}
}
}
// open as sheet -
myFileDialog.beginSheetModalForWindow(self.view.window!, completionHandler: myCompletionHandler);
}
@IBAction func generateVFFFileFromSBMLFileAction(sender:NSButton) -> Void {
// just in case ... double check to make sure we have he URLs -
if (self.sbml_file_path != nil && self.vff_file_path != nil){
// clearout the console -
mediator_delegate?.clearConsole()
// ok, when we implement more delegates, we would have some logic here
// to generate the proper delegate, for now just use the default -
delegate.execute(self.sbml_file_path!, output: self.vff_file_path!)
// KIA the delegate -
//delegate = nil
}
}
@IBAction func clearDataFromAllFieldsAction(sender:NSButton) -> Void {
// clear out the data -
self.mySBMLFilePathTextField?.stringValue = ""
self.myVFFFilePathTextField?.stringValue = ""
self.myGenerateConsoleTextField?.string = ""
// remove url's -
self.sbml_file_path = nil
self.vff_file_path = nil
// reset the generate button?
self.activateMyGenerationButton()
}
// MARK:- Helper methods -
func activateMyGenerationButton() -> Void {
// check conditions - both paths are there, then activate button
if (self.sbml_file_path != nil && self.vff_file_path != nil){
self.myGenerateButton?.enabled = true
}
else {
self.myGenerateButton?.enabled = false
}
}
}
<file_sep>/SBMLToVFFConverter/Mediator.swift
//
// MediatorProtocol.swift
// SBMLToVFFConverter
//
// Created by <NAME> on 2/29/16.
// Copyright © 2016 Varnerlab. All rights reserved.
//
import Foundation
protocol Mediator {
func send(message: String, client: MediatorClient?)
}<file_sep>/SBMLToVFFConverter/SBMLToLFBAFlatFileConversionDelegate.swift
//
// SBMLToLFBAFlatFileConversionDelegate.swift
// SBMLToVFFConverter
//
// Created by <NAME> on 12/16/15.
// Copyright © 2015 Varnerlab. All rights reserved.
//
import Cocoa
class SBMLToLFBAFlatFileConversionDelegate: NSObject, ConversionDelegateProtocol {
// instance variables -
let message_mediator:MessageMediator = MessageMediator.sharedInstance
// delegate methods -
func execute(input:NSURL, output:NSURL) -> Void {
// Build XML document -
var sbml_tree:NSXMLDocument?
// background thread -
let priority = DISPATCH_QUEUE_PRIORITY_HIGH
dispatch_async(dispatch_get_global_queue(priority, 0)) {[weak self]() -> Void in
// if have self - grab it
if let weak_self = self {
do {
// ok, we have the sbml_tree ... need to write the VFF -
let output_file_path = (input.URLByDeletingPathExtension?.absoluteString)!+".vff"
let output_file_name = NSURL(fileURLWithPath: output_file_path).lastPathComponent
let output_url = output.URLByAppendingPathComponent(output_file_name!, isDirectory: false);
// message -
let message_string = "Loading \(input.absoluteString)"
weak_self.message_mediator.send(message_string, client: nil)
// Build sbml_tree -
sbml_tree = try NSXMLDocument.init(contentsOfURL: input, options:NSXMLDocumentTidyXML)
// Generate buffer -
let buffer = weak_self.generateVFFBufferFromSBMLTree(sbml_tree!)
// dump to disk -
try buffer.writeToURL(output_url, atomically: true, encoding: NSUTF8StringEncoding)
// update the user -
let message_string_final = "Writing \(output_url.absoluteString)"
weak_self.message_mediator.send(message_string_final, client: nil)
}
catch let error as NSError {
print(error.localizedDescription)
}
}
}
}
func generateVFFBufferFromSBMLTree(tree:NSXMLDocument) -> String {
// method variables -
var buffer:String = ""
var product_node_array:[NSXMLNode]
var reactant_node_array:[NSXMLNode]
var reactant_array_xpath:String = ""
var product_array_xpath:String = ""
var reactant_fragment:String = ""
var product_fragment:String = ""
do {
// create xpath and grad nodes -
let reaction_id_xpath = ".//reaction/@id"
let node_array:[NSXMLNode] = try tree.nodesForXPath(reaction_id_xpath)
for xml_node in node_array {
// Grab the id = and get the reactants, products and other metadata for this reaction -
let reaction_name = xml_node.stringValue!
// Get the reactants -
reactant_array_xpath = ".//reaction[@id='\(reaction_name)']/listOfReactants/speciesReference"
reactant_node_array = try tree.nodesForXPath(reactant_array_xpath)
// Get the products -
product_array_xpath = ".//reaction[@id='\(reaction_name)']/listOfProducts/speciesReference"
product_node_array = try tree.nodesForXPath(product_array_xpath)
// Is this reaction reversible?
let is_reaction_reversible = try isReactionWithIDReversible(reaction_name,sbml_tree: tree)
// build the fragments -
reactant_fragment = try generateReactionFragmentFromSpeciesNodeArray(reactant_node_array)
product_fragment = try generateReactionFragmentFromSpeciesNodeArray(product_node_array)
// build the reaction string -
buffer+=reaction_name
buffer+=",[],"
buffer+=reactant_fragment
buffer+=","
buffer+=product_fragment
buffer+=","
if (is_reaction_reversible == true){
buffer+="-inf,inf"
}
else {
buffer+="0,inf"
}
// end and newline -
buffer+=";\n"
// message -
let message_string = "Processing \(reaction_name)"
message_mediator.send(message_string, client: nil)
}
}
catch {
print("ERROR: Failed to load the reactions from the SBML file")
}
return buffer
}
// MARK: private helper methods
private func isReactionWithIDReversible(reaction_id:String,sbml_tree:NSXMLDocument) throws -> Bool {
// method variables -
var is_reaction_reversible = true
// xpath for for reversible -
let xpath_string = ".//reaction[@id='\(reaction_id)']/@reversible"
let reversible_node:[NSXMLNode] = try sbml_tree.nodesForXPath(xpath_string)
if (reversible_node.count == 1) {
// ok, we have a node, reversible or not?
let flag = reversible_node.first?.stringValue
if (flag == "false"){
is_reaction_reversible = false
}
}
// return -
return is_reaction_reversible;
}
private func generateReactionFragmentFromSpeciesNodeArray(node_array:[NSXMLNode]) throws -> String {
// method variables -
var buffer = ""
// ok, we have a species node array -
for species_node in node_array {
if let child_node = species_node as? NSXMLElement {
// Get species symbol -
let species_symbol = child_node.attributeForName("species")?.stringValue!
// Get the stoichiometric coefficient -
if let stoichiometric_coeffcient = child_node.attributeForName("stoichiometry")?.stringValue {
// ok, we have a stochiometric coefficient -
buffer+="\(stoichiometric_coeffcient)*\(species_symbol!)+"
}
else {
// no coefficient -
buffer+="\(species_symbol!)+"
}
}
}
// return -
return String(buffer.characters.dropLast())
}
}
|
73558b8ba9ca4bddb7667da6d8fd615030c2bbb9
|
[
"Swift"
] | 7
|
Swift
|
varnerlab/SBMLToVFFParser
|
c48c46d0dd79b62fd310b50f7f9a713fd0697b95
|
f25bb639ba11f71de1295ac96b03d1a8bc3ff0cb
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// flashcard2
//
// Created by CS on 9/9/19.
// Copyright © 2019 CS. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var QLabel: UILabel!
@IBOutlet weak var ALabel: UILabel!
@IBOutlet weak var qField: UITextField!
@IBOutlet weak var aField: UITextField!
@IBOutlet weak var inputArea: UIView!
var questions: [String] = [] //Question array
var answers: [String] = [] //Answer array
var currentQuestionIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
inputArea.isHidden = true
QLabel.text = "No question yet."
ALabel.text = "???"
qField.delegate = self
aField.delegate = self
}
//displayAlert(msgTitle: "Ready", msgContent: "Go")
func displayAlert(msgTitle:String, msgContent:String){
let alertController = UIAlertController(title: msgTitle, message: msgContent,
preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Close", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
@IBAction func showHideInputAreaAction(_ sender: Any) {
inputArea.isHidden = !inputArea.isHidden
}
@IBAction func nextQBtnAction(_ sender: Any) {
if questions.count == 0 {
displayAlert(msgTitle: "No question", msgContent: "")
return
}
currentQuestionIndex = currentQuestionIndex + 1
if currentQuestionIndex == questions.count {
currentQuestionIndex = 0
}
QLabel.text = questions[currentQuestionIndex]
ALabel.text = "???"
}
@IBAction func showAnswerBtnAction(_ sender: Any) {
if answers.count == 0 {
ALabel.text = "No answer yet"
return
}
ALabel.text = answers[currentQuestionIndex]
}
@IBAction func deleteQABtnAction(_ sender: Any) {
if questions.count == 0 {
displayAlert(msgTitle: "No question to delete", msgContent: "")
return
}
questions.remove(at: currentQuestionIndex)
answers.remove(at: currentQuestionIndex)
if questions.count == 0 {
QLabel.text = "No question"
ALabel.text = "No answer"
return
}
if currentQuestionIndex == questions.count {
currentQuestionIndex = 0
}
QLabel.text = questions[currentQuestionIndex]
ALabel.text = "???"
}
@IBAction func xBtnAction(_ sender: Any) {
inputArea.isHidden = true
view.endEditing(true) //hide the keyboard
}
@IBAction func addQAAction(_ sender: Any) {
//enterQ.resignFirstResponder()
//enterA.resignFirstResponder() //hide the keyboard
view.endEditing(true) //hide the keyboard
if aField.text == "" || qField.text == "" {
displayAlert(msgTitle: "Input Error", msgContent: "")
return
}
questions.append(qField.text!)
answers.append(aField.text!)
qField.text = ""
aField.text = ""
displayAlert(msgTitle: "QA Saved!", msgContent: "")
}
}
|
f1932ba1578a8f1de387eaa4748ae252258375f8
|
[
"Swift"
] | 1
|
Swift
|
yoyang2/flashcard2
|
8b8d682c6e5c3092ca67eacc279ea249666fd286
|
718c8988db6f80cebec2c0ef43ffaf375e8ebf55
|
refs/heads/master
|
<repo_name>msztolcman/irename<file_sep>/setup.py
import pkg_resources
import platform
import sys
def validate_python_version():
"""
Validate python interpreter version. Only 3.3+ allowed.
"""
if pkg_resources.parse_version(platform.python_version()) < pkg_resources.parse_version('3.3.0'):
print("Sorry, Python 3.3+ is required")
sys.exit(1)
validate_python_version()
from codecs import open
from os import path
from setuptools import setup, find_packages
BASE_DIR = path.abspath(path.dirname(__file__))
with open(path.join(BASE_DIR, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='irename',
version='1.0.0',
description='interactive rename files using favorite editoror',
long_description=long_description,
url='http://msztolcman.github.io/irename/',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Topic :: Utilities',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=['argparse'],
packages=find_packages(),
keywords=['file management', 'rename', 'move', 'terminal', 'cli'],
entry_points={
'console_scripts': [
'irename=irename.__main__:main',
],
},
)
<file_sep>/README.md
irename
=======
`irename` allows to easy rename many files using Your favorite editor.
When You call `irename` (with some options or paths) list of files is saved
to text file, and Your favorite text editor is launched. You can edit names
or paths in this file, and after You save changes and quit from editor,
this changes are applied.
`irename` use by default editor set in environment variables: `$EDITOR`,
or `$VISUAL` if the former is empty. If neither of them aren't set, use `vim`.
Current stable version
----------------------
1.0.0
Python version
--------------
`irename` works only with Python 3.3+. Older Python versions are unsupported.
Usage
-----
Everything is in help :) Just execute:
irename --help
Look at result:
% irename --help
usage: irename [-h] [--editor EDITOR] [--editor-arguments ARGUMENTS]
[--verbose] [--interactive] [--force] [--version]
[files [files ...]]
positional arguments:
files files to rename
optional arguments:
-h, --help show this help message and exit
--editor EDITOR, -e EDITOR
Change default editor
--editor-arguments ARGUMENTS, -c ARGUMENTS
Pass additional arguments to editor
--verbose, -v Be verbose
--interactive, -i Ask before every rename
--force, -f Do not ask if destination file already exists
--version show program's version number and exit
Installation
------------
1. Using PIP
`irename` should work on any platform where [Python](http://python.org)
is available, it means Linux, Windows, MacOS X etc.
Simplest way is to use Python's built-in package system:
pip3 install irename
2. Using [pipsi](https://github.com/mitsuhiko/pipsi)
pipsi install --python3 irename
3. Using sources
Download sources from [Github](https://github.com/msztolcman/irename/archive/1.0.0.zip):
wget -O 1.0.0.zip https://github.com/msztolcman/irename/archive/1.0.0.zip
or
curl -o 1.0.0.zip https://github.com/msztolcman/irename/archive/1.0.0.zip
Unpack:
unzip 1.0.0.zip
And install
cd irename-1.0.0
python3 setup.py install
Voila!
Authors
-------
<NAME> <<EMAIL>>
Contact
-------
If you like or dislike this software, please do not hesitate to tell me about
this me via email (<EMAIL>).
If you find bug or have an idea to enhance this tool, please use GitHub's
[issues](https://github.com/msztolcman/irename/issues).
License
-------
The MIT License (MIT)
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ChangeLog
---------
### v1.0.0
* First public version
<file_sep>/irename/__main__.py
import argparse
import atexit
import configparser
import glob
import os
import shlex
import shutil
import subprocess
import sys
import tempfile
from irename import __version__ as version
TMP_FILE_PATH = None
CONFIG_FILE_PATH = os.path.expanduser('~/.irename.rc')
DEFAULT_EDITOR = 'vim'
DEFAULT_EDITOR_ARGUMENTS = ''
def cleanup():
if not TMP_FILE_PATH:
return
try:
os.unlink(TMP_FILE_PATH)
except:
pass
atexit.register(cleanup)
class ConfigError(Exception):
pass
class Config:
def __init__(self):
self._data = {}
def set(self, key, value):
self._data[key] = value
def get(self, key, default=None):
return self._data.get(key, default)
def get_config(path):
data = configparser.ConfigParser()
read = data.read(path)
cfg = Config()
cfg.set('editor', os.environ.get('EDITOR', os.environ.get('VISUAL', 'vim')))
cfg.set('editor_arguments', '')
cfg.set('force', False)
cfg.set('interactive', False)
cfg.set('verbose', False)
if not read:
return cfg
if 'irename' not in data:
raise ConfigError("Missing 'irename' section in config file")
for key in data['irename']:
cfg.set(key, data['irename'][key])
return cfg
def parse_args(argv, defaults=None):
if defaults is None:
defaults = {}
p = argparse.ArgumentParser()
p.add_argument('--editor', '-e', type=str, default=defaults.get('editor'),
help='Change default editor')
p.add_argument('--editor-arguments', '-c', type=str, default=defaults.get('editor-arguments'), metavar='ARGUMENTS',
help='Pass additional arguments to editor')
p.add_argument('--verbose', '-v', action='store_true', default=defaults.get('verbose'),
help='Be verbose')
p.add_argument('--interactive', '-i', action='store_true', default=defaults.get('interactive'),
help='Ask before every rename')
p.add_argument('--force', '-f', action='store_true', default=defaults.get('force'),
help='Do not ask if destination file already exists')
p.add_argument('files', type=str, nargs='*',
help='files to rename')
p.add_argument('--version', action='version', version='%%(prog)s %s' % version)
args = p.parse_args(argv)
if not args.files:
args.files = glob.glob('./*')
if not args.files:
p.error('Can\'t find any files')
args.files.sort()
return args
def main():
global TMP_FILE_PATH
config = get_config(CONFIG_FILE_PATH)
args = parse_args(sys.argv[1:], config)
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as fh:
TMP_FILE_PATH = fh.name
fh.write("\n".join(args.files))
if args.verbose:
print("Using temporary file %s" % fh.name)
editor_command = [args.editor]
if args.editor_arguments:
editor_command.extend(shlex.split(args.editor_arguments))
editor_command.append(fh.name)
proc = subprocess.Popen(editor_command)
proc.wait()
with open(fh.name, 'r') as fh:
new_names = [name.strip() for name in fh]
if len(args.files) != len(new_names):
print('Number of lines does not match', file=sys.stderr)
sys.exit(1)
for old_name, new_name in zip(args.files, new_names):
if old_name == new_name:
continue
agree = True
asked = False
if not args.force and os.path.exists(new_name):
agree = input("Path '%s' already exists. Overwrite? (y/N) " % new_name).lower() in ('y', 'yes')
asked = True
if not asked and args.interactive:
agree = input("Rename '%s' -> '%s'? (Y/n) " % (old_name, new_name)).lower() in ('y', 'yes')
asked = True
if agree:
if not asked and args.verbose:
print("Renaming %s -> %s" % (old_name, new_name))
if os.path.isdir(new_name):
shutil.rmtree(new_name)
shutil.move(old_name, new_name)
if __name__ == '__main__':
main()
<file_sep>/tox.ini
[tox]
envlist = py33, py34, py35
; changedir=test
[flake8]
max-line-length = 140
[testenv]
deps = -rrequirements-dev.txt
commands = py.test
[pytest]
testpaths = test
<file_sep>/README.rst
irename
=======
``irename`` allows to easy rename many files using Your favorite editor.
When You call ``irename`` (with some options or paths) list of files is
saved to text file, and Your favorite text editor is launched. You can
edit names or paths in this file, and after You save changes and quit
from editor, this changes are applied.
``irename`` use by default editor set in environment variables:
``$EDITOR``, or ``$VISUAL`` if the former is empty. If neither of them
aren't set, use ``vim``.
Current stable version
----------------------
1.0.0
Python version
--------------
``irename`` works only with Python 3.3+. Older Python versions are
unsupported.
Usage
-----
Everything is in help :) Just execute:
::
irename --help
Look at result:
::
% irename --help
usage: irename [-h] [--editor EDITOR] [--editor-arguments ARGUMENTS]
[--verbose] [--interactive] [--force] [--version]
[files [files ...]]
positional arguments:
files files to rename
optional arguments:
-h, --help show this help message and exit
--editor EDITOR, -e EDITOR
Change default editor
--editor-arguments ARGUMENTS, -c ARGUMENTS
Pass additional arguments to editor
--verbose, -v Be verbose
--interactive, -i Ask before every rename
--force, -f Do not ask if destination file already exists
--version show program's version number and exit
Installation
------------
1. Using PIP
``irename`` should work on any platform where
`Python <http://python.org>`__ is available, it means Linux, Windows,
MacOS X etc.
Simplest way is to use Python's built-in package system:
::
pip3 install irename
2. Using `pipsi <https://github.com/mitsuhiko/pipsi>`__
pipsi install --python3 irename
3. Using sources
Download sources from
`Github <https://github.com/msztolcman/irename/archive/1.0.0.zip>`__:
::
wget -O 1.0.0.zip https://github.com/msztolcman/irename/archive/1.0.0.zip
or
::
curl -o 1.0.0.zip https://github.com/msztolcman/irename/archive/1.0.0.zip
Unpack:
::
unzip 1.0.0.zip
And install
::
cd irename-1.0.0
python3 setup.py install
Voila!
Authors
-------
<NAME> <EMAIL>
Contact
-------
If you like or dislike this software, please do not hesitate to tell me
about this me via email (<EMAIL>).
If you find bug or have an idea to enhance this tool, please use
GitHub's `issues <https://github.com/msztolcman/irename/issues>`__.
License
-------
The MIT License (MIT)
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ChangeLog
---------
v1.0.0
~~~~~~
- First public version
|
357472c3a2e00e9c3b4ccadc6145b0d027aa53d5
|
[
"Markdown",
"Python",
"reStructuredText",
"INI"
] | 5
|
Python
|
msztolcman/irename
|
03c510ef3a35b117229174f0b9ff75034aa93dd3
|
ee0d466dcd8b58ed0119756533227b4306a4c395
|
refs/heads/master
|
<repo_name>nicholas-brooks/iislogs-parser-cmd<file_sep>/README.md
# IIS Logs Parser Cmd
Utility that reads IIS Logs from a folder, parses the UserAgent, then writes out the requests with OS and Browser information to a CSV file. Useful to then import to Excel and analyse OS and Browser usage.
This was build for a specific need. Clone it and make changes to Program.cs to fit your needs.
This was developed and run with .net core 2.2.
## To Run
```
cd app
dotnet run SOURCE_FOLDER DESTINATION_PATH
```
## To Build
```
cd app
dotnet build
```
## Thanks To
Thanks to the devs of the following repos (nuget packages). They make this util easy:
* https://github.com/Kabindas/IISLogParser
* https://github.com/ua-parser/uap-csharp
<file_sep>/app/Program.cs
using System;
using System.Collections.Generic;
using IISLogParser;
using UAParser;
using System.Linq;
using System.IO;
namespace iislogsanalyser
{
class Program
{
private static Parser AgentParser = Parser.GetDefault();
static int Main(string[] args)
{
var (status, source, destination) = ParseInput(args);
if (status != 0)
return status;
using (var stream = File.CreateText(destination))
{
stream.WriteLine("Timestamp,OS Family,OS,Browser Family,Browser,Request,Method,Status,Duration");
foreach (var file in Directory.EnumerateFiles(source, "*.log").OrderBy(x => x))
{
Console.WriteLine($"Parsing ${file} ...");
ParseContentsInto(stream, file);
}
}
return 0;
}
private static (int status, string source, string destination) ParseInput(string[] args)
{
if (args.Length != 2)
{
ShowHelp();
return (1, "", "");
}
if (!Directory.Exists(args[0]))
{
Show("Source folder does not exist");
return (1, "", "");
}
if (!Directory.EnumerateFiles(args[0], "*.log").Any())
{
Show("Source folder does not contain any log files");
return (1, "", "");
}
if (File.Exists(args[1]))
{
Show("Destination path already exists");
return (1, "", "");
}
return (0, args[0], args[1]);
}
private static void ParseContentsInto(StreamWriter stream, string filePath)
{
using (var parser = new ParserEngine(filePath))
{
while (parser.MissingRecords)
{
foreach(var log in parser.ParseLog())
{
try
{
var ((osFamily, os), (browserFamily, browser)) = GetUserAgent(log.csUserAgent);
stream.WriteLine($"{log.DateTimeEvent.ToString("yyyy-MM-dd HH:mm:ss")},{osFamily},{os},{browserFamily},{browser},{log.csUriStem},{log.csMethod},{log.scStatus},{log.timeTaken}");
}
catch (Exception e)
{
Show($"Error - {e.Message}");
}
}
}
}
}
private static void ShowHelp()
{
const string Help =
@"iisloganalyser SOURCE_FOLDER DESTINATION_PATH
Where:
SOURCE_FOLDER Folder containing one or more log files (e.g. u_ex181201.log)
DESTINATION_PATH CSV File to write parsed logs to. (e.g. output.csv).
Must not exist.
";
Show(Help);
}
private static void Show(string msg)
{
Console.WriteLine(msg);
}
private static ((string osFamily, string os), (string browserFamily, string browser)) GetUserAgent(string userAgent)
{
if (string.IsNullOrEmpty(userAgent))
return (("Uknown", "Unknown"), ("Uknown", "Unknown"));
var clientInfo = AgentParser.Parse(userAgent.Replace('+', ' '));
return (GetOS(clientInfo.OS), GetBrowser(clientInfo.UA));
}
private static (string family, string os) GetOS(OS os)
{
switch (os.Family)
{
case "Windows":
switch (os.Major)
{
case "XP":
return (os.Family, "Windows XP");
case "Vista":
return (os.Family, "Windows Vista");
case "8":
return (os.Family, $"{os.Family} {os.Major}.{os.Minor}");
default:
return (os.Family, $"{os.Family} {os.Major}");
}
case "Mac OS X":
return (os.Family, $"{os.Family} {os.Major}.{os.Minor}");
case "Ubuntu":
case "Windows NT 4.0":
case "Other":
return (os.Family, os.Family);
default:
return (os.Family, $"{os.Family} {os.Major}");
}
}
private static (string family, string browser) GetBrowser(UserAgent ua)
{
switch (ua.Family)
{
case "Other":
return ("Other", "Other");
default:
return (ua.Family, $"{ua.Family} {ua.Major}");
}
}
}
}
|
0c79433db1c25819521d204dbac71989fcfcf050
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
nicholas-brooks/iislogs-parser-cmd
|
a5c9cc65e1d87c51626dbb58616dca8fc0b6dcc3
|
2a38f8b59a76761941e389abb5137aa30f07263b
|
refs/heads/main
|
<repo_name>Zenit0A/saifbot2<file_sep>/mybot.py
messagee='spam py saif'
from googletrans import Translator
import os
whiteList=['a222da24-92d5-490b-a2c0-1acb609902b8']
from time import sleep as sl
from threading import Thread as th
import samino
c=samino.Client('220B50483BB71470AE607E8A0AD2834BC286F0E1AF76CF1FEAEB74BBA38CF28ED18D58EB6A0E867FF6')
em='<EMAIL>'
pa='<PASSWORD>'
lol=c.get_from_link('http://aminoapps.com/p/uquks8')
c.login(em,pa)
chatt=lol.objectId
blackList=['2932c23c-2d78-47a2-8fe3-1c93aa887064']
local=samino.Local(lol.comId)
local.send_message(chatt,'._.')
@c.event("on_message")
def on_message(data: samino.lib.Event):
content=data.message.content
comId=data.ndcId
msgId=data.message.messageId
chatId=data.message.chatId
msg=data.message.content
if msg.startswith("!tr"):
text = Translator().translate(text=data.message.replyMessage.content, dest=msg.split(" ")[1]).text
local.send_message(chatId, f"""{text}""", replyTo=msgId)
pass
if msg.startswith('!prov'):
uoper=data.message.userId
lollll=c.get_user_info(uoper)
niikk=lollll.nicknamd
messop=f'hi {niikk}'
local.start_chat(uoper,messop)
local.send_message(chatId,'تم الدخول لخاصك',replyTo=msgId)
if msg.startswith('!start.vc'):
user=data.message.userId
if user in whiteList:
local.start_vc(chatId)
local.send_message(chatId,'تم بدا الدردشه الصوتيه',replyTo=msgId)
else:
local.send_message(chatId,'عذرا انت لست من القائمه البيضاء',replyTo=msgId)
if msg.startswith('!end.vc'):
user=data.message.userId
if user in whiteList:
local.end_vc(chatId)
local.send_message(chatId,'تم انهاء الدردشه الصوتيه',replyTo=msgId)
else:
local.send_message(chatId,'عذرًا انت لست من القائمه البيضاء',replyTo=msgId)
if msg.startswith('!id'):
if 'http' in msg:
comId=c.get_from_link(msg[4:]).comId
chatId=c.get_from_link(msg[4:]).objectId
local.send_message(chatId,f'comId :{comId}\nchatId: {chatId}',replyTo=msgId)
if msg.startswith('!kick'):
userr=data.message.userId
if userr in whileList:
uosr=c.get_from_link(msg[6:]).objectId
local.kick(chatId,uosr)
local.send_message(chatId,'تم طرد العضو بنجاح',replyTo=msgId)
else:
local.send_message(chatId,'عفوا انت لست من القائمه البيضاء',replyTo=msgId)
if msg.startswith('!follow'):
if 'http' in msg:
sopq=c.get_from_link(msg[8:]).objectId
local.follow(sopq)
local.send_message(chatId,'تم متابعة العضو',replyTo=msgId)
if msg.startswith('!unview'):
userl=data.message.userId
if userl in whiteList:
local.chat_settings(chatId,viewOnly=False)
local.send_message(chatId,'تم اغلاق وضع الاطلاع',replyTo=msgId)
else:
local.send_message(chatId,'عذرا انت لست من القائمه البيضاء',replyTo=msgId)
if msg.startswith('!follow.me'):
usqy=data.message.userId
local.follow(usqy)
local.send_message(chatId,'تم متابعتك',replyTo=msgId)
if msg.startswith('!daily'):
local.send_message(chatId,'بدأ ارسال القروش',replyTo=msgId)
useerri=data.message.userId
for _ in range(200):
th(target=c.watch_ad,args=(useerri, )).start()
if msg.startswith("!view"):
userId=data.message.userId
if userId in whiteList:
local.chat_settings(chatId,viewOnly="enable")
local.send_message(chatId,'تم فتح وضع الاطلاع فقط',replyTo=msgId)
else:
local.send_message(chatId,"عذرا انت لست من القائمة البيضاء",replyTo=msgId)
if msg.startswith('!join'):
if 'http' in msg:
opqo=c.get_from_link(msg[6:]).objectId
local.join_chat(opqo)
local.send_message(chatId,'تم الدخول للشات',replyTo=msgId)
if content.startswith('!msg'):
mess=content[5:]
local.send_message(chatId,mess,replyTo=msgId)
if msg.startswith("!info"):
if 'http' in msg:
usrl=c.get_from_link(msg[6:]).objectId
dono=c.get_user_info(usrl)
name2=dono.nickname
icon2=dono.icon
create=dono.createdTime
ser=dono.content
ID=data.message.userId
local.send_message(chatId,
'[c]-nickname: '+name2+'''
[c]-'''
'''icon: '''+icon2+'''
[c]-'''
'''id: '''+ID+'''
[c]-'''
f'''the time create for account: {create}'''+'''
[c]-'''
f''' content: {ser}'''
,replyTo=msgId)
if msg.startswith('!help'):
local.send_message(chatId,'''
[c] ملاحظه:
[c] بادئة الاوامر !
[c]!daily لارسال القروش لك
[c]!info [رابط الشخص] لارسال معلومات الشخص
[c]!msg [الرساله] لارسال الكلمة التي بعد الامر
[c]!follow.me لمتابعتك
[c]!follow [رابط الشخص] لمتابعة العضو الذي تم ارسال رابطه
[c]!id [رابط القروب] لاستخراج ايدي القروب وايدي المنتدى
[c]!tr لترجمة النص الذي ترد عليه
[c] ملاحظة لامر الترجمه:
[c] لترجمة النص يجب الرد على الرساله ب امر!tr وكتابة اول حرفين من اللغة الذي تريد ترجمت النص اليها
[c] اوامر الوايت ليست:
[c]!unview لالغاء وضع الاطلاع
[c]!view لفتح وضع الاطلاع
[c]!start.vc لبدء دردشه صوتيه
[c]!end.vc لانهاء الدردشه الصوتيه
''',replyTo=msgId)
@c.event("on_member_join")
def on_join(data: samino.Event):
local = samino.Local(data.ndcId)
user=data.message.userId
chatId = data.message.chatId
nickname = data.message.author.nickname
local.send_message(chatId, "welcome to the chat",embedLink="ndc://user-profile/"+user,embedTitle=nickname)
@c.event('on_member_left')
def on_member_left(data):
user=data.message.userId
m3lm=c.get_user_info(user)
nickname=m3lm.nickname
local.send_message(chatId,'bye bye '+nickname)
print('تم')
c.launch()
|
0e67f1e71f655c08276fa13150290be0a5d2fad9
|
[
"Python"
] | 1
|
Python
|
Zenit0A/saifbot2
|
c2eeaa3a27df31757acccc5cf7ed85b2eb6a7f85
|
955e6b5ffa0f0d4f91557aa7a983d399f2ff20c6
|
HEAD
|
<file_sep>/**
* @module cocos2dx_studio
*/
var cc = cc || {};
/**
* @class Bone
*/
cc.Bone = {
/**
* @method isTransformDirty
* @return A value converted from C/C++ "bool"
*/
isTransformDirty : function () {},
/**
* @method updateZOrder
*/
updateZOrder : function () {},
/**
* @method getDisplayRenderNode
* @return A value converted from C/C++ "cocos2d::Node*"
*/
getDisplayRenderNode : function () {},
/**
* @method getTween
* @return A value converted from C/C++ "cocostudio::Tween*"
*/
getTween : function () {},
/**
* @method getParentBone
* @return A value converted from C/C++ "cocostudio::Bone*"
*/
getParentBone : function () {},
/**
* @method getBlendType
* @return A value converted from C/C++ "cocostudio::BlendType"
*/
getBlendType : function () {},
/**
* @method updateColor
*/
updateColor : function () {},
/**
* @method getName
* @return A value converted from C/C++ "std::string"
*/
getName : function () {},
/**
* @method setTransformDirty
* @param {bool}
*/
setTransformDirty : function () {},
/**
* @method addChildBone
* @param {cocostudio::Bone*}
*/
addChildBone : function () {},
/**
* @method updateDisplayedOpacity
* @param {unsigned char}
*/
updateDisplayedOpacity : function () {},
/**
* @method setParentBone
* @param {cocostudio::Bone*}
*/
setParentBone : function () {},
/**
* @method setZOrder
* @param {int}
*/
setZOrder : function () {},
/**
* @method getIgnoreMovementBoneData
* @return A value converted from C/C++ "bool"
*/
getIgnoreMovementBoneData : function () {},
/**
* @method setIgnoreMovementBoneData
* @param {bool}
*/
setIgnoreMovementBoneData : function () {},
/**
* @method setName
* @param {std::string}
*/
setName : function () {},
/**
* @method removeFromParent
* @param {bool}
*/
removeFromParent : function () {},
/**
* @method getChildArmature
* @return A value converted from C/C++ "cocostudio::Armature*"
*/
getChildArmature : function () {},
/**
* @method update
* @param {float}
*/
update : function () {},
/**
* @method setDisplayManager
* @param {cocostudio::DisplayManager*}
*/
setDisplayManager : function () {},
/**
* @method getTweenData
* @return A value converted from C/C++ "cocostudio::FrameData*"
*/
getTweenData : function () {},
/**
* @method getColliderBodyList
* @return A value converted from C/C++ "Array*"
*/
getColliderBodyList : function () {},
/**
* @method setBoneData
* @param {cocostudio::BoneData*}
*/
setBoneData : function () {},
/**
* @method setArmature
* @param {cocostudio::Armature*}
*/
setArmature : function () {},
/**
* @method getNodeToWorldTransform
* @return A value converted from C/C++ "AffineTransform"
*/
getNodeToWorldTransform : function () {},
/**
* @method removeChildBone
* @param {cocostudio::Bone*}
* @param {bool}
*/
removeChildBone : function () {},
/**
* @method setChildArmature
* @param {cocostudio::Armature*}
*/
setChildArmature : function () {},
/**
* @method getNodeToArmatureTransform
* @return A value converted from C/C++ "AffineTransform"
*/
getNodeToArmatureTransform : function () {},
/**
* @method getDisplayManager
* @return A value converted from C/C++ "cocostudio::DisplayManager*"
*/
getDisplayManager : function () {},
/**
* @method getArmature
* @return A value converted from C/C++ "cocostudio::Armature*"
*/
getArmature : function () {},
/**
* @method setBlendType
* @param {cocostudio::BlendType}
*/
setBlendType : function () {},
/**
* @method changeDisplayByIndex
* @param {int}
* @param {bool}
*/
changeDisplayByIndex : function () {},
/**
* @method updateDisplayedColor
* @param {cocos2d::Color3B}
*/
updateDisplayedColor : function () {},
/**
* @method getBoneData
* @return A value converted from C/C++ "cocostudio::BoneData*"
*/
getBoneData : function () {},
/**
* @method Bone
* @constructor
*/
Bone : function () {},
};
/**
* @class ArmatureAnimation
*/
cc.ArmatureAnimation = {
/**
* @method getSpeedScale
* @return A value converted from C/C++ "float"
*/
getSpeedScale : function () {},
/**
* @method getAnimationScale
* @return A value converted from C/C++ "float"
*/
getAnimationScale : function () {},
/**
* @method play
* @param {const char*}
* @param {int}
* @param {int}
* @param {int}
* @param {int}
*/
play : function () {},
/**
* @method pause
*/
pause : function () {},
/**
* @method setAnimationScale
* @param {float}
*/
setAnimationScale : function () {},
/**
* @method resume
*/
resume : function () {},
/**
* @method stop
*/
stop : function () {},
/**
* @method setAnimationData
* @param {cocostudio::AnimationData*}
*/
setAnimationData : function () {},
/**
* @method setSpeedScale
* @param {float}
*/
setSpeedScale : function () {},
/**
* @method update
* @param {float}
*/
update : function () {},
/**
* @method getAnimationData
* @return A value converted from C/C++ "cocostudio::AnimationData*"
*/
getAnimationData : function () {},
/**
* @method playByIndex
* @param {int}
* @param {int}
* @param {int}
* @param {int}
* @param {int}
*/
playByIndex : function () {},
/**
* @method init
* @return A value converted from C/C++ "bool"
* @param {cocostudio::Armature*}
*/
init : function () {},
/**
* @method getMovementCount
* @return A value converted from C/C++ "int"
*/
getMovementCount : function () {},
/**
* @method getCurrentMovementID
* @return A value converted from C/C++ "std::string"
*/
getCurrentMovementID : function () {},
/**
* @method setAnimationInternal
* @param {float}
*/
setAnimationInternal : function () {},
/**
* @method create
* @return A value converted from C/C++ "cocostudio::ArmatureAnimation*"
* @param {cocostudio::Armature*}
*/
create : function () {},
/**
* @method ArmatureAnimation
* @constructor
*/
ArmatureAnimation : function () {},
};
/**
* @class ArmatureDataManager
*/
cc.ArmatureDataManager = {
/**
* @method getAnimationDatas
* @return A value converted from C/C++ "Dictionary*"
*/
getAnimationDatas : function () {},
/**
* @method removeAnimationData
* @param {const char*}
*/
removeAnimationData : function () {},
/**
* @method addArmatureData
* @param {const char*}
* @param {cocostudio::ArmatureData*}
*/
addArmatureData : function () {},
/**
* @method getTextureDatas
* @return A value converted from C/C++ "Dictionary*"
*/
getTextureDatas : function () {},
/**
* @method getTextureData
* @return A value converted from C/C++ "cocostudio::TextureData*"
* @param {const char*}
*/
getTextureData : function () {},
/**
* @method getArmatureData
* @return A value converted from C/C++ "cocostudio::ArmatureData*"
* @param {const char*}
*/
getArmatureData : function () {},
/**
* @method getAnimationData
* @return A value converted from C/C++ "cocostudio::AnimationData*"
* @param {const char*}
*/
getAnimationData : function () {},
/**
* @method removeAll
*/
removeAll : function () {},
/**
* @method addAnimationData
* @param {const char*}
* @param {cocostudio::AnimationData*}
*/
addAnimationData : function () {},
/**
* @method init
* @return A value converted from C/C++ "bool"
*/
init : function () {},
/**
* @method removeArmatureData
* @param {const char*}
*/
removeArmatureData : function () {},
/**
* @method getArmatureDatas
* @return A value converted from C/C++ "Dictionary*"
*/
getArmatureDatas : function () {},
/**
* @method removeTextureData
* @param {const char*}
*/
removeTextureData : function () {},
/**
* @method addTextureData
* @param {const char*}
* @param {cocostudio::TextureData*}
*/
addTextureData : function () {},
/**
* @method isAutoLoadSpriteFile
* @return A value converted from C/C++ "bool"
*/
isAutoLoadSpriteFile : function () {},
/**
* @method addSpriteFrameFromFile
* @param {const char*}
* @param {const char*}
*/
addSpriteFrameFromFile : function () {},
/**
* @method destoryInstance
*/
destoryInstance : function () {},
/**
* @method getInstance
* @return A value converted from C/C++ "cocostudio::ArmatureDataManager*"
*/
getInstance : function () {},
};
/**
* @class Armature
*/
cc.Armature = {
/**
* @method getBone
* @return A value converted from C/C++ "cocostudio::Bone*"
* @param {const char*}
*/
getBone : function () {},
/**
* @method changeBoneParent
* @param {cocostudio::Bone*}
* @param {const char*}
*/
changeBoneParent : function () {},
/**
* @method setAnimation
* @param {cocostudio::ArmatureAnimation*}
*/
setAnimation : function () {},
/**
* @method getBoneAtPoint
* @return A value converted from C/C++ "cocostudio::Bone*"
* @param {float}
* @param {float}
*/
getBoneAtPoint : function () {},
/**
* @method getArmatureTransformDirty
* @return A value converted from C/C++ "bool"
*/
getArmatureTransformDirty : function () {},
/**
* @method setVersion
* @param {float}
*/
setVersion : function () {},
/**
* @method updateOffsetPoint
*/
updateOffsetPoint : function () {},
/**
* @method getParentBone
* @return A value converted from C/C++ "cocostudio::Bone*"
*/
getParentBone : function () {},
/**
* @method setName
* @param {std::string}
*/
setName : function () {},
/**
* @method removeBone
* @param {cocostudio::Bone*}
* @param {bool}
*/
removeBone : function () {},
/**
* @method getBatchNode
* @return A value converted from C/C++ "cocostudio::BatchNode*"
*/
getBatchNode : function () {},
/**
* @method getName
* @return A value converted from C/C++ "std::string"
*/
getName : function () {},
/**
* @method getNodeToParentTransform
* @return A value converted from C/C++ "cocos2d::AffineTransform"
*/
getNodeToParentTransform : function () {},
/**
* @method setParentBone
* @param {cocostudio::Bone*}
*/
setParentBone : function () {},
/**
* @method getBoundingBox
* @return A value converted from C/C++ "Rect"
*/
getBoundingBox : function () {},
/**
* @method setBatchNode
* @param {cocostudio::BatchNode*}
*/
setBatchNode : function () {},
/**
* @method draw
*/
draw : function () {},
/**
* @method setArmatureData
* @param {cocostudio::ArmatureData*}
*/
setArmatureData : function () {},
/**
* @method setTextureAtlas
* @param {TextureAtlas*}
*/
setTextureAtlas : function () {},
/**
* @method addBone
* @param {cocostudio::Bone*}
* @param {const char*}
*/
addBone : function () {},
/**
* @method update
* @param {float}
*/
update : function () {},
/**
* @method getArmatureData
* @return A value converted from C/C++ "cocostudio::ArmatureData*"
*/
getArmatureData : function () {},
/**
* @method getVersion
* @return A value converted from C/C++ "float"
*/
getVersion : function () {},
/**
* @method getAnimation
* @return A value converted from C/C++ "cocostudio::ArmatureAnimation*"
*/
getAnimation : function () {},
/**
* @method getBoneDic
* @return A value converted from C/C++ "Dictionary*"
*/
getBoneDic : function () {},
/**
* @method getTextureAtlas
* @return A value converted from C/C++ "TextureAtlas*"
*/
getTextureAtlas : function () {},
/**
* @method Armature
* @constructor
*/
Armature : function () {},
};
/**
* @class Skin
*/
cc.Skin = {
/**
* @method getBone
* @return A value converted from C/C++ "cocostudio::Bone*"
*/
getBone : function () {},
/**
* @method getNodeToWorldTransformAR
* @return A value converted from C/C++ "AffineTransform"
*/
getNodeToWorldTransformAR : function () {},
/**
* @method getNodeToWorldTransform
* @return A value converted from C/C++ "AffineTransform"
*/
getNodeToWorldTransform : function () {},
/**
* @method updateTransform
*/
updateTransform : function () {},
/**
* @method getDisplayName
* @return A value converted from C/C++ "std::string"
*/
getDisplayName : function () {},
/**
* @method updateArmatureTransform
*/
updateArmatureTransform : function () {},
/**
* @method initWithSpriteFrameName
* @return A value converted from C/C++ "bool"
* @param {const char*}
*/
initWithSpriteFrameName : function () {},
/**
* @method initWithFile
* @return A value converted from C/C++ "bool"
* @param {const char*}
*/
initWithFile : function () {},
/**
* @method setBone
* @param {cocostudio::Bone*}
*/
setBone : function () {},
/**
* @method createWithSpriteFrameName
* @return A value converted from C/C++ "cocostudio::Skin*"
* @param {const char*}
*/
createWithSpriteFrameName : function () {},
/**
* @method Skin
* @constructor
*/
Skin : function () {},
};
<file_sep>#include "jsb_cocos2dx_studio_auto.hpp"
#include "cocos2d_specifics.hpp"
#include "CocoStudio.h"
template<class T>
static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) {
TypeTest<T> t;
T* cobj = new T();
cocos2d::Object *_ccobj = dynamic_cast<cocos2d::Object *>(cobj);
if (_ccobj) {
_ccobj->autorelease();
}
js_type_class_t *p;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, p);
assert(p);
JSObject *_tmp = JS_NewObject(cx, p->jsclass, p->proto, p->parentProto);
js_proxy_t *pp = jsb_new_proxy(cobj, _tmp);
JS_AddObjectRoot(cx, &pp->obj);
JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(_tmp));
return JS_TRUE;
}
static JSBool empty_constructor(JSContext *cx, uint32_t argc, jsval *vp) {
return JS_FALSE;
}
JSClass *jsb_Bone_class;
JSObject *jsb_Bone_prototype;
JSBool js_cocos2dx_studio_Bone_isTransformDirty(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_isTransformDirty : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->isTransformDirty();
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_isTransformDirty : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_updateZOrder(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_updateZOrder : Invalid Native Object");
if (argc == 0) {
cobj->updateZOrder();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_updateZOrder : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getDisplayRenderNode(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getDisplayRenderNode : Invalid Native Object");
if (argc == 0) {
cocos2d::Node* ret = cobj->getDisplayRenderNode();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocos2d::Node>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getDisplayRenderNode : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getTween(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getTween : Invalid Native Object");
if (argc == 0) {
cocostudio::Tween* ret = cobj->getTween();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Tween>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getTween : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getParentBone(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getParentBone : Invalid Native Object");
if (argc == 0) {
cocostudio::Bone* ret = cobj->getParentBone();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Bone>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getParentBone : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getBlendType(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getBlendType : Invalid Native Object");
if (argc == 0) {
int ret = (int)cobj->getBlendType();
jsval jsret;
jsret = int32_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getBlendType : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_updateColor(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_updateColor : Invalid Native Object");
if (argc == 0) {
cobj->updateColor();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_updateColor : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getName(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getName : Invalid Native Object");
if (argc == 0) {
std::string ret = cobj->getName();
jsval jsret;
jsret = std_string_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getName : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setTransformDirty(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setTransformDirty : Invalid Native Object");
if (argc == 1) {
JSBool arg0;
ok &= JS_ValueToBoolean(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setTransformDirty : Error processing arguments");
cobj->setTransformDirty(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setTransformDirty : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_addChildBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_addChildBone : Invalid Native Object");
if (argc == 1) {
cocostudio::Bone* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_addChildBone : Error processing arguments");
cobj->addChildBone(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_addChildBone : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_updateDisplayedOpacity(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_updateDisplayedOpacity : Invalid Native Object");
if (argc == 1) {
uint16_t arg0;
ok &= jsval_to_uint16(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_updateDisplayedOpacity : Error processing arguments");
cobj->updateDisplayedOpacity(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_updateDisplayedOpacity : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_init(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = NULL;
cocostudio::Bone* cobj = NULL;
obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_init : Invalid Native Object");
do {
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
bool ret = cobj->init(arg0);
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while(0);
do {
if (argc == 0) {
bool ret = cobj->init();
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while(0);
JS_ReportError(cx, "js_cocos2dx_studio_Bone_init : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setParentBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setParentBone : Invalid Native Object");
if (argc == 1) {
cocostudio::Bone* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setParentBone : Error processing arguments");
cobj->setParentBone(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setParentBone : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setZOrder(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setZOrder : Invalid Native Object");
if (argc == 1) {
int arg0;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setZOrder : Error processing arguments");
cobj->setZOrder(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setZOrder : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getIgnoreMovementBoneData(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getIgnoreMovementBoneData : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->getIgnoreMovementBoneData();
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getIgnoreMovementBoneData : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setIgnoreMovementBoneData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setIgnoreMovementBoneData : Invalid Native Object");
if (argc == 1) {
JSBool arg0;
ok &= JS_ValueToBoolean(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setIgnoreMovementBoneData : Error processing arguments");
cobj->setIgnoreMovementBoneData(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setIgnoreMovementBoneData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setName(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setName : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setName : Error processing arguments");
cobj->setName(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setName : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_removeFromParent(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_removeFromParent : Invalid Native Object");
if (argc == 1) {
JSBool arg0;
ok &= JS_ValueToBoolean(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_removeFromParent : Error processing arguments");
cobj->removeFromParent(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_removeFromParent : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getChildArmature(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getChildArmature : Invalid Native Object");
if (argc == 0) {
cocostudio::Armature* ret = cobj->getChildArmature();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Armature>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getChildArmature : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_update(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_update : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_update : Error processing arguments");
cobj->update(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_update : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setDisplayManager(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setDisplayManager : Invalid Native Object");
if (argc == 1) {
cocostudio::DisplayManager* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::DisplayManager*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setDisplayManager : Error processing arguments");
cobj->setDisplayManager(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setDisplayManager : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getTweenData(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getTweenData : Invalid Native Object");
if (argc == 0) {
cocostudio::FrameData* ret = cobj->getTweenData();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::FrameData>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getTweenData : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getColliderBodyList(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getColliderBodyList : Invalid Native Object");
if (argc == 0) {
Array* ret = cobj->getColliderBodyList();
jsval jsret;
jsret = ccarray_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getColliderBodyList : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setBoneData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setBoneData : Invalid Native Object");
if (argc == 1) {
cocostudio::BoneData* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::BoneData*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setBoneData : Error processing arguments");
cobj->setBoneData(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setBoneData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setArmature(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setArmature : Invalid Native Object");
if (argc == 1) {
cocostudio::Armature* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Armature*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setArmature : Error processing arguments");
cobj->setArmature(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setArmature : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_addDisplay(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = NULL;
cocostudio::Bone* cobj = NULL;
obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_addDisplay : Invalid Native Object");
do {
if (argc == 2) {
Node* arg0;
#pragma warning NO CONVERSION TO NATIVE FOR Node*;
if (!ok) { ok = JS_TRUE; break; }
int arg1;
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
if (!ok) { ok = JS_TRUE; break; }
cobj->addDisplay(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
} while(0);
do {
if (argc == 2) {
cocostudio::DisplayData* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::DisplayData*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
if (!ok) { ok = JS_TRUE; break; }
int arg1;
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
if (!ok) { ok = JS_TRUE; break; }
cobj->addDisplay(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
} while(0);
JS_ReportError(cx, "js_cocos2dx_studio_Bone_addDisplay : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getNodeToWorldTransform(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getNodeToWorldTransform : Invalid Native Object");
if (argc == 0) {
AffineTransform ret = cobj->getNodeToWorldTransform();
jsval jsret;
jsret = ccaffinetransform_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getNodeToWorldTransform : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_removeChildBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_removeChildBone : Invalid Native Object");
if (argc == 2) {
cocostudio::Bone* arg0;
JSBool arg1;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
ok &= JS_ValueToBoolean(cx, argv[1], &arg1);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_removeChildBone : Error processing arguments");
cobj->removeChildBone(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_removeChildBone : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setChildArmature(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setChildArmature : Invalid Native Object");
if (argc == 1) {
cocostudio::Armature* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Armature*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setChildArmature : Error processing arguments");
cobj->setChildArmature(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setChildArmature : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getNodeToArmatureTransform(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getNodeToArmatureTransform : Invalid Native Object");
if (argc == 0) {
AffineTransform ret = cobj->getNodeToArmatureTransform();
jsval jsret;
jsret = ccaffinetransform_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getNodeToArmatureTransform : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getDisplayManager(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getDisplayManager : Invalid Native Object");
if (argc == 0) {
cocostudio::DisplayManager* ret = cobj->getDisplayManager();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::DisplayManager>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getDisplayManager : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getArmature(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getArmature : Invalid Native Object");
if (argc == 0) {
cocostudio::Armature* ret = cobj->getArmature();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Armature>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getArmature : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_setBlendType(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setBlendType : Invalid Native Object");
if (argc == 1) {
cocostudio::BlendType arg0;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_setBlendType : Error processing arguments");
cobj->setBlendType(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_setBlendType : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_changeDisplayByIndex(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_changeDisplayByIndex : Invalid Native Object");
if (argc == 2) {
int arg0;
JSBool arg1;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
ok &= JS_ValueToBoolean(cx, argv[1], &arg1);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_changeDisplayByIndex : Error processing arguments");
cobj->changeDisplayByIndex(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_changeDisplayByIndex : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_updateDisplayedColor(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_updateDisplayedColor : Invalid Native Object");
if (argc == 1) {
cocos2d::Color3B arg0;
ok &= jsval_to_cccolor3b(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Bone_updateDisplayedColor : Error processing arguments");
cobj->updateDisplayedColor(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_updateDisplayedColor : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_getBoneData(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Bone* cobj = (cocostudio::Bone *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Bone_getBoneData : Invalid Native Object");
if (argc == 0) {
cocostudio::BoneData* ret = cobj->getBoneData();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::BoneData>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_getBoneData : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_create(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
do {
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
cocostudio::Bone* ret = cocostudio::Bone::create(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Bone>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while (0);
do {
if (argc == 0) {
cocostudio::Bone* ret = cocostudio::Bone::create();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Bone>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while (0);
JS_ReportError(cx, "js_cocos2dx_studio_Bone_create : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Bone_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
if (argc == 0) {
cocostudio::Bone* cobj = new cocostudio::Bone();
cocos2d::Object *_ccobj = dynamic_cast<cocos2d::Object *>(cobj);
if (_ccobj) {
_ccobj->autorelease();
}
TypeTest<cocostudio::Bone> t;
js_type_class_t *typeClass;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass);
assert(typeClass);
JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
// link the native object with the javascript object
js_proxy_t* p = jsb_new_proxy(cobj, obj);
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::Bone");
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Bone_constructor : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
extern JSObject *jsb_NodeRGBA_prototype;
void js_cocos2dx_studio_Bone_finalize(JSFreeOp *fop, JSObject *obj) {
CCLOGINFO("jsbindings: finalizing JS object %p (Bone)", obj);
}
static JSBool js_cocos2dx_studio_Bone_ctor(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
cocostudio::Bone *nobj = new cocostudio::Bone();
js_proxy_t* p = jsb_new_proxy(nobj, obj);
nobj->autorelease();
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::Bone");
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
void js_register_cocos2dx_studio_Bone(JSContext *cx, JSObject *global) {
jsb_Bone_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_Bone_class->name = "Bone";
jsb_Bone_class->addProperty = JS_PropertyStub;
jsb_Bone_class->delProperty = JS_DeletePropertyStub;
jsb_Bone_class->getProperty = JS_PropertyStub;
jsb_Bone_class->setProperty = JS_StrictPropertyStub;
jsb_Bone_class->enumerate = JS_EnumerateStub;
jsb_Bone_class->resolve = JS_ResolveStub;
jsb_Bone_class->convert = JS_ConvertStub;
jsb_Bone_class->finalize = js_cocos2dx_studio_Bone_finalize;
jsb_Bone_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
{0, 0, 0, JSOP_NULLWRAPPER, JSOP_NULLWRAPPER}
};
static JSFunctionSpec funcs[] = {
JS_FN("isTransformDirty", js_cocos2dx_studio_Bone_isTransformDirty, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("updateZOrder", js_cocos2dx_studio_Bone_updateZOrder, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getDisplayRenderNode", js_cocos2dx_studio_Bone_getDisplayRenderNode, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTween", js_cocos2dx_studio_Bone_getTween, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getParentBone", js_cocos2dx_studio_Bone_getParentBone, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getBlendType", js_cocos2dx_studio_Bone_getBlendType, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("updateColor", js_cocos2dx_studio_Bone_updateColor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getName", js_cocos2dx_studio_Bone_getName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setTransformDirty", js_cocos2dx_studio_Bone_setTransformDirty, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addChildBone", js_cocos2dx_studio_Bone_addChildBone, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("updateDisplayedOpacity", js_cocos2dx_studio_Bone_updateDisplayedOpacity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("init", js_cocos2dx_studio_Bone_init, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setParentBone", js_cocos2dx_studio_Bone_setParentBone, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setZOrder", js_cocos2dx_studio_Bone_setZOrder, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getIgnoreMovementBoneData", js_cocos2dx_studio_Bone_getIgnoreMovementBoneData, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setIgnoreMovementBoneData", js_cocos2dx_studio_Bone_setIgnoreMovementBoneData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setName", js_cocos2dx_studio_Bone_setName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeFromParent", js_cocos2dx_studio_Bone_removeFromParent, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getChildArmature", js_cocos2dx_studio_Bone_getChildArmature, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("update", js_cocos2dx_studio_Bone_update, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setDisplayManager", js_cocos2dx_studio_Bone_setDisplayManager, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTweenData", js_cocos2dx_studio_Bone_getTweenData, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getColliderBodyList", js_cocos2dx_studio_Bone_getColliderBodyList, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setBoneData", js_cocos2dx_studio_Bone_setBoneData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setArmature", js_cocos2dx_studio_Bone_setArmature, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addDisplay", js_cocos2dx_studio_Bone_addDisplay, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getNodeToWorldTransform", js_cocos2dx_studio_Bone_getNodeToWorldTransform, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeChildBone", js_cocos2dx_studio_Bone_removeChildBone, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setChildArmature", js_cocos2dx_studio_Bone_setChildArmature, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getNodeToArmatureTransform", js_cocos2dx_studio_Bone_getNodeToArmatureTransform, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getDisplayManager", js_cocos2dx_studio_Bone_getDisplayManager, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getArmature", js_cocos2dx_studio_Bone_getArmature, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setBlendType", js_cocos2dx_studio_Bone_setBlendType, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("changeDisplayByIndex", js_cocos2dx_studio_Bone_changeDisplayByIndex, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("updateDisplayedColor", js_cocos2dx_studio_Bone_updateDisplayedColor, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getBoneData", js_cocos2dx_studio_Bone_getBoneData, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("ctor", js_cocos2dx_studio_Bone_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
static JSFunctionSpec st_funcs[] = {
JS_FN("create", js_cocos2dx_studio_Bone_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
jsb_Bone_prototype = JS_InitClass(
cx, global,
jsb_NodeRGBA_prototype,
jsb_Bone_class,
js_cocos2dx_studio_Bone_constructor, 0, // constructor
properties,
funcs,
NULL, // no static properties
st_funcs);
// make the class enumerable in the registered namespace
JSBool found;
JS_SetPropertyAttributes(cx, global, "Bone", JSPROP_ENUMERATE | JSPROP_READONLY, &found);
// add the proto and JSClass to the type->js info hash table
TypeTest<cocostudio::Bone> t;
js_type_class_t *p;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, p);
if (!p) {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->type = typeId;
p->jsclass = jsb_Bone_class;
p->proto = jsb_Bone_prototype;
p->parentProto = jsb_NodeRGBA_prototype;
HASH_ADD_INT(_js_global_type_ht, type, p);
}
}
JSClass *jsb_ArmatureAnimation_class;
JSObject *jsb_ArmatureAnimation_prototype;
JSBool js_cocos2dx_studio_ArmatureAnimation_getSpeedScale(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_getSpeedScale : Invalid Native Object");
if (argc == 0) {
float ret = cobj->getSpeedScale();
jsval jsret;
jsret = DOUBLE_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_getSpeedScale : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_getAnimationScale(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_getAnimationScale : Invalid Native Object");
if (argc == 0) {
float ret = cobj->getAnimationScale();
jsval jsret;
jsret = DOUBLE_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_getAnimationScale : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_play(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_play : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_play : Error processing arguments");
cobj->play(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 2) {
const char* arg0;
int arg1;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_play : Error processing arguments");
cobj->play(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 3) {
const char* arg0;
int arg1;
int arg2;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_play : Error processing arguments");
cobj->play(arg0, arg1, arg2);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 4) {
const char* arg0;
int arg1;
int arg2;
int arg3;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2);
ok &= jsval_to_int32(cx, argv[3], (int32_t *)&arg3);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_play : Error processing arguments");
cobj->play(arg0, arg1, arg2, arg3);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 5) {
const char* arg0;
int arg1;
int arg2;
int arg3;
int arg4;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2);
ok &= jsval_to_int32(cx, argv[3], (int32_t *)&arg3);
ok &= jsval_to_int32(cx, argv[4], (int32_t *)&arg4);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_play : Error processing arguments");
cobj->play(arg0, arg1, arg2, arg3, arg4);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_play : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_pause(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_pause : Invalid Native Object");
if (argc == 0) {
cobj->pause();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_pause : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_setAnimationScale(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setAnimationScale : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setAnimationScale : Error processing arguments");
cobj->setAnimationScale(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_setAnimationScale : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_resume(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_resume : Invalid Native Object");
if (argc == 0) {
cobj->resume();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_resume : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_stop(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_stop : Invalid Native Object");
if (argc == 0) {
cobj->stop();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_stop : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_setAnimationData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setAnimationData : Invalid Native Object");
if (argc == 1) {
cocostudio::AnimationData* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::AnimationData*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setAnimationData : Error processing arguments");
cobj->setAnimationData(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_setAnimationData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_setSpeedScale(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setSpeedScale : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setSpeedScale : Error processing arguments");
cobj->setSpeedScale(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_setSpeedScale : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_update(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_update : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_update : Error processing arguments");
cobj->update(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_update : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_getAnimationData(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_getAnimationData : Invalid Native Object");
if (argc == 0) {
cocostudio::AnimationData* ret = cobj->getAnimationData();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::AnimationData>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_getAnimationData : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_playByIndex(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_playByIndex : Invalid Native Object");
if (argc == 1) {
int arg0;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_playByIndex : Error processing arguments");
cobj->playByIndex(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 2) {
int arg0;
int arg1;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_playByIndex : Error processing arguments");
cobj->playByIndex(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 3) {
int arg0;
int arg1;
int arg2;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_playByIndex : Error processing arguments");
cobj->playByIndex(arg0, arg1, arg2);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 4) {
int arg0;
int arg1;
int arg2;
int arg3;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2);
ok &= jsval_to_int32(cx, argv[3], (int32_t *)&arg3);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_playByIndex : Error processing arguments");
cobj->playByIndex(arg0, arg1, arg2, arg3);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
if (argc == 5) {
int arg0;
int arg1;
int arg2;
int arg3;
int arg4;
ok &= jsval_to_int32(cx, argv[0], (int32_t *)&arg0);
ok &= jsval_to_int32(cx, argv[1], (int32_t *)&arg1);
ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2);
ok &= jsval_to_int32(cx, argv[3], (int32_t *)&arg3);
ok &= jsval_to_int32(cx, argv[4], (int32_t *)&arg4);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_playByIndex : Error processing arguments");
cobj->playByIndex(arg0, arg1, arg2, arg3, arg4);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_playByIndex : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_init(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_init : Invalid Native Object");
if (argc == 1) {
cocostudio::Armature* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Armature*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_init : Error processing arguments");
bool ret = cobj->init(arg0);
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_init : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_getMovementCount(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_getMovementCount : Invalid Native Object");
if (argc == 0) {
int ret = cobj->getMovementCount();
jsval jsret;
jsret = int32_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_getMovementCount : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_getCurrentMovementID(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_getCurrentMovementID : Invalid Native Object");
if (argc == 0) {
std::string ret = cobj->getCurrentMovementID();
jsval jsret;
jsret = std_string_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_getCurrentMovementID : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_setAnimationInternal(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setAnimationInternal : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_setAnimationInternal : Error processing arguments");
cobj->setAnimationInternal(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_setAnimationInternal : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_create(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
if (argc == 1) {
cocostudio::Armature* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Armature*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureAnimation_create : Error processing arguments");
cocostudio::ArmatureAnimation* ret = cocostudio::ArmatureAnimation::create(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::ArmatureAnimation>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_create : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureAnimation_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
if (argc == 0) {
cocostudio::ArmatureAnimation* cobj = new cocostudio::ArmatureAnimation();
cocos2d::Object *_ccobj = dynamic_cast<cocos2d::Object *>(cobj);
if (_ccobj) {
_ccobj->autorelease();
}
TypeTest<cocostudio::ArmatureAnimation> t;
js_type_class_t *typeClass;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass);
assert(typeClass);
JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
// link the native object with the javascript object
js_proxy_t* p = jsb_new_proxy(cobj, obj);
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::ArmatureAnimation");
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureAnimation_constructor : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
void js_cocos2dx_studio_ArmatureAnimation_finalize(JSFreeOp *fop, JSObject *obj) {
CCLOGINFO("jsbindings: finalizing JS object %p (ArmatureAnimation)", obj);
}
static JSBool js_cocos2dx_studio_ArmatureAnimation_ctor(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
cocostudio::ArmatureAnimation *nobj = new cocostudio::ArmatureAnimation();
js_proxy_t* p = jsb_new_proxy(nobj, obj);
nobj->autorelease();
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::ArmatureAnimation");
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
void js_register_cocos2dx_studio_ArmatureAnimation(JSContext *cx, JSObject *global) {
jsb_ArmatureAnimation_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_ArmatureAnimation_class->name = "ArmatureAnimation";
jsb_ArmatureAnimation_class->addProperty = JS_PropertyStub;
jsb_ArmatureAnimation_class->delProperty = JS_DeletePropertyStub;
jsb_ArmatureAnimation_class->getProperty = JS_PropertyStub;
jsb_ArmatureAnimation_class->setProperty = JS_StrictPropertyStub;
jsb_ArmatureAnimation_class->enumerate = JS_EnumerateStub;
jsb_ArmatureAnimation_class->resolve = JS_ResolveStub;
jsb_ArmatureAnimation_class->convert = JS_ConvertStub;
jsb_ArmatureAnimation_class->finalize = js_cocos2dx_studio_ArmatureAnimation_finalize;
jsb_ArmatureAnimation_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
{0, 0, 0, JSOP_NULLWRAPPER, JSOP_NULLWRAPPER}
};
static JSFunctionSpec funcs[] = {
JS_FN("getSpeedScale", js_cocos2dx_studio_ArmatureAnimation_getSpeedScale, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getAnimationScale", js_cocos2dx_studio_ArmatureAnimation_getAnimationScale, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("play", js_cocos2dx_studio_ArmatureAnimation_play, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("pause", js_cocos2dx_studio_ArmatureAnimation_pause, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setAnimationScale", js_cocos2dx_studio_ArmatureAnimation_setAnimationScale, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("resume", js_cocos2dx_studio_ArmatureAnimation_resume, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("stop", js_cocos2dx_studio_ArmatureAnimation_stop, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setAnimationData", js_cocos2dx_studio_ArmatureAnimation_setAnimationData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setSpeedScale", js_cocos2dx_studio_ArmatureAnimation_setSpeedScale, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("update", js_cocos2dx_studio_ArmatureAnimation_update, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getAnimationData", js_cocos2dx_studio_ArmatureAnimation_getAnimationData, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("playByIndex", js_cocos2dx_studio_ArmatureAnimation_playByIndex, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("init", js_cocos2dx_studio_ArmatureAnimation_init, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getMovementCount", js_cocos2dx_studio_ArmatureAnimation_getMovementCount, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getCurrentMovementID", js_cocos2dx_studio_ArmatureAnimation_getCurrentMovementID, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setAnimationInternal", js_cocos2dx_studio_ArmatureAnimation_setAnimationInternal, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("ctor", js_cocos2dx_studio_ArmatureAnimation_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
static JSFunctionSpec st_funcs[] = {
JS_FN("create", js_cocos2dx_studio_ArmatureAnimation_create, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
jsb_ArmatureAnimation_prototype = JS_InitClass(
cx, global,
NULL, // parent proto
jsb_ArmatureAnimation_class,
js_cocos2dx_studio_ArmatureAnimation_constructor, 0, // constructor
properties,
funcs,
NULL, // no static properties
st_funcs);
// make the class enumerable in the registered namespace
JSBool found;
JS_SetPropertyAttributes(cx, global, "ArmatureAnimation", JSPROP_ENUMERATE | JSPROP_READONLY, &found);
// add the proto and JSClass to the type->js info hash table
TypeTest<cocostudio::ArmatureAnimation> t;
js_type_class_t *p;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, p);
if (!p) {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->type = typeId;
p->jsclass = jsb_ArmatureAnimation_class;
p->proto = jsb_ArmatureAnimation_prototype;
p->parentProto = NULL;
HASH_ADD_INT(_js_global_type_ht, type, p);
}
}
JSClass *jsb_ArmatureDataManager_class;
JSObject *jsb_ArmatureDataManager_prototype;
JSBool js_cocos2dx_studio_ArmatureDataManager_getAnimationDatas(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getAnimationDatas : Invalid Native Object");
if (argc == 0) {
Dictionary* ret = cobj->getAnimationDatas();
jsval jsret;
jsret = ccdictionary_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_getAnimationDatas : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_removeAnimationData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_removeAnimationData : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_removeAnimationData : Error processing arguments");
cobj->removeAnimationData(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_removeAnimationData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_addArmatureData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addArmatureData : Invalid Native Object");
if (argc == 2) {
const char* arg0;
cocostudio::ArmatureData* arg1;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
do {
if (!argv[1].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]);
proxy = jsb_get_js_proxy(tmpObj);
arg1 = (cocostudio::ArmatureData*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg1, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addArmatureData : Error processing arguments");
cobj->addArmatureData(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_addArmatureData : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = NULL;
cocostudio::ArmatureDataManager* cobj = NULL;
obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo : Invalid Native Object");
do {
if (argc == 3) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
const char* arg1;
std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
const char* arg2;
std::string arg2_tmp; ok &= jsval_to_std_string(cx, argv[2], &arg2_tmp); arg2 = arg2_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
cobj->addArmatureFileInfo(arg0, arg1, arg2);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
} while(0);
do {
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
cobj->addArmatureFileInfo(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
} while(0);
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_getTextureDatas(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getTextureDatas : Invalid Native Object");
if (argc == 0) {
Dictionary* ret = cobj->getTextureDatas();
jsval jsret;
jsret = ccdictionary_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_getTextureDatas : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_getTextureData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getTextureData : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getTextureData : Error processing arguments");
cocostudio::TextureData* ret = cobj->getTextureData(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::TextureData>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_getTextureData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_getArmatureData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getArmatureData : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getArmatureData : Error processing arguments");
cocostudio::ArmatureData* ret = cobj->getArmatureData(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::ArmatureData>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_getArmatureData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_getAnimationData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getAnimationData : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getAnimationData : Error processing arguments");
cocostudio::AnimationData* ret = cobj->getAnimationData(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::AnimationData>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_getAnimationData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_removeAll(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_removeAll : Invalid Native Object");
if (argc == 0) {
cobj->removeAll();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_removeAll : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_addAnimationData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addAnimationData : Invalid Native Object");
if (argc == 2) {
const char* arg0;
cocostudio::AnimationData* arg1;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
do {
if (!argv[1].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]);
proxy = jsb_get_js_proxy(tmpObj);
arg1 = (cocostudio::AnimationData*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg1, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addAnimationData : Error processing arguments");
cobj->addAnimationData(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_addAnimationData : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_init(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_init : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->init();
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_init : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_removeArmatureData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_removeArmatureData : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_removeArmatureData : Error processing arguments");
cobj->removeArmatureData(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_removeArmatureData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_getArmatureDatas(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_getArmatureDatas : Invalid Native Object");
if (argc == 0) {
Dictionary* ret = cobj->getArmatureDatas();
jsval jsret;
jsret = ccdictionary_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_getArmatureDatas : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_removeTextureData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_removeTextureData : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_removeTextureData : Error processing arguments");
cobj->removeTextureData(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_removeTextureData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_addTextureData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addTextureData : Invalid Native Object");
if (argc == 2) {
const char* arg0;
cocostudio::TextureData* arg1;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
do {
if (!argv[1].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]);
proxy = jsb_get_js_proxy(tmpObj);
arg1 = (cocostudio::TextureData*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg1, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addTextureData : Error processing arguments");
cobj->addTextureData(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_addTextureData : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_isAutoLoadSpriteFile(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_isAutoLoadSpriteFile : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->isAutoLoadSpriteFile();
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_isAutoLoadSpriteFile : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile : Invalid Native Object");
if (argc == 2) {
const char* arg0;
const char* arg1;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile : Error processing arguments");
cobj->addSpriteFrameFromFile(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_destoryInstance(JSContext *cx, uint32_t argc, jsval *vp)
{
if (argc == 0) {
cocostudio::ArmatureDataManager::destoryInstance();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_destoryInstance : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_ArmatureDataManager_getInstance(JSContext *cx, uint32_t argc, jsval *vp)
{
if (argc == 0) {
cocostudio::ArmatureDataManager* ret = cocostudio::ArmatureDataManager::getInstance();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::ArmatureDataManager>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_ArmatureDataManager_getInstance : wrong number of arguments");
return JS_FALSE;
}
void js_cocos2dx_studio_ArmatureDataManager_finalize(JSFreeOp *fop, JSObject *obj) {
CCLOGINFO("jsbindings: finalizing JS object %p (ArmatureDataManager)", obj);
}
void js_register_cocos2dx_studio_ArmatureDataManager(JSContext *cx, JSObject *global) {
jsb_ArmatureDataManager_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_ArmatureDataManager_class->name = "ArmatureDataManager";
jsb_ArmatureDataManager_class->addProperty = JS_PropertyStub;
jsb_ArmatureDataManager_class->delProperty = JS_DeletePropertyStub;
jsb_ArmatureDataManager_class->getProperty = JS_PropertyStub;
jsb_ArmatureDataManager_class->setProperty = JS_StrictPropertyStub;
jsb_ArmatureDataManager_class->enumerate = JS_EnumerateStub;
jsb_ArmatureDataManager_class->resolve = JS_ResolveStub;
jsb_ArmatureDataManager_class->convert = JS_ConvertStub;
jsb_ArmatureDataManager_class->finalize = js_cocos2dx_studio_ArmatureDataManager_finalize;
jsb_ArmatureDataManager_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
{0, 0, 0, JSOP_NULLWRAPPER, JSOP_NULLWRAPPER}
};
static JSFunctionSpec funcs[] = {
JS_FN("getAnimationDatas", js_cocos2dx_studio_ArmatureDataManager_getAnimationDatas, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeAnimationData", js_cocos2dx_studio_ArmatureDataManager_removeAnimationData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addArmatureData", js_cocos2dx_studio_ArmatureDataManager_addArmatureData, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addArmatureFileInfo", js_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTextureDatas", js_cocos2dx_studio_ArmatureDataManager_getTextureDatas, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTextureData", js_cocos2dx_studio_ArmatureDataManager_getTextureData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getArmatureData", js_cocos2dx_studio_ArmatureDataManager_getArmatureData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getAnimationData", js_cocos2dx_studio_ArmatureDataManager_getAnimationData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeAll", js_cocos2dx_studio_ArmatureDataManager_removeAll, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addAnimationData", js_cocos2dx_studio_ArmatureDataManager_addAnimationData, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("init", js_cocos2dx_studio_ArmatureDataManager_init, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeArmatureData", js_cocos2dx_studio_ArmatureDataManager_removeArmatureData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getArmatureDatas", js_cocos2dx_studio_ArmatureDataManager_getArmatureDatas, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeTextureData", js_cocos2dx_studio_ArmatureDataManager_removeTextureData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addTextureData", js_cocos2dx_studio_ArmatureDataManager_addTextureData, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isAutoLoadSpriteFile", js_cocos2dx_studio_ArmatureDataManager_isAutoLoadSpriteFile, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addSpriteFrameFromFile", js_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
static JSFunctionSpec st_funcs[] = {
JS_FN("destoryInstance", js_cocos2dx_studio_ArmatureDataManager_destoryInstance, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getInstance", js_cocos2dx_studio_ArmatureDataManager_getInstance, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
jsb_ArmatureDataManager_prototype = JS_InitClass(
cx, global,
NULL, // parent proto
jsb_ArmatureDataManager_class,
empty_constructor, 0,
properties,
funcs,
NULL, // no static properties
st_funcs);
// make the class enumerable in the registered namespace
JSBool found;
JS_SetPropertyAttributes(cx, global, "ArmatureDataManager", JSPROP_ENUMERATE | JSPROP_READONLY, &found);
// add the proto and JSClass to the type->js info hash table
TypeTest<cocostudio::ArmatureDataManager> t;
js_type_class_t *p;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, p);
if (!p) {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->type = typeId;
p->jsclass = jsb_ArmatureDataManager_class;
p->proto = jsb_ArmatureDataManager_prototype;
p->parentProto = NULL;
HASH_ADD_INT(_js_global_type_ht, type, p);
}
}
JSClass *jsb_Armature_class;
JSObject *jsb_Armature_prototype;
JSBool js_cocos2dx_studio_Armature_getBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getBone : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getBone : Error processing arguments");
cocostudio::Bone* ret = cobj->getBone(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Bone>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getBone : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_changeBoneParent(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_changeBoneParent : Invalid Native Object");
if (argc == 2) {
cocostudio::Bone* arg0;
const char* arg1;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_changeBoneParent : Error processing arguments");
cobj->changeBoneParent(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_changeBoneParent : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_setAnimation(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setAnimation : Invalid Native Object");
if (argc == 1) {
cocostudio::ArmatureAnimation* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::ArmatureAnimation*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setAnimation : Error processing arguments");
cobj->setAnimation(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_setAnimation : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getBoneAtPoint(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getBoneAtPoint : Invalid Native Object");
if (argc == 2) {
double arg0;
double arg1;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
ok &= JS_ValueToNumber(cx, argv[1], &arg1);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getBoneAtPoint : Error processing arguments");
cocostudio::Bone* ret = cobj->getBoneAtPoint(arg0, arg1);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Bone>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getBoneAtPoint : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getArmatureTransformDirty(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getArmatureTransformDirty : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->getArmatureTransformDirty();
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getArmatureTransformDirty : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_setVersion(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setVersion : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setVersion : Error processing arguments");
cobj->setVersion(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_setVersion : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_updateOffsetPoint(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_updateOffsetPoint : Invalid Native Object");
if (argc == 0) {
cobj->updateOffsetPoint();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_updateOffsetPoint : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getParentBone(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getParentBone : Invalid Native Object");
if (argc == 0) {
cocostudio::Bone* ret = cobj->getParentBone();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Bone>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getParentBone : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_setName(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setName : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setName : Error processing arguments");
cobj->setName(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_setName : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_removeBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_removeBone : Invalid Native Object");
if (argc == 2) {
cocostudio::Bone* arg0;
JSBool arg1;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
ok &= JS_ValueToBoolean(cx, argv[1], &arg1);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_removeBone : Error processing arguments");
cobj->removeBone(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_removeBone : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getBatchNode(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getBatchNode : Invalid Native Object");
if (argc == 0) {
cocostudio::BatchNode* ret = cobj->getBatchNode();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::BatchNode>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getBatchNode : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getName(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getName : Invalid Native Object");
if (argc == 0) {
std::string ret = cobj->getName();
jsval jsret;
jsret = std_string_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getName : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_init(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = NULL;
cocostudio::Armature* cobj = NULL;
obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_init : Invalid Native Object");
do {
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
bool ret = cobj->init(arg0);
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while(0);
do {
if (argc == 0) {
bool ret = cobj->init();
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while(0);
do {
if (argc == 2) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
cocostudio::Bone* arg1;
do {
if (!argv[1].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]);
proxy = jsb_get_js_proxy(tmpObj);
arg1 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg1, cx, JS_FALSE, "Invalid Native Object");
} while (0);
if (!ok) { ok = JS_TRUE; break; }
bool ret = cobj->init(arg0, arg1);
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while(0);
JS_ReportError(cx, "js_cocos2dx_studio_Armature_init : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getNodeToParentTransform(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getNodeToParentTransform : Invalid Native Object");
if (argc == 0) {
cocos2d::AffineTransform ret = cobj->getNodeToParentTransform();
jsval jsret;
#pragma warning NO CONVERSION FROM NATIVE FOR const AffineTransform;
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getNodeToParentTransform : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_setParentBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setParentBone : Invalid Native Object");
if (argc == 1) {
cocostudio::Bone* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setParentBone : Error processing arguments");
cobj->setParentBone(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_setParentBone : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getBoundingBox(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getBoundingBox : Invalid Native Object");
if (argc == 0) {
Rect ret = cobj->getBoundingBox();
jsval jsret;
jsret = ccrect_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getBoundingBox : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_setBatchNode(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setBatchNode : Invalid Native Object");
if (argc == 1) {
cocostudio::BatchNode* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::BatchNode*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setBatchNode : Error processing arguments");
cobj->setBatchNode(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_setBatchNode : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_draw(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_draw : Invalid Native Object");
if (argc == 0) {
cobj->draw();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_draw : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_setArmatureData(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setArmatureData : Invalid Native Object");
if (argc == 1) {
cocostudio::ArmatureData* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::ArmatureData*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setArmatureData : Error processing arguments");
cobj->setArmatureData(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_setArmatureData : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_setTextureAtlas(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setTextureAtlas : Invalid Native Object");
if (argc == 1) {
TextureAtlas* arg0;
#pragma warning NO CONVERSION TO NATIVE FOR TextureAtlas*;
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_setTextureAtlas : Error processing arguments");
cobj->setTextureAtlas(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_setTextureAtlas : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_addBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_addBone : Invalid Native Object");
if (argc == 2) {
cocostudio::Bone* arg0;
const char* arg1;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_addBone : Error processing arguments");
cobj->addBone(arg0, arg1);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_addBone : wrong number of arguments: %d, was expecting %d", argc, 2);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_update(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_update : Invalid Native Object");
if (argc == 1) {
double arg0;
ok &= JS_ValueToNumber(cx, argv[0], &arg0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Armature_update : Error processing arguments");
cobj->update(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_update : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getArmatureData(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getArmatureData : Invalid Native Object");
if (argc == 0) {
cocostudio::ArmatureData* ret = cobj->getArmatureData();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::ArmatureData>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getArmatureData : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getVersion(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getVersion : Invalid Native Object");
if (argc == 0) {
float ret = cobj->getVersion();
jsval jsret;
jsret = DOUBLE_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getVersion : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getAnimation(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getAnimation : Invalid Native Object");
if (argc == 0) {
cocostudio::ArmatureAnimation* ret = cobj->getAnimation();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::ArmatureAnimation>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getAnimation : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getBoneDic(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getBoneDic : Invalid Native Object");
if (argc == 0) {
Dictionary* ret = cobj->getBoneDic();
jsval jsret;
jsret = ccdictionary_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getBoneDic : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_getTextureAtlas(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Armature* cobj = (cocostudio::Armature *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Armature_getTextureAtlas : Invalid Native Object");
if (argc == 0) {
TextureAtlas* ret = cobj->getTextureAtlas();
jsval jsret;
#pragma warning NO CONVERSION FROM NATIVE FOR TextureAtlas*;
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_getTextureAtlas : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_create(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
do {
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
cocostudio::Armature* ret = cocostudio::Armature::create(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Armature>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while (0);
do {
if (argc == 0) {
cocostudio::Armature* ret = cocostudio::Armature::create();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Armature>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while (0);
do {
if (argc == 2) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
cocostudio::Bone* arg1;
do {
if (!argv[1].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]);
proxy = jsb_get_js_proxy(tmpObj);
arg1 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg1, cx, JS_FALSE, "Invalid Native Object");
} while (0);
if (!ok) { ok = JS_TRUE; break; }
cocostudio::Armature* ret = cocostudio::Armature::create(arg0, arg1);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Armature>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while (0);
JS_ReportError(cx, "js_cocos2dx_studio_Armature_create : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Armature_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
if (argc == 0) {
cocostudio::Armature* cobj = new cocostudio::Armature();
cocos2d::Object *_ccobj = dynamic_cast<cocos2d::Object *>(cobj);
if (_ccobj) {
_ccobj->autorelease();
}
TypeTest<cocostudio::Armature> t;
js_type_class_t *typeClass;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass);
assert(typeClass);
JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
// link the native object with the javascript object
js_proxy_t* p = jsb_new_proxy(cobj, obj);
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::Armature");
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Armature_constructor : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
extern JSObject *jsb_NodeRGBA_prototype;
void js_cocos2dx_studio_Armature_finalize(JSFreeOp *fop, JSObject *obj) {
CCLOGINFO("jsbindings: finalizing JS object %p (Armature)", obj);
}
static JSBool js_cocos2dx_studio_Armature_ctor(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
cocostudio::Armature *nobj = new cocostudio::Armature();
js_proxy_t* p = jsb_new_proxy(nobj, obj);
nobj->autorelease();
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::Armature");
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
void js_register_cocos2dx_studio_Armature(JSContext *cx, JSObject *global) {
jsb_Armature_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_Armature_class->name = "Armature";
jsb_Armature_class->addProperty = JS_PropertyStub;
jsb_Armature_class->delProperty = JS_DeletePropertyStub;
jsb_Armature_class->getProperty = JS_PropertyStub;
jsb_Armature_class->setProperty = JS_StrictPropertyStub;
jsb_Armature_class->enumerate = JS_EnumerateStub;
jsb_Armature_class->resolve = JS_ResolveStub;
jsb_Armature_class->convert = JS_ConvertStub;
jsb_Armature_class->finalize = js_cocos2dx_studio_Armature_finalize;
jsb_Armature_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
{0, 0, 0, JSOP_NULLWRAPPER, JSOP_NULLWRAPPER}
};
static JSFunctionSpec funcs[] = {
JS_FN("getBone", js_cocos2dx_studio_Armature_getBone, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("changeBoneParent", js_cocos2dx_studio_Armature_changeBoneParent, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setAnimation", js_cocos2dx_studio_Armature_setAnimation, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getBoneAtPoint", js_cocos2dx_studio_Armature_getBoneAtPoint, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getArmatureTransformDirty", js_cocos2dx_studio_Armature_getArmatureTransformDirty, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setVersion", js_cocos2dx_studio_Armature_setVersion, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("updateOffsetPoint", js_cocos2dx_studio_Armature_updateOffsetPoint, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getParentBone", js_cocos2dx_studio_Armature_getParentBone, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setName", js_cocos2dx_studio_Armature_setName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeBone", js_cocos2dx_studio_Armature_removeBone, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getBatchNode", js_cocos2dx_studio_Armature_getBatchNode, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getName", js_cocos2dx_studio_Armature_getName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("init", js_cocos2dx_studio_Armature_init, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getNodeToParentTransform", js_cocos2dx_studio_Armature_getNodeToParentTransform, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setParentBone", js_cocos2dx_studio_Armature_setParentBone, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getBoundingBox", js_cocos2dx_studio_Armature_getBoundingBox, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setBatchNode", js_cocos2dx_studio_Armature_setBatchNode, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("draw", js_cocos2dx_studio_Armature_draw, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setArmatureData", js_cocos2dx_studio_Armature_setArmatureData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setTextureAtlas", js_cocos2dx_studio_Armature_setTextureAtlas, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addBone", js_cocos2dx_studio_Armature_addBone, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("update", js_cocos2dx_studio_Armature_update, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getArmatureData", js_cocos2dx_studio_Armature_getArmatureData, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getVersion", js_cocos2dx_studio_Armature_getVersion, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getAnimation", js_cocos2dx_studio_Armature_getAnimation, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getBoneDic", js_cocos2dx_studio_Armature_getBoneDic, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTextureAtlas", js_cocos2dx_studio_Armature_getTextureAtlas, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("ctor", js_cocos2dx_studio_Armature_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
static JSFunctionSpec st_funcs[] = {
JS_FN("create", js_cocos2dx_studio_Armature_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
jsb_Armature_prototype = JS_InitClass(
cx, global,
jsb_NodeRGBA_prototype,
jsb_Armature_class,
js_cocos2dx_studio_Armature_constructor, 0, // constructor
properties,
funcs,
NULL, // no static properties
st_funcs);
// make the class enumerable in the registered namespace
JSBool found;
JS_SetPropertyAttributes(cx, global, "Armature", JSPROP_ENUMERATE | JSPROP_READONLY, &found);
// add the proto and JSClass to the type->js info hash table
TypeTest<cocostudio::Armature> t;
js_type_class_t *p;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, p);
if (!p) {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->type = typeId;
p->jsclass = jsb_Armature_class;
p->proto = jsb_Armature_prototype;
p->parentProto = jsb_NodeRGBA_prototype;
HASH_ADD_INT(_js_global_type_ht, type, p);
}
}
JSClass *jsb_Skin_class;
JSObject *jsb_Skin_prototype;
JSBool js_cocos2dx_studio_Skin_getBone(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_getBone : Invalid Native Object");
if (argc == 0) {
cocostudio::Bone* ret = cobj->getBone();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Bone>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_getBone : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_getNodeToWorldTransformAR(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_getNodeToWorldTransformAR : Invalid Native Object");
if (argc == 0) {
AffineTransform ret = cobj->getNodeToWorldTransformAR();
jsval jsret;
jsret = ccaffinetransform_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_getNodeToWorldTransformAR : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_getNodeToWorldTransform(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_getNodeToWorldTransform : Invalid Native Object");
if (argc == 0) {
AffineTransform ret = cobj->getNodeToWorldTransform();
jsval jsret;
jsret = ccaffinetransform_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_getNodeToWorldTransform : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_updateTransform(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_updateTransform : Invalid Native Object");
if (argc == 0) {
cobj->updateTransform();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_updateTransform : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_getDisplayName(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_getDisplayName : Invalid Native Object");
if (argc == 0) {
std::string ret = cobj->getDisplayName();
jsval jsret;
jsret = std_string_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_getDisplayName : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_updateArmatureTransform(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_updateArmatureTransform : Invalid Native Object");
if (argc == 0) {
cobj->updateArmatureTransform();
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_updateArmatureTransform : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_initWithSpriteFrameName(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_initWithSpriteFrameName : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Skin_initWithSpriteFrameName : Error processing arguments");
bool ret = cobj->initWithSpriteFrameName(arg0);
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_initWithSpriteFrameName : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_initWithFile(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_initWithFile : Invalid Native Object");
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Skin_initWithFile : Error processing arguments");
bool ret = cobj->initWithFile(arg0);
jsval jsret;
jsret = BOOLEAN_TO_JSVAL(ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_initWithFile : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_setBone(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocostudio::Skin* cobj = (cocostudio::Skin *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "js_cocos2dx_studio_Skin_setBone : Invalid Native Object");
if (argc == 1) {
cocostudio::Bone* arg0;
do {
if (!argv[0].isObject()) { ok = JS_FALSE; break; }
js_proxy_t *proxy;
JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]);
proxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocostudio::Bone*)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, JS_FALSE, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Skin_setBone : Error processing arguments");
cobj->setBone(arg0);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_setBone : wrong number of arguments: %d, was expecting %d", argc, 1);
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_create(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
do {
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
if (!ok) { ok = JS_TRUE; break; }
cocostudio::Skin* ret = cocostudio::Skin::create(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Skin>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while (0);
do {
if (argc == 0) {
cocostudio::Skin* ret = cocostudio::Skin::create();
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Skin>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
} while (0);
JS_ReportError(cx, "js_cocos2dx_studio_Skin_create : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_createWithSpriteFrameName(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
if (argc == 1) {
const char* arg0;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
JSB_PRECONDITION2(ok, cx, JS_FALSE, "js_cocos2dx_studio_Skin_createWithSpriteFrameName : Error processing arguments");
cocostudio::Skin* ret = cocostudio::Skin::createWithSpriteFrameName(arg0);
jsval jsret;
do {
if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<cocostudio::Skin>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj);
} else {
jsret = JSVAL_NULL;
}
} while (0);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_createWithSpriteFrameName : wrong number of arguments");
return JS_FALSE;
}
JSBool js_cocos2dx_studio_Skin_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
if (argc == 0) {
cocostudio::Skin* cobj = new cocostudio::Skin();
cocos2d::Object *_ccobj = dynamic_cast<cocos2d::Object *>(cobj);
if (_ccobj) {
_ccobj->autorelease();
}
TypeTest<cocostudio::Skin> t;
js_type_class_t *typeClass;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass);
assert(typeClass);
JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
// link the native object with the javascript object
js_proxy_t* p = jsb_new_proxy(cobj, obj);
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::Skin");
return JS_TRUE;
}
JS_ReportError(cx, "js_cocos2dx_studio_Skin_constructor : wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
}
extern JSObject *jsb_Sprite_prototype;
void js_cocos2dx_studio_Skin_finalize(JSFreeOp *fop, JSObject *obj) {
CCLOGINFO("jsbindings: finalizing JS object %p (Skin)", obj);
}
static JSBool js_cocos2dx_studio_Skin_ctor(JSContext *cx, uint32_t argc, jsval *vp)
{
JSObject *obj = JS_THIS_OBJECT(cx, vp);
cocostudio::Skin *nobj = new cocostudio::Skin();
js_proxy_t* p = jsb_new_proxy(nobj, obj);
nobj->autorelease();
JS_AddNamedObjectRoot(cx, &p->obj, "cocostudio::Skin");
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
void js_register_cocos2dx_studio_Skin(JSContext *cx, JSObject *global) {
jsb_Skin_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_Skin_class->name = "Skin";
jsb_Skin_class->addProperty = JS_PropertyStub;
jsb_Skin_class->delProperty = JS_DeletePropertyStub;
jsb_Skin_class->getProperty = JS_PropertyStub;
jsb_Skin_class->setProperty = JS_StrictPropertyStub;
jsb_Skin_class->enumerate = JS_EnumerateStub;
jsb_Skin_class->resolve = JS_ResolveStub;
jsb_Skin_class->convert = JS_ConvertStub;
jsb_Skin_class->finalize = js_cocos2dx_studio_Skin_finalize;
jsb_Skin_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
{0, 0, 0, JSOP_NULLWRAPPER, JSOP_NULLWRAPPER}
};
static JSFunctionSpec funcs[] = {
JS_FN("getBone", js_cocos2dx_studio_Skin_getBone, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getNodeToWorldTransformAR", js_cocos2dx_studio_Skin_getNodeToWorldTransformAR, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getNodeToWorldTransform", js_cocos2dx_studio_Skin_getNodeToWorldTransform, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("updateTransform", js_cocos2dx_studio_Skin_updateTransform, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getDisplayName", js_cocos2dx_studio_Skin_getDisplayName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("updateArmatureTransform", js_cocos2dx_studio_Skin_updateArmatureTransform, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("initWithSpriteFrameName", js_cocos2dx_studio_Skin_initWithSpriteFrameName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("initWithFile", js_cocos2dx_studio_Skin_initWithFile, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setBone", js_cocos2dx_studio_Skin_setBone, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("ctor", js_cocos2dx_studio_Skin_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
static JSFunctionSpec st_funcs[] = {
JS_FN("create", js_cocos2dx_studio_Skin_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("createWithSpriteFrameName", js_cocos2dx_studio_Skin_createWithSpriteFrameName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
jsb_Skin_prototype = JS_InitClass(
cx, global,
jsb_Sprite_prototype,
jsb_Skin_class,
js_cocos2dx_studio_Skin_constructor, 0, // constructor
properties,
funcs,
NULL, // no static properties
st_funcs);
// make the class enumerable in the registered namespace
JSBool found;
JS_SetPropertyAttributes(cx, global, "Skin", JSPROP_ENUMERATE | JSPROP_READONLY, &found);
// add the proto and JSClass to the type->js info hash table
TypeTest<cocostudio::Skin> t;
js_type_class_t *p;
uint32_t typeId = t.s_id();
HASH_FIND_INT(_js_global_type_ht, &typeId, p);
if (!p) {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->type = typeId;
p->jsclass = jsb_Skin_class;
p->proto = jsb_Skin_prototype;
p->parentProto = jsb_Sprite_prototype;
HASH_ADD_INT(_js_global_type_ht, type, p);
}
}
void register_all_cocos2dx_studio(JSContext* cx, JSObject* obj) {
// first, try to get the ns
JS::RootedValue nsval(cx);
JSObject *ns;
JS_GetProperty(cx, obj, "cc", &nsval);
if (nsval == JSVAL_VOID) {
ns = JS_NewObject(cx, NULL, NULL, NULL);
nsval = OBJECT_TO_JSVAL(ns);
JS_SetProperty(cx, obj, "cc", nsval);
} else {
JS_ValueToObject(cx, nsval, &ns);
}
obj = ns;
js_register_cocos2dx_studio_Skin(cx, obj);
js_register_cocos2dx_studio_ArmatureAnimation(cx, obj);
js_register_cocos2dx_studio_Armature(cx, obj);
js_register_cocos2dx_studio_ArmatureDataManager(cx, obj);
js_register_cocos2dx_studio_Bone(cx, obj);
}
<file_sep>#ifndef __cocos2dx_studio_h__
#define __cocos2dx_studio_h__
#include "jsapi.h"
#include "jsfriendapi.h"
extern JSClass *jsb_Bone_class;
extern JSObject *jsb_Bone_prototype;
JSBool js_cocos2dx_studio_Bone_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_studio_Bone_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_studio_Bone(JSContext *cx, JSObject *global);
void register_all_cocos2dx_studio(JSContext* cx, JSObject* obj);
JSBool js_cocos2dx_studio_Bone_isTransformDirty(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_updateZOrder(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getDisplayRenderNode(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getTween(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getParentBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getBlendType(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_updateColor(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getName(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setTransformDirty(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_addChildBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_updateDisplayedOpacity(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_init(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setParentBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setZOrder(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getIgnoreMovementBoneData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setIgnoreMovementBoneData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setName(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_removeFromParent(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getChildArmature(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_update(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setDisplayManager(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getTweenData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getColliderBodyList(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setBoneData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setArmature(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_addDisplay(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getNodeToWorldTransform(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_removeChildBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setChildArmature(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getNodeToArmatureTransform(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getDisplayManager(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getArmature(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_setBlendType(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_changeDisplayByIndex(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_updateDisplayedColor(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_getBoneData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_create(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Bone_Bone(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_ArmatureAnimation_class;
extern JSObject *jsb_ArmatureAnimation_prototype;
JSBool js_cocos2dx_studio_ArmatureAnimation_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_studio_ArmatureAnimation_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_studio_ArmatureAnimation(JSContext *cx, JSObject *global);
void register_all_cocos2dx_studio(JSContext* cx, JSObject* obj);
JSBool js_cocos2dx_studio_ArmatureAnimation_getSpeedScale(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_getAnimationScale(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_play(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_pause(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_setAnimationScale(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_resume(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_stop(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_setAnimationData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_setSpeedScale(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_update(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_getAnimationData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_playByIndex(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_init(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_getMovementCount(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_getCurrentMovementID(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_setAnimationInternal(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_create(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureAnimation_ArmatureAnimation(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_ArmatureDataManager_class;
extern JSObject *jsb_ArmatureDataManager_prototype;
JSBool js_cocos2dx_studio_ArmatureDataManager_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_studio_ArmatureDataManager_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_studio_ArmatureDataManager(JSContext *cx, JSObject *global);
void register_all_cocos2dx_studio(JSContext* cx, JSObject* obj);
JSBool js_cocos2dx_studio_ArmatureDataManager_getAnimationDatas(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_removeAnimationData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_addArmatureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_addArmatureFileInfo(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_getTextureDatas(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_getTextureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_getArmatureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_getAnimationData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_removeAll(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_addAnimationData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_init(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_removeArmatureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_getArmatureDatas(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_removeTextureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_addTextureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_isAutoLoadSpriteFile(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_addSpriteFrameFromFile(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_destoryInstance(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_ArmatureDataManager_getInstance(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_Armature_class;
extern JSObject *jsb_Armature_prototype;
JSBool js_cocos2dx_studio_Armature_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_studio_Armature_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_studio_Armature(JSContext *cx, JSObject *global);
void register_all_cocos2dx_studio(JSContext* cx, JSObject* obj);
JSBool js_cocos2dx_studio_Armature_getBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_changeBoneParent(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_setAnimation(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getBoneAtPoint(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getArmatureTransformDirty(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_setVersion(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_updateOffsetPoint(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getParentBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_setName(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_removeBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getBatchNode(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getName(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_init(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getNodeToParentTransform(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_setParentBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getBoundingBox(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_setBatchNode(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_draw(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_setArmatureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_setTextureAtlas(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_addBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_update(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getArmatureData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getVersion(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getAnimation(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getBoneDic(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_getTextureAtlas(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_create(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Armature_Armature(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_Skin_class;
extern JSObject *jsb_Skin_prototype;
JSBool js_cocos2dx_studio_Skin_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_studio_Skin_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_studio_Skin(JSContext *cx, JSObject *global);
void register_all_cocos2dx_studio(JSContext* cx, JSObject* obj);
JSBool js_cocos2dx_studio_Skin_getBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_getNodeToWorldTransformAR(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_getNodeToWorldTransform(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_updateTransform(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_getDisplayName(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_updateArmatureTransform(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_initWithSpriteFrameName(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_initWithFile(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_setBone(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_create(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_createWithSpriteFrameName(JSContext *cx, uint32_t argc, jsval *vp);
JSBool js_cocos2dx_studio_Skin_Skin(JSContext *cx, uint32_t argc, jsval *vp);
#endif
|
b65ab385227c4d600420fbce1e7ad749033bd00c
|
[
"JavaScript",
"C++"
] | 3
|
JavaScript
|
yuxin-cocoside/bindings-auto-generated
|
c1da46eabb46727a66daa4d64d9841b09fa6d63c
|
a054200f533d4a4ed87cd6e81386c33c74224848
|
refs/heads/master
|
<file_sep>package org.smh.restful.RestfulTest.control;
import org.smh.restful.RestfulTest.util.RedisClusterUtils;
import org.smh.restful.RestfulTest.vo.RequestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestfulController {
@Autowired
private RedisClusterUtils redisClusterUtils;
@RequestMapping(value = "/rest", method = RequestMethod.POST)
public String testBase (@RequestBody RequestVo requestVo) {
if(null != requestVo) {
redisClusterUtils.setValueByKey("001::name", requestVo.getName());
redisClusterUtils.setValueByKey("001::age", String.valueOf(requestVo.getAge()));
redisClusterUtils.setValueByKey("001::className", requestVo.getClassName());
} else {
return "error";
}
return "ok";
}
@RequestMapping(value = "/getTestValue", method = RequestMethod.POST)
public String getTestValue(){
System.out.println(redisClusterUtils.getValueByKey("001::name"));
System.out.println(redisClusterUtils.getValueByKey("001::age"));
System.out.println(redisClusterUtils.getValueByKey("001::className"));
return "ok";
}
}
<file_sep>package org.smh.restful.RestfulTest.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.Set;
@Configuration
@PropertySource("classpath:redis.properties")
@ConfigurationProperties(prefix = "restful.redis")
public class RedisConfig {
private String host;
private int port;
private int timeout;
private int maxIdle;
private long maxWaitMillis;
private String password;
private boolean blockWhenExhausted;
private int maxTotal;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public long getMaxWaitMillis() {
return maxWaitMillis;
}
public void setMaxWaitMillis(long maxWaitMillis) {
this.maxWaitMillis = maxWaitMillis;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isBlockWhenExhausted() {
return blockWhenExhausted;
}
public void setBlockWhenExhausted(boolean blockWhenExhausted) {
this.blockWhenExhausted = blockWhenExhausted;
}
public int getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
}
@Bean
public JedisPool jedisPoolFactory() {
System.out.println("start to init jedis");
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setTestOnReturn(true);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
return jedisPool;
}
@Bean
public JedisCluster initJedisCluster(){
System.out.println("start to init jedis cluster ");
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setTestOnReturn(true);
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.198.128", 6379));
nodes.add(new HostAndPort("192.168.198.128", 6380));
nodes.add(new HostAndPort("192.168.198.128", 6381));
nodes.add(new HostAndPort("192.168.198.129", 6382));
nodes.add(new HostAndPort("192.168.198.129", 6383));
nodes.add(new HostAndPort("192.168.198.129", 6384));
JedisCluster jedisCluster = new JedisCluster(nodes, 1500, 1500, 10, "123456", jedisPoolConfig);
// JedisCluster jedisCluster = new JedisCluster(nodes, jedisPoolConfig);
return jedisCluster;
}
}
<file_sep>server.port=8081
spring.application.name=swagger-demo
<file_sep># WOJIAOGAOBINGFA
save a lot
<file_sep>package com.smh.swagger.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("swagger")
@Api("SWAGGER demo 控制层")
public class SwaggerDemoController {
@ApiOperation(value = "demo方法")
@GetMapping("demo")
public String demo() {
return "hello swagger";
}
}
|
7dbbc117d6079b2aaa569953c9fc1d16651b2475
|
[
"Markdown",
"Java",
"INI"
] | 5
|
Java
|
UpUpShao/WOJIAOGAOBINGFA
|
66ba70f00de5787213c8001e3b2e2190489ddd56
|
71c8a54d4d42664622fed5cdf5547f79d1ee4ab3
|
refs/heads/master
|
<file_sep>import math
class FuelCounterUpper:
def calculate_fuel_required(self, mass):
result = mass / 3
result = math.floor(result)
result -= 2
return result
def fuel_requirement(self, file_input):
sum_result = 0
with open(file_input) as data:
for line in data:
number = int(line)
fuel = self.calculate_fuel_required(number)
sum_result += fuel
return sum_result
def calculate_double_fuel_required(self, mass):
new_mass = self.calculate_fuel_required(mass)
if new_mass <= 0:
return 0
return new_mass + self.calculate_double_fuel_required(new_mass)
def double_checker_fuel_requirement(self, file_input):
sum_result = 0
with open(file_input) as data:
with open(file_input) as data:
for line in data:
number = int(line)
fuel = self.calculate_double_fuel_required(number)
sum_result += fuel
return sum_result
if __name__ == "__main__":
sol = FuelCounterUpper()
result = sol.calculate_fuel_required(12)
assert result == 2
result = sol.calculate_fuel_required(14)
assert result == 2
result = sol.calculate_fuel_required(1969)
assert result == 654
result = sol.calculate_fuel_required(100756)
assert result == 33583
result = sol.fuel_requirement("input.txt")
print(result)
result = sol.calculate_double_fuel_required(14)
assert result == 2
result = sol.calculate_double_fuel_required(1969)
assert result == 966
result = sol.calculate_double_fuel_required(100756)
assert result == 50346
result = sol.double_checker_fuel_requirement("input.txt")
print(result)<file_sep>class Graph:
def __init__(self):
self.graph = {}
self.closure = {}
def make_graph_file(self, file_input):
orbits = []
with open(file_input) as data:
for line in data:
line = line.rstrip()
orbits.append(line)
self.make_graph(orbits)
def make_graph(self, orbit_mappings):
for orbit in orbit_mappings:
[parent, child] = orbit.split(")")
if parent not in self.graph:
self.graph[parent] = []
if child not in self.graph:
self.graph[child] = []
# add child to parent
self.graph[parent].append(child)
def compute_transitive_closure(self, current_node, seen_list):
self.closure[current_node] = seen_list
for adjacent_node in self.graph[current_node]:
self.compute_transitive_closure(adjacent_node, seen_list + [current_node])
if __name__ == "__main__":
# GOAL: find all transitive closures
# TEST DATA
sol = Graph()
input_data = ['COM)B', 'B)C', 'C)D', 'D)E', 'E)F', 'B)G', 'G)H', 'D)I', 'E)J', 'J)K', 'K)L']
sol.make_graph(input_data)
assert sol.graph == {'COM': ['B'], 'B': ['C', 'G'], 'C': ['D'], 'D': ['E', 'I'], 'E': ['F', 'J'], 'F': [], 'G': ['H'], 'H': [], 'I': [], 'J': ['K'], 'K': ['L'], 'L': []}
sol.compute_transitive_closure('COM', [])
total_closures = 0
for available_nodes in sol.closure.values():
total_closures += len(available_nodes)
assert total_closures == 42
# PART 1
sol = Graph()
sol.make_graph_file("input.txt")
sol.compute_transitive_closure('COM', [])
print(sol.graph)
total_closures = 0
for available_nodes in sol.closure.values():
total_closures += len(available_nodes)
assert total_closures == 295936
#PART 2
you_set = set(sol.closure['YOU'])
san_set = set(sol.closure['SAN'])
diff = you_set.symmetric_difference(san_set)
assert len(diff) == 457
<file_sep>from enum import Enum
import pprint
pp = pprint.PrettyPrinter(indent=2)
class ManhattanDistance:
class DIRECTION(Enum):
UP = 'U'
DOWN = 'D'
LEFT = 'L'
RIGHT = 'R'
def __init__(self):
self.central_coordinates = (0, 0)
# coordinate tuple to type
self.seen_coords = {}
self.distance = None
def compute_manhattan_distance(self, coordinate):
# absolute value since distance is never negative1
return abs(coordinate[0]) + abs(coordinate[1])
def compute(self, start, direction, dist, wire_type, total_dist):
'''
Marks all coordinate from start position in a direction and adds to set
Will simultaneously check if wires cross and update closest coordinate
:param start: the starting coordiante
:param dist: the distance upwards to travel
:return last_coordinate: the last coordinate in this direction
'''
current = start
for i in range(dist):
# coordinate builds on previous coordinate
if direction is self.DIRECTION.UP.value:
coordinate = (current[0], current[1] + 1)
elif direction is self.DIRECTION.DOWN.value:
coordinate = (current[0], current[1] - 1)
elif direction is self.DIRECTION.LEFT.value:
coordinate = (current[0] - 1, current[1])
elif direction is self.DIRECTION.RIGHT.value:
coordinate = (current[0] + 1, current[1])
total_dist += 1
# handle if this coordinate is the first time being seen
if coordinate not in self.seen_coords:
self.seen_coords[coordinate] = {}
self.seen_coords[coordinate][wire_type] = total_dist
# add the wire type
# if there is more than 1 wire type at a coordinate there is an overlap
if len(self.seen_coords[coordinate]) > 1:
if self.distance is None:
self.distance = self.compute_manhattan_distance(coordinate)
else:
self.distance = min(self.compute_manhattan_distance(coordinate), self.distance)
# update current to end of last coordinate
current = coordinate
return current
def add_wire(self, start, dir_dist, wire_type):
'''
adds a wire to the control panel
:param dir_dist: direction distance
:return:
'''
# go through all direction distances and populate seen coordinates
last_coordinate = start
total_distance = 0
for item in dir_dist:
direction = item[0]
amount = int(item[1:])
last_coordinate = self.compute(last_coordinate, direction, amount, wire_type, total_distance)
total_distance += amount
def compute_distance_file(self, file_input):
# wire num to distances
wires = []
with open(file_input) as data:
for line in data:
distances = line.split(',')
wires.append(distances)
self.compute_distance(wires)
def compute_distance(self, wires):
wire_type = 0
for wire in wires:
self.add_wire(self.central_coordinates, wire, wire_type)
wire_type += 1
def get_least_steps(self):
min_distance = None
for coordinate, wire in sol.seen_coords.items():
if len(wire) > 1:
if min_distance is None:
min_distance = 0
for value in wire.values():
min_distance += value
else:
temp_distance = 0
for value in wire.values():
temp_distance += value
if temp_distance < min_distance:
min_distance = temp_distance
return min_distance
if __name__ == "__main__":
sol = ManhattanDistance()
result = sol.compute((0, 0), 'U', 50, 1, 0)
assert result == (0, 50)
assert len(sol.seen_coords) == 50
sol = ManhattanDistance()
result = sol.compute((0, 0), 'D', 50, 1, 0)
assert result == (0, -50)
assert len(sol.seen_coords) == 50
sol = ManhattanDistance()
result = sol.compute((0, 0), 'L', 50, 1, 0)
assert result == (-50, 0)
assert len(sol.seen_coords) == 50
sol = ManhattanDistance()
result = sol.compute((0, 0), 'R', 50, 1, 0)
assert result == (50, 0)
assert len(sol.seen_coords) == 50
sol = ManhattanDistance()
result = sol.compute((0, 0), 'U', 50, 1, 0)
assert result == (0, 50)
assert len(sol.seen_coords) == 50
result = sol.compute((0, 0), 'U', 50, 2, 0)
assert result == (0, 50)
assert len(sol.seen_coords) == 50
sol = ManhattanDistance()
sol.compute_distance([['R8', 'U5', 'L5', 'D3'],
['U7', 'R6', 'D4', 'L4']])
assert sol.distance == 6
sol = ManhattanDistance()
sol.compute_distance([['R98', 'U47', 'R26', 'D63', 'R33', 'U87', 'L62', 'D20', 'R33', 'U53', 'R51'],
['U98', 'R91', 'D20', 'R16', 'D67', 'R40', 'U7', 'R15', 'U6', 'R7']])
assert sol.distance == 135
sol = ManhattanDistance()
sol.compute_distance([['R75', 'D30', 'R83', 'U83', 'L12', 'D49', 'R71', 'U7', 'L72'],
['U62', 'R66', 'U55', 'R34', 'D71', 'R55', 'D58', 'R83']])
assert sol.distance == 159
sol = ManhattanDistance()
sol.compute_distance_file("input.txt")
steps = sol.get_least_steps()
assert sol.distance == 399
assert steps == 15678
<file_sep>from enum import Enum
from itertools import permutations
class IntcodeProgram:
EXTRA_MEMORY = 5000000
class Opcodes(Enum):
HALT = 99
ADD = 1
MUL = 2
SAVE = 3
READ = 4
JUMP_T = 5
JUMP_F = 6
LESS_THAN = 7
EQUAL = 8
RELATIVE = 9
class Modes(Enum):
POSITION = 0
IMMEDIATE = 1
RELATIVE = 2
def __init__(self, program):
self.instruction_pointer = 0
self.program = program.copy() + [0] * self.EXTRA_MEMORY
self.relative_base = 0
self.output_buffer = []
def get_instruction_set(self, instruction):
# depending on the instruction we will parse the digits in some fashion
instruction_set = []
opcode = instruction % 100
instruction_set.append(opcode)
instruction = int(instruction / 100)
if opcode == self.Opcodes.ADD.value or opcode == self.Opcodes.MUL.value:
# look for three params
for i in range(3):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
elif opcode == self.Opcodes.SAVE.value\
or opcode == self.Opcodes.READ.value\
or opcode == self.Opcodes.RELATIVE.value:
# look for 2 params
for i in range(1):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
elif opcode == self.Opcodes.JUMP_T.value or opcode == self.Opcodes.JUMP_F.value:
# look for 2 params
for i in range(2):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
elif opcode == self.Opcodes.EQUAL.value or opcode == self.Opcodes.LESS_THAN.value:
# look for 3 params
for i in range(3):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
return instruction_set
def add(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
summed_val = value_1 + value_2
self.write(param_3, mode_3, input_codes, summed_val)
def mul(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
product_val = value_1 * value_2
self.write(param_3, mode_3, input_codes, product_val)
def save(self, input_codes, input_signal, instruction_set, instruction_pointer):
[mode_1] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
self.write(param_1, mode_1, input_codes, int(input_signal))
def output(self, input_codes, instruction_set, instruction_pointer):
[mode_1] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
return self.read(param_1, mode_1, input_codes)
def jump_t(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
# set the instruction pointer to the value from the second param
if value_1 != 0:
return value_2
return None
def jump_f(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
# set the instruction pointer to the value from the second param
if value_1 == 0:
return value_2
return None
def less_than(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
if value_1 < value_2:
self.write(param_3, mode_3, input_codes, 1)
else:
self.write(param_3, mode_3, input_codes, 0)
def equal(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
if value_1 == value_2:
self.write(param_3, mode_3, input_codes, 1)
else:
self.write(param_3, mode_3, input_codes, 0)
def relative(self, input_codes, instruction_set, instruction_pointer):
[mode_1] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
self.relative_base += self.read(param_1, mode_1, input_codes)
def run(self, input_signal):
while True:
instruction = self.program[self.instruction_pointer]
instruction_set = self.get_instruction_set(instruction)
opcode = instruction_set[0]
if opcode == self.Opcodes.HALT.value:
return self.output_buffer
elif opcode == self.Opcodes.ADD.value:
self.add(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.MUL.value:
self.mul(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.SAVE.value:
if len(input_signal) == 0:
return "waiting"
self.save(self.program, input_signal[0], instruction_set, self.instruction_pointer)
self.instruction_pointer += 2
input_signal = input_signal[1:]
elif opcode == self.Opcodes.READ.value:
result = self.output(self.program, instruction_set, self.instruction_pointer)
self.output_buffer.append(result)
self.instruction_pointer += 2
elif opcode == self.Opcodes.JUMP_T.value:
new_pointer = self.jump_t(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer = new_pointer if new_pointer is not None else self.instruction_pointer + 3
elif opcode == self.Opcodes.JUMP_F.value:
new_pointer = self.jump_f(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer = new_pointer if new_pointer is not None else self.instruction_pointer + 3
elif opcode == self.Opcodes.LESS_THAN.value:
self.less_than(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.EQUAL.value:
self.equal(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.RELATIVE.value:
self.relative(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 2
else:
return "error"
def read(self, param, mode, input_codes):
if mode == self.Modes.IMMEDIATE.value:
return param
elif mode == self.Modes.POSITION.value:
return input_codes[param]
elif mode == self.Modes.RELATIVE.value:
return input_codes[self.relative_base + param]
def write(self, param, mode, input_codes, value):
if mode == self.Modes.IMMEDIATE.value:
input_codes[input_codes[param]] = value
elif mode == self.Modes.POSITION.value:
input_codes[param] = value
elif mode == self.Modes.RELATIVE.value:
input_codes[self.relative_base + param] = value
def run_intcode_max_signal(phase_settings, file_input):
'''
To do this, before running the program,
replace position 1 with the value 12 and
replace position 2 with the value 2.
What value is left at position 0 after the program halts?
'''
with open(file_input) as data:
for line in data:
# list comprehension to turn all strings in list to ints
input_values = [int(str_num) for str_num in line.split(',')]
return run_max_signal(phase_settings, input_values)
def create_amplifiers(phase_setting, program):
amplifiers = []
for phase in phase_setting:
amp = IntcodeProgram(program)
amp.run([phase])
amplifiers.append(amp)
return amplifiers
def run_max_signal(phase_settings, program):
permuted_phases = permutations(phase_settings)
max_signal = 0
for phases in permuted_phases:
amplifiers = create_amplifiers(phases, program)
input_signal = 0
for amp in amplifiers:
input_signal = amp.run([input_signal])
if input_signal > max_signal:
max_signal = input_signal
return max_signal
def run_intcode_max_signal_feedback(phase_settings, file_input):
'''
To do this, before running the program,
replace position 1 with the value 12 and
replace position 2 with the value 2.
What value is left at position 0 after the program halts?
'''
with open(file_input) as data:
for line in data:
# list comprehension to turn all strings in list to ints
input_values = [int(str_num) for str_num in line.split(',')]
return run_max_signal_feedback(phase_settings, input_values)
def run_through_amplifiers(amplifiers, input_signal):
for amp in amplifiers:
input_signal = amp.run([input_signal])
return input_signal
def run_max_signal_feedback(phase_settings, program):
permuted_phases = permutations(phase_settings)
max_signal = 0
for phases in permuted_phases:
amplifiers = create_amplifiers(phases, program)
input_signal = 0
while True:
new_output = run_through_amplifiers(amplifiers, input_signal)
if new_output is "terminated":
break
input_signal = new_output
if input_signal > max_signal:
max_signal = input_signal
return max_signal
def run_intcode_boost(file_input, input):
with open(file_input) as data:
for line in data:
# list comprehension to turn all strings in list to ints
input_values = [int(str_num) for str_num in line.split(',')]
sol = IntcodeProgram(input_values)
return sol.run([input])
if __name__ == "__main__":
# program = [3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8]
# sol = IntcodeProgram(program)
# result = sol.run([8])
# assert result == 1
# sol = IntcodeProgram(program)
# result = sol.run([9])
# assert result == 0
# sol = IntcodeProgram(program)
# result = sol.run([7])
# assert result == 0
#
# program = [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]
# sol = IntcodeProgram(program)
# result = sol.run([7])
# assert result == 1
# sol = IntcodeProgram(program)
# result = sol.run([8])
# assert result == 0
# sol = IntcodeProgram(program)
# result = sol.run([9])
# assert result == 0
#
# program = [3, 3, 1108, -1, 8, 3, 4, 3, 99]
# sol = IntcodeProgram(program)
# result = sol.run([7])
# assert result == 0
# sol = IntcodeProgram(program)
# result = sol.run([8])
# assert result == 1
# sol = IntcodeProgram(program)
# result = sol.run([9])
# assert result == 0
#
# program = [3, 3, 1107, -1, 8, 3, 4, 3, 99]
# sol = IntcodeProgram(program)
# result = sol.run([7])
# assert result == 1
# sol = IntcodeProgram(program)
# result = sol.run([8])
# assert result == 0
# sol = IntcodeProgram(program)
# result = sol.run([9])
# assert result == 0
#
# program = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9]
# sol = IntcodeProgram(program)
# result = sol.run([0])
# assert result == 0
# sol = IntcodeProgram(program)
# result = sol.run([1])
# assert result == 1
#
# program = [3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1]
# sol = IntcodeProgram(program)
# result = sol.run([0])
# assert result == 0
# sol = IntcodeProgram(program)
# result = sol.run([1])
# assert result == 1
#
# program = [3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31,
# 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104,
# 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]
# sol = IntcodeProgram(program)
# result = sol.run([7])
# assert result == 999
# sol = IntcodeProgram(program)
# result = sol.run([8])
# assert result == 1000
# sol = IntcodeProgram(program)
# result = sol.run([9])
# assert result == 1001
#
# # ===============================
#
# program = [3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0]
# sol = IntcodeProgram(program)
# result = sol.run([4, 0])
# sol = IntcodeProgram(program)
# result = sol.run([3, result])
# sol = IntcodeProgram(program)
# result = sol.run([2, result])
# sol = IntcodeProgram(program)
# result = sol.run([1, result])
# sol = IntcodeProgram(program)
# result = sol.run([0, result])
# assert result == 43210
#
# program = [3, 31, 3, 32, 1002, 32, 10, 32, 1001, 31, -2, 31, 1007, 31, 0, 33,
# 1002, 33, 7, 33, 1, 33, 31, 31, 1, 32, 31, 31, 4, 31, 99, 0, 0, 0]
# sol = IntcodeProgram(program)
# result = sol.run([1, 0])
# sol = IntcodeProgram(program)
# result = sol.run([0, result])
# sol = IntcodeProgram(program)
# result = sol.run([4, result])
# sol = IntcodeProgram(program)
# result = sol.run([3, result])
# sol = IntcodeProgram(program)
# result = sol.run([2, result])
# assert result == 65210
#
# program = [3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23,
# 101, 5, 23, 23, 1, 24, 23, 23, 4, 23, 99, 0, 0]
# sol = IntcodeProgram(program)
# result = sol.run([0, 0])
# sol = IntcodeProgram(program)
# result = sol.run([1, result])
# sol = IntcodeProgram(program)
# result = sol.run([2, result])
# sol = IntcodeProgram(program)
# result = sol.run([3, result])
# sol = IntcodeProgram(program)
# result = sol.run([4, result])
# assert result == 54321
#
# program = [3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0]
# signal = run_max_signal([0, 1, 2, 3, 4], program)
# print(signal)
# assert signal == 43210
#
# program = [3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23,
# 101, 5, 23, 23, 1, 24, 23, 23, 4, 23, 99, 0, 0]
# signal = run_max_signal([0, 1, 2, 3, 4], program)
# print(signal)
# assert signal == 54321
#
# program = [3, 31, 3, 32, 1002, 32, 10, 32, 1001, 31, -2, 31, 1007, 31, 0, 33,
# 1002, 33, 7, 33, 1, 33, 31, 31, 1, 32, 31, 31, 4, 31, 99, 0, 0, 0]
# signal = run_max_signal([0, 1, 2, 3, 4], program)
# print(signal)
# assert signal == 65210
#
# signal = run_intcode_max_signal([0, 1, 2, 3, 4], "input_old.txt")
# assert signal == 17406
# print(signal)
#
# # ===============================
#
# program = [3, 26, 1001, 26, -4, 26, 3, 27, 1002, 27, 2, 27, 1, 27, 26,
# 27, 4, 27, 1001, 28, -1, 28, 1005, 28, 6, 99, 0, 0, 5]
# signal = run_max_signal_feedback([5, 6, 7, 8, 9], program)
# assert signal == 139629729
# print(signal)
#
# program = [3, 52, 1001, 52, -5, 52, 3, 53, 1, 52, 56, 54, 1007, 54, 5, 55, 1005, 55, 26, 1001, 54,
# -5, 54, 1105, 1, 12, 1, 53, 54, 53, 1008, 54, 0, 55, 1001, 55, 1, 55, 2, 53, 55, 53, 4,
# 53, 1001, 56, -1, 56, 1005, 56, 6, 99, 0, 0, 0, 0, 10]
# signal = run_max_signal_feedback([5, 6, 7, 8, 9], program)
# assert signal == 18216
# print(signal)
#
# signal = run_intcode_max_signal_feedback([5, 6, 7, 8, 9], "input_old.txt")
# assert signal == 1047153
# print(signal)
#
# # ===============================
# # if debugged then the value at address 1985 would be read
# program = [109, 2000, 109, 19, 204, -34]
# sol = IntcodeProgram(program)
# output = sol.run(None)
# assert output is "error"
#
# program = [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]
# sol = IntcodeProgram(program)
# output = sol.run(None)
# assert output == [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]
#
# program = [1102, 34915192, 34915192, 7, 4, 7, 99, 0]
# sol = IntcodeProgram(program)
# output = sol.run(None)
# print(output[0])
# assert len(str(output[0])) == 16
#
# program = [104, 1125899906842624, 99]
# sol = IntcodeProgram(program)
# output = sol.run(None)
# assert output[0] == program[1]
boost_keycode = run_intcode_boost("input.txt", 1)
assert boost_keycode[0] == 2752191671
boost_keycode = run_intcode_boost("input.txt", 2)
assert boost_keycode[0] == 87571
<file_sep>Pillow==6.2.1
numpy==1.18.4
<file_sep>import math
from operator import itemgetter
class MonitoringStation:
def __init__(self, grid):
self.grid = grid
self.max_x = len(grid[0]) - 1
self.max_y = len(grid) - 1
self.asteroids = {}
self.locate_asteroids()
def locate_asteroids(self):
for y in range(len(self.grid)):
for x in range(len(self.grid[0])):
if self.grid[y][x] is not '#':
continue
# slope will be added to set if there is 1 asteroid on it
self.asteroids[(x, y)] = set()
def identify_visibility(self):
for asteroid_start in self.asteroids:
for asteroid_end in self.asteroids:
if asteroid_start is asteroid_end:
continue
rise = asteroid_start[1] - asteroid_end[1]
run = asteroid_start[0] - asteroid_end[0]
if run != 0:
slope = rise / run
rad_angle = math.atan(slope)
if run > 0 and rise > 0:
# quadrant 1
self.asteroids[asteroid_start].add(math.degrees(rad_angle))
elif run < 0 and rise > 0:
# quadrant 2
self.asteroids[asteroid_start].add(math.degrees(rad_angle + math.pi))
elif run < 0 and rise < 0:
# quadrant 3
self.asteroids[asteroid_start].add(math.degrees(rad_angle + 2 * math.pi))
elif run > 0 and rise < 0:
# quadrant 4
self.asteroids[asteroid_start].add(math.degrees(rad_angle + 3 * math.pi))
elif str(rad_angle) == "0.0":
# pointing directly to right
self.asteroids[asteroid_start].add(math.degrees(0.0))
elif str(rad_angle) == "-0.0":
# pointing directly to left
self.asteroids[asteroid_start].add(math.degrees(math.pi))
else:
if rise > 0:
# pointing directly up
self.asteroids[asteroid_start].add(math.degrees(math.pi / 2))
else:
# pointing directly down
self.asteroids[asteroid_start].add(math.degrees(-math.pi / 2))
max_key = None
for key, value in self.asteroids.items():
if max_key is None:
max_key = key
if len(value) > len(self.asteroids[max_key]):
max_key = key
return max_key, len(self.asteroids[max_key])
def distance_between(self, coord_1, coord_2):
y_delta = (coord_2[1] - coord_1[1])
y_product = math.pow(y_delta, 2)
x_delta = (coord_2[0] - coord_1[0])
x_product = math.pow(x_delta, 2)
y_x_sum = y_product + x_product
return math.pow(y_x_sum, 0.5)
def save_distance_from_pivot(self, angle_set, angle, pivot, asteroid):
if angle not in angle_set:
angle_set[angle] = []
distance = self.distance_between(pivot, asteroid)
angle_set[angle].append((asteroid, distance))
def setup_key_idx(self, angle_set):
key_idx = {}
for key in angle_set.keys():
key_idx[key] = 0
return key_idx
def sort_angle_set_by_distance(self, angle_set):
for key in angle_set:
new_list = sorted(angle_set[key], key=itemgetter(1))
angle_set[key] = new_list
def sort_angle_set_keys(self, angle_set):
angle_list = list(angle_set.items())
sorted_angle_list = sorted(angle_list, key=itemgetter(0))
return sorted_angle_list
def handle_negative_angles(self, angle_set):
new_angle_set = {}
for key in angle_set.keys():
if key < 0.0:
new_key = 360 + key
new_angle_set[new_key] = angle_set[key]
else:
new_angle_set[key] = angle_set[key]
return new_angle_set
def vaporize(self, pivot):
angle_set = {}
for asteroid in self.asteroids:
if pivot == asteroid:
continue
rise = pivot[1] - asteroid[1]
run = pivot[0] - asteroid[0]
if run != 0:
slope = rise / run
rad_angle = math.atan(slope)
# The distance of the coordinate is saved with the coordinate
# the radian angle - math.pi / 2 due to directly up being the starting coordinates
if run > 0 and rise > 0:
# quadrant 1
key = (math.degrees(rad_angle - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
elif run < 0 and rise > 0:
# quadrant 2
key = (math.degrees(rad_angle + math.pi - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
elif run < 0 and rise < 0:
# quadrant 3
key = (math.degrees(rad_angle + math.pi - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
elif run > 0 and rise < 0:
# quadrant 4
key = (math.degrees(rad_angle + 2 * math.pi - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
elif str(rad_angle) == "0.0":
# pointing directly to right
key = (math.degrees(0.0 - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
elif str(rad_angle) == "-0.0":
# pointing directly to right
key = (math.degrees(math.pi - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
else:
if rise > 0:
# pointing directly up
key = (math.degrees(math.pi / 2 - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
else:
# pointing directly down
key = (math.degrees(math.pi/2 * 3 - math.pi / 2))
self.save_distance_from_pivot(angle_set, key, pivot, asteroid)
self.sort_angle_set_by_distance(angle_set)
angle_set = self.handle_negative_angles(angle_set)
sorted_angle_list = self.sort_angle_set_keys(angle_set)
key_idx = self.setup_key_idx(angle_set)
rotation = 0
# identify order of output
output_list = []
while len(sorted_angle_list) > 0:
current_pairing = sorted_angle_list[rotation]
# print(current_pairing)
key = current_pairing[0]
key_list = current_pairing[1]
current_key_idx = key_idx[key]
output_list.append(key_list[current_key_idx][0])
# print(key_list[current_key_idx])
key_idx[key] += 1
# if idx key is greater than list at that angle then remove it
if key_idx[key] >= len(key_list):
sorted_angle_list.remove(current_pairing)
# we can't continue if we've reached the end
if len(sorted_angle_list) == 0:
break
# because the list shrinks we don't move the idx
rotation %= len(sorted_angle_list)
continue
# i only moves forward if the list doesn't change size
rotation += 1
rotation %= len(sorted_angle_list)
return output_list
def tests():
grid = [
'#.',
'.#',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((0, 0), 1)
grid = [
'.#',
'#.',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((1, 0), 1)
grid = [
'.#',
'..',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((1, 0), 0)
grid = [
'.#',
'.#',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((1, 0), 1)
grid = [
'#.',
'#.',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((0, 0), 1)
grid = [
'#.',
'#.',
'#.',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((0, 1), 2)
grid = [
'#.',
'#.',
'#.',
'#.',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((0, 1), 2)
grid = [
'.#..#',
'.....',
'..#..',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((1, 0), 2)
grid = [
'#.#',
'.#.',
'#..',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((0, 0), 3)
grid = [
'#.#',
'.#.',
'#.#',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((1, 1), 4)
grid = [
'####',
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((1, 0), 2)
grid = [
'.#..#',
'.....',
'#####',
'....#',
'...##'
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((3, 4), 8)
grid = [
'......#.#.',
'#..#.#....',
'..#######.',
'.#.#.###..',
'.#..#.....',
'..#....#.#',
'#..#....#.',
'.##.#..###',
'##...#..#.',
'.#....####'
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((5, 8), 33)
grid = [
'#.#...#.#.',
'.###....#.',
'.#....#...',
'##.#.#.#.#',
'....#.#.#.',
'.##..###.#',
'..#...##..',
'..##....##',
'......#...',
'.####.###.'
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((1, 2), 35)
grid = [
'.#..#..###',
'####.###.#',
'....###.#.',
'..###.##.#',
'##.##.#.#.',
'....###..#',
'..#.#..#.#',
'#..#.#.###',
'.##...##.#',
'.....#.#..'
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((6, 3), 41)
grid = [
'.#..##.###...#######',
'##.############..##.',
'.#.######.########.#',
'.###.#######.####.#.',
'#####.##.#.##.###.##',
'..#####..#.#########',
'####################',
'#.####....###.#.#.##',
'##.#################',
'#####.##.###..####..',
'..######..##.#######',
'####.##.####...##..#',
'.#####..#.######.###',
'##...#.##########...',
'#.##########.#######',
'.####.#.###.###.#.##',
'....##.##.###..#####',
'.#.#.###########.###',
'#.#.#.#####.####.###',
'###.##.####.##.#..##'
]
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((11, 13), 210)
grid = []
with open("input.txt") as data:
for line in data:
grid.append(line.rstrip())
sol = MonitoringStation(grid)
best_asteroid = sol.identify_visibility()
assert best_asteroid == ((13, 17), 269)
result = sol.distance_between((-2, 1), (1, 5))
assert result == 5.0
result = sol.distance_between((-2, -3), (-4, 4))
result = round(result, 2)
assert result == 7.28
if __name__ == "__main__":
# tests()
grid = [
'#...#',
'.#.#.',
'..#..',
'.#.#.',
'#...#',
]
sol = MonitoringStation(grid)
result = sol.vaporize((2, 2))
print(result)
assert result == [(3, 1), (3, 3), (1, 3), (1, 1), (4, 0), (4, 4), (0, 4), (0, 0)]
grid = [
'###',
'###',
'###',
]
sol = MonitoringStation(grid)
result = sol.vaporize((1, 1))
print(result)
assert result == [(1, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2), (0, 1), (0, 0)]
grid = [
'#..',
'..#',
'#..',
]
sol = MonitoringStation(grid)
result = sol.vaporize((2, 1))
print(result)
assert result == [(0, 2), (0, 0)]
grid = [
'.#..##.###...#######',
'##.############..##.',
'.#.######.########.#',
'.###.#######.####.#.',
'#####.##.#.##.###.##',
'..#####..#.#########',
'####################',
'#.####....###.#.#.##',
'##.#################',
'#####.##.###..####..',
'..######..##.#######',
'####.##.####...##..#',
'.#####..#.######.###',
'##...#.##########...',
'#.##########.#######',
'.####.#.###.###.#.##',
'....##.##.###..#####',
'.#.#.###########.###',
'#.#.#.#####.####.###',
'###.##.####.##.#..##'
]
sol = MonitoringStation(grid)
result = sol.vaporize((11, 13))
# print(result)
answers = {
1: (11, 12),
2: (12, 1),
3: (12, 2),
10: (12, 8),
20: (16, 0),
50: (16, 9),
100: (10, 16),
199: (9, 6),
200: (8, 2),
201: (10, 9),
299: (11, 1)
}
for key in answers.keys():
assert result[key - 1] == answers[key]
# ===========================================
grid = []
with open("input.txt") as data:
for line in data:
grid.append(line.rstrip())
sol = MonitoringStation(grid)
result = sol.vaporize((13, 17))
element = result[200 - 1]
assert element[0] * 100 + element[1] == 612
<file_sep>
def check_increasing(num_str):
valid = True
min_str = num_str[0]
for i in range(1, len(num_str)):
# if encountering a num that is less than the seen min then stop
if int(num_str[i]) < int(min_str):
valid = False
break
min_str = num_str[i]
return valid
def check_duplicates(num_str):
duplicates = False
for i in range(0, len(num_str) - 1):
if num_str[i] == num_str[i + 1]:
duplicates = True
break
return duplicates
def check_duplicates_freq(num_str):
num_freq = {}
for i in range(0, len(num_str)):
if num_str[i] not in num_freq:
num_freq[num_str[i]] = 1
else:
num_freq[num_str[i]] += 1
for num in num_freq.values():
# skip if freq is 1
if num == 1:
continue
# # skip if freq is even, meaning it's not of 2 pair
# if num % 2 == 0:
# return True
if num == 2:
return True
return False
if __name__ == "__main__":
valid_count = 0
for num in range(156218, 652527):
num_str = str(num)
if not check_increasing(num_str):
continue
if not check_duplicates(num_str):
continue
# We made it here so the number must be valid
valid_count += 1
# Check the answer
print(valid_count)
assert valid_count == 1694
# Part 2 ================
result = check_duplicates_freq("156666")
assert result == False
result = check_duplicates_freq("123444")
assert result == False
result = check_duplicates_freq("111122")
assert result == True
reult = check_duplicates_freq("112233")
assert result == True
result = check_duplicates_freq("122244")
assert result == True
valid_count = 0
for num in range(156218, 652527):
num_str = str(num)
if not check_increasing(num_str):
continue
if not check_duplicates(num_str):
continue
if not check_duplicates_freq(num_str):
continue
# We made it here so the number must be valid
valid_count += 1
# Check the answer
print(valid_count)
assert valid_count == 1148
<file_sep>class IntcodeProgram:
def run_intcode(self, file_input):
'''
To do this, before running the program,
replace position 1 with the value 12 and
replace position 2 with the value 2.
What value is left at position 0 after the program halts?
'''
with open(file_input) as data:
for line in data:
# list comprehension to turn all strings in list to ints
input_values = [int(str_num) for str_num in line.split(',')]
input_values[1] = 12
input_values[2] = 2
result = self.run(input_values)
return result
def run(self, input):
# every 4 digits is an opcode
for i in range(0, len(input), 4):
opcode = input[i]
if opcode == 99:
break
elif opcode == 1:
# add
n1_idx = input[i + 1]
n2_idx = input[i + 2]
summed_val = input[n1_idx] + input[n2_idx]
save_idx = input[i + 3]
input[save_idx] = summed_val
elif opcode == 2:
# multiply
n1_idx = input[i + 1]
n2_idx = input[i + 2]
product_val = input[n1_idx] * input[n2_idx]
save_idx = input[i + 3]
input[save_idx] = product_val
else:
break
return input
def compute_noun_verb(self, file_input):
'''
To do this, before running the program,
replace position 1 with the value 12 and
replace position 2 with the value 2.
What value is left at position 0 after the program halts?
'''
with open(file_input) as data:
for line in data:
input_values_initial = [int(str_num) for str_num in line.split(',')]
for noun in range(99):
for verb in range(99):
input_values = input_values_initial.copy()
input_values[1] = noun
input_values[2] = verb
result = self.run(input_values)
if result[0] == 19690720:
return 100 * noun + verb
return 0
if __name__ == "__main__":
sol = IntcodeProgram()
input_list = [1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]
result = sol.run(input_list)
assert result == [3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50]
input_list = [1, 0, 0, 0, 99]
result = sol.run(input_list)
assert result == [2, 0, 0, 0, 99]
input_list = [2, 3, 0, 3, 99]
result = sol.run(input_list)
assert result == [2, 3, 0, 6, 99]
input_list = [2, 4, 4, 5, 99, 0]
result = sol.run(input_list)
assert result == [2, 4, 4, 5, 99, 9801]
input_list = [1, 1, 1, 4, 99, 5, 6, 0, 99]
result = sol.run(input_list)
assert result == [30, 1, 1, 4, 2, 5, 6, 0, 99]
result = sol.run_intcode("input.txt")
assert result == [4714701, 12, 2, 2, 1, 1, 2, 3, 1, 3, 4, 3, 1, 5, 0, 3, 2, 13, 1, 60, 1, 5, 19, 61, 2, 10, 23, 244, 1, 27, 5, 245, 2, 9, 31, 735, 1, 35, 5, 736, 2, 6, 39, 1472, 1, 43, 5, 1473, 2, 47, 10, 5892, 2, 51, 6, 11784, 1, 5, 55, 11785, 2, 10, 59, 47140, 1, 63, 6, 47142, 2, 67, 6, 94284, 1, 71, 5, 94285, 1, 13, 75, 94290, 1, 6, 79, 94292, 2, 83, 13, 471460, 1, 87, 6, 471462, 1, 10, 91, 471466, 1, 95, 9, 471469, 2, 99, 13, 2357345, 1, 103, 6, 2357347, 2, 107, 6, 4714694, 1, 111, 2, 4714696, 1, 115, 13, 0, 99, 2, 0, 14, 0]
assert result[0] == 4714701
print(result[0])
result = sol.compute_noun_verb("input.txt")
print(result)
<file_sep>from enum import Enum
import math
class IntcodeProgram:
EXTRA_MEMORY = 5000000
class Opcodes(Enum):
HALT = 99
ADD = 1
MUL = 2
SAVE = 3
READ = 4
JUMP_T = 5
JUMP_F = 6
LESS_THAN = 7
EQUAL = 8
RELATIVE = 9
class Modes(Enum):
POSITION = 0
IMMEDIATE = 1
RELATIVE = 2
def __init__(self, program):
self.instruction_pointer = 0
self.program = program.copy() + [0] * self.EXTRA_MEMORY
self.relative_base = 0
self.output_buffer = []
def get_instruction_set(self, instruction):
# depending on the instruction we will parse the digits in some fashion
instruction_set = []
opcode = instruction % 100
instruction_set.append(opcode)
instruction = int(instruction / 100)
if opcode == self.Opcodes.ADD.value or opcode == self.Opcodes.MUL.value:
# look for three params
for i in range(3):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
elif opcode == self.Opcodes.SAVE.value\
or opcode == self.Opcodes.READ.value\
or opcode == self.Opcodes.RELATIVE.value:
# look for 2 params
for i in range(1):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
elif opcode == self.Opcodes.JUMP_T.value or opcode == self.Opcodes.JUMP_F.value:
# look for 2 params
for i in range(2):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
elif opcode == self.Opcodes.EQUAL.value or opcode == self.Opcodes.LESS_THAN.value:
# look for 3 params
for i in range(3):
mode = instruction % 10
instruction = int(instruction / 10)
instruction_set.append(mode)
return instruction_set
def add(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
summed_val = value_1 + value_2
self.write(param_3, mode_3, input_codes, summed_val)
def mul(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
product_val = value_1 * value_2
self.write(param_3, mode_3, input_codes, product_val)
def save(self, input_codes, input_signal, instruction_set, instruction_pointer):
[mode_1] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
self.write(param_1, mode_1, input_codes, int(input_signal))
def output(self, input_codes, instruction_set, instruction_pointer):
[mode_1] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
return self.read(param_1, mode_1, input_codes)
def jump_t(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
# set the instruction pointer to the value from the second param
if value_1 != 0:
return value_2
return None
def jump_f(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
# set the instruction pointer to the value from the second param
if value_1 == 0:
return value_2
return None
def less_than(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
if value_1 < value_2:
self.write(param_3, mode_3, input_codes, 1)
else:
self.write(param_3, mode_3, input_codes, 0)
def equal(self, input_codes, instruction_set, instruction_pointer):
[mode_1, mode_2, mode_3] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
param_2 = input_codes[instruction_pointer + 2]
param_3 = input_codes[instruction_pointer + 3]
value_1 = self.read(param_1, mode_1, input_codes)
value_2 = self.read(param_2, mode_2, input_codes)
if value_1 == value_2:
self.write(param_3, mode_3, input_codes, 1)
else:
self.write(param_3, mode_3, input_codes, 0)
def relative(self, input_codes, instruction_set, instruction_pointer):
[mode_1] = instruction_set[1:]
param_1 = input_codes[instruction_pointer + 1]
self.relative_base += self.read(param_1, mode_1, input_codes)
def run(self, input_signal):
while True:
instruction = self.program[self.instruction_pointer]
instruction_set = self.get_instruction_set(instruction)
opcode = instruction_set[0]
if opcode == self.Opcodes.HALT.value:
return self.output_buffer
elif opcode == self.Opcodes.ADD.value:
self.add(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.MUL.value:
self.mul(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.SAVE.value:
if len(input_signal) == 0:
return "waiting"
self.save(self.program, input_signal[0], instruction_set, self.instruction_pointer)
self.instruction_pointer += 2
input_signal = input_signal[1:]
elif opcode == self.Opcodes.READ.value:
result = self.output(self.program, instruction_set, self.instruction_pointer)
self.output_buffer.append(result)
self.instruction_pointer += 2
elif opcode == self.Opcodes.JUMP_T.value:
new_pointer = self.jump_t(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer = new_pointer if new_pointer is not None else self.instruction_pointer + 3
elif opcode == self.Opcodes.JUMP_F.value:
new_pointer = self.jump_f(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer = new_pointer if new_pointer is not None else self.instruction_pointer + 3
elif opcode == self.Opcodes.LESS_THAN.value:
self.less_than(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.EQUAL.value:
self.equal(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 4
elif opcode == self.Opcodes.RELATIVE.value:
self.relative(self.program, instruction_set, self.instruction_pointer)
self.instruction_pointer += 2
else:
return "error"
def read(self, param, mode, input_codes):
if mode == self.Modes.IMMEDIATE.value:
return param
elif mode == self.Modes.POSITION.value:
return input_codes[param]
elif mode == self.Modes.RELATIVE.value:
return input_codes[self.relative_base + param]
def write(self, param, mode, input_codes, value):
if mode == self.Modes.IMMEDIATE.value:
input_codes[input_codes[param]] = value
elif mode == self.Modes.POSITION.value:
input_codes[param] = value
elif mode == self.Modes.RELATIVE.value:
input_codes[self.relative_base + param] = value
class RobotCamera:
def __init__(self, program_input, starting_color):
self.camera = IntcodeProgram(program_input)
self.current_coordinate = (0, 0)
self.direction = (math.pi / 2) # always start facing up
self.coordinates_seen = {}
self.starting_color = starting_color
def update_direction(self, direction):
# go left
if direction == 0:
self.direction = self.direction + (math.pi / 2)
if self.direction >= (2 * math.pi):
self.direction %= (2 * math.pi)
# go right
elif direction == 1:
self.direction = self.direction - (math.pi / 2)
while self.direction < 0.0:
self.direction += (2 * math.pi)
else:
print("direction error")
def move_to_cell(self):
# facing right
if self.direction == 0:
self.current_coordinate = (self.current_coordinate[0] + 1, self.current_coordinate[1])
# facing up
elif self.direction == (math.pi / 2):
self.current_coordinate = (self.current_coordinate[0], self.current_coordinate[1] + 1)
# facing left
elif self.direction == math.pi:
self.current_coordinate = (self.current_coordinate[0] - 1, self.current_coordinate[1])
# facing down
elif self.direction == 3 * (math.pi / 2):
self.current_coordinate = (self.current_coordinate[0], self.current_coordinate[1] - 1)
def paint(self):
# program runs until termination on an internal condition
while True:
# if not the first time at this cell then retrieve the last color it was painted
if len(self.coordinates_seen) == 0:
current_color = self.starting_color
elif self.current_coordinate in self.coordinates_seen:
current_color = self.coordinates_seen[self.current_coordinate]
else:
# all colors start black
current_color = 0
# retrieve output data
self.camera.run([current_color])
if len(self.camera.output_buffer) == 0:
break
new_color = self.camera.output_buffer[0]
new_direction = self.camera.output_buffer[1]
# clear output buffer
self.camera.output_buffer = []
# mark the color for a cell
self.coordinates_seen[self.current_coordinate] = new_color
self.update_direction(new_direction)
self.move_to_cell()
def normalize_coordinate_colorings(coordinates):
min_x = None
min_y = None
for coordinate in coordinates.keys():
if min_x is None and min_y is None:
min_x = coordinate[0]
min_y = coordinate[1]
else:
min_x = min(min_x, coordinate[0])
min_y = min(min_y, coordinate[1])
delta_x = abs(min_x)
delta_y = abs(min_y)
normalized = {}
for coord, color in coordinates.items():
new_coord = (coord[0] + delta_x, coord[1] + delta_y)
normalized[new_coord] = color
return normalized
def get_max_region(coordinates):
max_x = None
max_y = None
for coord in coordinates.keys():
if max_x is None and max_y is None:
max_x = coord[0]
max_y = coord[1]
else:
max_x = max(max_x, coord[0])
max_y = max(max_y, coord[1])
return (max_x, max_y)
def print_area(area):
for row in area:
print(' '.join(row))
def generate_painted_output(coordinate_colorings):
(max_x, max_y) = get_max_region(coordinate_colorings)
# add 1 because these are just maxes of coordinates, we need to ensure we accommodate for idx out of bounds
area = [[' ' for i in range(max_x + 1)] for j in range(max_y + 1)]
for coord, color in coordinate_colorings.items():
y = coord[1]
x = coord[0]
if color == 0:
continue
area[y][x] = "#"
return area
def flip_image(area):
# only look at half of y
for y in range(int(len(area) / 2)):
for x in range(len(area[0])):
temp = area[y][x]
# -1 to prevent index out of bounds
area[y][x] = area[len(area) - 1 - y][x]
area[len(area) - 1 - y][x] = temp
if __name__ == "__main__":
with open("input.txt") as data:
for line in data:
# list comprehension to turn all strings in list to ints
input_values = [int(str_num) for str_num in line.split(',')]
robot = RobotCamera(input_values, 0)
robot.paint()
assert len(robot.coordinates_seen) == 1934
robot = RobotCamera(input_values, 1)
robot.paint()
normalized_colorings = normalize_coordinate_colorings(robot.coordinates_seen)
area = generate_painted_output(normalized_colorings)
# print_area(area)
flip_image(area)
print_area(area)
<file_sep>from PIL import Image
def parseImageFile(file_input, x, y):
with open(file_input) as data:
for line in data:
return parseImage(line, x, y)
def parseImage(data_content, x, y):
image_layers = []
while len(data_content) > 0:
image = []
for i in range(y):
data = data_content[:x]
data_content = data_content[x:]
image.append(data)
image_layers.append(image)
return image_layers
def getNumFreq(image):
num_freq = {}
for row in image:
for pixel in range(len(row)):
if row[pixel] not in num_freq:
num_freq[row[pixel]] = 0
num_freq[row[pixel]] += 1
return num_freq
def getSmallestZeroFreq(images):
best_freq = None
for image in images:
freq = getNumFreq(image)
if best_freq is None:
best_freq = freq
elif freq['0'] < best_freq['0']:
best_freq = freq
return best_freq
def decodeImages(image_layers):
final_image = []
row_size = len(image_layers[0])
col_size = len(image_layers[0][0])
for row in range(row_size):
for col in range(col_size):
# best pixel initially is transparent
best_pixel = '2'
for layer in image_layers:
if int(best_pixel) < int('2'):
# if best_pixel has been set then we've found the top pixel
break
elif int(layer[row][col]) < int(best_pixel):
best_pixel = layer[row][col]
# add the best pixel
final_image.append(best_pixel)
return final_image
if __name__ == "__main__":
#Part 1
output = parseImage("123456789012", 3, 2)
image1_freq = getNumFreq(output[0])
image2_freq = getNumFreq(output[1])
assert image1_freq == {'1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1}
assert image2_freq == {'7': 1, '8': 1, '9': 1, '0': 1, '1': 1, '2': 1}
output = parseImage("113416700012", 3, 2)
image1_freq = getNumFreq(output[0])
image2_freq = getNumFreq(output[1])
assert image1_freq == {'1': 3, '3': 1, '4': 1, '6': 1}
assert image2_freq == {'7': 1, '0': 3, '1': 1, '2': 1}
output = parseImageFile("input.txt", 25, 6)
freq = getSmallestZeroFreq(output)
assert freq == {'1': 15, '2': 130, '0': 5}
product = freq['1'] * freq['2']
assert product == 1950
#Part 2
# image rules
# 0 is black
# 1 is white
# 2 is transparent
# ordering of image has precedence
# 0 + 1 + 2 = 0
# 2 + 2 + 0 + 1 = 0
# 0 + 1 + 2 + 0 = 0
# 2 + 1 + 2 + 0 = 1
# 2 + 2 + 1 + 0 = 1
# 2 + 2 + 2 + 0 = 0
# seems the rule is to find the first instance of a 0 or 1 when going down layers
image_layers = parseImage("0222112222120000", 2, 2)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '0110'
image_layers = parseImage("012", 1, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '0'
image_layers = parseImage("2201", 1, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '0'
image_layers = parseImage("0120", 1, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '0'
image_layers = parseImage("2120", 1, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '1'
image_layers = parseImage("2210", 1, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '1'
image_layers = parseImage("2220", 1, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '0'
image_layers = parseImage("222210", 3, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '210'
image_layers = parseImage("222210201", 3, 1)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '210'
image_layers = parseImageFile("input.txt", 25, 6)
decoded_image = decodeImages(image_layers)
final_image = ''.join(decoded_image)
assert final_image == '111101001001100100101000010000101001001010010100001110011000100101111010000100001010011110100101000010000101001001010010100001000010010100101001011110'
# use an image library
cmap = {'0': (255, 255, 255),
'1': (0, 0, 0)}
data = [cmap[letter] for letter in final_image]
img = Image.new('RGB', (25, len(final_image) // 6), "white")
img.putdata(data)
img.show()
# display the final image on the screen
# the bits are not the answer
final_image = final_image.replace('0', ' ')
final_image = final_image.replace('1', '#')
size = len(final_image)
for row in range(0, size, 25):
print(' '.join(final_image[row:row + 25]))
<file_sep>import numpy
class NBodyProblem:
def __init__(self, file_input):
self.planet_dict = dict() # maps coordinate to velocity
with open(file_input) as data:
for line in data:
line = line.rstrip()
line = line[1:-1]
# this line extracts the x, y, z values into a list
coordiantes = [int(comp.strip()[2:]) for comp in line.split(",")]
self.planet_dict[tuple(coordiantes)] = [0, 0, 0]
# self.printState(self.planet_dict)
def printState(self, plant_state):
# print starting info
for key, value in plant_state.items():
print(f'{key} : {value}')
print()
def runSimulation(self, steps):
# compute velocities
current_step = 0
while current_step < steps:
planet_dict = self.planet_dict.copy()
for coord in planet_dict.keys():
for other_coord in planet_dict.keys():
# skip over coordinates that are the same
if other_coord is coord:
continue
# generate velocity for the the coordinate to update
velocity = planet_dict[coord]
deltas = self._compute_velocity_vals(coord, other_coord)
new_velocity = []
for (v1, v2) in zip(velocity, deltas):
new_velocity.append(v1 + v2)
planet_dict[coord] = new_velocity
# update the coordinates with the generated velocity
new_planet_dict = dict()
for coord, velocity in planet_dict.items():
new_coord = []
for (item1, item2) in zip(coord, velocity):
new_coord.append(item1 + item2)
new_planet_dict[tuple(new_coord)] = velocity
# update state
self.planet_dict = new_planet_dict
# self.printState(self.planet_dict)
current_step += 1
def _compute_velocity_vals(self, start_coord, other_coord):
return_coord = [0, 0, 0]
# X
if start_coord[0] > other_coord[0]:
return_coord[0] -= 1
elif start_coord[0] < other_coord[0]:
return_coord[0] += 1
# Y
if start_coord[1] > other_coord[1]:
return_coord[1] -= 1
elif start_coord[1] < other_coord[1]:
return_coord[1] += 1
# Z
if start_coord[2] > other_coord[2]:
return_coord[2] -= 1
elif start_coord[2] < other_coord[2]:
return_coord[2] += 1
return return_coord
def _computeEnergy(self, coordinate, velocity):
potential = sum(abs(val) for val in coordinate)
kinetic = sum(abs(val) for val in velocity)
return potential * kinetic
def computeTotalEnergy(self):
total = 0
for coord, velocity in self.planet_dict.items():
total += self._computeEnergy(coord, velocity)
return total
def _compute_velocity_val(self, start_coord, other_coord):
if start_coord > other_coord:
return -1
elif start_coord < other_coord:
return 1
else:
return 0
def extractCoordinates(self):
x_coordinates = []
y_coordinates = []
z_coordinates = []
for coord in self.planet_dict.keys():
x_coordinates.append((coord[0], 0))
y_coordinates.append((coord[1], 0))
z_coordinates.append((coord[2], 0))
return x_coordinates, y_coordinates, z_coordinates
def computeTotalSteps(self):
x_coords, y_coords, z_coords = self.extractCoordinates()
x_result = self.findCycleStart(x_coords)
y_result = self.findCycleStart(y_coords)
z_result = self.findCycleStart(z_coords)
return numpy.lcm(numpy.lcm(x_result, y_result), z_result)
def findCycleStart(self, coord_dict):
# compute velocities
current_step = 0
planet_dict = coord_dict.copy()
while True:
for i in range(len(planet_dict)):
for other_coord in planet_dict:
# skip over coordinates that are the same
if other_coord is planet_dict[i]:
continue
# generate velocity for the the coordinate to update
velocity = planet_dict[i][1]
delta = self._compute_velocity_val(planet_dict[i][0], other_coord[0])
new_velocity = velocity + delta
planet_dict[i] = (planet_dict[i][0], new_velocity)
# update the coordinates with the generated velocity
new_planet_coord = []
for coord, velocity in planet_dict:
new_coord = coord + velocity
new_planet_coord.append((new_coord, velocity))
planet_dict = new_planet_coord
current_step += 1
if planet_dict[0][0] == coord_dict[0][0] and planet_dict[0][1] == coord_dict[0][1] \
and planet_dict[1][0] == coord_dict[1][0] and planet_dict[1][1] == coord_dict[1][1] \
and planet_dict[2][0] == coord_dict[2][0] and planet_dict[2][1] == coord_dict[2][1] \
and planet_dict[3][0] == coord_dict[3][0] and planet_dict[3][1] == coord_dict[3][1]:
return current_step
if __name__ == '__main__':
sol = NBodyProblem('test_input_1.txt')
delta = sol._compute_velocity_vals((-1, 0, 2), (2, -10, -7))
assert delta == [1, -1, -1]
delta = sol._compute_velocity_vals((-1, 0, 2), (-1, 0, 2))
assert delta == [0, 0, 0]
sol.runSimulation(10)
assert sol.planet_dict == {(2, 1, -3): [-3, -2, 1], (1, -8, 0): [-1, 1, 3], (3, -6, 1): [3, 2, -3], (2, 0, 4): [1, -1, -1]}
key = list(sol.planet_dict.keys())[0]
value = sol.planet_dict[key]
energy = sol._computeEnergy(key, value)
assert energy == 36
key = list(sol.planet_dict.keys())[1]
value = sol.planet_dict[key]
energy = sol._computeEnergy(key, value)
assert energy == 45
total_energy = sol.computeTotalEnergy()
assert total_energy == 179
sol = NBodyProblem('test_input_2.txt')
sol.runSimulation(100)
total_energy = sol.computeTotalEnergy()
assert total_energy == 1940
sol = NBodyProblem('input.txt')
sol.runSimulation(1000)
total_energy = sol.computeTotalEnergy()
assert total_energy == 12466
# print(total_energy)
print("Part 2")
sol = NBodyProblem('test_input_1.txt')
result = sol.computeTotalSteps()
assert result == 2772
sol = NBodyProblem('test_input_2.txt')
result = sol.computeTotalSteps()
assert result == 4686774924
sol = NBodyProblem('input.txt')
result = sol.computeTotalSteps()
assert result == 360689156787864
print(result)
|
b537e679007f14f5f887948a0e0bda1dc1e405d5
|
[
"Python",
"Text"
] | 11
|
Python
|
ejwessel/AdventOfCode2019
|
7f4655cb5333d6a5e694db0631e87aa38d44131e
|
3aab4b3f47048d90e6aa94c9bdb8fc1460daa56c
|
refs/heads/master
|
<file_sep>import React, {Component} from 'react';
import { StyleSheet, View, Button } from 'react-native';
import {connect} from 'react-redux';
import {addPlace, deletePlace, selectPlace, deselectPlace} from '../store/actions/index';
import { createAppContainer } from 'react-navigation';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import { createStackNavigator } from 'react-navigation-stack';
import FindPlaceScreen from '../screens/FindPlace/FindPlace';
import SharePlaceScreen from '../screens/SharePlace/SharePlace';
import PlaceDetail from '../screens/PlaceDetail/PlaceDetail';
import { createDrawerNavigator } from 'react-navigation-drawer';
import SideDrawer from '../screens/SideDrawer/SideDrawer';
import { Ionicons } from '@expo/vector-icons';
import IconButton from '../src/components/IconButton';
const HomeStack = createStackNavigator({
FindPlace:{
screen:FindPlaceScreen,
navigationOptions:({navigation})=>({
headerLeft: <IconButton onPressMenu={()=>navigation.openDrawer()} />
})
} ,
Place: PlaceDetail,
},
{
initialRouteName: 'FindPlace',
});
const DrawerNav = createDrawerNavigator({
Find:{
screen: HomeStack,
navigationOptions:{
drawerLabel: 'Home'
}
},
Drawer:{
screen: SideDrawer,
navigationOptions:({navigation})=>({
drawerLabel: 'Log Out',
headerLeft: <IconButton onPressMenu={()=>navigation.openDrawer()} />
})
},
},
{
drawerPosition:'left',
initialRouteName: 'Find'
}
);
const TabNavigator = createBottomTabNavigator({
FindPlace: {
screen: DrawerNav,
},
SharePlace: SharePlaceScreen,
},
{
defaultNavigationOptions:({navigation}) => ({
tabBarIcon: ({focused, horizontal,tintColor})=>{
const {routeName} = navigation.state;
let IconComponent = Ionicons;
let iconName;
if(routeName==='FindPlace'){
iconName='md-map';
}else if(routeName==='SharePlace'){
iconName='md-share-alt';
}
return <IconComponent name={iconName} size={25} color={tintColor} />
},
}),
initialRouteName: 'FindPlace'
}
);
const AppContainer = createAppContainer(TabNavigator);
class RnApp extends Component {
placeAddedHandler= placeName =>{
this.props.onAddPlace(placeName);
};
placeSelectedHandler = key =>{
this.props.onSelectPlace(key);
};
placeDeletedHandler = () =>{
this.props.onDeletePlace();
};
ModalClosedHandler = () =>{
this.props.onDeselectPlace();
};
render(){
return (
<AppContainer />
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 30,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'flex-start',
},
});
const mapStateToProps = state =>{
return{
places: state.places.places,
selectedPlace: state.places.selectedPlace
};
};
const mapDispatchToProps = dispatch => {
return {
onAddPlace: (name) => dispatch(addPlace(name)),
onDeletePlace: () => dispatch(deletePlace()),
onSelectPlace: (key) => dispatch(selectPlace(key)),
onDeselectPlace: () => dispatch(deselectPlace())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(RnApp);<file_sep>import React, { Component } from 'react';
import { View, Text, TextInput, Button, StyleSheet, ScrollView,Image } from 'react-native';
import { connect } from 'react-redux';
import { addPlace } from '../../store/actions/index';
import MainText from '../../src/components/UI/MainText/MainText';
import HeadingText from '../../src/components/UI/HeadingText/HeadingText';
import PlaceInput from '../../src/components/PlaceInput/PlaceInput';
import PickImage from '../../src/components/PickImage/PickImage';
import PickLocation from '../../src/components/PickLocation/PickLocation';
class SharePlaceScreen extends Component {
state={
placeName: ""
}
placeNameChangedHandler = val =>{
this.setState({
placeName:val
})
}
placeAddedHandler = () => {
if(this.state.placeName.trim()!==""){
this.props.onAddPlace(this.state.placeName);
}
}
render() {
return (
<ScrollView>
<View style={styles.container}>
<MainText><HeadingText>Share a place with us!</HeadingText></MainText>
<PickImage/>
<PickLocation/>
<PlaceInput placeName={this.state.placeName}
onChangeText={this.placeNameChangedHandler}/>
<View style={styles.button}>
<Button title='Share the place' onPress={this.placeAddedHandler}/>
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container:{
width:'100%',
alignItems: 'center'
},
button: {
margin: 8
},
});
const mapDispatchToProops = dispatch => {
return {
onAddPlace: (placeName) => dispatch(addPlace(placeName))
};
};
export default connect(null, mapDispatchToProops)(SharePlaceScreen);<file_sep>import React, {Component} from 'react';
import {View, Image, Text, Button, StyleSheet, TouchableOpacity} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import {connect} from 'react-redux';
import {deletePlace} from '../../store/actions/index';
class PlaceDetail extends Component {
placeDeletedHandler = () =>{
let params = this.props.navigation.state.params;
this.props.onDeletePlace(params.key);
this.props.navigation.goBack();
}
render(){
let params = this.props.navigation.state.params;
return(
<View style={styles.container}>
<View>
<Image source ={params.image} style={styles.placeImage}/>
<Text style={styles.placeName}>{params.name}</Text>
</View>
<View>
<TouchableOpacity onPress={this.placeDeletedHandler}>
<View style={styles.deleteButton}>
<Ionicons size={30} name='ios-trash' color='red'/>
</View>
</TouchableOpacity>
<Button title="Close" onPress={this.props.onModalClosed}/>
</View>
</View>
);
}
};
const styles= StyleSheet.create({
container:{
margin:22
},
placeImage:{
width:"100%",
height: "30%"
},
placeName:{
fontWeight: "bold",
textAlign: "center",
fontSize: 28
},
deleteButton:{
alignItems:"center"
}
});
const mapDispatchToProps = dispatch => {
return {
onDeletePlace: (key) => dispatch(deletePlace(key))
};
};
export default connect(null,mapDispatchToProps)(PlaceDetail);<file_sep>import React from 'react';
import {View, TouchableOpacity,StyleSheet} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
const IconButton = (props) =>(
<TouchableOpacity onPress={props.onPressMenu} style={styles.container}>
<View>
<Ionicons size={30} name='ios-menu' color='orange'/>
</View>
</TouchableOpacity>
);
const styles = StyleSheet.create({
container:{
marginLeft: 22,
}
});
export default IconButton;
<file_sep>import React, { Component } from 'react';
import { View, Text, Button, TextInput, StyleSheet, ImageBackground, Dimensions } from 'react-native';
import DefaultInput from '../../src/components/UI/DefaultInput/DefaultInput';
import HeadingText from '../../src/components/UI/HeadingText/HeadingText';
import MainText from '../../src/components/UI/MainText/MainText';
import backgroundImage from '../../src/assets/background1.jpg';
import ButtonWithBackground from '../../src/components/UI/ButtonWithBackground/ButtonWithBackground';
import validate from '../../src/utility/validation';
import {tryAuth} from '../../store/actions/index'
import {connect} from 'react-redux';
class AuthScreen extends Component {
state ={
respStyles:{
pwContainerDirection: "column",
pwContainerJustifyContent: "flex-start",
pwWrapperWidth: "100%",
},
authMode: "login",
controls:{
email:{
value: "",
valid: false,
validationRules:{
isEmail:true
},
touched:false
},
password:{
value: "",
valid: false,
validationRules:{
minLength: 6
},
touched:false
},
confirmPassword:{
value: "",
valid: false,
validationRules:{
equalTo:'password'
},
touched:false
}
}
};
constructor(props){
super(props);
Dimensions.addEventListener("change", this.updateStyles);
}
componentWillUnmount(){
Dimensions.removeEventListener("change",this.updateStyles);
}
switchAuthModeHandler = () =>{
this.setState(prevState=>{
return{
authMode: prevState.authMode ==="login" ? "signup" : "login"
};
});
}
updateStyles= (dims) =>{
this.setState({
respStyles:{
pwContainerDirection: Dimensions.get('window').height>500 ? "column" : "row",
pwContainerJustifyContent: Dimensions.get('window').height>500 ? "flex-start": "space-between",
pwWrapperWidth: Dimensions.get('window').height>500 ? "100%" : "45%"
}
});
}
updateInputState= (key,value)=>{
let connectedValue={};
if(this.state.controls[key].validationRules.equalTo){
const equalControl= this.state.controls[key].validationRules.equalTo;
const equalValue= this.state.controls[equalControl].value;
connectedValue= {
...connectedValue,
equalTo: equalValue
};
}
if(key==='password'){
connectedValue= {
...connectedValue,
equalTo: value
};
}
this.setState(prevState => {
return{
controls:{
...prevState.controls,
confirmPassword:{
...prevState.controls.confirmPassword,
valid: key=== 'password' ? validate(prevState.controls.confirmPassword.value,prevState.controls.confirmPassword.validationRules,connectedValue): prevState.controls.confirmPassword.valid
},
[key]: {
...prevState.controls[key],
value:value,
valid: validate(value,prevState.controls[key].validationRules,connectedValue),
touched:true
}
}
};
});
}
loginHandler = () =>{
const authData ={
email: this.state.controls.email.value,
password: <PASSWORD>.controls.password.value
};
this.props.onLogin(authData);
this.props.navigation.navigate('Home');
}
render() {
let headingTxt=null;
let confirmPasswordControl = null;
if(Dimensions.get('window').height>500){
headingTxt=(
<MainText>
<HeadingText>Please Log In</HeadingText>
</MainText>
);
}
if(this.state.authMode==="signup"){
confirmPasswordControl =(
<View style={{width: this.state.respStyles.pwWrapperWidth}}>
<DefaultInput placeholder='Confirm Password'
value={this.state.controls.confirmPassword.value}
onChangeText={val => this.updateInputState('confirmPassword',val)}
valid={this.state.controls.confirmPassword.valid}
touched={this.state.controls.confirmPassword.touched}/>
</View>
);
}
return (
<ImageBackground source={backgroundImage} style={styles.backgroundImage}>
<View style={styles.container}>
{headingTxt}
<ButtonWithBackground color='#29aaf4' onPress={this.switchAuthModeHandler}>
Switch to {this.state.authMode==='login' ? "Sign up": "Login"}</ButtonWithBackground>
<View style={styles.inputContainer}>
<DefaultInput placeholder='Your E-Mail Address'
value={this.state.controls.email.value}
onChangeText={(val)=>this.updateInputState('email',val)}
valid={this.state.controls.email.valid}
touched={this.state.controls.email.touched}/>
<View style={{flexDirection: this.state.respStyles.pwContainerDirection,
justifyContent: this.state.respStyles.pwContainerJustifyContent}}>
<View style={{width: this.state.respStyles.pwWrapperWidth}}>
<DefaultInput placeholder='Password'
value={this.state.controls.password.value}
onChangeText={val => this.updateInputState('password',val)}
valid={this.state.controls.password.valid}
touched={this.state.controls.password.touched}/>
</View>
</View>
{confirmPasswordControl}
</View>
<ButtonWithBackground onPress={this.loginHandler} color='#29aaf4'
disabled={!this.state.controls.confirmPassword.valid && this.state.authMode==="signup" || !this.state.controls.email.valid || !this.state.controls.password.valid}>Submit</ButtonWithBackground>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
inputContainer: {
width: '80%'
},
textHeading: {
fontSize: 28,
fontWeight: 'bold'
},
backgroundImage: {
width: '100%',
flex:1
},
passwordContainer:{
flexDirection:Dimensions.get('window').height>500?"column":"row",
justifyContent: "space-between"
},
passwordWrapper:{
width: Dimensions.get('window').height>500 ? "100%" : "45%"
}
});
const mapDispatchToProps= dispatch => {
return{
onLogin: (authData) => dispatch(tryAuth(authData))
};
};
export default connect(null,mapDispatchToProps)(AuthScreen);<file_sep>import React, {Component} from 'react';
import { StyleSheet, View } from 'react-native';
import {Provider} from 'react-redux';
import configureStore from './store/configureStore';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import AuthScreen from './screens/Auth/Auth';
import RnApp from './src/RnApp';
const store = configureStore();
const RootStack = createStackNavigator({
Home: {
screen: RnApp,
navigationOptions: {
headerLeft: null,
gesturesEnabled: false,
headerBackTitle: null,
header: null
}
},
Auth: {
screen: AuthScreen,
navigationOptions: {
title: 'Login'
}
}
},
{
initialRouteName: 'Auth',
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends Component {
render(){
return (
<Provider store={store}>
<AppContainer navigation={this.props.navigation} />
</Provider>
);
}
}
|
22fc2ec0d4369c1de1f4626d4077a993119e8027
|
[
"JavaScript"
] | 6
|
JavaScript
|
WiluGIT/rn-app
|
5a4265d4163428c1918d72e41719473904316439
|
44ce65e6a663ebfdf7dd64cbda04453d350584d5
|
refs/heads/master
|
<file_sep>package net.gaox.common.api;
import com.alibaba.fastjson.JSON;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* <p> response包装类 </p>
*
* @author gaox·Eric
* @date 2019/5/4 00:27
*/
public class ApiResponse extends HashMap<String, Object> {
/**
* 成功消息封装
*
* @return
*/
public static ApiResponse success() {
ApiResponse apiResult = new ApiResponse();
apiResult.put("success", true);
return apiResult;
}
/**
* 错误消息封装
*
* @return
*/
public static ApiResponse fail() {
ApiResponse apiResult = new ApiResponse();
apiResult.put("success", false);
return apiResult;
}
/**
* 错误消息封装
*
* @param msg 错误信息
* @return
*/
public static ApiResponse fail(String msg) {
ApiResponse apiResult = new ApiResponse();
apiResult.put("success", false);
apiResult.put("msg", msg);
return apiResult;
}
/**
* 添加消息体
*
* @param key
* @param object
* @return
*/
public ApiResponse and(String key, Object object) {
this.put(key, object);
return this;
}
/**
* 异常信息放入
*
* @param msg
* @return
*/
public ApiResponse error(String msg) {
this.put("msg", msg);
return this;
}
/**
* 异常信息,包含异常码及异常信息
*
* @param error
* @return
*/
public ApiResponse error(ApiError error) {
this.put("msg", error.getMsg());
this.put("code", error.getCode());
return this;
}
/**
* tostring方法
*
* @return
*/
@Override
public String toString() {
return JSON.toJSONString(this);
}
/**
* 放入一个包含data属性的内容
*
* @param data
* @return
*/
@SuppressWarnings("unchecked")
public ApiResponse data(Object data) {
if (this.containsKey("data")) {
Map<String, Object> object = (Map<String, Object>) this.get("data");
object.putAll((Map<String, Object>) data);
} else {
this.put("data", data);
}
return this;
}
/**
* 封装response的response
*
* @param data
* @return
*/
@SuppressWarnings("unchecked")
public ApiResponse data(Map<String, Object> data) {
if (this.containsKey("data")) {
Map<String, Object> object = (Map<String, Object>) this.get("data");
object.putAll(data);
} else {
this.put("data", data);
}
return this;
}
/**
* 封装集合类型消息
* 会覆盖之前相同项消息
*
* @param map
* @return
*/
public ApiResponse and(Map<String, Object> map) {
for (Entry<String, Object> entry : map.entrySet()) {
this.put(entry.getKey(), entry.getValue());
}
return this;
}
/**
* 消息模型
*
* @param obj
* @param clazz
* @return
*/
public ApiResponse andModel(Object obj, Class<?> clazz) {
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
PropertyDescriptor[] ps = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor p : ps) {
if ("class".equals(p.getName())) {
continue;
}
Method method = p.getReadMethod();
try {
Object value = method.invoke(obj);
this.put(p.getName(), value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return this;
}
}<file_sep>package net.gaox.sponsor.service.impl;
import lombok.extern.slf4j.Slf4j;
import net.gaox.common.api.ApiException;
import net.gaox.sponsor.constant.Constants;
import net.gaox.sponsor.dao.AdUserRepository;
import net.gaox.sponsor.entity.AdUser;
import net.gaox.sponsor.service.IUserService;
import net.gaox.sponsor.utils.CommonUtils;
import net.gaox.sponsor.model.vo.CreateUserRequest;
import net.gaox.sponsor.model.vo.CreateUserResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 20:23
*/
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
private final AdUserRepository userRepository;
public UserServiceImpl(AdUserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public CreateUserResponse createUser(CreateUserRequest request) throws ApiException {
if (!request.validate()) {
throw new ApiException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
}
AdUser oldUser = userRepository.
findByUsername(request.getUsername());
if (oldUser != null) {
throw new ApiException(Constants.ErrorMsg.SAME_NAME_ERROR);
}
AdUser newUser = userRepository.save(new AdUser(
request.getUsername(),
CommonUtils.md5(request.getUsername())
));
return new CreateUserResponse(
newUser.getId(), newUser.getUsername(), newUser.getToken(),
newUser.getCreateTime(), newUser.getUpdateTime()
);
}
}<file_sep>package net.gaox.sponsor.service;
import net.gaox.common.api.ApiException;
import net.gaox.sponsor.model.vo.CreateUserRequest;
import net.gaox.sponsor.model.vo.CreateUserResponse;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 20:23
*/
public interface IUserService {
/**
* <h2>创建用户</h2>
*/
CreateUserResponse createUser(CreateUserRequest request) throws ApiException;
}<file_sep>--
-- init data for table `ad_user`
--
INSERT INTO `ad_user`
VALUES (15, 'qinyi', 'B2E56F2420D73FEC125D2D51641C5713', 1, '2018-11-19 20:29:01', '2018-11-19 20:29:01');
--
-- init data for table `ad_creative`
--
INSERT INTO `ad_creative`
VALUES (10, '第一个创意', 1, 1, 720, 1080, 1024, 0, 1, 15, 'https://www.imooc.com', '2018-11-19 21:31:31',
'2018-11-19 21:31:31');
--
-- init data for table `ad_plan`
--
INSERT INTO `ad_plan`
VALUES (10, 15, '推广计划名称', 1, '2018-11-28 00:00:00', '2019-11-20 00:00:00', '2018-11-19 20:42:27',
'2018-11-19 20:57:12');
--
-- init data for table `ad_unit`
--
INSERT INTO `ad_unit`
VALUES (10, 10, '第一个推广单元', 1, 1, 10000000, '2018-11-20 11:43:26', '2018-11-20 11:43:26'),
(12, 10, '第二个推广单元', 1, 1, 15000000, '2018-01-01 00:00:00', '2018-01-01 00:00:00');
--
-- init data for table `ad_unit_district`
--
INSERT INTO `ad_unit_district`
VALUES (10, 10, '安徽省', '淮北市'),
(11, 10, '安徽省', '宿州市'),
(12, 10, '安徽省', '合肥市'),
(14, 10, '辽宁省', '大连市');
--
-- init data for table `ad_unit_it`
--
INSERT INTO `ad_unit_it`
VALUES (10, 10, '台球'),
(11, 10, '游泳'),
(12, 10, '乒乓球');
--
-- init data for table `ad_unit_keyword`
--
INSERT INTO `ad_unit_keyword`
VALUES (10, 10, '宝马'),
(11, 10, '奥迪'),
(12, 10, '大众');
--
-- init data for table `creative_unit`
--
INSERT INTO `creative_unit`
VALUES (10, 10, 10);
<file_sep>package net.gaox.search.client;
import net.gaox.common.api.ApiResponse;
import net.gaox.search.model.vo.AdPlanGetRequest;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* <p> Feign远程调用接口配置 </p>
* FeignClient指定调用的应用
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/19 00:47
*/
@FeignClient(value = "eureka-client-ad-sponsor", fallback = SponsorClientHystrix.class)
public interface SponsorClient {
/**
* 使用feign调用接口
* 指定调用接口,接口方法
*
* @param request
* @return
*/
@PostMapping("/ad-sponsor/get/adPlan")
ApiResponse getAdPlans(@RequestBody AdPlanGetRequest request);
}<file_sep>package net.gaox.search.controller;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.gaox.common.annotation.IgnoreResponseAdvice;
import net.gaox.common.api.ApiResponse;
import net.gaox.search.client.SponsorClient;
import net.gaox.search.model.vo.AdPlanGetRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 23:42
*/
@Slf4j
@RestController
public class SearchController {
private final RestTemplate restTemplate;
private final SponsorClient sponsorClient;
public SearchController(RestTemplate restTemplate, SponsorClient sponsorClient) {
this.restTemplate = restTemplate;
this.sponsorClient = sponsorClient;
}
@IgnoreResponseAdvice
@PostMapping("/getAdPlans")
public ApiResponse getAdPlans(@RequestBody AdPlanGetRequest request) {
log.info("ad-search: getAdPlans -> {}", JSONObject.toJSONString(request));
ApiResponse body = sponsorClient.getAdPlans(request);
log.info("get 【{}】", JSONObject.toJSONString(body));
return body;
}
/**
* 使用ribbon调用微服务接口
*
* @param request
* @return
*/
@IgnoreResponseAdvice
@PostMapping("/getAdPlansByRibbon")
public ApiResponse getAdPlansByRebbon(@RequestBody AdPlanGetRequest request) {
log.info("ad-search: getAdPlansByRibbon -> {}", JSONObject.toJSONString(request));
ApiResponse body = restTemplate.postForEntity(
"http://eureka-client-ad-sponsor/ad-sponsor/get/adPlan", request, ApiResponse.class
).getBody();
log.info("get 【{}】", JSONObject.toJSONString(body));
return body;
}
}<file_sep>## Advertising system based on Spring Cloud
### project background
> needs to complete an advertising system for the media and advertisers to place and display ads
### destination
> is the same as the project background. In fact, as long as understand the advertising system can achieve the function, also know the background and purpose
Select the microservices development framework
> reduces coupling between service functions, makes developer assignment easier, and so on
### design ideas
> must first be about how and why tables are designed, about the hierarchical table structure, and about what data is stored in each table. After the release system, is to achieve the table data to add, delete, modify and check; Finally, the retrieval system loads the data in the data table into the system, constructs the inverted index, and realizes the efficient retrieval service.
### Advertising system main points
- SpringCloud
- advertising search
- microservices architecture
- SpringCloud
- Eureka service governance
- implement service registration and discovery
- Zuul gateway
- implement routing forwarding and request information recording (custom filter)
- Feign
- kafka message queue component
- resolve MySQL Binlog<file_sep>package net.gaox.search.mysql.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.gaox.search.mysql.constant.OpType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/20 16:07
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TableTemplate {
private String tableName;
private String level;
private Map<OpType, List<String>> opTypeFieldSetMap = new HashMap<>();
/**
* 字段索引 -> 字段名
* */
private Map<Integer, String> posMap = new HashMap<>();
}
<file_sep>package net.gaox.sponsor.service;
import net.gaox.common.api.ApiException;
import net.gaox.sponsor.entity.AdPlan;
import net.gaox.sponsor.model.vo.AdPlanGetRequest;
import net.gaox.sponsor.model.vo.AdPlanRequest;
import net.gaox.sponsor.model.vo.AdPlanResponse;
import java.util.List;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 20:23
*/
public interface IAdPlanService {
/**
* <h2>创建推广计划</h2>
*/
AdPlanResponse createAdPlan(AdPlanRequest request) throws ApiException;
/**
* <h2>获取推广计划</h2>
*/
List<AdPlan> getAdPlanByIds(AdPlanGetRequest request) throws ApiException;
/**
* <h2>更新推广计划</h2>
*/
AdPlanResponse updateAdPlan(AdPlanRequest request) throws ApiException;
/**
* <h2>删除推广计划</h2>
*/
void deleteAdPlan(AdPlanRequest request) throws ApiException;
}
<file_sep>package net.gaox;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 16:12
*/
@EnableFeignClients
@EnableCircuitBreaker
@EnableEurekaClient
@SpringBootApplication
public class SponsorApplication {
public static void main(String[] args) {
SpringApplication.run(SponsorApplication.class, args);
}
}<file_sep>package net.gaox.sponsor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import net.gaox.sponsor.constant.CommonStatus;
import javax.persistence.*;
import java.util.Date;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 20:23
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Accessors(chain = true)
@Table(name = "ad_user")
public class AdUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Basic
@Column(name = "username", nullable = false)
private String username;
@Basic
@Column(name = "token", nullable = false)
private String token;
@Basic
@Column(name = "user_status", nullable = false)
private Integer userStatus;
@Basic
@Column(name = "create_time", nullable = false)
private Date createTime;
@Basic
@Column(name = "update_time", nullable = false)
private Date updateTime;
public AdUser(String username, String token) {
this.username = username;
this.token = token;
this.userStatus = CommonStatus.VALID.getStatus();
this.createTime = new Date();
this.updateTime = this.createTime;
}
}<file_sep>package net.gaox.sponsor.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 20:23
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreateUserResponse {
private Long userId;
private String username;
private String token;
private Date createTime;
private Date updateTime;
}
<file_sep>package net.gaox.sponsor.service;
import net.gaox.sponsor.model.vo.CreativeRequest;
import net.gaox.sponsor.model.vo.CreativeResponse;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 20:23
*/
public interface ICreativeService {
CreativeResponse createCreative(CreativeRequest request);
}
<file_sep>package net.gaox.search.index;
import com.alibaba.fastjson.JSON;
import net.gaox.common.dump.DataConstant;
import net.gaox.common.dump.table.*;
import net.gaox.search.handler.AdLevelDataHandler;
import net.gaox.search.mysql.constant.OpType;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
/**
* 1. 索引之间存在着层级的划分, 也就是依赖关系的划分
* <p> 2. 加载全量索引其实是增量索引 "添加" 的一种特殊实现 </p>
* <p>
* 依赖dataTable Bean,加载
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/20 16:07
*/
@Component
@DependsOn("dataTable")
public class IndexFileLoader {
/**
* 系统启动时将索引全量加载到系统
*/
@PostConstruct
public void init() {
List<String> adPlanStrings = loadDumpData(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_PLAN));
adPlanStrings.forEach(p -> AdLevelDataHandler.handleLevel2(JSON.parseObject(p, AdPlanTable.class), OpType.ADD));
List<String> adCreativeStrings = loadDumpData(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_CREATIVE));
adCreativeStrings.forEach(c -> AdLevelDataHandler.handleLevel2(JSON.parseObject(c, AdCreativeTable.class), OpType.ADD));
List<String> adUnitStrings = loadDumpData(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT));
adUnitStrings.forEach(u -> AdLevelDataHandler.handleLevel3(JSON.parseObject(u, AdUnitTable.class), OpType.ADD));
List<String> adCreativeUnitStrings = loadDumpData(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_CREATIVE_UNIT));
adCreativeUnitStrings.forEach(cu -> AdLevelDataHandler.handleLevel3(JSON.parseObject(cu, AdCreativeUnitTable.class), OpType.ADD));
List<String> adUnitDistrictStrings = loadDumpData(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_DISTRICT));
adUnitDistrictStrings.forEach(d -> AdLevelDataHandler.handleLevel4(JSON.parseObject(d, AdUnitDistrictTable.class), OpType.ADD));
List<String> adUnitItStrings = loadDumpData(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_IT));
adUnitItStrings.forEach(i -> AdLevelDataHandler.handleLevel4(JSON.parseObject(i, AdUnitItTable.class), OpType.ADD));
List<String> adUnitKeywordStrings = loadDumpData(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_KEYWORD));
adUnitKeywordStrings.forEach(k -> AdLevelDataHandler.handleLevel4(JSON.parseObject(k, AdUnitKeywordTable.class), OpType.ADD));
}
/**
* 读取写入数据,**.data文件
*
* @param fileName
* @return
*/
private List<String> loadDumpData(String fileName) {
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {
return br.lines().collect(Collectors.toList());
} catch (IOException ex) {
//抛出异常,在过滤器中拦截信息
throw new RuntimeException(ex.getMessage());
}
}
}<file_sep>package net.gaox.search.mysql.listener;
import net.gaox.search.mysql.dto.BinlogRowData;
/**
* 由binlog实现增量索引的更新接口
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/20 16:07
*/
public interface Ilistener {
/**
* 注册不同的监听器
*/
void register();
/**
* 监听binlog事件
*
* @param eventData binlog对象
*/
void onEvent(BinlogRowData eventData);
}
<file_sep>## 基于Spring Cloud实现的广告系统
### 项目背景
> 需要完成一个广告系统提供给媒体方和广告主去投放并展示广告
### 目的
> 与项目背景是相同的。其实只要搞清楚了广告系统能够实现的功能,也就知道了背景和目的
选择微服务开发框架
> 降低服务功能之间的耦合、开发人员分配也更加简单等等
### 设计思路
> 首先肯定是数据表怎样去设计、为什么这样设计,要说清楚分层的表结构,每张表存储什么样的数据。之后是投放系统,就是实现对表数据的增删改查;最后是检索系统,将数据表中的数据加载到系统中,构造倒排索引,实现高效检索服务。
### 广告系统主要知识点
- SpringCloud
- 广告检索
- 微服务架构
- SpringCloud
- Eureka服务治理
- 实现服务注册与发现
- Zuul网关
- 实现路由转发与请求信息记录(自定义过滤器)
- Feign
- kafka消息队列组件
- 解析MySQL Binlog
<file_sep>package net.gaox.sponsor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import net.gaox.common.dump.table.AdPlanTable;
import net.gaox.sponsor.constant.CommonStatus;
import javax.persistence.*;
import java.util.Date;
/**
* <p> </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/18 20:23
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Accessors(chain = true)
@Table(name = "ad_plan")
public class AdPlan {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Basic
@Column(name = "user_id", nullable = false)
private Long userId;
@Basic
@Column(name = "plan_name", nullable = false)
private String planName;
@Basic
@Column(name = "plan_status", nullable = false)
private Integer planStatus;
@Basic
@Column(name = "start_date", nullable = false)
private Date startDate;
@Basic
@Column(name = "end_date", nullable = false)
private Date endDate;
@Basic
@Column(name = "create_time", nullable = false)
private Date createTime;
@Basic
@Column(name = "update_time", nullable = false)
private Date updateTime;
public AdPlan(Long userId, String planName, Date startDate, Date endDate) {
this.userId = userId;
this.planName = planName;
this.planStatus = CommonStatus.VALID.getStatus();
this.startDate = startDate;
this.endDate = endDate;
this.createTime = new Date();
this.updateTime = this.createTime;
}
public AdPlanTable toAdPlanTable() {
return new AdPlanTable(
this.getId(),
this.getUserId(),
this.getPlanStatus(),
this.getStartDate(),
this.getEndDate()
);
}
}<file_sep>package net.gaox.sponsor.controller;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.gaox.common.dump.DataConstant;
import net.gaox.common.dump.table.AdCreativeUnitTable;
import net.gaox.common.dump.table.AdUnitDistrictTable;
import net.gaox.common.dump.table.AdUnitItTable;
import net.gaox.common.dump.table.AdUnitKeywordTable;
import net.gaox.sponsor.constant.CommonStatus;
import net.gaox.sponsor.dao.AdPlanRepository;
import net.gaox.sponsor.dao.AdUnitRepository;
import net.gaox.sponsor.dao.CreativeRepository;
import net.gaox.sponsor.dao.unit_condition.AdUnitDistrictRepository;
import net.gaox.sponsor.dao.unit_condition.AdUnitItRepository;
import net.gaox.sponsor.dao.unit_condition.AdUnitKeywordRepository;
import net.gaox.sponsor.dao.unit_condition.CreativeUnitRepository;
import net.gaox.sponsor.entity.AdPlan;
import net.gaox.sponsor.entity.AdUnit;
import net.gaox.sponsor.entity.Creative;
import net.gaox.sponsor.entity.unit_condition.AdUnitDistrict;
import net.gaox.sponsor.entity.unit_condition.AdUnitIt;
import net.gaox.sponsor.entity.unit_condition.AdUnitKeyword;
import net.gaox.sponsor.entity.unit_condition.CreativeUnit;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p> 更新索引数据控制器 </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/21 22:41
*/
@Slf4j
@RestController
@RequestMapping("/init/data")
public class DataController {
private final AdPlanRepository planRepository;
private final AdUnitRepository unitRepository;
private final CreativeRepository creativeRepository;
private final CreativeUnitRepository creativeUnitRepository;
private final AdUnitDistrictRepository districtRepository;
private final AdUnitItRepository itRepository;
private final AdUnitKeywordRepository keywordRepository;
public DataController(AdPlanRepository planRepository, AdUnitRepository unitRepository,
CreativeRepository creativeRepository, CreativeUnitRepository creativeUnitRepository,
AdUnitDistrictRepository districtRepository, AdUnitItRepository itRepository,
AdUnitKeywordRepository keywordRepository) {
this.planRepository = planRepository;
this.unitRepository = unitRepository;
this.creativeRepository = creativeRepository;
this.creativeUnitRepository = creativeUnitRepository;
this.districtRepository = districtRepository;
this.itRepository = itRepository;
this.keywordRepository = keywordRepository;
}
@GetMapping
public void dumpAdTableData() {
dumpAdPlanTable(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_PLAN));
dumpAdUnitTable(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT));
dumpAdCreativeTable(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_CREATIVE));
dumpAdCreativeUnitTable(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_CREATIVE_UNIT));
dumpAdUnitDistrictTable(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_DISTRICT));
dumpAdUnitItTable(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_IT));
dumpAdUnitKeywordTable(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_KEYWORD));
}
private void dumpAdPlanTable(String fileName) {
List<AdPlan> adPlans = planRepository.findAllByPlanStatus(CommonStatus.VALID.getStatus());
if (CollectionUtils.isEmpty(adPlans)) {
return;
}
List<Object> planTables = adPlans.stream().map(AdPlan::toAdPlanTable).collect(Collectors.toList());
writer2file(fileName, planTables, "dumpAdPlanTable");
}
private void dumpAdUnitTable(String fileName) {
List<AdUnit> adUnits = unitRepository.findAllByUnitStatus(CommonStatus.VALID.getStatus());
if (CollectionUtils.isEmpty(adUnits)) {
return;
}
List<Object> unitTables = adUnits.stream().map(AdUnit::toAdUnitTable).collect(Collectors.toList());
writer2file(fileName, unitTables, "dumpAdUnitTable");
}
private void dumpAdCreativeTable(String fileName) {
List<Creative> creatives = creativeRepository.findAll();
if (CollectionUtils.isEmpty(creatives)) {
return;
}
List<Object> creativeTables = creatives.stream().map(Creative::toAdCreativeTable).collect(Collectors.toList());
writer2file(fileName, creativeTables, "dumpAdCreativeTable");
}
private void dumpAdCreativeUnitTable(String fileName) {
List<CreativeUnit> creativeUnits = creativeUnitRepository.findAll();
if (CollectionUtils.isEmpty(creativeUnits)) {
return;
}
List<Object> creativeUnitTables = creativeUnits.stream()
.map(c -> new AdCreativeUnitTable(c.getCreativeId(), c.getUnitId())).collect(Collectors.toList());
writer2file(fileName, creativeUnitTables, "dumpAdCreativeUnit");
}
private void dumpAdUnitDistrictTable(String fileName) {
List<AdUnitDistrict> unitDistricts = districtRepository.findAll();
if (CollectionUtils.isEmpty(unitDistricts)) {
return;
}
List<Object> unitDistrictTables = unitDistricts.stream()
.map(d -> new AdUnitDistrictTable(d.getUnitId(), d.getProvince(), d.getCity())).collect(Collectors.toList());
writer2file(fileName, unitDistrictTables, "dumpAdUnitDistrictTable");
}
private void dumpAdUnitItTable(String fileName) {
List<AdUnitIt> unitIts = itRepository.findAll();
if (CollectionUtils.isEmpty(unitIts)) {
return;
}
List<Object> unitItTables = unitIts.stream()
.map(i -> new AdUnitItTable(i.getUnitId(), i.getItTag())).collect(Collectors.toList());
writer2file(fileName, unitItTables, "dumpAdUnitItTable");
}
private void dumpAdUnitKeywordTable(String fileName) {
List<AdUnitKeyword> unitKeywords = keywordRepository.findAll();
if (CollectionUtils.isEmpty(unitKeywords)) {
return;
}
List<Object> unitItTables = unitKeywords.stream()
.map(k -> new AdUnitKeywordTable(k.getUnitId(), k.getKeyword())).collect(Collectors.toList());
writer2file(fileName, unitItTables, "dumpAdUnitItTable");
}
private void writer2file(String fileName, List<Object> list, String msg) {
File file = new File(fileName);
File fileParent = file.getParentFile();
// 当父目录不存在时,创建父目录
if (!fileParent.exists()) {
fileParent.mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath()))) {
String collect = list.stream().map(JSON::toJSONString).collect(Collectors.joining("\n"));
writer.write(collect);
writer.newLine();
} catch (IOException ex) {
ex.printStackTrace();
log.error("{} error", msg);
}
}
}<file_sep>package net.gaox.search.index.creativeunit;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p> 创意单元与推广单元 </p>
*
* @author gaox·Eric
* @site gaox.net
* @date 2019/12/20 16:07
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreativeUnitObject {
/**
* 创意单元id
*/
private Long adId;
/**
* 推广单元id
*/
private Long unitId;
/**
* 索引定义方式 adId-unitId
*/
}
|
c92ecfb6817091e70caf58c205a580ced478e8ce
|
[
"Markdown",
"Java",
"SQL"
] | 19
|
Java
|
gaoxizhi/springcloud-ad
|
230cae549313ff7e31340cbda9a285e11bcca68d
|
31143ffee65ef9550748d4094e6f4c2bdd1493fc
|
refs/heads/master
|
<file_sep>local t = {}
local arguments = {}
local targets = {}
local what = arg[1]
local function has_command(what)
local path = package.searchpath(what, (MAKEDIR / "scripts" / "command" / "?.lua"):string())
return path ~= nil
end
if what == nil then
what = 'remake'
else
local i = 2
if not has_command(what) then
what = 'remake'
i = 1
end
while i <= #arg do
if arg[i]:sub(1, 1) == '-' then
local k = arg[i]:sub(2)
i = i + 1
arguments[k] = arg[i]
else
targets[#targets+1] = arg[i]
end
i = i + 1
end
end
t.what = what
t.targets = targets
t.C = arguments.C ; arguments.C = nil
t.args = arguments
return t
<file_sep>local util = require "util"
local globals = require "globals"
package.cpath = string.gsub([[${luamake}/?.${extension};./${builddir}/bin/?.${extension}]], "%$%{([^}]*)%}", {
luamake = MAKEDIR:string(),
builddir = globals.builddir,
extension = package.cpath:match '[/\\]%?%.([a-z]+)',
})
table.insert(arg, 2, "test.lua")
util.command "lua"
<file_sep>local util = require 'util'
util.cmd_init()
util.cmd_clean()
util.cmd_make()
<file_sep>local util = require 'util'
util.command('init', true)
util.cmd_make()
<file_sep>local util = require 'utility'
local guide = require 'parser.guide'
local collector = require 'core.collector'
local files = require 'files'
local SPLIT_CHAR = '\x1F'
local LAST_REGEX = SPLIT_CHAR .. '[^' .. SPLIT_CHAR .. ']*$'
local FIRST_REGEX = '^[^' .. SPLIT_CHAR .. ']*'
local HEAD_REGEX = '^' .. SPLIT_CHAR .. '?[^' .. SPLIT_CHAR .. ']*'
local ANY_FIELD_CHAR = '*'
local INDEX_CHAR = '['
local RETURN_INDEX = SPLIT_CHAR .. '#'
local PARAM_INDEX = SPLIT_CHAR .. '&'
local TABLE_KEY = SPLIT_CHAR .. '<'
local WEAK_TABLE_KEY = SPLIT_CHAR .. '<<'
local INDEX_FIELD = SPLIT_CHAR .. INDEX_CHAR
local ANY_FIELD = SPLIT_CHAR .. ANY_FIELD_CHAR
local WEAK_ANY_FIELD = SPLIT_CHAR .. ANY_FIELD_CHAR .. ANY_FIELD_CHAR
local URI_CHAR = '@'
local URI_REGEX = URI_CHAR .. '([^' .. URI_CHAR .. ']*)' .. URI_CHAR .. '(.*)'
---@class node
-- 当前节点的id
---@field id string
-- 使用该ID的单元
---@field source parser.guide.object
-- 使用该ID的单元
---@field sources parser.guide.object[]
-- 前进的关联ID
---@field forward string
-- 第一个前进关联的tag
---@field finfo? node.info
-- 前进的关联ID
---@field forwards string[]
-- 后退的关联ID
---@field backward string
-- 第一个后退关联的tag
---@field binfo? node.info
-- 后退的关联ID
---@field backwards string[]
-- 函数调用参数信息(用于泛型)
---@field call parser.guide.object
---@field skip boolean
---@alias noders table<string, node[]>
---@alias node.filter fun(id: string, field?: string):boolean
---@class node.info
---@field reject? string
---@field deep? boolean
---@field filter? node.filter
---@field filterValid? node.filter
---@field dontCross? boolean
---创建source的链接信息
---@param noders noders
---@param id string
---@return node
local function getNode(noders, id)
if not noders[id] then
noders[id] = {
id = id,
}
end
return noders[id]
end
---如果对象是 arg self, 则认为 id 是 method 的 node
---@param source parser.guide.object
---@return nil
local function getMethodNode(source)
if source.type ~= 'local' or source[1] ~= 'self' then
return nil
end
if source._mnode ~= nil then
return source._mnode or nil
end
source._mnode = false
local func = guide.getParentFunction(source)
if func.isGeneric then
return
end
if source.parent.type ~= 'funcargs' then
return
end
local setmethod = func.parent
if setmethod and ( setmethod.type == 'setmethod'
or setmethod.type == 'setfield'
or setmethod.type == 'setindex') then
source._mnode = setmethod.node
return setmethod.node
end
end
---获取语法树单元的key
---@param source parser.guide.object
---@return string? key
---@return parser.guide.object? node
local function getKey(source)
if source.type == 'local' then
if source.parent.type == 'funcargs' then
return 'p:' .. source.start, nil
end
return 'l:' .. source.start, nil
elseif source.type == 'setlocal'
or source.type == 'getlocal' then
return getKey(source.node)
elseif source.type == 'setglobal'
or source.type == 'getglobal' then
local node = source.node
if node.tag == '_ENV' then
return ('%q'):format(source[1] or ''), nil
else
return ('%q'):format(source[1] or ''), node
end
elseif source.type == 'getfield'
or source.type == 'setfield' then
return ('%q'):format(source.field and source.field[1] or ''), source.node
elseif source.type == 'tablefield' then
return ('%q'):format(source.field and source.field[1] or ''), source.parent
elseif source.type == 'getmethod'
or source.type == 'setmethod' then
return ('%q'):format(source.method and source.method[1] or ''), source.node
elseif source.type == 'setindex'
or source.type == 'getindex' then
local index = source.index
if not index then
return INDEX_CHAR, source.node
end
if index.type == 'string'
or index.type == 'boolean'
or index.type == 'integer'
or index.type == 'number' then
return ('%q'):format(index[1] or ''), source.node
else
return INDEX_CHAR, source.node
end
elseif source.type == 'tableindex' then
local index = source.index
if not index then
return ANY_FIELD_CHAR, source.parent
end
if index.type == 'string'
or index.type == 'boolean'
or index.type == 'integer'
or index.type == 'number' then
return ('%q'):format(index[1] or ''), source.parent
elseif index.type ~= 'function'
and index.type ~= 'table' then
return ANY_FIELD_CHAR, source.parent
end
elseif source.type == 'tableexp' then
return tostring(source.tindex), source.parent
elseif source.type == 'table' then
return 't:' .. source.start, nil
elseif source.type == 'label' then
return 'l:' .. source.start, nil
elseif source.type == 'goto' then
if source.node then
return 'l:' .. source.node.start, nil
end
return nil, nil
elseif source.type == 'function' then
return 'f:' .. source.start, nil
elseif source.type == 'string' then
return 'str:', nil
elseif source.type == 'integer' then
return 'int:'
elseif source.type == 'number' then
return 'num:'
elseif source.type == 'boolean' then
return 'bool:'
elseif source.type == 'nil' then
return 'nil:', nil
elseif source.type == '...' then
return 'va:' .. source.start, nil
elseif source.type == 'varargs' then
if source.node then
return 'va:' .. source.node.start, nil
end
elseif source.type == 'select' then
return ('s:%d%s%d'):format(source.start, RETURN_INDEX, source.sindex)
elseif source.type == 'call' then
local node = source.node
if node.special == 'rawget'
or node.special == 'rawset' then
if not source.args then
return nil, nil
end
local tbl, key = source.args[1], source.args[2]
if not tbl or not key then
return nil, nil
end
if key.type == 'string' then
return ('%q'):format(key[1] or ''), tbl
else
return '', tbl
end
end
return 'c:' .. source.finish, nil
elseif source.type == 'doc.class.name'
or source.type == 'doc.alias.name'
or source.type == 'doc.extends.name' then
local name = source[1]
return 'dn:' .. name, nil
elseif source.type == 'doc.type.name' then
local name = source[1]
if source.typeGeneric then
return 'dg:' .. source.typeGeneric[name][1].start, nil
else
return 'dn:' .. name, nil
end
elseif source.type == 'doc.see.name' then
local name = source[1]
return 'dsn:' .. name, nil
elseif source.type == 'doc.class' then
return 'dc:' .. source.start
elseif source.type == 'doc.type' then
return 'dt:' .. source.start
elseif source.type == 'doc.param' then
return 'dp:' .. source.start
elseif source.type == 'doc.vararg' then
return 'dv:' .. source.start
elseif source.type == 'doc.field.name' then
return 'dfn:' .. source.start
elseif source.type == 'doc.type.enum'
or source.type == 'doc.resume' then
return 'de:' .. source.start
elseif source.type == 'doc.type.table' then
return 'dtable:' .. source.start
elseif source.type == 'doc.type.ltable' then
return 'dltable:' .. source.start
elseif source.type == 'doc.type.field' then
return 'dfield:' .. source.start
elseif source.type == 'doc.type.array' then
return 'darray:' .. source.finish
elseif source.type == 'doc.type.function' then
return 'dfun:' .. source.start, nil
elseif source.type == 'doc.see.field' then
return ('%q'):format(source[1]), source.parent.name
elseif source.type == 'generic.closure' then
return 'gc:' .. source.call.start, nil
elseif source.type == 'generic.value' then
local tail = ''
if guide.getUri(source.closure.call) ~= guide.getUri(source.proto) then
tail = URI_CHAR .. guide.getUri(source.closure.call)
end
return ('gv:%s|%s%s'):format(
source.closure.call.start,
getKey(source.proto),
tail
)
end
return nil, nil
end
local function getNodeKey(source)
if source.type == 'getlocal'
or source.type == 'setlocal' then
source = source.node
end
local methodNode = getMethodNode(source)
if methodNode then
return getNodeKey(methodNode)
end
local key, node = getKey(source)
if key and guide.isGlobal(source) then
return 'g:' .. key, nil
end
return key, node
end
local IDList = {}
---获取语法树单元的字符串ID
---@param source parser.guide.object
---@return string? id
local function getID(source)
if not source then
return nil
end
if source._id ~= nil then
return source._id or nil
end
if source.type == 'field'
or source.type == 'method' then
source._id = false
return nil
end
local current = source
local index = 0
while true do
if current.type == 'paren' then
current = current.exp
if not current then
return nil
end
goto CONTINUE
end
local id, node = getNodeKey(current)
if not id then
break
end
index = index + 1
IDList[index] = id
if not node then
break
end
current = node
::CONTINUE::
end
if index == 0 then
source._id = false
return nil
end
for i = index + 1, #IDList do
IDList[i] = nil
end
util.revertTable(IDList)
local id = table.concat(IDList, SPLIT_CHAR)
source._id = id
return id
end
---添加关联的前进ID
---@param noders noders
---@param id string
---@param forwardID string
---@param info? node.info
local function pushForward(noders, id, forwardID, info)
if not id
or not forwardID
or forwardID == ''
or id == forwardID then
return
end
local node = getNode(noders, id)
if not node.forward then
node.forward = forwardID
node.finfo = info
return
end
if node.forward == forwardID then
return
end
if not node.forwards then
node.forwards = {}
end
if node.forwards[forwardID] ~= nil then
return
end
node.forwards[forwardID] = info or false
node.forwards[#node.forwards+1] = forwardID
end
---添加关联的后退ID
---@param noders noders
---@param id string
---@param backwardID string
---@param info? node.info
local function pushBackward(noders, id, backwardID, info)
if not id
or not backwardID
or backwardID == ''
or id == backwardID then
return
end
local node = getNode(noders, id)
if not node.backward then
node.backward = backwardID
node.binfo = info
return
end
if node.backward == backwardID then
return
end
if not node.backwards then
node.backwards = {}
end
if node.backwards[backwardID] ~= nil then
return
end
node.backwards[backwardID] = info or false
node.backwards[#node.backwards+1] = backwardID
end
---@class noder
local m = {}
m.SPLIT_CHAR = SPLIT_CHAR
m.RETURN_INDEX = RETURN_INDEX
m.PARAM_INDEX = PARAM_INDEX
m.TABLE_KEY = TABLE_KEY
m.ANY_FIELD = ANY_FIELD
m.URI_CHAR = URI_CHAR
m.INDEX_FIELD = INDEX_FIELD
m.WEAK_TABLE_KEY = WEAK_TABLE_KEY
m.WEAK_ANY_FIELD = WEAK_ANY_FIELD
--- 寻找doc的主体
---@param obj parser.guide.object
---@return parser.guide.object
local function getDocStateWithoutCrossFunction(obj)
for _ = 1, 1000 do
local parent = obj.parent
if not parent then
return obj
end
if parent.type == 'doc' then
return obj
end
if parent.type == 'doc.type.function' then
return nil
end
obj = parent
end
error('guide.getDocState overstack')
end
---添加关联单元
---@param noders noders
---@param source parser.guide.object
function m.pushSource(noders, source, id)
id = id or m.getID(source)
if not id then
return
end
if id == 'str:'
or id == 'nil:'
or id == 'num:'
or id == 'int:'
or id == 'bool:' then
return
end
local node = getNode(noders, id)
if not node.source then
node.source = source
return
end
if not node.sources then
node.sources = {}
end
node.sources[#node.sources+1] = source
end
local DUMMY_FUNCTION = function () end
---遍历关联单元
---@param node node
---@return fun():parser.guide.object
function m.eachSource(node)
if not node.source then
return DUMMY_FUNCTION
end
local index
local sources = node.sources
return function ()
if not index then
index = 0
return node.source
end
if not sources then
return nil
end
index = index + 1
return sources[index]
end
end
---遍历forward
---@param node node
---@return fun():string, string
function m.eachForward(node)
if not node.forward then
return DUMMY_FUNCTION
end
local index
local forwards = node.forwards
return function ()
if not index then
index = 0
return node.forward, node.finfo
end
if not forwards then
return nil
end
index = index + 1
local id = forwards[index]
local tag = forwards[id]
return id, tag
end
end
---遍历backward
---@param node node
---@return fun():string, node.info
function m.eachBackward(node)
if not node.backward then
return DUMMY_FUNCTION
end
local index
local backwards = node.backwards
return function ()
if not index then
index = 0
return node.backward, node.binfo
end
if not backwards then
return nil
end
index = index + 1
local id = backwards[index]
local tag = backwards[id]
return id, tag
end
end
local function bindValue(noders, source, id)
local value = source.value
if not value then
return
end
local valueID = getID(value)
if not valueID then
return
end
if source.type == 'getlocal'
or source.type == 'setlocal' then
source = source.node
end
if source.bindDocs and value.type ~= 'table' then
for _, doc in ipairs(source.bindDocs) do
if doc.type == 'doc.class'
or doc.type == 'doc.type' then
return
end
end
end
-- x = y : x -> y
pushForward(noders, id, valueID, {
reject = 'set',
})
-- 参数/call禁止反向查找赋值
local valueType = valueID:match '^(.-:).'
if not valueType then
return
end
if valueType ~= 'p:'
and valueType ~= 's:'
and valueType ~= 'c:' then
pushBackward(noders, valueID, id, {
reject = 'set',
})
else
pushBackward(noders, valueID, id, {
reject = 'set',
deep = true,
})
end
end
local function compileCallParam(noders, call, sourceID)
if not sourceID then
return
end
if not call.args then
return
end
local node = call.node
local fixIndex = 0
if call.node.special == 'pcall' then
fixIndex = 1
node = call.args[1]
elseif call.node.special == 'xpcall' then
fixIndex = 2
node = call.args[1]
end
local nodeID = getID(node)
if not nodeID then
return
end
for firstIndex, callArg in ipairs(call.args) do
firstIndex = firstIndex - fixIndex
if firstIndex > 0 and callArg.type == 'function' then
if callArg.args then
for secondIndex, funcParam in ipairs(callArg.args) do
local paramID = ('%s%s%s%s%s'):format(
nodeID,
PARAM_INDEX,
firstIndex,
PARAM_INDEX,
secondIndex
)
pushForward(noders, getID(funcParam), paramID)
end
end
end
end
end
local function compileCallReturn(noders, call, sourceID, returnIndex)
if not sourceID then
return
end
local node = call.node
local nodeID = getID(node)
if not nodeID then
return
end
local callID = getID(call)
if not callID then
return
end
-- 将setmetatable映射到 param1 以及 param2.__index 上
if node.special == 'setmetatable' then
local tblID = getID(call.args and call.args[1])
local metaID = getID(call.args and call.args[2])
local indexID
if metaID then
indexID = ('%s%s%q'):format(
metaID,
SPLIT_CHAR,
'__index'
)
end
pushForward(noders, sourceID, tblID)
pushForward(noders, sourceID, indexID, {
filter = function (id, field)
if field then
return true
end
return id:sub(1, 2) ~= 'f:'
end,
filterValid = function (id, field)
return not field
end
})
pushBackward(noders, tblID, sourceID)
--pushBackward(noders, indexID, callID)
return
end
if node.special == 'require' then
local arg1 = call.args and call.args[1]
if arg1 and arg1.type == 'string' then
getNode(noders, sourceID).require = arg1[1]
end
pushBackward(noders, callID, sourceID, {
deep = true,
})
return
end
if node.special == 'pcall'
or node.special == 'xpcall' then
local index = returnIndex - 1
if index <= 0 then
return
end
local funcID = call.args and getID(call.args[1])
if not funcID then
return
end
local pfuncXID = ('%s%s%s'):format(
funcID,
RETURN_INDEX,
index
)
pushForward(noders, sourceID, pfuncXID)
pushBackward(noders, pfuncXID, sourceID, {
deep = true,
})
return
end
local funcXID = ('%s%s%s'):format(
nodeID,
RETURN_INDEX,
returnIndex
)
getNode(noders, sourceID).call = call
pushForward(noders, sourceID, funcXID)
pushBackward(noders, funcXID, sourceID, {
deep = true,
})
end
function m.compileDocValue(noders, tp, id, source)
if tp == 'doc.type' then
if source.bindSources then
for _, src in ipairs(source.bindSources) do
pushForward(noders, getID(src), id)
pushForward(noders, id, getID(src))
end
end
for _, enumUnit in ipairs(source.enums) do
pushForward(noders, id, getID(enumUnit))
end
for _, resumeUnit in ipairs(source.resumes) do
pushForward(noders, id, getID(resumeUnit))
end
for _, typeUnit in ipairs(source.types) do
local unitID = getID(typeUnit)
pushForward(noders, id, unitID)
if source.bindSources then
for _, src in ipairs(source.bindSources) do
pushBackward(noders, unitID, getID(src))
end
end
end
end
if tp == 'doc.type.table' then
if source.tkey then
local keyID = ('%s%s'):format(
id,
TABLE_KEY
)
pushForward(noders, keyID, getID(source.tkey))
end
if source.tvalue then
local valueID = ('%s%s'):format(
id,
ANY_FIELD
)
pushForward(noders, valueID, getID(source.tvalue))
end
end
if tp == 'doc.type.ltable' then
local firstField = source.fields[1]
if not firstField then
return
end
local keyID = ('%s%s'):format(
id,
WEAK_TABLE_KEY
)
local valueID = ('%s%s'):format(
id,
WEAK_ANY_FIELD
)
pushForward(noders, keyID, 'dn:string')
pushForward(noders, valueID, getID(firstField.extends))
for _, field in ipairs(source.fields) do
local extendsID = ('%s%s%q'):format(
id,
SPLIT_CHAR,
field.name[1]
)
pushForward(noders, extendsID, getID(field))
pushForward(noders, extendsID, getID(field.extends))
end
end
if tp == 'doc.type.array' then
if source.node then
local nodeID = ('%s%s'):format(
id,
ANY_FIELD
)
pushForward(noders, nodeID, getID(source.node))
end
local keyID = ('%s%s'):format(
id,
TABLE_KEY
)
pushForward(noders, keyID, 'dn:integer')
end
end
---@param noders noders
---@param source parser.guide.object
---@return parser.guide.object[]
function m.compileNode(noders, source)
local id = getID(source)
bindValue(noders, source, id)
if source.special == 'setmetatable'
or source.special == 'require'
or source.special == 'dofile'
or source.special == 'loadfile'
or source.special == 'rawset'
or source.special == 'rawget' then
local node = getNode(noders, id)
node.skip = true
end
if source.type == 'string' then
pushForward(noders, id, 'str:')
end
if source.type == 'boolean' then
pushForward(noders, id, 'dn:boolean')
end
if source.type == 'number' then
pushForward(noders, id, 'dn:number')
end
if source.type == 'integer' then
pushForward(noders, id, 'dn:integer')
end
if source.type == 'nil' then
pushForward(noders, id, 'dn:nil')
end
-- self -> mt:xx
if source.type == 'local' and source[1] == 'self' then
local func = guide.getParentFunction(source)
if func.isGeneric then
return
end
if source.parent.type ~= 'funcargs' then
return
end
local setmethod = func.parent
-- guess `self`
if setmethod and ( setmethod.type == 'setmethod'
or setmethod.type == 'setfield'
or setmethod.type == 'setindex') then
pushForward(noders, id, getID(setmethod.node))
pushBackward(noders, getID(setmethod.node), id, {
deep = true,
})
end
end
-- 分解 @type
--if source.type == 'doc.type' then
-- if source.bindSources then
-- for _, src in ipairs(source.bindSources) do
-- pushForward(noders, getID(src), id)
-- pushForward(noders, id, getID(src))
-- end
-- end
-- for _, enumUnit in ipairs(source.enums) do
-- pushForward(noders, id, getID(enumUnit))
-- end
-- for _, resumeUnit in ipairs(source.resumes) do
-- pushForward(noders, id, getID(resumeUnit))
-- end
-- for _, typeUnit in ipairs(source.types) do
-- local unitID = getID(typeUnit)
-- pushForward(noders, id, unitID)
-- if source.bindSources then
-- for _, src in ipairs(source.bindSources) do
-- pushBackward(noders, unitID, getID(src))
-- end
-- end
-- end
--end
-- 分解 @alias
if source.type == 'doc.alias' then
pushForward(noders, getID(source.alias), getID(source.extends))
end
-- 分解 @class
if source.type == 'doc.class' then
pushForward(noders, id, getID(source.class))
pushForward(noders, getID(source.class), id)
if source.extends then
for _, ext in ipairs(source.extends) do
pushBackward(noders, id, getID(ext))
end
end
if source.bindSources then
for _, src in ipairs(source.bindSources) do
pushForward(noders, getID(src), id)
pushForward(noders, id, getID(src))
end
end
for _, field in ipairs(source.fields) do
local key = field.field[1]
if key then
local keyID = ('%s%s%q'):format(
id,
SPLIT_CHAR,
key
)
pushForward(noders, keyID, getID(field.field))
pushForward(noders, getID(field.field), keyID)
pushForward(noders, keyID, getID(field.extends))
pushBackward(noders, getID(field.extends), keyID)
end
end
end
if source.type == 'doc.param' then
pushForward(noders, id, getID(source.extends))
for _, src in ipairs(source.bindSources) do
if src.type == 'local' and src.parent.type == 'in' then
pushForward(noders, getID(src), id)
end
end
end
if source.type == 'doc.vararg' then
pushForward(noders, getID(source), getID(source.vararg))
end
if source.type == 'doc.see' then
local nameID = getID(source.name)
local classID = nameID:gsub('^dsn:', 'dn:')
pushForward(noders, nameID, classID)
if source.field then
local fieldID = getID(source.field)
local fieldClassID = fieldID:gsub('^dsn:', 'dn:')
pushForward(noders, fieldID, fieldClassID)
end
end
m.compileDocValue(noders, source.type, id, source)
if source.type == 'call' then
if source.parent.type ~= 'select' then
compileCallReturn(noders, source, id, 1)
end
compileCallParam(noders, source, id)
end
if source.type == 'select' then
if source.vararg.type == 'call' then
local call = source.vararg
compileCallReturn(noders, call, id, source.sindex)
end
if source.vararg.type == 'varargs' then
pushForward(noders, id, getID(source.vararg))
end
end
if source.type == 'doc.type.function' then
if source.returns then
for index, rtn in ipairs(source.returns) do
local returnID = ('%s%s%s'):format(
id,
RETURN_INDEX,
index
)
pushForward(noders, returnID, getID(rtn))
end
for index, param in ipairs(source.args) do
local paramID = ('%s%s%s'):format(
id,
PARAM_INDEX,
index
)
pushForward(noders, paramID, getID(param.extends))
end
end
-- @type fun(x: T):T 的情况
local docType = getDocStateWithoutCrossFunction(source)
if docType and docType.type == 'doc.type' then
guide.eachSourceType(source, 'doc.type.name', function (typeName)
if typeName.typeGeneric then
source.isGeneric = true
return false
end
end)
end
end
if source.type == 'doc.type.name' then
local uri = guide.getUri(source)
collector.subscribe(uri, id, getNode(noders, id))
end
if source.type == 'doc.class.name'
or source.type == 'doc.alias.name' then
local uri = guide.getUri(source)
collector.subscribe(uri, id, getNode(noders, id))
local defID = 'def:' .. id
collector.subscribe(uri, defID, getNode(noders, defID))
m.pushSource(noders, source, defID)
local defAnyID = 'def:dn:'
collector.subscribe(uri, defAnyID, getNode(noders, defAnyID))
m.pushSource(noders, source, defAnyID)
end
if id and id:sub(1, 2) == 'g:' then
local uri = guide.getUri(source)
collector.subscribe(uri, id, getNode(noders, id))
if guide.isSet(source) then
local defID = 'def:' .. id
collector.subscribe(uri, defID, getNode(noders, defID))
m.pushSource(noders, source, defID)
if guide.isGlobal(source) then
local defAnyID = 'def:g:'
collector.subscribe(uri, defAnyID, getNode(noders, defAnyID))
m.pushSource(noders, source, defAnyID)
end
end
end
-- 将函数的返回值映射到具体的返回值上
if source.type == 'function' then
local hasDocReturn = {}
-- 检查 luadoc
if source.bindDocs then
for _, doc in ipairs(source.bindDocs) do
if doc.type == 'doc.return' then
for _, rtn in ipairs(doc.returns) do
local fullID = ('%s%s%s'):format(
id,
RETURN_INDEX,
rtn.returnIndex
)
pushForward(noders, fullID, getID(rtn))
for _, typeUnit in ipairs(rtn.types) do
pushBackward(noders, getID(typeUnit), fullID, {
deep = true,
dontCross = true,
})
end
hasDocReturn[rtn.returnIndex] = true
end
end
if doc.type == 'doc.param' then
local paramName = doc.param[1]
if source.docParamMap then
local paramIndex = source.docParamMap[paramName]
local param = source.args[paramIndex]
if param then
pushForward(noders, getID(param), getID(doc))
param.docParam = doc
local paramID = ('%s%s%s'):format(
id,
PARAM_INDEX,
paramIndex
)
pushForward(noders, paramID, getID(doc.extends))
end
end
end
if doc.type == 'doc.vararg' then
if source.args then
for _, param in ipairs(source.args) do
if param.type == '...' then
pushForward(noders, getID(param), getID(doc))
end
end
end
end
if doc.type == 'doc.generic' then
source.isGeneric = true
end
if doc.type == 'doc.overload' then
pushForward(noders, id, getID(doc.overload))
end
end
end
-- 检查实体返回值
if source.returns then
local returns = {}
for _, rtn in ipairs(source.returns) do
for index, rtnObj in ipairs(rtn) do
if not hasDocReturn[index] then
if not returns[index] then
returns[index] = {}
end
returns[index][#returns[index]+1] = rtnObj
end
end
end
for index, rtnObjs in ipairs(returns) do
local returnID = ('%s%s%s'):format(
id,
RETURN_INDEX,
index
)
for _, rtnObj in ipairs(rtnObjs) do
pushForward(noders, returnID, getID(rtnObj))
pushBackward(noders, getID(rtnObj), returnID, {
deep = true,
dontCross = true,
})
end
end
end
end
if source.type == 'table' then
local firstField = source[1]
if firstField then
if firstField.type == 'varargs' then
local keyID = ('%s%s'):format(
id,
TABLE_KEY
)
local valueID = ('%s%s'):format(
id,
ANY_FIELD
)
source.array = firstField
pushForward(noders, keyID, 'dn:integer')
pushForward(noders, valueID, getID(firstField))
else
local keyID = ('%s%s'):format(
id,
WEAK_TABLE_KEY
)
local valueID = ('%s%s'):format(
id,
WEAK_ANY_FIELD
)
if firstField.type == 'tablefield' then
pushForward(noders, keyID, 'dn:string')
pushForward(noders, valueID, getID(firstField.value))
elseif firstField.type == 'tableindex' then
pushForward(noders, keyID, getID(firstField.index))
pushForward(noders, valueID, getID(firstField.value))
elseif firstField.type == 'tableexp' then
pushForward(noders, keyID, 'dn:integer')
pushForward(noders, valueID, getID(firstField))
end
end
end
end
if source.type == 'main' then
if source.returns then
for _, rtn in ipairs(source.returns) do
local rtnObj = rtn[1]
if rtnObj then
pushForward(noders, 'mainreturn', getID(rtnObj))
pushBackward(noders, getID(rtnObj), 'mainreturn', {
deep = true,
})
end
end
end
end
if source.type == 'generic.closure' then
for i, rtn in ipairs(source.returns) do
local closureID = ('%s%s%s'):format(
id,
RETURN_INDEX,
i
)
local returnID = getID(rtn)
pushForward(noders, closureID, returnID)
end
end
if source.type == 'generic.value' then
local proto = source.proto
local closure = source.closure
local upvalues = closure.upvalues
if proto.type == 'doc.type.name' then
local key = proto[1]
if upvalues[key] then
for _, paramID in ipairs(upvalues[key]) do
pushForward(noders, id, paramID)
pushBackward(noders, paramID, id)
end
end
end
--if proto.type == 'doc.type' then
-- for _, tp in ipairs(source.types) do
-- pushForward(noders, id, getID(tp))
-- pushBackward(noders, getID(tp), id)
-- end
--end
m.compileDocValue(noders, proto.type, id, source)
end
end
---根据ID来获取所有的node
---@param root parser.guide.object
---@param id string
---@return node?
function m.getNodeByID(root, id)
root = guide.getRoot(root)
local noders = root._noders
if not noders then
return nil
end
return noders[id]
end
---根据ID来获取第一个节点的ID
---@param id string
---@return string
function m.getFirstID(id)
local firstID, count = id:match(FIRST_REGEX)
if count == 0 then
return nil
end
if firstID == '' then
return nil
end
return firstID
end
---根据ID来获取第一个节点的ID或field
---@param id string
---@return string
function m.getHeadID(id)
local headID, count = id:match(HEAD_REGEX)
if count == 0 then
return nil
end
if headID == '' then
return nil
end
return headID
end
---根据ID来获取上个节点的ID
---@param id string
---@return string
function m.getLastID(id)
local lastID, count = id:gsub(LAST_REGEX, '')
if count == 0 then
return nil
end
if lastID == '' then
return nil
end
return lastID
end
---获取ID的长度
---@param id string
---@return integer
function m.getIDLength(id)
if not id then
return 0
end
local _, count = id:gsub(SPLIT_CHAR, SPLIT_CHAR)
return count + 1
end
---测试id是否包含field,如果遇到函数调用则中断
---@param id string
---@return boolean
function m.hasField(id)
local firstID = m.getFirstID(id)
if firstID == id or not firstID then
return false
end
local nextChar = id:sub(#firstID + 1, #firstID + 1)
if nextChar ~= SPLIT_CHAR then
return false
end
local next2Char = id:sub(#firstID + 2, #firstID + 2)
if next2Char == RETURN_INDEX
or next2Char == PARAM_INDEX then
return false
end
return true
end
---把形如 `@file:\\\XXXXX@gv:1|1`拆分成uri与id
---@param id string
---@return uri? string
---@return string id
function m.getUriAndID(id)
local uri, newID = id:match(URI_REGEX)
return uri, newID
end
---是否是普通的field,例如数字或字符串,而不是函数返回值等
---@param field any
function m.isCommonField(field)
if not field then
return false
end
if field:sub(1, #RETURN_INDEX) == RETURN_INDEX then
return false
end
if field:sub(1, #PARAM_INDEX) == PARAM_INDEX then
return false
end
return true
end
---获取source的ID
---@param source parser.guide.object
---@return string
function m.getID(source)
return getID(source)
end
---获取source的key
---@param source parser.guide.object
---@return string
function m.getKey(source)
return getKey(source)
end
---清除临时id(用于泛型的临时对象)
---@param root parser.guide.object
---@param id string
function m.removeID(root, id)
if not id then
return
end
root = guide.getRoot(root)
local noders = root._noders
noders[id] = nil
end
---寻找doc的主体
---@param doc parser.guide.object
function m.getDocState(doc)
return getDocStateWithoutCrossFunction(doc)
end
---获取对象的noders
---@param source parser.guide.object
---@return noders
function m.getNoders(source)
local root = guide.getRoot(source)
if not root._noders then
root._noders = {}
end
return root._noders
end
---编译整个文件的node
---@param source parser.guide.object
---@return table
function m.compileNodes(source)
local root = guide.getRoot(source)
local noders = m.getNoders(source)
if next(noders) then
return noders
end
log.debug('compileNodes:', guide.getUri(root))
collector.dropUri(guide.getUri(root))
guide.eachSource(root, function (src)
m.pushSource(noders, src)
m.compileNode(noders, src)
end)
log.debug('compileNodes finish:', guide.getUri(root))
return noders
end
files.watch(function (ev, uri)
uri = files.asKey(uri)
if ev == 'update' then
local state = files.getState(uri)
if state then
m.compileNodes(state.ast)
end
end
if ev == 'remove' then
collector.dropUri(uri)
end
end)
return m
<file_sep>local execute = vim.api.nvim_command
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path})
execute 'packadd packer.nvim'
end
return require('packer').startup(function()
-- Packer can manage itself
use 'wbthomason/packer.nvim'
-- You can alias plugin names
use {'dracula/vim', as = 'dracula'}
use {
'kyazdani42/nvim-tree.lua',
requires = 'kyazdani42/nvim-web-devicons'
}
use 'kyazdani42/nvim-web-devicons'
use {
'glepnir/galaxyline.nvim',
branch = 'main',
-- your statusline
-- config = function() require'my_statusline' end,
-- some optional icons
requires = {'kyazdani42/nvim-web-devicons', opt = true}
}
use 'hrsh7th/nvim-compe'
end)
<file_sep>local util = require "util"
local globals = require "globals"
util.cmd_init(true)
if globals.compiler == "msvc" then
local msvc = require "msvc_util"
if msvc.hasEnvConfig() then
util.cmd_clean()
msvc.cleanEnvConfig()
else
local fs = require "bee.filesystem"
pcall(fs.remove_all, fs.path(globals.builddir))
end
else
util.cmd_clean()
end
<file_sep>local globals = require "globals"
local sp = require 'bee.subprocess'
local thread = require 'bee.thread'
local function ninja(args)
if globals.compiler == 'msvc' then
local msvc = require "msvc_util"
if args.env then
for k, v in pairs(msvc.getEnv()) do
args.env[k] = v
end
else
args.env = msvc.getEnv()
end
args.env.VS_UNICODE_OUTPUT = false
args.searchPath = true
table.insert(args, 1, {'cmd', '/c', 'ninja'})
else
args.searchPath = true
table.insert(args, 1, 'ninja')
end
table.insert(args, 2, "-f")
table.insert(args, 3, WORKDIR / globals.builddir / "build.ninja")
args.stdout = true
args.stderr = "stdout"
args.cwd = WORKDIR
local process = assert(sp.spawn(args))
while true do
local n = sp.peek(process.stdout)
if n == nil then
local s = process.stdout:read "a"
if s then
io.write(s)
io.flush()
end
break
end
if n > 0 then
io.write(process.stdout:read(n))
io.flush()
else
thread.sleep(1)
end
end
local code = process:wait()
if code ~= 0 then
os.exit(code, true)
end
end
local function command(what, ...)
local path = assert(package.searchpath(what, (MAKEDIR / "scripts" / "command" / "?.lua"):string()))
assert(loadfile(path))(...)
end
local function sandbox(filename, ...)
assert(require "sandbox"{
root = WORKDIR:string(),
main = filename,
io_open = io.open,
preload = globals.compiler == 'msvc' and {
msvc = require "msvc",
},
builddir = globals.builddir,
})(...)
end
local function cmd_init(dontgenerate)
local sim = require 'simulator'
sim:dofile(WORKDIR / "make.lua")
if not dontgenerate then
sim:finish()
end
end
local function cmd_make()
local arguments = require "arguments"
ninja(arguments.targets)
end
local function cmd_clean()
ninja { "-t", "clean" }
end
return {
command = command,
sandbox = sandbox,
cmd_init = cmd_init,
cmd_make = cmd_make,
cmd_clean = cmd_clean,
}
<file_sep>local noder = require 'core.noder'
local guide = require 'parser.guide'
local files = require 'files'
local generic = require 'core.generic'
local ws = require 'workspace'
local vm = require 'vm.vm'
local collector = require 'core.collector'
local ignoredSources = {
['int:'] = true,
['num:'] = true,
['str:'] = true,
['bool:'] = true,
['nil:'] = true,
}
local ignoredIDs = {
['dn:unknown'] = true,
['dn:nil'] = true,
['dn:any'] = true,
['dn:boolean'] = true,
['dn:table'] = true,
['dn:number'] = true,
['dn:integer'] = true,
['dn:userdata'] = true,
['dn:lightuserdata'] = true,
['dn:function'] = true,
['dn:thread'] = true,
}
local m = {}
---@alias guide.searchmode '"ref"'|'"def"'|'"field"'|'"allref"'|'"alldef"'
---添加结果
---@param status guide.status
---@param mode guide.searchmode
---@param source parser.guide.object
---@param force boolean
function m.pushResult(status, mode, source, force)
if not source then
return
end
local results = status.results
local mark = status.rmark
if mark[source] then
return
end
mark[source] = true
if force then
results[#results+1] = source
return
end
local parent = source.parent
if mode == 'def' or mode == 'alldef' then
if source.type == 'local'
or source.type == 'setlocal'
or source.type == 'setglobal'
or source.type == 'label'
or source.type == 'setfield'
or source.type == 'setmethod'
or source.type == 'setindex'
or source.type == 'tableindex'
or source.type == 'tablefield'
or source.type == 'tableexp'
or source.type == 'function'
or source.type == 'table'
or source.type == 'doc.class.name'
or source.type == 'doc.alias.name'
or source.type == 'doc.field.name'
or source.type == 'doc.type.enum'
or source.type == 'doc.resume'
or source.type == 'doc.type.array'
or source.type == 'doc.type.table'
or source.type == 'doc.type.ltable'
or source.type == 'doc.type.field'
or source.type == 'doc.type.function' then
results[#results+1] = source
return
end
if source.type == 'call' then
if source.node.special == 'rawset' then
results[#results+1] = source
end
end
if parent.type == 'return' then
if noder.getID(source) ~= status.id then
results[#results+1] = source
end
end
elseif mode == 'ref' or mode == 'field' or mode == 'allref' then
if source.type == 'local'
or source.type == 'setlocal'
or source.type == 'getlocal'
or source.type == 'setglobal'
or source.type == 'getglobal'
or source.type == 'label'
or source.type == 'goto'
or source.type == 'setfield'
or source.type == 'getfield'
or source.type == 'setmethod'
or source.type == 'getmethod'
or source.type == 'setindex'
or source.type == 'getindex'
or source.type == 'tableindex'
or source.type == 'tablefield'
or source.type == 'tableexp'
or source.type == 'function'
or source.type == 'table'
or source.type == 'string'
or source.type == 'boolean'
or source.type == 'number'
or source.type == 'integer'
or source.type == 'nil'
or source.type == 'doc.class.name'
or source.type == 'doc.type.name'
or source.type == 'doc.alias.name'
or source.type == 'doc.extends.name'
or source.type == 'doc.field.name'
or source.type == 'doc.type.enum'
or source.type == 'doc.resume'
or source.type == 'doc.type.array'
or source.type == 'doc.type.table'
or source.type == 'doc.type.ltable'
or source.type == 'doc.type.field'
or source.type == 'doc.type.function' then
results[#results+1] = source
return
end
if source.type == 'call' then
if source.node.special == 'rawset'
or source.node.special == 'rawget' then
results[#results+1] = source
end
end
if parent.type == 'return' then
if noder.getID(source) ~= status.id then
results[#results+1] = source
end
end
end
end
---获取uri
---@param obj parser.guide.object
---@return uri
function m.getUri(obj)
if obj.uri then
return obj.uri
end
local root = guide.getRoot(obj)
if root then
return root.uri
end
return ''
end
---@param obj parser.guide.object
---@return parser.guide.object?
function m.getObjectValue(obj)
while obj.type == 'paren' do
obj = obj.exp
if not obj then
return nil
end
end
if obj.type == 'boolean'
or obj.type == 'number'
or obj.type == 'integer'
or obj.type == 'string' then
return obj
end
if obj.value then
return obj.value
end
if obj.type == 'field'
or obj.type == 'method' then
return obj.parent and obj.parent.value
end
if obj.type == 'call' then
if obj.node.special == 'rawset' then
return obj.args and obj.args[3]
else
return obj
end
end
if obj.type == 'select' then
return obj
end
return nil
end
local function checkLock(status, k1, k2)
local locks = status.lock
local lock1 = locks[k1]
if not lock1 then
lock1 = {}
locks[k1] = lock1
end
if lock1[''] then
return true
end
if k2 == nil then
k2 = ''
end
if lock1[k2] then
return true
end
lock1[k2] = true
return false
end
local strs = {}
local function footprint(status, ...)
if TRACE then
log.debug(...)
end
if FOOTPRINT then
local n = select('#', ...)
for i = 1, n do
strs[i] = tostring(select(i, ...))
end
status.footprint[#status.footprint+1] = table.concat(strs, '\t', 1, n)
end
end
local function crossSearch(status, uri, expect, mode, sourceUri)
if status.dontCross > 0 then
return
end
if checkLock(status, uri, expect) then
return
end
footprint(status, 'crossSearch', uri, expect)
m.searchRefsByID(status, uri, expect, mode)
--status.lock[uri] = nil
footprint(status, 'crossSearch finish, back to:', sourceUri)
end
local function checkCache(status, uri, expect, mode)
local cache = vm.getCache('search:' .. mode)
local fileCache = cache[uri]
if not fileCache then
fileCache = {}
cache[uri] = fileCache
end
if fileCache[expect] then
for _, res in ipairs(fileCache[expect]) do
m.pushResult(status, mode, res, true)
end
return true
end
fileCache[expect] = status.results
return false
end
local function stop(status, msg)
if TEST then
if FOOTPRINT then
log.debug(table.concat(status.footprint, '\n'))
end
error(msg)
else
log.warn(msg)
if FOOTPRINT then
log.debug(table.concat(status.footprint, '\n'))
end
return
end
end
local function checkSLock(status, slock, id, field)
if noder.getIDLength(id) > 20 then
stop(status, 'too long!')
return false
end
local cmark = slock[id]
if not cmark then
cmark = {}
slock[id] = {}
end
if cmark[field or ''] then
return false
end
cmark[field or ''] = true
local right = ''
while field and field ~= '' do
local lastID = noder.getLastID(field)
if not lastID then
break
end
right = lastID .. right
if cmark[right] then
return false
end
field = field:sub(1, - #lastID - 1)
end
return true
end
local function isCallID(field)
if not field then
return false
end
if field:sub(1, 2) == noder.RETURN_INDEX then
return true
end
return false
end
function m.searchRefsByID(status, uri, expect, mode)
local ast = files.getState(uri)
if not ast then
return
end
local root = ast.ast
local searchStep
noder.compileNodes(root)
status.id = expect
local callStack = status.callStack
local slock = status.slock[uri] or {}
local elock = status.elock[uri] or {}
status.slock[uri] = slock
status.elock[uri] = elock
local function search(id, field)
local firstID = noder.getFirstID(id)
if ignoredIDs[firstID] and (field or firstID ~= id) then
return
end
if not checkSLock(status, slock, id, field) then
footprint(status, 'slocked:', id, field)
return
end
footprint(status, 'search:', id, field)
searchStep(id, field)
footprint(status, 'pop:', id, field)
end
local function splitID(id, field)
if field then
return
end
local leftID = ''
local rightID
while true do
local firstID = noder.getHeadID(rightID or id)
if not firstID or firstID == id then
return
end
leftID = leftID .. firstID
if leftID == id then
return
end
rightID = id:sub(#leftID + 1)
search(leftID, rightID)
local isCall = isCallID(firstID)
if isCall then
break
end
end
end
local function searchID(id, field)
if not id then
return
end
if field then
id = id .. field
end
search(id, nil)
end
---@return parser.guide.object?
local function findLastCall()
for i = #callStack, 1, -1 do
local call = callStack[i]
if call then
-- 标记此处的call失效,等待在堆栈平衡时弹出
callStack[i] = false
return call
end
end
return nil
end
local genericCallArgs = {}
local closureCache = {}
local function checkGeneric(source, field)
if not source.isGeneric then
return
end
if not isCallID(field) then
return
end
local call = findLastCall()
if not call then
return
end
if call.args then
for _, arg in ipairs(call.args) do
genericCallArgs[arg] = true
end
end
local cacheID = noder.getID(source) .. noder.getID(call)
local closure = closureCache[cacheID]
if closure == false then
return
end
if not closure then
closure = generic.createClosure(source, call)
closureCache[cacheID] = closure or false
if not closure then
return
end
end
local id = noder.getID(closure)
searchID(id, field)
end
local function checkENV(source, field)
if not field then
return
end
if source.special ~= '_G' then
return
end
local newID = 'g:' .. field:sub(2)
searchID(newID)
end
local freject = {}
local breject = {}
---@param ward '"forward"'|'"backward"'
---@param info node.info
local function checkThenPushReject(ward, info)
local reject = info.reject
if not reject then
return true
end
local checkReject
local pushReject
if ward == 'forward' then
checkReject = breject
pushReject = freject
else
checkReject = freject
pushReject = breject
end
if checkReject[reject] and checkReject[reject] > 0 then
return false
end
pushReject[reject] = (pushReject[reject] or 0) + 1
return true
end
---@param ward '"forward"'|'"backward"'
---@param info node.info
local function popReject(ward, info)
local reject = info.reject
if not reject then
return
end
local popTags
if ward == 'forward' then
popTags = freject
else
popTags = breject
end
popTags[reject] = popTags[reject] - 1
end
---@type table<node.filter, integer>
local filters = {}
---@param id string
---@param info node.info
local function pushInfoFilter(id, field, info)
local filter = info.filter
if not filter then
return
end
local filterValid = info.filterValid
if filterValid and not filterValid(id, field) then
return
end
filters[filter] = (filters[filter] or 0) + 1
end
---@param id string
---@param info node.info
local function releaseInfoFilter(id, field, info)
local filter = info.filter
if not filter then
return
end
local filterValid = info.filterValid
if filterValid and not filterValid(id, field) then
return
end
if filters[filter] <= 1 then
filters[filter] = nil
else
filters[filter] = filters[filter] - 1
end
end
---@param id string
---@param info node.info
local function checkInfoFilter(id, field, info)
for filter in pairs(filters) do
if not filter(id, field) then
return false
end
end
return true
end
---@param id string
---@param info node.info
local function checkInfoBeforeForward(id, field, info)
pushInfoFilter(id, field, info)
if not checkThenPushReject('forward', info) then
return false
end
return true
end
---@param id string
---@param info node.info
local function releaseInfoAfterForward(id, field, info)
popReject('forward', info)
releaseInfoFilter(id, field, info)
end
local function checkForward(id, node, field)
for forwardID, info in noder.eachForward(node) do
if info and not checkInfoBeforeForward(forwardID, field, info) then
goto CONTINUE
end
if not checkInfoFilter(forwardID, field, info) then
goto CONTINUE
end
local targetUri, targetID = noder.getUriAndID(forwardID)
if targetUri and not files.eq(targetUri, uri) then
crossSearch(status, targetUri, targetID .. (field or ''), mode, uri)
else
searchID(targetID or forwardID, field)
end
if info then
releaseInfoAfterForward(forwardID, field, info)
end
::CONTINUE::
end
end
---@param id string
---@param field string
---@param info node.info
local function checkInfoBeforeBackward(id, field, info)
if info.deep and mode ~= 'allref' then
return false
end
if not checkThenPushReject('backward', info) then
return false
end
pushInfoFilter(id, field, info)
if info.dontCross then
status.dontCross = status.dontCross + 1
end
return true
end
---@param id string
---@param field string
---@param info node.info
local function releaseInfoAfterBackward(id, field, info)
popReject('backward', info)
releaseInfoFilter(id, field, info)
if info.dontCross then
status.dontCross = status.dontCross - 1
end
end
local function checkBackward(id, node, field)
if ignoredIDs[id] then
return
end
if mode ~= 'ref' and mode ~= 'field' and mode ~= 'allref' and not field then
return
end
for backwardID, info in noder.eachBackward(node) do
if info and not checkInfoBeforeBackward(backwardID, field, info) then
goto CONTINUE
end
if not checkInfoFilter(backwardID, field, info) then
goto CONTINUE
end
local targetUri, targetID = noder.getUriAndID(backwardID)
if targetUri and not files.eq(targetUri, uri) then
crossSearch(status, targetUri, targetID .. (field or ''), mode, uri)
else
searchID(targetID or backwardID, field)
end
if info then
releaseInfoAfterBackward(backwardID, field, info)
end
::CONTINUE::
end
end
local function searchSpecial(id, field)
-- Special rule: ('').XX -> stringlib.XX
if id == 'str:'
or id == 'dn:string' then
if field or mode == 'field' then
searchID('dn:stringlib', field)
else
searchID('dn:string', field)
end
end
end
local function checkRequire(requireName, field)
local tid = 'mainreturn' .. (field or '')
local uris = ws.findUrisByRequirePath(requireName)
footprint(status, ('require %q:\n%s'):format(requireName, table.concat(uris, '\n')))
for _, ruri in ipairs(uris) do
if not files.eq(uri, ruri) then
crossSearch(status, ruri, tid, mode, uri)
end
end
end
local function searchGlobal(id, node, field)
if id:sub(1, 2) ~= 'g:' then
return
end
if checkLock(status, id, field) then
return
end
local tid = id .. (field or '')
footprint(status, ('checkGlobal:%s + %s'):format(id, field, tid))
local crossed = {}
if mode == 'def' or mode == 'alldef' then
for _, guri in collector.each('def:' .. id) do
if files.eq(uri, guri) then
goto CONTINUE
end
crossSearch(status, guri, tid, mode, uri)
::CONTINUE::
end
else
for _, guri in collector.each(id) do
if crossed[guri] then
goto CONTINUE
end
if mode == 'def' or mode == 'alldef' then
goto CONTINUE
end
if files.eq(uri, guri) then
goto CONTINUE
end
crossSearch(status, guri, tid, mode, uri)
::CONTINUE::
end
end
end
local function searchClass(id, node, field)
if id:sub(1, 3) ~= 'dn:' then
return
end
if checkLock(status, id, field) then
return
end
local tid = id .. (field or '')
local sid = id
if ignoredIDs[id]
or id == 'dn:string' then
sid = 'def:' .. sid
end
for _, guri in collector.each(sid) do
if not files.eq(uri, guri) then
crossSearch(status, guri, tid, mode, uri)
end
end
end
local function checkMainReturn(id, node, field)
if id ~= 'mainreturn' then
return
end
local calls = vm.getLinksTo(uri)
for _, call in ipairs(calls) do
local curi = guide.getUri(call)
local cid = ('%s%s'):format(
noder.getID(call),
field or ''
)
if not files.eq(curi, uri) then
crossSearch(status, curi, cid, mode, uri)
end
end
end
local function lockExpanding(id, field)
local locked = elock[id]
if locked and field then
if #locked <= #field then
if field:sub(-#locked) == locked then
footprint(status, 'elocked:', id, locked, field)
return false
end
end
end
elock[id] = field
return true
end
local function releaseExpanding(id, field)
elock[id] = nil
end
local function searchNode(id, node, field)
if node.call then
callStack[#callStack+1] = node.call
end
if field == nil and node.source and not ignoredSources[id] then
for source in noder.eachSource(node) do
local force = genericCallArgs[source]
m.pushResult(status, mode, source, force)
end
end
if node.require then
checkRequire(node.require, field)
end
if lockExpanding(id, field) then
if node.forward then
checkForward(id, node, field)
end
if node.backward then
checkBackward(id, node, field)
end
releaseExpanding(id, field)
end
if node.source then
checkGeneric(node.source, field)
checkENV(node.source, field)
end
if mode == 'allref' or mode == 'alldef' then
checkMainReturn(id, node, field)
end
if node.call then
callStack[#callStack] = nil
end
return false
end
local function searchAnyField(id, field)
if mode == 'ref' or mode == 'allref' then
return
end
local lastID = noder.getLastID(id)
if not lastID then
return
end
local originField = id:sub(#lastID + 1)
if originField == noder.TABLE_KEY
or originField == noder.WEAK_TABLE_KEY then
return
end
local anyFieldID = lastID .. noder.ANY_FIELD
local anyFieldNode = noder.getNodeByID(root, anyFieldID)
if anyFieldNode then
searchNode(anyFieldID, anyFieldNode, field)
end
end
local function searchWeak(id, field)
local lastID = noder.getLastID(id)
if not lastID then
return
end
local originField = id:sub(#lastID + 1)
if originField == noder.WEAK_TABLE_KEY then
local newID = lastID .. noder.TABLE_KEY
local newNode = noder.getNodeByID(root, newID)
if newNode then
searchNode(newID, newNode, field)
end
end
if originField == noder.WEAK_ANY_FIELD then
local newID = lastID .. noder.ANY_FIELD
local newNode = noder.getNodeByID(root, newID)
if newNode then
searchNode(newID, newNode, field)
end
end
end
local stepCount = 0
local stepMaxCount = 1e3
local statusMaxCount = 1e4
if mode == 'allref' or mode == 'alldef' then
stepMaxCount = 1e4
statusMaxCount = 1e5
end
function searchStep(id, field)
stepCount = stepCount + 1
status.count = status.count + 1
if stepCount > stepMaxCount
or status.count > statusMaxCount then
stop(status, 'too deep!')
return
end
searchSpecial(id, field)
local node = noder.getNodeByID(root, id)
if node then
searchNode(id, node, field)
if node.skip and field then
return
end
end
searchGlobal(id, node, field)
searchClass(id, node, field)
splitID(id, field)
searchAnyField(id, field)
searchWeak(id, field)
end
search(expect)
--清除来自泛型的临时对象
for _, closure in pairs(closureCache) do
noder.removeID(root, noder.getID(closure))
if closure then
for _, value in ipairs(closure.values) do
noder.removeID(root, noder.getID(value))
end
end
end
end
local function prepareSearch(source)
if not source then
return
end
if source.type == 'field'
or source.type == 'method' then
source = source.parent
end
if not source then
return
end
local root = guide.getRoot(source)
if not root then
return
end
noder.compileNodes(root)
local uri = guide.getUri(source)
local id = noder.getID(source)
return uri, id
end
local function getField(status, source, mode)
if source.type == 'table' then
for _, field in ipairs(source) do
m.pushResult(status, mode, field)
end
return
end
if source.type == 'doc.type.ltable' then
for _, field in ipairs(source.fields) do
m.pushResult(status, mode, field)
end
end
if source.type == 'doc.class.name' then
local class = source.parent
for _, field in ipairs(class.fields) do
m.pushResult(status, mode, field.field)
end
return
end
local field = source.next
if field then
if field.type == 'getmethod'
or field.type == 'setmethod'
or field.type == 'getfield'
or field.type == 'setfield'
or field.type == 'getindex'
or field.type == 'setindex' then
m.pushResult(status, mode, field)
end
return
end
end
local function searchAllGlobalByUri(status, mode, uri, fullID)
local ast = files.getState(uri)
if not ast then
return
end
local root = ast.ast
noder.compileNodes(root)
local noders = noder.getNoders(root)
if fullID then
for id, node in pairs(noders) do
if node.source
and id == fullID then
for source in noder.eachSource(node) do
m.pushResult(status, mode, source)
end
end
end
else
for id, node in pairs(noders) do
if node.source
and id:sub(1, 2) == 'g:'
and not id:find(noder.SPLIT_CHAR) then
for source in noder.eachSource(node) do
m.pushResult(status, mode, source)
end
end
end
end
end
local function searchAllGlobals(status, mode)
for uri in files.eachFile() do
searchAllGlobalByUri(status, mode, uri)
end
end
---查找全局变量
---@param uri uri
---@param mode guide.searchmode
---@param name string
---@return parser.guide.object[]
function m.findGlobals(uri, mode, name)
local status = m.status(mode)
if name then
local fullID = ('g:%q'):format(name)
searchAllGlobalByUri(status, mode, uri, fullID)
else
searchAllGlobalByUri(status, mode, uri)
end
return status.results
end
---搜索对象的引用
---@param status guide.status
---@param source parser.guide.object
---@param mode guide.searchmode
function m.searchRefs(status, source, mode)
local uri, id = prepareSearch(source)
if not id then
return
end
if checkCache(status, uri, id, mode) then
return
end
if TRACE then
log.debug('searchRefs:', id)
end
m.searchRefsByID(status, uri, id, mode)
end
---搜索对象的field
---@param status guide.status
---@param source parser.guide.object
---@param mode guide.searchmode
---@param field string
function m.searchFields(status, source, mode, field)
local uri, id = prepareSearch(source)
if not id then
return
end
if TRACE then
log.debug('searchFields:', id, field)
end
if field == '*' then
if source.special == '_G' then
if checkCache(status, uri, '*', mode) then
return
end
searchAllGlobals(status, mode)
else
if checkCache(status, uri, id .. '*', mode) then
return
end
local newStatus = m.status('field')
m.searchRefsByID(newStatus, uri, id, 'field')
for _, def in ipairs(newStatus.results) do
getField(status, def, mode)
end
end
else
if source.special == '_G' then
local fullID = ('g:%q'):format(field)
if checkCache(status, uri, fullID, mode) then
return
end
m.searchRefsByID(status, uri, fullID, mode)
else
local fullID = ('%s%s%q'):format(id, noder.SPLIT_CHAR, field)
if checkCache(status, uri, fullID, mode) then
return
end
m.searchRefsByID(status, uri, fullID, mode)
end
end
end
---@class guide.status
---搜索结果
---@field results parser.guide.object[]
---@field rmark table
---@field id string
---创建搜索状态
---@param mode guide.searchmode
---@return guide.status
function m.status(mode)
local status = {
callStack = {},
crossed = {},
lock = {},
slock = {},
elock = {},
results = {},
rmark = {},
smark = {},
footprint = {},
count = 0,
ftag = {},
btag = {},
dontCross = 0,
cache = vm.getCache('searcher:' .. mode)
}
return status
end
--- 请求对象的引用
---@param obj parser.guide.object
---@param field? string
---@return parser.guide.object[]
function m.requestReference(obj, field)
local status = m.status('ref')
if field then
m.searchFields(status, obj, 'ref', field)
else
m.searchRefs(status, obj, 'ref')
end
return status.results
end
--- 请求对象的全部引用(深度搜索)
---@param obj parser.guide.object
---@param field? string
---@return parser.guide.object[]
function m.requestAllReference(obj, field)
local status = m.status('allref')
if field then
m.searchFields(status, obj, 'allref', field)
else
m.searchRefs(status, obj, 'allref')
end
return status.results
end
--- 请求对象的定义
---@param obj parser.guide.object
---@param field? string
---@return parser.guide.object[]
function m.requestDefinition(obj, field)
local status = m.status('def')
if field then
m.searchFields(status, obj, 'def', field)
else
m.searchRefs(status, obj, 'def')
end
return status.results
end
--- 请求对象的全部定义(深度搜索)
---@param obj parser.guide.object
---@param field? string
---@return parser.guide.object[]
function m.requestAllDefinition(obj, field)
local status = m.status('alldef')
if field then
m.searchFields(status, obj, 'alldef', field)
else
m.searchRefs(status, obj, 'alldef')
end
return status.results
end
--m.requestReference = m.requestAllReference
--m.requestDefinition = m.requestAllDefinition
return m
<file_sep>local opt = { noremap = true, silent = true}
vim.api.nvim_set_keymap('n', '<C-u>', ':w<CR>', opt)
vim.api.nvim_set_keymap('n', '<C-l>', ':luafile %<CR>', opt)
vim.api.nvim_set_keymap('n', '<Leader>e', ':NvimTreeToggle<CR>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('i', 'jj', '<ESC>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('i', 'jk', '<ESC>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('i', 'kj', '<ESC>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('i', 'kk', '<ESC>', { noremap = true, silent = true })
<file_sep>local collector = require 'core.collector'
---@type vm
local vm = require 'vm.vm'
local noder = require 'core.noder'
function vm.hasGlobalSets(name)
local id = ('def:g:%q'):format(name)
return collector.has(id)
end
function vm.getGlobalSets(name)
local cache = vm.getCache 'getGlobalSets'
if cache[name] then
return cache[name]
end
local results = {}
cache[name] = results
local id
if name == '*' then
id = 'def:g:'
else
id = ('def:g:%q'):format(name)
end
for node in collector.each(id) do
for source in noder.eachSource(node) do
results[#results+1] = source
end
end
return results
end
<file_sep>local util = require 'util'
util.cmd_init()
util.cmd_make()
<file_sep>local platform = require 'bee.platform'
local isWindows = platform.OS == 'Windows'
local isMingw = os.getenv 'MSYSTEM' ~= nil
local isWindowsShell = (isWindows) and (not isMingw)
local shell = {}
function shell:add_readonly(filename)
if isWindowsShell then
os.execute(('attrib +r %q'):format(filename))
else
os.execute(('chmod a-w %q'):format(filename))
end
end
function shell:del_readonly(filename)
if isWindowsShell then
os.execute(('attrib -r %q'):format(filename))
else
os.execute(('chmod a+w %q'):format(filename))
end
end
function shell:pwd()
local command = isWindows and 'echo %cd%' or 'pwd -P'
return (io.popen(command):read 'a'):gsub('[\n\r]*$', '')
end
function shell:path()
if isWindowsShell then
return 'cmd', '/c'
else
return '/bin/sh', '-c'
end
end
shell.isMingw = isMingw
shell.isWindowsShell = isWindowsShell
return shell
<file_sep>local dontgenerate = ...
local sim = require 'simulator'
sim:dofile(WORKDIR / "make.lua")
if not dontgenerate then
sim:finish()
end
<file_sep>local lm = require 'luamake'
local isWindows = lm.os == 'windows'
local exe = isWindows and ".exe" or ""
local dll = isWindows and ".dll" or ".so"
lm.c = lm.compiler == 'msvc' and 'c89' or 'c11'
lm.cxx = 'c++17'
lm.builddir = ("build/%s"):format((function ()
if isWindows then
if lm.compiler == "gcc" then
return "mingw"
end
return "msvc"
end
return lm.os
end)())
require(('project.%s'):format(lm.os))
lm:copy "copy_script" {
input = "bootstrap/main.lua",
output = "$bin/main.lua",
deps = "bootstrap",
}
lm:build "test" {
"$bin/bootstrap"..exe, "@test/test.lua",
deps = { "bootstrap", "copy_script", "bee" },
pool = "console"
}
|
dab1a833d160c9348fa22ce260e63854605497ce
|
[
"Lua"
] | 15
|
Lua
|
napalm1970/vim
|
e54168b1ab9a857f393ee4ff6c4a8435b77d1090
|
cacbe067bd31fef1e2d9f653c35631109df33434
|
refs/heads/main
|
<repo_name>advertronics/simple-calculator<file_sep>/main.js
/*----Global Variables---*/
let input = document.querySelector("input")
let userInputs = []
let equalsClicked = false
const operands = document.querySelectorAll(".operand")
const operators = document.querySelectorAll(".operator")
const equals = document.querySelector("#equals")
const clearBtn = document.querySelector("#clear")
/*----Event Listeners----*/
// disable inputs from keyboard
input.onkeydown = function (e) {
return false
}
//clear the input on clicking the AC button
clearBtn.addEventListener("click", () => {
input.value = ""
userInputs = []
equalsClicked = false
})
// listening to selections from the number buttons (including 0 and decimal point)
for(let operandBtn of operands){
operandBtn.addEventListener("click", () => {
// to ensure you can start another operation without clicking the AC button
if(equalsClicked){
userInputs = []
input.value = ""
equalsClicked = false
}
const operandValue = operandBtn.textContent
input.value = input.value + operandValue.trim()
const inputArr = input.value.split(" ")
})
}
// listening for the operator selected
for(let operator of operators){
operator.addEventListener("click", () => {
if(!equalsClicked){
const inputArr = input.value.split(" ")
const recentInput = inputArr.pop()
console.log(recentInput)
const valueOne = calculateRealValue(recentInput) // calculating the real value of all the entered inputs preceding the sign input
userInputs.push(valueOne)
} else{
input.value = userInputs[0]
equalsClicked = false
}
userInputs.push(operator.textContent)
input.value = input.value + operator.textContent
console.log(userInputs)
})
}
// listening to when the user want to get the results of operation
equals.addEventListener("click", () => {
const inputArr = input.value.split(" ")
const recentInput = inputArr.pop()
console.log(recentInput)
const valueOne = calculateRealValue(recentInput)
userInputs.push(valueOne)
//userInputs.push(equals.textContent)
input.value = input.value + equals.textContent
console.log(userInputs)
while(userInputs.length > 1){ // iterate through the userInputs array untill all the expressions have been evaluated
expressionEvaluation(userInputs)
}
equalsClicked = true // sometimes user want to do more calculations even after pressing (=) we record this and enable him to continue
input.value = input.value + userInputs[0]
})
/*----Functions----*/
// after all operands have been entered, we need to calculate their real value
function calculateRealValue(str){
arr = str.split(".") // because entered value also includes floating point numbers
console.log(arr)
let decimalPart = 0.0
if(arr.length > 1){
splitDecimal = arr[1].split("")
console.log(splitDecimal)
for(i=0; i < splitDecimal.length; i++){
decimalPart = decimalPart + parseInt(splitDecimal[i])*(Math.pow(0.1, i+1))
}
}
let realValue = 0
for(i = arr[0].length - 1; i >= 0; i--){
realValue = realValue + parseInt(arr[0][i])*(Math.pow(10, (arr[0].length - 1) - i))
}
return realValue + decimalPart
}
// we need to work out the solution to the expression in the input field..taking into mind precedence of operators
function expressionEvaluation(arr){
higherPrecedence(arr)
console.log(arr)
if(arr.indexOf(" / ") == -1 && arr.indexOf(" x ") == -1){ // ensure there are no more higher precedence operators left before proceeding to lower precedence operators
for(i=0; i < arr.length; i++){
let results = 0
if(arr[i] == " + "){
results = arr[i-1] + arr[i+1]
arr.splice(i-1, 3, results)
}
if(arr[i] == " - "){
results = arr[i-1] - arr[i+1]
arr.splice(i-1, 3, results)
}
}
console.log(arr)
} else { // if there more higher precedence operator, call the higherPrecedence() function again
higherPrecedence(arr)
}
}
function higherPrecedence(arr){
for(i=0; i < arr.length; i++){
let results = 0
if(arr[i] == " / "){
results = arr[i-1] / arr[i+1]
arr.splice(i-1, 3, results)
}
if(arr[i] == " x "){
results = arr[i - 1] * arr[i + 1]
arr.splice(i-1, 3, results)
}
}
}
|
669551ca5060bacdf71bf83fdad7fe5614e8e33b
|
[
"JavaScript"
] | 1
|
JavaScript
|
advertronics/simple-calculator
|
6155be0286ab4b3f9571ad876988b2fb86a69e2a
|
7eb887155df74b8b27dc09e1eb9c7a9751f08309
|
refs/heads/master
|
<repo_name>Devour2005/CoonSpringHibnerJSi18<file_sep>/src/main/java/com/springapp/Calculation/DataInputForm.java
package com.springapp.calculation;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class DataInputForm implements Serializable {
private static final long serialVersionUID = 13456L;
@NotBlank
private String precision;
@NotBlank
private String numberOfThreads;
private Long elapsedTime;
public Long getElapsedTime() {
return elapsedTime;
}
public void setElapsedTime(Long elapsedTime) {
this.elapsedTime = elapsedTime;
}
public String getPrecision() {
return precision;
}
public void setPrecision(String precision) {
this.precision = precision;
}
public String getNumberOfThreads() {
return numberOfThreads;
}
public void setNumberOfThreads(String numberOfThreads) {
this.numberOfThreads = numberOfThreads;
}
}
<file_sep>/i18/src/main/java/com/springapp/Validators/CalculationValidator.java
package com.springapp.validators;
import com.springapp.calculation.DataInputForm;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Service("calculationValidator")
public class CalculationValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return DataInputForm.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "precision", "precision.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "numberOfThreads", "numberOfThreads.required");
// ValidationUtils.
DataInputForm dataInputForm = (DataInputForm) target;
if ((!dataInputForm.getPrecision().isEmpty())
&& ((!dataInputForm.getPrecision().matches("^([0-9])+$")
|| (Integer.valueOf(dataInputForm.getPrecision()) <= 0)))) {
errors.rejectValue("precision", "precision.match");
}
if ((!dataInputForm.getNumberOfThreads().isEmpty())
&& ((!dataInputForm.getNumberOfThreads().matches("^([0-9])+$"))
|| (Integer.valueOf(dataInputForm.getNumberOfThreads()) <= 0))) {
errors.rejectValue("numberOfThreads", "numberOfThreads.match");
}
}
}
<file_sep>/src/main/java/com/springapp/Exceptions/CommonException.java
package com.springapp.exceptions;
@SuppressWarnings("serial")
public class CommonException extends Exception {
public CommonException(String message) {
super(message);
}
}
<file_sep>/src/main/java/com/springapp/Entity/Role.java
package com.springapp.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "roles")
public class Role implements Serializable {
private static final long serialVersionUID = 3L;
@Id
@Column(name = "role_id", unique = true, nullable = false)
private Integer role_id;
@SuppressWarnings("unchecked")
@OneToMany(mappedBy = "role",
fetch = FetchType.EAGER/*,cascade = CascadeType.ALL*/)
private Set<User> users = new HashSet();
public void setUsers(Set<User> users) {
this.users = users;
}
public Set<User> getUsers() {
return users;
}
@Column(name = "roleName", unique = true, nullable = false)
private String roleName;
public Role() {
}
public Role(String roleName, Set<User> users) {
this.roleName = roleName;
this.users = users;
}
public int getRoleId() {
return role_id;
}
public void setRole_id(Integer id) {
this.role_id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String name) {
this.roleName = name;
}
@Override
public String toString() {
return "Role{" +
"id=" + role_id +
", name='" + roleName + '\'' +
'}';
}
}<file_sep>/src/main/resources/db.properties
db.username=root
db.password=<PASSWORD>
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/coonportalsprng
db.pool_size=5
db.dialect=org.hibernate.dialect.MySQLDialect
db.hbm2ddl_auto=update
db.show_sql=true
db.current_session_context_class=thread
db.auto_commit=false
db.persist_valid_mode=none
db.flush_mode=COMMIT
<file_sep>/i18/src/main/java/com/springapp/Controllers/LoginController.java
package com.springapp.controllers;
import com.springapp.entity.User;
import com.springapp.service.computerService.ComputerService;
import com.springapp.service.roleService.RoleService;
import com.springapp.service.userService.UserService;
import com.springapp.validators.LoginValidator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
//Log4j
private static final Logger logger = Logger.getLogger(LoginController.class);
public LoginController() {
}
@Qualifier("loginValidator")
@Autowired
private LoginValidator loginValidator;
public LoginController(LoginValidator loginValidator) {
this.loginValidator = loginValidator;
}
@InitBinder("loginForm")
private void initBinder(WebDataBinder binder) {
binder.setValidator(loginValidator);
// binder.setValidator(new LoginValidator());
}
@Qualifier("userServiceImpl")
@Autowired
private UserService userService;
@Qualifier("computerServiceImpl")
@Autowired
private ComputerService computerService;
@Qualifier("roleServiceImpl")
@Autowired
private RoleService roleService;
/**
* This method will load the login.jsp page when the application starts
*/
/* @RequestMapping(value = {"/", "login", "/login"}, method = RequestMethod.GET)
public ModelAndView loginPage() {
return new ModelAndView("login", "loginForm", new LoginForm());
}*/
/* @RequestMapping(value = {"/", "login"}, method = RequestMethod.GET)
public String loginPage() {
return "login";
}*/
// @RequestMapping(value = "/login", method = RequestMethod.POST)
public String userWelcomePage(/*@ModelAttribute("loginForm")
LoginForm loginForm,*/
ModelMap model,
HttpSession session) {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
String role = String.valueOf(authentication.getAuthorities());
String login = authentication.getName();
User user = userService.getUserByLogin(login);
session.setAttribute("user", user);
model.addAttribute("role", role);
model.addAttribute("user", user);
if (!role.contains("admin")) {
logger.info("Role 'User' - Go to Welcome Page");
return "welcome";
} else {
model.addAttribute("computers", computerService.getAllComputers());
model.addAttribute("members", userService.getAllUsers());
logger.info("Role 'Admin' - Go to Admin Page");
return "administration";
}
}
}
<file_sep>/src/main/java/com/springapp/Calculation/Calculation.java
package com.springapp.calculation;
import com.springapp.controllers.CalculatorController;
import org.apache.log4j.Logger;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Calculation implements Callable<BigDecimal>, IParallelPiEx{
private static final Logger logger = Logger.getLogger(Calculation.class);
@Override
public BigDecimal call() throws Exception {
return calculatePi(CalculatorController.numberOfThreads, CalculatorController.precision);
}
@Override
public BigDecimal calculatePi(int numberOfThreads, int precision) {
ExecutorService es = Executors.newFixedThreadPool(numberOfThreads);
List<Callable<BigDecimal>> callabBD = new ArrayList<Callable<BigDecimal>>();
for (int i = 0; i <= precision + 2; i++) {
callabBD.add(new OneElementCalculation(i, precision));
}
logger.info("Start of calculation!");
long t0 = System.nanoTime();
BigDecimal sum = BigDecimal.ZERO;
try {
List<Future<BigDecimal>> futures = es.invokeAll(callabBD);
for (Future<BigDecimal> fut : futures) {
sum = sum.add(fut.get(), new MathContext(precision + 1, RoundingMode.HALF_DOWN));
}
} catch (InterruptedException | ExecutionException exc) {
logger.error("Exception while calculation" + exc.getMessage());
} finally {
System.out.println("Real Pi = 3.1415926535897932384626433832795028841971693993" +
"7510582097494459230781640628620899862803482534211706798214808651328230" +
"664709384460955058223172535940812848111745028410270193852110555964462294895493038196");
long t1 = System.nanoTime();
System.out.println("Calc Pi = " + sum);
CalculatorController.elapsedTime = (t1 - t0) / 1_000_000;
logger.info("End with time = " + CalculatorController.elapsedTime);
logger.info("End of calculation!");
es.shutdown();
}
return sum;
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springapp</groupId>
<artifactId>CoonHibernateSpringSecurity</artifactId>
<packaging>war</packaging>
<version>1</version>
<name>CoonHibernateSpringSecurity</name>
<url>http://maven.apache.org</url>
<properties>
<jdk.version>1.7</jdk.version>
<src.main.dir>src/main</src.main.dir>
<main.resources.dir>${src.main.dir}/resources</main.resources.dir>
<spring.version>4.0.5.RELEASE</spring.version>
<aspect.version>1.8.1</aspect.version>
<!--<spring.version>3.2.9.RELEASE</spring.version>-->
<org.slf4j-version>1.7.5</org.slf4j-version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- SPRING DEPENDENCY -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<!-- Spring security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- AspectJ DEPENDENCY -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspect.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspect.version}</version>
</dependency>
<!-- HIBERNATE DEPENDENCY -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.0.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
<scope>compile</scope>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6</version>
</dependency>
<!-- Commons collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<!-- TEST DEPENDENCY -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- DATABASE DEPENDENCY -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<!-- SERVLET DEPENDENCY -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- LOGGING DEPENDENCY -->
<!-- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<!–<scope>compile</scope>–>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<!–<scope>compile</scope>–>
</dependency>-->
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.4.9</version>
</dependency>
<!-- OTHER DEPENDENCY -->
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
<build>
<finalName>CoonHibernateSpringSecurity</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>3.0</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<webXml>${src.main.dir}/webapp/WEB-INF/web.xml</webXml>
<outputDirectory>${basedir}/dest</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/src/main/java/com/springapp/DAO/UserDao/UserDaoImpl.java
package com.springapp.dao.userDao;
import com.springapp.entity.Computer;
import com.springapp.entity.User;
import com.springapp.exceptions.LoginException;
import com.springapp.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
@Repository("UserDaoImpl")
@SuppressWarnings("unchecked")
public class UserDaoImpl extends AbstractUserDao {
@Qualifier("sessionFactory")
@Autowired
private SessionFactory sessionFactory;
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
@Override
@Transactional
public boolean insertUser(User user) {
if (isUserExists(user)) {
return false;
}
currentSession().save(user);
return true;
}
@Override
@Transactional
public boolean isUserExists(User user) {
Session session = HibernateUtil.openSession();
boolean result = true;
Query query = session.createQuery("SELECT u FROM User u WHERE u.login=? OR u.email=?");
query.setString(0, user.getLogin());
query.setString(1, user.getEmail());
User u = (User) query.uniqueResult();
if (u == null) {
result = false;
}
return result;
}
@Override
@Transactional
public boolean isEmailExists(User user) {
Session session = HibernateUtil.openSession();
boolean result = true;
Query query = session.createQuery("SELECT u FROM User u WHERE u.email=?");
query.setString(0, user.getEmail());
User u = (User) query.uniqueResult();
if (u == null) {
result = false;
}
return result;
}
/* @Override
@Transactional
public boolean updateUser(User user) {
if (isUserExists(user)) {
return false;
}
currentSession().update(user);
return true;
} */
@Override
@Transactional
public void updateUser(User user) /*throws NotUniqueEmailException*/ {
if (user == null) {
throw new NullPointerException();
}
if (user.getUserId() < 1) {
throw new IllegalArgumentException();
}
if (user.getEmail() == null || user.getEmail().intern().equals("")) {
throw new IllegalArgumentException();
}
currentSession().saveOrUpdate(user);
}
@Override
@Transactional
public void deleteUser(Integer userId) {
User user = (User) currentSession().get(User.class, userId);
currentSession().delete(user);
}
/* public void deleteUser(User user) {
if (user == null) {
throw new NullPointerException();
}
currentSession().delete(user);
}*/
@Override
@Transactional
public User authorization(String login, String password) throws LoginException {
User user = getUserByLogin(login);
if (user != null && user.getLogin().equals(login) && user.getPassword().equals(password)) {
return user;
} else {
return null;
// throw new LoginException("No Such User!");
}
}
@Override
@Transactional
public User getUserByLogin(String login) {
return (User) currentSession().createCriteria(User.class)
.add(Restrictions.eq("login", login)).uniqueResult();
}
/*public User findByLogin(String login) {
if (login == null || login.intern() == "") {
throw new IllegalArgumentException();
}
Criteria criteria = currentSession().createCriteria(User.class)
.add(Restrictions.like("login", login));
if (criteria.list().isEmpty()) {
return new User();
}
return (User) criteria.list().get(0);
}*/
@Override
@Transactional
public User getUserByEmail(String email) {
return (User) currentSession().createCriteria(User.class)
.add(Restrictions.eq("email", email)).uniqueResult();
}
/* public User getUserByEmail(String email) {
if (email == null || email.intern().equals("")) {
throw new IllegalArgumentException();
}
Criteria criteria = currentSession().createCriteria(User.class)
.add(Restrictions.like("email", email));
if (criteria.list().isEmpty()) {
return new User();
}
return (User) criteria.list().get(0);
}*/
@Override
@Transactional
public User getUserById(int userId) {
return (User) currentSession().createCriteria(User.class)
.add(Restrictions.eq("userId", userId)).uniqueResult();
}
@Override
@Transactional
public List<User> getAllUsers() {
Criteria criteria = currentSession().createCriteria(User.class);
return criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}
/* @Override
@Transactional
public List<User> getAllUsers() {
Session session = HibernateUtil.openSession();
return session.createQuery("from User").list();
}*/
@Override
@Transactional
public Set<Computer> getAllUsersComputers(String login) {
return getAllRecords(login);
}
@Transactional
protected Set<Computer> getAllRecords(String login) {
User user = getUserByLogin(login);
return user.getComputers();
}
}
<file_sep>/src/main/java/com/springapp/DAO/RoleDao/RoleDao.java
package com.springapp.dao.roleDao;
import com.springapp.entity.Role;
import com.springapp.exceptions.NotUniqueRoleNameException;
public interface RoleDao {
abstract public void create(Role role) throws NotUniqueRoleNameException/*, DBSystemException*/;
abstract public void update(Role role);
// throws DBSystemException;
abstract public void remove(Role role);
// throws DBSystemException;
abstract public Role findByName(String name);
}
<file_sep>/i18/src/main/java/com/springapp/Calculation/TimeCountAspect.java
package com.springapp.calculation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TimeCountAspect {
@Around("execution(* com.springapp.controllers.CalculatorController.calculMethod(..))")
public Object timeCounterClass(ProceedingJoinPoint joinpoint) {
Object result = null;
try {
System.out.println("Preparing to calculate");
long start = System.currentTimeMillis(); // Before method invoke
result = joinpoint.proceed(); // Method invoke
long end = System.currentTimeMillis(); // After method invoke
System.out.println("calculation took " + (end - start)
+ " milliseconds.");
} catch (Throwable t) {
System.out.println("Nothing happend!");
}
return result;
}
}
<file_sep>/i18/src/main/java/com/springapp/Exceptions/NotUniqueLoginException.java
package com.springapp.exceptions;
public class NotUniqueLoginException extends DBException {
public NotUniqueLoginException(String message) {
super(message);
}
public NotUniqueLoginException(String reason, Throwable cause) {
super(reason, cause);
}
}
<file_sep>/src/main/java/com/springapp/forms/RegisterForm.java
package com.springapp.forms;
import com.springapp.entity.Computer;
import com.springapp.entity.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;
public class RegisterForm implements Serializable {
private static final Log logger = LogFactory.getLog(RegisterForm.class);
private static final long serialVersionUID = 6L;
private Integer userId;
@NotBlank
@Size(min = 2, max = 25)
@Pattern(regexp = "^([a-zA-Z0-9_-])+$")
private String login;
@NotBlank
@Size(min = 2, max = 25)
@Pattern(regexp = "^([a-zA-Z])+$")
private String name;
@NotBlank
@Size(min = 2, max = 25)
@Pattern(regexp = "^([a-zA-Z0-9_-])+$")
private String password;
@NotBlank
@Size(min = 2, max = 25)
private String passwordConfirm;
@NotBlank
@Email
@Pattern(regexp = "^([a-zA-Z0-9_\\.\\-+])+@(([a-zA-Z0-9-])+\\.)+([a-zA-Z0-9]{2,4})+$")
private String email;
@NotBlank
@Email
private String emailConfirm;
private Timestamp regDate;
private String role;
private Set<Computer> computers = new LinkedHashSet<Computer>();
public RegisterForm() {
}
public User getUser() {
User user = new User();
user.setUserId(userId);
logger.trace("set user 'userId'" + userId);
user.setLogin(login);
logger.trace("set user 'login'" + login);
user.setEmail(email);
logger.trace("set user 'email'" + email);
user.setName(name);
logger.trace("set user 'name'" + name);
user.setPassword(<PASSWORD>);
logger.trace("set user 'password'" + password);
user.setRegDate(new Timestamp(new Date().getTime()));
logger.trace("set user 'regDate'" + regDate);
user.setComputers(computers);
return user;
}
public void setUser(User user) {
logger.trace("Constructor " + user);
this.userId = user.getUserId();
logger.trace("Get 'userId' " + getUserId());
this.login = user.getLogin();
logger.trace("Get 'login' " + user.getLogin());
this.password = <PASSWORD>();
logger.trace("Get 'password' " + user.getPassword());
this.name = user.getName();
logger.trace("get 'name'" + user.getName());
this.email = user.getEmail();
logger.trace("Get 'email' " + user.getEmail());
this.regDate = user.getRegDate();
logger.trace("Get 'regDate' " + user.getRegDate());
this.role = user.getRole().getRoleName();
logger.trace("get 'role'" + user.getRole().getRoleName());
this.computers = user.getComputers();
logger.trace("Get 'computers' " + user.getComputers());
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmailConfirm() {
return emailConfirm;
}
public void setEmailConfirm(String emailConfirm) {
this.emailConfirm = emailConfirm;
}
public Timestamp getRegDate() {
return regDate;
}
public void setRegDate(Timestamp regDate) {
this.regDate = regDate;
}
public Set<Computer> getComputers() {
return computers;
}
public void setComputers(Set<Computer> computers) {
this.computers = computers;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
<file_sep>/src/main/java/com/springapp/DAO/RoleDao/AbstractRoleDao.java
package com.springapp.dao.roleDao;
import com.springapp.entity.Role;
import com.springapp.exceptions.NotUniqueRoleNameException;
abstract public class AbstractRoleDao implements RoleDao {
abstract public void create(Role role) throws NotUniqueRoleNameException;
// throws NotUniqueRoleNameException, DBSystemException;
abstract public void update(Role role);
// throws DBSystemException;
abstract public void remove(Role role);
// throws DBSystemException;
abstract public Role findByName(String name);
}
<file_sep>/src/main/java/com/springapp/Controllers/AdminUserUpdateController.java
package com.springapp.controllers;
import com.springapp.entity.Computer;
import com.springapp.entity.User;
import com.springapp.service.Support;
import com.springapp.service.computerService.ComputerService;
import com.springapp.service.userService.UserService;
import com.springapp.validators.UpdateValidator;
import com.springapp.forms.UserForm;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.LinkedHashSet;
import java.util.Set;
@Controller
public class AdminUserUpdateController {
//Log4j
private static final Logger logger = Logger.getLogger(AdminUserUpdateController.class);
public AdminUserUpdateController() {
}
public AdminUserUpdateController(UpdateValidator updateValidator) {
this.updateValidator = updateValidator;
}
@Qualifier("userServiceImpl")
@Autowired
private UserService userService;
@Qualifier("computerServiceImpl")
@Autowired
private ComputerService computerService;
@Qualifier("updateValidator")
@Autowired
private UpdateValidator updateValidator;
@Qualifier("support")
@Autowired
private Support support;
@InitBinder("userForm")
private void initBinder(WebDataBinder binder) {
binder.setValidator(updateValidator);
// binder.registerCustomEditor(Set.class, "computers", new ComputerCollector(Set.class) {
// }); }
binder.registerCustomEditor(Set.class, "computers", new CustomCollectionEditor(Set.class) {
@Override
protected Object convertElement(Object element) {
String pcName = null;
Set<Computer> computerSet = new LinkedHashSet<>();
if (element instanceof String && !((String) element).equals("")) {
pcName = (String) element;
computerSet.add(computerService.getComputerByName(pcName));
new UserForm().setComputers(computerSet);
}
if (element instanceof String && ((String) element).equals("Delete")) {
computerSet.clear();
new UserForm().setComputers(computerSet);
}
return pcName != null ? computerService.getComputerByName(pcName) : null;
}
});
}
@RequestMapping(value = "/adminEdit/{userId}", method = RequestMethod.GET)
public String updateView(@PathVariable("userId") Integer userId,
UserForm userForm,
ModelMap model) {
User userForUpdate = userService.getUserById(userId);
userForm.setUser(userForUpdate);
model.addAttribute("userForUpdate", userForUpdate);
model.addAttribute("userForm", userForm);
model.addAttribute("computers", computerService.getAllComputers());
logger.info("Go to Admin's User update Page");
return "adminUserUpdate";
}
@RequestMapping(value = "adminEdit.do/{userId}", method = RequestMethod.POST)
public ModelAndView updateUserProcess(@ModelAttribute(value = "userForm")
@PathVariable("userId") Integer userId,
Model model,
UserForm userForm,
BindingResult result) {
User userForUpdate = userService.getUserById(userId);
model.addAttribute("userForm", userForm);
model.addAttribute("userForUpdate", userForUpdate);
model.addAttribute("computers", computerService.getAllComputers());
updateValidator.validate(userForm, result);
if (result.hasErrors()) {
logger.error("Validation error while updating User - " + userForm.getLogin());
return new ModelAndView("adminUserUpdate");
}
return updatingUser(userForUpdate, model, userForm);
}
private ModelAndView updatingUser(User userForUpdate, Model model,
UserForm userForm) {
if (support.isEmailExists(userForm, userForUpdate)) {
logger.error("Can't update user - not unique email!!");
model.addAttribute("errorMsg", "Email is already in use!");
return new ModelAndView("adminUserUpdate");
}
support.fillForm(userForm, userForUpdate);
userForUpdate = userForm.getUser();
userService.updateUser(userForUpdate);
logger.info("User " + userForm.getLogin() + " is updated by Admin!");
return new ModelAndView("redirect:/adminPage");
}
}
<file_sep>/src/main/java/com/springapp/forms/LoginForm.java
package com.springapp.forms;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class LoginForm implements Serializable {
private static final Log logger = LogFactory.getLog(LoginForm.class);
private static final long serialVersionUID = 123L;
@NotBlank
private String login;
@NotBlank
private String password;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getPassword() {
return password;
}
}
<file_sep>/src/main/resources/db_dump/initDBCoon_Roles.sql
-- ORDER OF TABLES IS VERY IMPORTANT
-- SCRIPT USED TO INIT DATABASE
SET FOREIGN_KEY_CHECKS=0;
CREATE DATABASE IF NOT EXISTS coonportalsprng;
USE coonportalsprng;
DROP TABLE IF EXISTS members CASCADE;
DROP TABLE IF EXISTS roles CASCADE;
DROP TABLE IF EXISTS computers CASCADE;
DROP TABLE IF EXISTS usercomp CASCADE;
USE coonportalsprng;
CREATE TABLE roles (
role_id INT(11) NOT NULL,
rolename VARCHAR(30) NOT NULL DEFAULT 'admin',
PRIMARY KEY (role_id)
)
ENGINE =InnoDB;
USE coonportalsprng;
CREATE TABLE members (
user_id INT(11) AUTO_INCREMENT,
login VARCHAR(30) NOT NULL NULL DEFAULT '' UNIQUE,
name VARCHAR(30) NOT NULL DEFAULT '',
password VARCHAR(30) NOT NULL DEFAULT '',
email VARCHAR(30) NOT NULL DEFAULT '' UNIQUE,
regdate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
role_id INT(11) NOT NULL DEFAULT 1,
INDEX `role_id_fk` (`role_id`),
CONSTRAINT `role_id_fk` FOREIGN KEY (`role_id`) REFERENCES `roles` (`role_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (user_id)
)
ENGINE =InnoDB;
USE coonportalsprng;
CREATE TABLE computers (
comp_id INT(11) AUTO_INCREMENT,
pcname VARCHAR(30) NOT NULL UNIQUE,
monitor VARCHAR(30) NOT NULL DEFAULT '',
keyboard VARCHAR(30) NOT NULL DEFAULT '',
mouse VARCHAR(30) NOT NULL DEFAULT '',
cpu VARCHAR(30) NOT NULL DEFAULT '',
PRIMARY KEY (comp_id)
)
ENGINE =InnoDB;
USE coonportalsprng;
CREATE TABLE usercomp (
user_id INT(11) NOT NULL,
comp_id INT(11) /*NOT NULL*/,
INDEX fk_user_id (user_id),
INDEX fk_comp_id (comp_id),
CONSTRAINT fk_user_id FOREIGN KEY (user_id)
REFERENCES members (user_id)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_comp_id FOREIGN KEY (comp_id)
REFERENCES computers (comp_id)
ON DELETE CASCADE ON UPDATE CASCADE
)
ENGINE =InnoDB;
USE coonportalsprng;
INSERT INTO `roles` (`role_id`,`rolename`)
VALUES
(1, 'admin'),
(2, 'user');
-- SCRIPT USED TO INITIALIZE TABLES DATA
USE coonportalsprng;
INSERT INTO `members` (`login`, `name`, `password`, `email`, `role_id`)
VALUES
('user1', 'user1', '1', '<EMAIL>', '1'),
('user2', 'user2', '2', '<EMAIL>', '2'),
('user3', 'user3', '3', '<EMAIL>', '2'),
('user4', 'user4', '4', '<EMAIL>', '2'),
('user5', 'user5', '5', '<EMAIL>', '2'),
('user6', 'user6', '6', '<EMAIL>', '2'),
('user7', 'user7', '7', '<EMAIL>', '2'),
('user8', 'user8', '8', '<EMAIL>', '2');
-- SCRIPT USED TO INITIALIZE TABLES DATA
USE coonportalsprng;
INSERT INTO `computers` (`pcname`, `monitor`, `keyboard`, `mouse`, `cpu`)
VALUES
('PC1', 'LG', 'Sven', 'Logitech', 'AMD Athlon X2'),
('PC2', 'Samsung', 'Sven', 'A4tech', 'Intel Core i3 3210'),
('PC3', 'ViewSonic', 'Sven', 'Asus', 'AMD Athlon 64 FX'),
('PC4', 'Samsung', 'Sven', 'Razer', 'Intel Xeon E3-1230'),
('PC5', 'LG', 'Sven', 'Sven', 'AMD Turion 64'),
('PC6', 'Asus', 'Sven', 'Sven', 'Intel Core i7 3770'),
('PC7', 'Apple', 'Sven', 'Logitech', 'Intel Core i5 3470T'),
('PC8', 'Asus', 'Sven', 'Asus', 'Intel Core i5 3550S');
-- SCRIPT USED TO INITIALIZE TABLES DATA
USE coonportalsprng;
INSERT INTO `usercomp` (`user_id`, `comp_id`)
VALUES
('1', '3'),
('2', '2'),
('3', '7'),
('4', '5'),
('5', '8'),
('6', '1'),
('7', '4'),
('8', '6');
SET FOREIGN_KEY_CHECKS=1;
<file_sep>/i18/src/main/java/com/springapp/Validators/UpdateValidator.java
package com.springapp.validators;
import com.springapp.forms.UserForm;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Service("updateValidator")
public class UpdateValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return UserForm.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "<PASSWORD>");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
UserForm userRegisterUpdt = (UserForm) target;
//Update Validation
if ((!userRegisterUpdt.getLogin().isEmpty()) &&
(!userRegisterUpdt.getLogin().matches("^([a-zA-Z0-9_-])+$"))) {
errors.rejectValue("login", "login.match");
}
if ((!userRegisterUpdt.getName().isEmpty()) &&
(!userRegisterUpdt.getName().matches("^([a-zA-Z])+$"))) {
errors.rejectValue("name", "name.match");
}
if ((!userRegisterUpdt.getEmail().isEmpty()) &&
(!userRegisterUpdt.getEmail().matches("^([a-zA-Z0-9_\\.\\-+])+" +
"@(([a-zA-Z0-9-])+\\.)+([a-zA-Z0-9]{2,4})+$"))) {
errors.rejectValue("email", "email.match");
}
}
}
<file_sep>/src/main/java/com/springapp/Service/ComputerService/ComputerServiceImpl.java
package com.springapp.service.computerService;
import com.springapp.dao.computerDao.ComputerDao;
import com.springapp.entity.Computer;
import com.springapp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service("computerServiceImpl")
public class ComputerServiceImpl implements ComputerService {
// public ComputerServiceImpl() {
// }
@Autowired
ComputerDao computerDao;
@Override
public Computer getComputerById(Integer compId) {
return computerDao.getComputerById(compId);
}
@Override
public Computer getComputerByName(String pcName) {
return computerDao.getComputerByName(pcName);
}
@Override
public boolean insertComputer(Computer computer) {
return computerDao.insertComputer(computer);
}
@Override
public boolean updateComputer(Computer computer) {
return computerDao.updateComputer(computer);
}
@Override
public void deleteComputer(Integer compId) {
computerDao.deleteComputer(compId);
}
@Override
public Set<Computer> getAllComputers() {
return computerDao.getAllComputers();
}
@Override
public Set<User> getAllUsersComputers(Integer compId) {
return computerDao.getAllUsersComputers(compId);
}
}
<file_sep>/i18/src/main/java/com/springapp/Exceptions/DBSystemException.java
package com.springapp.exceptions;
public class DBSystemException extends DBException {
public DBSystemException(String message) {
super(message);
}
public DBSystemException(String reason, Throwable cause) {
super(reason, cause);
}
}
<file_sep>/i18/src/main/java/com/springapp/Exceptions/NotUniqueEmailException.java
package com.springapp.exceptions;
public class NotUniqueEmailException extends DBException {
public NotUniqueEmailException(String message) {
super(message);
}
public NotUniqueEmailException(String reason, Throwable cause) {
super(reason, cause);
}
}
<file_sep>/i18/src/main/java/com/springapp/Service/RoleService/RoleServiceImpl.java
package com.springapp.service.roleService;
import com.springapp.dao.roleDao.RoleDao;
import com.springapp.entity.Role;
import com.springapp.exceptions.NotUniqueRoleNameException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("roleServiceImpl")
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleDao roleDao;
@Override
public void create(Role role) throws NotUniqueRoleNameException {
roleDao.create(role);
}
@Override
public void update(Role role) {
roleDao.update(role);
}
@Override
public void remove(Role role) {
roleDao.remove(role);
}
@Override
public Role findByName(String string) {
return roleDao.findByName(string);
}
}
<file_sep>/src/main/webapp/js/script.js
//Login form
function validateForm() {
var empName = isEmptyLog("j_username");
var empPass = isEmptyLog("j_password");
var regLogin = validateLogin();
if (!empName || !empPass) {
alert("Name and Password must be filled out");
return false;
} else if (!regLogin) {
alert("Illegal login format! Example 'E-not_2015'");
return false;
}else{
return true;
}
}
function validateRegForm() {
var empName = isEmpty("name");
var empLogin = isEmpty("login");
var empPass = isEmpty("password");
var empPassConfirm = isEmpty("passwordConfirm");
var empEmail = isEmpty("email");
var empEmailConfirm = isEmpty("emailConfirm");
var regLogin = validateLogin("login");
var regEmail = validateEmail("email");
var regEmailConfirm = validateEmail("emailConfirm");
var regName = validateName("name");
var validatePass = validatePassword();
if (!empName || !empLogin || !empPass || !empPassConfirm || !empEmail || !empEmailConfirm) {
alert("All fields must be filled out");
return false;
} else if (!regLogin) {
alert("Illegal login format! Example 'E-not_2015'");
return false;
} else if (!validatePass) {
alert("Passwords do not match!");
return false;
} else if (!regEmail || !regEmailConfirm) {
alert("Illegal email format! Example '<EMAIL>'");
return false;
} else if (!regEmail === regEmailConfirm) {
alert("Emails do not match!");
return false;
} else if (!regName) {
alert("Illegal Username format! Username must have alphabet characters only!");
return false;
} else {
return true;
}
}
function isEmptyLog(field) {
var fieldHolder = document.forms["login"][field];
return fieldHolder && fieldHolder.value;
}
function isEmpty(field) {
var fieldHolder = document.forms["regData"][field];
return fieldHolder && fieldHolder.value;
}
function validateEmail() {
var email = document.forms["regData"]["email"].value;
var chrbeforAt = email.substr(0, email.indexOf('@'));
if (!($.trim(email).length > 127)) {
if (chrbeforAt.length >= 2) {
var regExp = /^([a-zA-Z0-9_\.\-+])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regExp.test(email);
} else {
return false;
}
} else {
return true;
}
}
function validateName() {
var name = document.forms["regData"]["name"].value;
if (!($.trim(name).length > 25)) {
var nameReg = /^([a-zA-Z])+$/;
return nameReg.test(name);
} else {
return false;
}
}
function validatePassword() {
var pass = document.forms["regData"]["password"].value;
var passConfirm = document.forms["regData"]["passwordConfirm"].value;
return pass === passConfirm;
}
function validateLogin() {
var login = document.forms["login"]["j_username"].value;
if (!($.trim(login).length > 15)) {
var logReg = /^([a-zA-Z0-9_-])+$/;
return logReg.test(login);
} else {
return false;
}
}
<file_sep>/i18/src/main/java/com/springapp/DAO/RoleDao/RoleDaoImpl.java
package com.springapp.dao.roleDao;
import com.springapp.entity.Role;
import com.springapp.exceptions.NotUniqueRoleNameException;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository("RoleDaoImpl")
@SuppressWarnings("unchecked")
public class RoleDaoImpl extends AbstractRoleDao {
@Qualifier("sessionFactory")
@Autowired
private SessionFactory sessionFactory;
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
@Override
@Transactional
public void create(Role role) throws NotUniqueRoleNameException {
if (findByName(role.getRoleName()).getRoleName() != null) {
throw new NotUniqueRoleNameException("The name of role not unique!");
}
currentSession().save(role);
}
@Override
@Transactional
public void update(Role role) {
if (role == null || role.getRoleId() == 0) {
throw new IllegalArgumentException("Wrong argument! role can't be null or ID = '0'");
}
currentSession().update(role);
}
@Override
@Transactional
public void remove(Role role) {
if (role == null) {
throw new NullPointerException();
}
currentSession().delete(role);
}
@Override
@Transactional
public Role findByName(String name) {
if (name == null) {
return new Role();
}
if (name.intern().equals("")) {
throw new IllegalArgumentException("name of role can't be = null or ''");
}
Criteria criteria = currentSession().createCriteria(Role.class)
.add(Restrictions.like("roleName", name));
if (criteria.list().isEmpty()) {
return new Role();
}
return (Role) criteria.list().get(0);
}
}
<file_sep>/i18/src/main/java/com/springapp/Validators/UserValidator.java
package com.springapp.validators;
import com.springapp.forms.RegisterForm;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Service("userValidator")
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return RegisterForm.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "login.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "<PASSWORD>");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "passwordConfirm", "password<PASSWORD>");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailConfirm", "email.confirm.required");
RegisterForm userRegisterReg = (RegisterForm) target;
//Register Validation
if ((!userRegisterReg.getLogin().isEmpty()) && (!userRegisterReg.getLogin().matches("^([a-zA-Z0-9_-])+$"))) {
errors.rejectValue("login", "login.match");
}
if ((!userRegisterReg.getName().isEmpty()) && (!userRegisterReg.getName().matches("^([a-zA-Z])+$"))) {
errors.rejectValue("name", "name.match");
}
if (!userRegisterReg.getPassword().equalsIgnoreCase(userRegisterReg.getPasswordConfirm())) {
errors.rejectValue("passwordConfirm", "password.again");
}
if ((!userRegisterReg.getEmail().isEmpty()) &&
(!userRegisterReg.getEmail().matches("^([a-zA-Z0-9_\\.\\-+])+" +
"@(([a-zA-Z0-9-])+\\.)+([a-zA-Z0-9]{2,4})+$"))) {
errors.rejectValue("email", "email.match");
}
if ((!userRegisterReg.getEmail().equalsIgnoreCase(userRegisterReg.getEmailConfirm())) &&
(!userRegisterReg.getEmailConfirm().isEmpty())) {
errors.rejectValue("emailConfirm", "email.again");
}
}
}
|
1065ea6c5868ce3bb79a067c8062b5010cb06604
|
[
"SQL",
"JavaScript",
"Maven POM",
"INI",
"Java"
] | 25
|
Java
|
Devour2005/CoonSpringHibnerJSi18
|
f80b24524c6092ad81a5823e9a577bc758f8abde
|
4888c3e8c4fd2977fbd27d3ff4fe3335a78465bc
|
refs/heads/master
|
<file_sep><?php
header('Location:scripts/index.php');
<file_sep><?php
/**
* Licensed under The MIT License
* Redistributions of files must retain the this copyright notice.
*
* @author <NAME> <<EMAIL>>
* @version 1.0
*/
class CssAnimationRobber
{
const USER_AGENT_CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36';
const USER_AGENT_IOS = 'Mozilla/5.0 (iOS; U; zh-Hans) AppleWebKit/533.19.4 (KHTML, like Gecko) AdobeAIR/4.0';
const DEFAULT_NOTE = 'CSS动效提取器';
public function getAnimationCss($url = NULL, $css_links = NULL, $html = NULL)
{
$url = (string) $url;
$css_links = array_filter(is_array($css_links) ? $css_links : explode(',', str_replace("\n", ',', preg_replace('/\s/', '', (string) $css_links))));
$html = (string) $html;
$note = self::DEFAULT_NOTE;
$html .= $url ? self::getRemoteContents($url, self::USER_AGENT_IOS) : '';
$style_areas = array();
if ($html) {
preg_match_all('/<title[^<>]*>(.*?)<\/title>/i', $html, $head_match, PREG_PATTERN_ORDER);
$note .= ' - ' . (isset($head_match[1][0]) ? $head_match[1][0] : '');
preg_match_all('/<link[^<>]+href=[\'"]([^<>\'"]+)[\'"][^<>]*>/i', $html, $css_links_match, PREG_PATTERN_ORDER);
$css_links = array_merge($css_links, $css_links_match[1]);
}
// 聚合所有含有css 的资源
$css = $html;
foreach ($style_areas as $s_a_v) {
$css .= $s_a_v;
}
foreach ($css_links as $c_l_v) {
$_url = $c_l_v;
if ((0 === strpos($_url, 'http://')) || (0 === strpos($_url, 'https://'))) {
// do nothing
} else if (0 === strpos($_url, '//')) {
$_url = substr($url, 0, strpos($url, ':') + 1) . $_url;
} else if (0 === strpos($_url, '/')) {
$_url = substr($url, 0, strpos($url, '/', 7)) . $_url;
} else {
$_prefix = explode('/', $url);
array_pop($_prefix);
$_prefix = implode('/', $_prefix) . '/';
$_url = $_prefix . $_url;
}
if ($_url) {
// 抓取css
$_css = strip_tags(self::getRemoteContents($_url, self::USER_AGENT_IOS));
// 图片地址替换
$_img_url_prefix = explode('/', $_url);
array_pop($_img_url_prefix);
$_img_url_prefix = implode('/', $_img_url_prefix) . '/';
$_css = preg_replace('/url\s*\(([\'"]?)([^\(\)\:]+)([\'"]?)\)/', 'url($1' . $_img_url_prefix . '$2$3)', $_css);
// 拼接
$css .= $_css;
}
}
// 去除换行
$css = preg_replace("/[\n\r]/", '', $css);
// 去除注释
$css = preg_replace('/\/\*.*?\*\//', '', $css);
$css = preg_replace('/\/\*|\*\//', '', $css);
// 提取keyframes
$keyframes = array();
preg_match_all('/(@[^@\{\}\s]*keyframes\s+([^\{\}\s]+)\s*\{(?:[^\{\}]+\{[^\{\}]*\}\s*)+\})/', $css, $keyframes_match, PREG_PATTERN_ORDER);
foreach ($keyframes_match[1] as $k_m_k => $k_m_v) {
$keyframes[$keyframes_match[2][$k_m_k]][] = self::formatCssBlock($k_m_v);
}
// 提取animation
$animations = array();
preg_match_all('/[\.#][^\{\}]+\s*(\{[^\{\}]*animation\s*\:\s*([^\{\}\s]+)\s+[\{\}]*[^\{\}]+\})/', $css, $animations_match, PREG_PATTERN_ORDER);
foreach ($animations_match[1] as $a_m_k => $a_m_v) {
// 格式化代码
$animations[$animations_match[2][$a_m_k]][] = self::formatCssBlock($a_m_v);
}
// 没找到匹配的class 的keyframes 使用默认的class
foreach ($keyframes as $k_k => $k_v) {
empty($animations[$k_k]) && ($animations[$k_k][] = self::getDefaultCssAnimationBlock($k_k, $k_v));
}
return array(
'note' => $note,
'keyframes' => $keyframes,
'animations' => $animations,
);
}
static public function getDefaultCssAnimationBlock($keyframes_name, $keyframes_blocks)
{
$css = "";
$css .= "{\n";
$css .= strpos($keyframes_blocks[0], 'opacity') ? " opacity: 0;\n" : "";
$css .= " -webkit-animation: {$keyframes_name} 1s infinite 0.3s ease-in-out;\n";
$css .= " animation: {$keyframes_name} 1s infinite 0.3s ease-in-out;\n";
$css .= "}\n\n";
return $css;
}
static public function formatCssBlock($css, $level = 0)
{
$css = (string) $css;
// 处理开始花括号
$css = preg_replace("/^(\n?)\s*/", '$1' . str_pad('', $level * 4, ' '), preg_replace('/\s+$/', '', $css));
// 处理换行缩进
$css = preg_replace('/\s*([\{])\s*/', " $1\n" . str_pad('', ($level + 1) * 4, ' '), $css);
$css = preg_replace('/\s*([;])\s*/', "$1\n" . str_pad('', ($level + 1) * 4, ' '), $css);
// 处理闭合花括号
$css = preg_replace('/\s*\}\s*/', "\n" . str_pad('', $level * 4, ' ') . "}\n" . ($level > 0 ? "" : "\n"), $css);
// 处理二层嵌套的缩进
preg_match_all('/([^\{\}]+\{)((?:[^\{\}]+\{[^\{\}]*\}\s*)+)(\}\s*)/', $css, $sub_blocks, PREG_PATTERN_ORDER);
if (! empty($sub_blocks[2][0])) {
$css_start = $sub_blocks[1][0];
$css_end = $sub_blocks[3][0];
preg_match_all('/([^\{\}]+\{[^\{\}]*\}\s*)/', $sub_blocks[2][0], $sub_blocks, PREG_PATTERN_ORDER);
$css = '';
$css .= $css_start;
foreach ($sub_blocks[1] as $s_b_v) {
$css .= self::formatCssBlock($s_b_v, $level + 1);
}
$css .= $css_end;
}
return $css;
}
static public function getRemoteContents($url, $user_agent = NULL)
{
$url = trim((string) $url);
if (empty($url)) {
return '';
}
for ( $i = 0, $l = 3; $i < $l; ++ $i ) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
$user_agent && curl_setopt($curl, CURLOPT_USERAGENT, $user_agent ? $user_agent : self::USER_AGENT_CHROME);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
$html = trim(curl_exec($curl));
curl_close($curl);
if ($html) {
preg_match_all('/charset[ =][\'"]?([\w\-]+)[\'"]?/i', $html, $charset_match, PREG_PATTERN_ORDER);
$charset = strtoupper(isset($charset_match[1][0]) ? $charset_match[1][0] : '');
$charset && (false === strpos($charset, 'UTF')) && ($html = iconv($charset . '//IGNORE', 'UTF-8', $html));
break;
}
}
return $html;
}
}
<file_sep><?php
set_time_limit(60);
include_once './dependents/simple_html_dom.php';
include_once './CssAnimationRobber.php';
$url = isset($_REQUEST['url']) ? (string) $_REQUEST['url'] : NULL;
$css_links = isset($_REQUEST['css_links']) ? (string) $_REQUEST['css_links'] : NULL;
$html = isset($_REQUEST['html']) ? (string) $_REQUEST['html'] : NULL;
$css_animation_robber = new CssAnimationRobber();
$animations_css = $css_animation_robber->getAnimationCss($url, $css_links, $html);
$preview_html = fetch('./_preview.tpl.php', $animations_css);
$return = array();
$return['status'] = 1;
$return['info'] = array(
'note' => $animations_css['note'],
'html' => $preview_html,
);
echo json_encode($return);
function fetch($tpl, $params = array())
{
// 页面缓存
ob_start();
ob_implicit_flush(0);
// 导入变量
extract($params, EXTR_OVERWRITE);
// 载入模版文件
include $tpl;
// 输入
return ob_get_clean();
}<file_sep>#!/bin/sh
echo '----------------------------'
echo '----------------------------'
echo 'Please open " http://localhost:10086 " in your browser.'
echo '----------------------------'
echo '----------------------------'
php -S localhost:10086 -t ./scripts
<file_sep>css-animation-robber
====================
Rob HTML5 pages of all their css animations. Language: PHP + JavaScript
Run method:
1. Command: " php -S localhost:10086 -t ./scripts " or sh ./run.sh
2. Open " http://localhost:10086 " in your browser
<file_sep><style>
<?php
foreach ($keyframes as $k_v) {
echo implode('', $k_v);
}
?>
<?php
foreach ($animations as $name => $group) {
foreach ($group as $g_k => $g_v) {
echo ".preview-{$name}-{$g_k}{$g_v}";
}
}
?>
</style>
<?php
$background_colors = array('#FF6666', '#66FF66', '#9999FF');
$animation_colors = array('#666600', '#006666', '#660066');
$count = 0;
?>
<?php foreach ($animations as $name => $group) { ?>
<?php foreach ($group as $g_k => $g_v) { ?>
<?php $_class_name = 'preview-' . $name . '-' . $g_k; ?>
<div class="preview-animation-item" style="background-color:<?php echo $background_colors[$count % count($background_colors)]; ?>;">
<div class="preview-animation-area">
<div class="preview-animation-element <?php echo $_class_name; ?> <?php echo (strpos($g_v,'infinite')?'':'not-infinite'); ?>" style="color:<?php echo $animation_colors[$count % count($animation_colors)]; ?>;"><?php echo $name; ?></div>
</div>
<textarea class="preview-animation-code">.<?php echo $_class_name; ?><?php echo $g_v; ?>
<?php echo implode('', $keyframes[$name]); ?></textarea>
</div>
<?php ++ $count; ?>
<?php } ?>
<?php } ?>
<?php empty($animations) && print('<div style="width:100%;text-align:center;color:red;padding:5%% 0;">没抓取到任何动效</div>'); ?><file_sep><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>CSS动效提取器-CSS3-HTML5-幻灯片</title>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
}
.clearfix:after {
clear: both;
}
.clearfix {
clear: both;
}
.pull-left {
float: left;
}
.hide {
display: none;
}
.well > div {
margin:10px;
}
.preview-form {
width: 100%;
height: 20px;
position: relative;
z-index: 999;
}
.preview-form .preview-field {
width: 130px;
}
.preview-form .preview-input {
width: 60%;
}
.preview-form .preview-input input {
width: 100%;
height: 20px;
padding:0 5px;
margin:0 0 0 10px;
outline: none;
}
.preview-form .preview-input textarea {
width: 100%;
height: 60px;
padding:0 6px;
margin:0 0 0 10px;
outline: none;
}
.preview-form .preview-submit-btn {
height: 100%;
}
.preview-form .preview-submit-btn input {
height: 100%;
padding:0;
margin:0 0 0 30px;
outline: none;
}
.preview-animation-list {
position: relative;
z-index: 99;
}
.preview-animation-item {
margin:10px;
float: left;
}
.preview-animation-item .preview-animation-area {
width: 200px;
height: 170px;
position: relative;
}
.preview-animation-item .preview-animation-area .preview-animation-element {
display: inline-block;
line-height: 170px;
font-size: 1em;
text-align: center;
white-space:nowrap;
padding:0;
margin:0 auto;
background-position: center center;
position: absolute;
top:auto;
right: 0;
bottom: auto;
left: 0;
z-index: 99;
}
.preview-animation-item .preview-animation-code {
position: relative;
width: 196px;
height:68px;
margin:0 2px;
padding:0;
border:none;
outline:none;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: rgba(255, 255, 255, .8);
overflow: hidden;
z-index: 999;
}
.preview-refresh-btn {
color: #dd0000;
font-size:30px;
position: fixed;
top:50px;
right:20px;
z-index: 9999;
}
</style>
<script src="./dependents/jquery-1.10.2.js"></script>
</head>
<body>
<div class="well">
<legend id="note">CSS动效提取器</legend>
<br/>
<div class="clearfix preview-form">
<label class="pull-left preview-field preview-field-url"> HTML5 URL</label>
<div class="pull-left preview-input preview-input-url">
<input id="url" type="text" name="url" value="http://weixin.jobtong.com/e/1024/power" placeholder="请输入HTML5 URL" autocomplete="on"/>
</div>
<div class="clearfix"></div>
<label class="pull-left preview-field preview-field-css-links"> CSS URL</label>
<div class="pull-left preview-input preview-input-css-links">
<input id="css-links" type="text" name="css_links" value="" placeholder="请输入CSS URL" autocomplete="on"/>
</div>
<div class="clearfix"></div>
<label class="pull-left preview-field preview-field-html"> 含CSS 的HTML</label>
<div class="pull-left preview-input preview-input-html">
<textarea id="html" name="html" placeholder="请输入HTML" autocomplete="off"></textarea>
</div>
<div class="pull-left preview-submit-btn">
<input id="submit" type="button" value="提取CSS"/>
</div>
</div>
<br/>
<div id="preview" class="clearfix preview-animation-list"></div>
</div>
<input class="preview-refresh-btn js-refresh-btn" type="button" value="刷新动画"/>
<script>
! function() {
// set url to hash
function setDataToHash( data ) {
data = data || {};
location.hash = "url=" + encodeURIComponent( data.url || "" ) + "&cssLinks=" + encodeURIComponent( data.cssLinks || "" ) + "&html=" + encodeURIComponent( data.html || "" );
}
// get url from hash
function getDataFromHash() {
var href = location.href,
hash = href.split( "#" )[1] || "",
data = {
url: decodeURIComponent( ( ( hash.match( /url=([^&]*)/ ) || [] )[1] || "" ).replace( "+", "%20" ) ),
cssLinks: decodeURIComponent( ( ( hash.match( /cssLinks=([^&]*)/ ) || [] )[1] || "" ).replace( "+", "%20" ) ),
html: decodeURIComponent( ( ( hash.match( /html=([^&]*)/ ) || [] )[1] || "" ).replace( "+", "%20" ) )
};
return data;
}
// get animations
function getHtml() {
var $btn = $( "#submit" ),
btnText = $btn.val(),
loadingText = "分析提取ing...",
data = {
url: ( $( "#url" ).val() || "" ).replace( /^\s+|\s+$/, "" ),
cssLinks: ( $( "#css-links" ).val() || "" ).replace( /^\s+|\s+$/, "" ),
html: ( $( "#html" ).val() || "" ).replace( /^\s+|\s+$/, "" )
}
if ( $btn.attr( "disabled" ) ) {
return ;
}
$btn.attr( "disabled", true ).val( loadingText );
if (! data.url && ! data.cssLinks && ! data.html) {
alert( "请填写要抓取的内容" );
return;
}
$.getJSON( "rob.php", data, function( res ) {
if ( res.status ) {
$( "title" ).html( res.info.note );
$( "#note" ).html( res.info.note );
$( "#preview" ).html( res.info.html );
} else {
alert( "抓取失败,请稍后重试~" );
}
$btn.attr( "disabled", false ).val( btnText );
} );
}
// manual btn
$( "#submit" ).click( function() {
var data = {
url: $( "#url" ).val(),
cssLinks: $( "#css-links" ).val(),
html: $( "#html" ).val()
};
( data.url || data.cssLinks || data.html ) && setDataToHash( data );
getHtml();
} );
// hashchange
$( window ).bind( "hashchange", function() {
var data = getDataFromHash();
( data.url || data.cssLinks || data.html ) && ( $( "#url" ).val( data.url ), $( "#css-links" ).val( data.cssLinks ), $( "#html" ).val( data.html ), getHtml() );
} ).trigger( "hashchange" );
// auto refresh not-infinite animation
var autoRefreshTimer,
fRefresh = function() {
stopAutoRefresh();
$( "#preview" ).find( ".preview-animation-area > .not-infinite" ).css( "display", "none" );
setTimeout( function() {
$( "#preview" ).find( ".preview-animation-area > .not-infinite" ).css( "display", "inline-block" );
startAutoRefresh();
}, 100 );
},
startAutoRefresh = function() {
autoRefreshTimer = setTimeout( function() {
fRefresh();
}, 8000 );
},
stopAutoRefresh = function() {
clearTimeout( autoRefreshTimer );
};
// manual refresh
$( ".js-refresh-btn" ).click( function() {
var $btn = $( this );
$btn.attr( "disabled", true );
fRefresh();
setTimeout( function() {
$btn.attr( "disabled", false );
}, 1000 );
} );
startAutoRefresh();
} ();
</script>
</body>
</html>
|
dc528f2b673d155fb110ee1288a591e74b0548f7
|
[
"Markdown",
"PHP",
"Shell"
] | 7
|
PHP
|
chenweichuan/css-animation-robber
|
12cd07eeb7b4d28ca2938f00668468810c344147
|
1cfa72935201d85455315c0e26c765db5def81f0
|
refs/heads/master
|
<repo_name>XWHQSJ/HardJava<file_sep>/README.md
# HardJava
## 文件结构
PetStores Java宠物商店项目,源自Oracle-Java官方网站改编,基于Java awt&swing框架
QQ2018 qq的java版实现,功能相对简陋,但五脏俱全,基于Java socket&awt&swing框架
## Java知识点总结
<file_sep>/QQ2018/src/com/carillon/qq/server/Server.java
package com.carillon.qq.server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.json.JSONObject;
public class Server {
public static final int COMMAND_LOGIN = 1;
public static final int COMMAND_LOGOUT = 2;
public static final int COMMAND_SENDMSG = 3;
public static int SERVER_PORT = 7788;
private static List<ClientInfo> clientList = new CopyOnWriteArrayList<ClientInfo>();
static UserDAO dao = new UserDAO();
public static void main(String[] args) {
if (args.length == 1) {
SERVER_PORT = Integer.parseInt(args[0]);
}
System.out.printf("The Server is running, listen to port %d...\n", SERVER_PORT);
byte[] buffer = new byte[2048];
try (DatagramSocket socket = new DatagramSocket(SERVER_PORT)){
while(true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
int len = packet.getLength();
String string = new String(buffer, 0, len);
InetAddress address = packet.getAddress();
int port = packet.getPort();
JSONObject jsonObject = new JSONObject(string);
System.out.println(jsonObject);
int cmd = (int)jsonObject.get("command");
if (cmd == COMMAND_LOGIN) {
String userId = (String)jsonObject.get("user_id");
Map<String, String> user = dao.findById(userId);
if (user != null && jsonObject.get("user_pwd").equals(user.get("user_pwd"))) {
JSONObject sendJsonObject = new JSONObject(user);
sendJsonObject.put("result", 0);
ClientInfo clientInfo = new ClientInfo();
clientInfo.setUserId(userId);
clientInfo.setAddress(address);
clientInfo.setPort(port);
clientList.add(clientInfo);
List<Map<String, String>> friends = dao.findFriends(userId);
for(Map<String, String> friend : friends){
friend.put("online", "0");
String friendId = friend.get("user_id");
for(ClientInfo client : clientList) {
String uId = client.getUserId();
if(uId.equals(friendId)) {
friend.put("online", "1");
break;
}
}
}
sendJsonObject.put("friends", friends);
byte[] bs = sendJsonObject.toString().getBytes();
packet = new DatagramPacket(bs, bs.length, address,port);
socket.send(packet);
for(ClientInfo info : clientList) {
if (!info.getUserId().equals(userId)) {
jsonObject = new JSONObject();
jsonObject.put("user_id", userId);
jsonObject.put("online", "1");
byte[] bs2 = jsonObject.toString().getBytes();
packet = new DatagramPacket(bs2, bs2.length, info.getAddress(), info.getPort());
socket.send(packet);
}
}
}else {
JSONObject sendJsonObject = new JSONObject();
sendJsonObject.put("result", -1);
byte[] bs = sendJsonObject.toString().getBytes();
packet = new DatagramPacket(bs, bs.length, address, port);
socket.send(packet);
}
}else if (cmd == COMMAND_SENDMSG) {
String friendUserId = (String)jsonObject.get("receive_user_id");
for(ClientInfo info : clientList) {
if (info.getUserId().equals(friendUserId)) {
jsonObject.put("OnlineUserList", getUserOnlineStateList());
byte[] bs = jsonObject.toString().getBytes();
packet = new DatagramPacket(bs, bs.length, info.getAddress(), info.getPort());
socket.send(packet);
break;
}
}
}else if (cmd == COMMAND_LOGOUT) {
String userId = (String)jsonObject.get("user_id");
for(ClientInfo info : clientList) {
if (info.getUserId().equals(userId)) {
clientList.remove(info);
break;
}
}
for(ClientInfo info : clientList) {
jsonObject = new JSONObject();
jsonObject.put("user_id", userId);
jsonObject.put("online", "0");
byte[] bs2 = jsonObject.toString().getBytes();
packet = new DatagramPacket(bs2, bs2.length, info.getAddress(),info.getPort());
socket.send(packet);
}
}
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
private static List<Map<String, String>> getUserOnlineStateList() {
// TODO Auto-generated method stub
List<Map<String, String>> userList = dao.findAll();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
for(Map<String, String> user : userList) {
String userId = user.get("user_id");
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", userId);
map.put("online", "0");
for(ClientInfo info : clientList) {
if (info.getUserId().equals(userId)) {
map.put("online", "1");
break;
}
}
list.add(map);
}
return list;
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/ui/ProductListFrame.java
package com.carillon.jpetstore.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.TableModel;
import com.carillon.jpetstore.dao.ProductDao;
import com.carillon.jpetstore.dao.mysql.ProductDaoImp;
import com.carillon.jpetstore.domain.Product;
import javafx.scene.layout.Border;
public class ProductListFrame extends MyFrame{
private JTable table;
private JLabel lblImage;
private JLabel lblListprice;
private JLabel lblDescn;
private JLabel lblUnitcost;
private List<Product> products = null;
private ProductDao dao = new ProductDaoImp();
private Map<String, Integer> cart = new HashMap<String, Integer>();
private int selectedRow = -1;
public ProductListFrame() {
// TODO Auto-generated constructor stub
super("商品列表", 1000, 700);
products = dao.findAll();
getContentPane().add(getSearchPanel(), BorderLayout.NORTH);
JSplitPane splitPane = new JSplitPane();
splitPane.setDividerLocation(600);
splitPane.setLeftComponent(getLeftPanel());
splitPane.setRightComponent(getRightPanel());
getContentPane().add(splitPane, BorderLayout.CENTER);
}
private JPanel getSearchPanel() {
JPanel searchPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout)searchPanel.getLayout();
flowLayout.setVgap(20);
flowLayout.setHgap(40);
JLabel label = new JLabel("选择商品类别: ");
label.setFont(new Font("微软雅黑", Font.PLAIN, 15));
searchPanel.add(label);
String[] categorys = {"鱼类", "狗类", "爬行类", "猫类", "鸟类"};
JComboBox comboBox = new JComboBox(categorys);
comboBox.setFont(new Font("微软雅黑", Font.PLAIN, 15));
searchPanel.add(comboBox);
JButton btnGo = new JButton("查询");
btnGo.setFont(new Font("微软雅黑", Font.PLAIN, 15));
searchPanel.add(btnGo);
JButton btnReset = new JButton("重置");
btnReset.setFont(new Font("微软雅黑", Font.PLAIN, 15));
searchPanel.add(btnReset);
btnGo.addActionListener(e -> {
String category = (String) comboBox.getSelectedItem();
products = dao.findByCategory(category);
TableModel model = new ProductTableModel(products);
table.setModel(model);
});
btnReset.addActionListener(e -> {
products = dao.findAll();
TableModel model = new ProductTableModel(products);
table.setModel(model);
});
return searchPanel;
}
private JPanel getRightPanel() {
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.white);
rightPanel.setLayout(new GridLayout(2, 1, 0, 0));
lblImage = new JLabel();
rightPanel.add(lblImage);
lblImage.setHorizontalAlignment(SwingConstants.CENTER);
JPanel detailPanel = new JPanel();
detailPanel.setBackground(Color.white);
rightPanel.add(detailPanel);
detailPanel.setLayout(new GridLayout(8, 1, 0, 5));
JSeparator separator_1 = new JSeparator();
detailPanel.add(separator_1);
lblListprice = new JLabel();
detailPanel.add(lblListprice);
lblListprice.setFont(new Font("微软雅黑", Font.PLAIN, 16));
lblUnitcost = new JLabel();
detailPanel.add(lblUnitcost);
lblUnitcost.setFont(new Font("微软雅黑", Font.PLAIN, 16));
lblDescn = new JLabel();
detailPanel.add(lblDescn);
lblDescn.setFont(new Font("微软雅黑", Font.PLAIN, 16));
JSeparator separator_2 = new JSeparator();
detailPanel.add(separator_2);
JButton btnAdd = new JButton("添加到购物车");
btnAdd.setFont(new Font("微软雅黑", Font.PLAIN, 15));
detailPanel.add(btnAdd);
// 布局占位使用
JLabel label = new JLabel("");
detailPanel.add(label);
JButton btnCheck = new JButton("查看购物车");
btnCheck.setFont(new Font("微软雅黑", Font.PLAIN, 15));
detailPanel.add(btnCheck);
btnAdd.addActionListener(e -> {
if(selectedRow < 0) {
return;
}
Product selectProduct = products.get(selectedRow);
String productid = selectProduct.getProductid();
if(cart.containsKey(productid)) {
Integer quantity = cart.get(productid);
cart.put(productid, ++quantity);
}else {
cart.put(productid, 1);
}
System.out.println(cart);
});
btnCheck.addActionListener(e -> {
CartFrame cartFrame = new CartFrame(cart, this);
cartFrame.setVisible(true);
setVisible(false);
});
return rightPanel;
}
private JScrollPane getLeftPanel() {
JScrollPane leftScrollPane = new JScrollPane();
leftScrollPane.setViewportView(getTable());
return leftScrollPane;
}
private JTable getTable() {
TableModel model = new ProductTableModel(this.products);
if(table == null) {
table = new JTable(model);
table.setFont(new Font("微软雅黑", Font.PLAIN, 16));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 16));
table.setRowHeight(51);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
ListSelectionModel rowSelectionModel = table.getSelectionModel();
rowSelectionModel.addListSelectionListener(e -> {
if(e.getValueIsAdjusting()) {
return;
}
ListSelectionModel listSelectionModel = (ListSelectionModel) e.getSource();
selectedRow = listSelectionModel.getMinSelectionIndex();
if(selectedRow < 0) {
return;
}
Product product = products.get(selectedRow);
String petImage = String.format("/images/%s", product.getImage());
ImageIcon icon = new ImageIcon(ProductListFrame.class.getResource(petImage));
lblImage.setIcon(icon);
String descn = product.getDescn();
lblDescn.setText("商品描述: " + descn);
double listprice = product.getListprice();
String slistprice = String.format("商品市场价:%.2f", listprice);
lblListprice.setText(slistprice);
double unitcost = product.getUnitcost();
String slblUnitcost = String.format("商品单价: %.2f", unitcost);
lblUnitcost.setText(slblUnitcost);
});
}else {
table.setModel(model);
}
return table;
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/domain/OrderDetail.java
package com.carillon.jpetstore.domain;
// 订单明细
public class OrderDetail {
private long orderid; // 订单Id
private String productid; // 商品Id
private int quantity; // 商品数量
private double unitcost; // 商品价格
public long getOrderid() {
return orderid;
}
public void setOrderid(long orderid) {
this.orderid = orderid;
}
public double getUnitcost() {
return unitcost;
}
public void setUnitcost(double unitcost) {
this.unitcost = unitcost;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getProductid() {
return productid;
}
public void setProductid(String productid) {
this.productid = productid;
}
}
<file_sep>/On-Java8/OnJava8.md
# On Java 8 --中文版
## 第一章 对象的概念
## 第二章 安装Java和本书用例<file_sep>/PetStores/src/com/carillon/jpetstore/domain/Product.java
package com.carillon.jpetstore.domain;
public class Product {
private String productid; // 商品Id
private String category; // 商品类别
private String cname; // 商品中文名
private String ename; // 商品英文名
private String image; // 商品图片
private String descn; // 商品描述
private double listprice; // 商品市场价
private double unitcost; // 商品单价
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getDescn() {
return descn;
}
public void setDescn(String descn) {
this.descn = descn;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getListprice() {
return listprice;
}
public void setListprice(double listprice) {
this.listprice = listprice;
}
public String getProductid() {
return productid;
}
public void setProductid(String productid) {
this.productid = productid;
}
public double getUnitcost() {
return unitcost;
}
public void setUnitcost(double unitcost) {
this.unitcost = unitcost;
}
}<file_sep>/QQ2018/src/com/carillon/qq/client/ChatFrame.java
package com.carillon.qq.client;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.json.JSONArray;
import org.json.JSONObject;
public class ChatFrame extends JFrame implements Runnable {
private boolean isRunning = true;
// 当前用户Id
private String userId;
// 聊天好友用户Id
private String friendUserId;
// 聊天好友用户名
private String friendUserName;
// 获得当前屏幕的高和宽
private double screenHeight = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
private double screenWidth = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
// 登录窗口宽和高
private int frameWidth = 345;
private int frameHeight = 310;
// 查看消息文本区
private JTextArea txtMainInfo;
// 发送消息文本区
private JTextArea txtInfo;
// 消息日志
private StringBuffer infoLog;
// 接收消息子线程
private Thread receiveMessageThread;
// 日期格式化
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 好友列表Frame
private FriendsFrame friendsFrame;
public ChatFrame(FriendsFrame friendsFrame, Map<String, String> user, Map<String, String> friend) {
// 初始化成员变量
this.friendsFrame = friendsFrame;
this.userId = user.get("user_id");
String userIcon = user.get("user_icon");
this.friendUserId = friend.get("user_id");
this.friendUserName = friend.get("user_name");
this.infoLog = new StringBuffer();
// 初始化查看消息面板
getContentPane().add(getPanLine1());
// 初始化发送消息面板
getContentPane().add(getPanLine2());
/// 初始化当前Frame
String iconFile = String.format("/resource/img/%s.jpg", userIcon);
setIconImage(Toolkit.getDefaultToolkit().getImage(Client.class.getResource(iconFile)));
String title = String.format("与%s聊天中...", friendUserName);
setTitle(title);
setResizable(false);
getContentPane().setLayout(null);
// 设置Frame大小
setSize(frameWidth, frameHeight);
// 计算Frame位于屏幕中心的坐标
int x = (int) (screenWidth - frameWidth) / 2;
int y = (int) (screenHeight - frameHeight) / 2;
// 设置Frame位于屏幕中心
setLocation(x, y);
receiveMessageThread = new Thread(this);
receiveMessageThread.start();
// 注册窗口事件
addWindowListener(new WindowAdapter() {
// 单击窗口关闭按钮时调用
public void windowClosing(WindowEvent e) {
isRunning = false;
setVisible(false);
// 重启好友列表线程
friendsFrame.resetThread();
}
});
}
// 查看消息面板
private JPanel getPanLine1() {
txtMainInfo = new JTextArea();
txtMainInfo.setEditable(false);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 5, 320, 200);
scrollPane.setViewportView(txtMainInfo);
JPanel panLine1 = new JPanel();
panLine1.setLayout(null);
panLine1.setBounds(new Rectangle(5, 5, 330, 210));
panLine1.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
panLine1.add(scrollPane);
return panLine1;
}
// 发送消息面板
private JPanel getPanLine2() {
JPanel panLine2 = new JPanel();
panLine2.setLayout(null);
panLine2.setBounds(5, 220, 330, 50);
panLine2.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
panLine2.add(getSendButton());
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 5, 222, 40);
panLine2.add(scrollPane);
txtInfo = new JTextArea();
scrollPane.setViewportView(txtInfo);
return panLine2;
}
private JButton getSendButton() {
JButton button = new JButton("发送");
button.setBounds(232, 10, 90, 30);
button.addActionListener(e -> {
sendMessage();
txtInfo.setText("");
});
return button;
}
private void sendMessage() {
if (!txtInfo.getText().equals("")) {
// 获得当前时间,并格式化
String date = dateFormat.format(new Date());
String info = String.format("#%s#" + "\n" + "您对%s说:%s", date, friendUserName, txtInfo.getText());
infoLog.append(info).append('\n');
txtMainInfo.setText(infoLog.toString());
Map<String, String> message = new HashMap<String, String>();
message.put("receive_user_id", friendUserId);
message.put("user_id", userId);
message.put("message", txtInfo.getText());
JSONObject jsonObj = new JSONObject(message);
jsonObj.put("command", Client.COMMAND_SENDMSG);
try {
InetAddress address = InetAddress.getByName(Client.SERVER_IP);
/* 发送数据报 */
byte[] b = jsonObj.toString().getBytes();
DatagramPacket packet = new DatagramPacket(b, b.length, address, Client.SERVER_PORT);
Client.socket.send(packet);
} catch (IOException e) {
}
}
}
@Override
public void run() {
// 准备一个缓冲区
byte[] buffer = new byte[1024];
while (isRunning) {
try {
InetAddress address = InetAddress.getByName(Client.SERVER_IP);
/* 接收数据报 */
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, Client.SERVER_PORT);
// 开始接收
Client.socket.receive(packet);
// 接收数据长度
int len = packet.getLength();
String str = new String(buffer, 0, len);
// 打印接收的数据
System.out.printf("从服务器接收的数据:【%s】\n", str);
JSONObject jsonObj = new JSONObject(str);
// 获得当前时间,并格式化
String date = dateFormat.format(new Date());
String message = (String) jsonObj.get("message");
String info = String.format("#%s#" + "\n" + "%s对您说:%s", date, friendUserName, message);
infoLog.append(info).append('\n');
txtMainInfo.setText(infoLog.toString());
txtMainInfo.setCaretPosition(txtMainInfo.getDocument().getLength());
Thread.sleep(100);
// 刷新好友列表
JSONArray userList = (JSONArray) jsonObj.get("OnlineUserList");
for (Object item : userList) {
JSONObject onlineUser = (JSONObject) item;
String userId = (String) onlineUser.get("user_id");
String online = (String) onlineUser.get("online");
friendsFrame.refreshFriendList(userId, online);
}
} catch (Exception e) {
}
}
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/domain/Account.java
package com.carillon.jpetstore.domain;
public class Account {
/* 私有成员变量 */
private String userid; // 用户Id
private String password; // <PASSWORD>
private String email; // 用户邮箱
private String username; // 用户名
private String addr; // 地址
private String city; // 所在城市
private String country; // 国家
private String phone; // 电话号码
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/ui/CartFrame.java
package com.carillon.jpetstore.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.sql.Date;
import java.util.Map;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import com.carillon.jpetstore.dao.OrderDao;
import com.carillon.jpetstore.dao.OrderDetailDao;
import com.carillon.jpetstore.dao.ProductDao;
import com.carillon.jpetstore.dao.mysql.OrderDaoImp;
import com.carillon.jpetstore.dao.mysql.OrderDetailDaoImp;
import com.carillon.jpetstore.dao.mysql.ProductDaoImp;
import com.carillon.jpetstore.domain.Order;
import com.carillon.jpetstore.domain.OrderDetail;
import com.carillon.jpetstore.domain.Product;
public class CartFrame extends MyFrame{
private JTable table;
private Object[][] data = null;
private ProductDao dao = new ProductDaoImp();
private Map<String, Integer> cart;
private ProductListFrame productListFrame;
public CartFrame(Map<String, Integer> cart, ProductListFrame productListFrame) {
// TODO Auto-generated constructor stub
super("商品购物车", 1000, 700);
this.cart = cart;
this.productListFrame = productListFrame;
JPanel topPanel = new JPanel();
FlowLayout f1_topPanel = (FlowLayout)topPanel.getLayout();
f1_topPanel.setVgap(10);
f1_topPanel.setHgap(20);
getContentPane().add(topPanel, BorderLayout.NORTH);
JButton btnReturn = new JButton("返回商品列表");
btnReturn.setFont(new Font("微软雅黑", Font.PLAIN, 15));
topPanel.add(btnReturn);
JButton btnSubmit = new JButton("提交订单");
topPanel.add(btnSubmit);
btnSubmit.setFont(new Font("微软雅黑", Font.PLAIN, 15));
JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(getTable());
btnSubmit.addActionListener(e -> {
generateOrders();
JLabel label = new JLabel("订单已经生成,等待付款.");
label.setFont(new Font("微软雅黑", Font.PLAIN, 15));
if (JOptionPane.showConfirmDialog(this, label, "信息", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
System.exit(0);
}else {
System.exit(0);
}
});
btnReturn.addActionListener(e -> {
for(int i = 0; i < data.length; ++i) {
String productid = (String)data[i][0];
Integer quantity = (Integer) data[i][3];
cart.put(productid, quantity);
}
this.productListFrame.setVisible(true);
setVisible(false);
});
}
private JTable getTable() {
// TODO Auto-generated method stub
data = new Object[cart.size()][5];
Set<String> keys = this.cart.keySet();
int index = 0;
for(String productid : keys) {
Product product = dao.findById(productid);
data[index][0] = product.getProductid();
data[index][1] = product.getCname();
data[index][2] = new Double(product.getUnitcost());
data[index][3] = new Integer(cart.get(productid));
double amount = (double)data[index][2] * (int) data[index][3];
data[index][4] = new Double(amount);
index++;
}
TableModel model = new CartTableModel(data);
if (table == null) {
table = new JTable(model);
table.setFont(new Font("微软雅黑", Font.PLAIN, 16));
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 16));
table.setRowHeight(51);
table.setRowSelectionAllowed(false);
}else {
table.setModel(model);
}
return table;
}
private double getOrderTotalAmount() {
// TODO Auto-generated method stub
double totalAmount = 0.0;
for(int i = 0; i < data.length; ++i) {
totalAmount += (Double) data[i][4];
System.out.println("print data msg: " + totalAmount);
}
System.out.println("print totalAmount msg: " + totalAmount);
return totalAmount;
}
private void generateOrders() {
// TODO Auto-generated method stub
OrderDao orderDao = new OrderDaoImp();
OrderDetailDao orderDetailDao = new OrderDetailDaoImp();
Order order = new Order();
java.util.Date now = new java.util.Date();
System.out.println("print now msg: " + now);
long orderId = now.getTime();
System.out.println("print orderId msg: " + orderId);
order.setOrderid(orderId);
order.setOrderdate(now);
order.setAmount(getOrderTotalAmount());
System.out.println("print userid msg: " + MainApp.account.getUserid());
order.setUserid(MainApp.account.getUserid());
order.setStatus(0);
System.out.println("print create msg1");
orderDao.create(order);
System.out.println("print create msg2");
for(int i = 0; i < data.length; ++i) {
OrderDetail orderDetail = new OrderDetail();
orderDetail.setOrderid(orderId);
orderDetail.setProductid((String) data[i][0]);
orderDetail.setQuantity((int)data[i][3]);
orderDetail.setUnitcost((double) data[i][2]);
orderDetailDao.create(orderDetail);
}
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/domain/Order.java
package com.carillon.jpetstore.domain;
import java.util.Date;
public class Order {
private long orderid; // 订单Id
private String userid; // 下订单的用户Id
private Date orderdate; // 下订单的时间
private int status; // 订单付款状态 0待付款 1已付款
private double amount; // 订单应付金额
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public long getOrderid() {
return orderid;
}
public void setOrderid(long orderid) {
this.orderid = orderid;
}
public Date getOrderdate() {
return orderdate;
}
public void setOrderdate(Date orderdate) {
this.orderdate = orderdate;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/dao/OrderDao.java
package com.carillon.jpetstore.dao;
import java.util.List;
import com.carillon.jpetstore.domain.Order;
public interface OrderDao {
// 查询所有订单信息
List<Order> findAll();
// 根据主键查询订单信息
Order findById(int orderid);
// 常见订单信息
int create(Order order);
// 修改订单信息
int modify(Order order);
// 删除订单信息
int remove(Order order);
}
<file_sep>/PetStores/src/com/carillon/jpetstore/ui/LoginFrame.java
package com.carillon.jpetstore.ui;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import com.carillon.jpetstore.dao.AccountDao;
import com.carillon.jpetstore.dao.mysql.AccountDaoImp;
import com.carillon.jpetstore.domain.Account;
public class LoginFrame extends MyFrame{
private JTextField txtAccountId;
private JPasswordField txtPassword;
public LoginFrame() {
super("登录", 400, 230);
getContentPane().setLayout(null);
JLabel label1 = new JLabel();
label1.setHorizontalAlignment(SwingConstants.RIGHT);
label1.setBounds(51, 33, 83, 30);
getContentPane().add(label1);
label1.setText("账号");
label1.setFont(new Font("微软雅黑", Font.PLAIN, 15));
txtAccountId = new JTextField(10);
txtAccountId.setText("j2ee");
txtAccountId.setBounds(158, 33, 157, 30);
txtAccountId.setFont(new Font("微软雅黑", Font.PLAIN, 15));
getContentPane().add(txtAccountId);
JLabel label2 = new JLabel();
label2.setText("密码");
label2.setFont(new Font("微软雅黑", Font.PLAIN, 15));
label2.setHorizontalAlignment(SwingConstants.RIGHT);
label2.setBounds(51, 85, 83, 30);
getContentPane().add(label2);
txtPassword = new JPasswordField(10);
txtPassword.setText("<PASSWORD>");
txtPassword.setBounds(158, 85, 157, 30);
getContentPane().add(txtPassword);
JButton btnOk = new JButton();
btnOk.setText("确定");
btnOk.setFont(new Font("微软雅黑", Font.PLAIN, 15));
btnOk.setBounds(61, 140, 100, 30);
getContentPane().add(btnOk);
JButton btnCancel = new JButton();
btnCancel.setText("取消");
btnCancel.setFont(new Font("微软雅黑", Font.PLAIN, 15));
btnCancel.setBounds(225, 140, 100, 30);
getContentPane().add(btnCancel);
btnOk.addActionListener(e -> {
AccountDao accountDao = new AccountDaoImp();
Account account = accountDao.findById(txtAccountId.getText());
String passwordText = new String(txtPassword.getPassword());
if(account != null && passwordText.equals(account.getPassword())) {
System.out.println("登录成功");
ProductListFrame form = new ProductListFrame();
form.setVisible(true);
setVisible(false);
MainApp.account = account;
}else {
JLabel label = new JLabel("您输入的账号或密码有误,请重新输入!");
label.setFont(new Font("微软雅黑", Font.PLAIN, 15));
JOptionPane.showMessageDialog(null, label, "登录失败", JOptionPane.ERROR_MESSAGE);
}
});
btnCancel.addActionListener(e -> {
System.exit(0);
});
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/dao/mysql/ProductDaoImp.java
package com.carillon.jpetstore.dao.mysql;
import com.carillon.jpetstore.domain.Product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.carillon.jpetstore.dao.ProductDao;
public class ProductDaoImp implements ProductDao{
@Override
public List<Product> findAll() {
// TODO Auto-generated method stub
String sql = "select productid, category, cname, ename, image, " +
"listprice, unitcost, descn from product";
List<Product> products = new ArrayList<Product>();
try(
// 创建数据库连接
Connection conn = DBHelper.getConnection();
// 创建语句对象
PreparedStatement pstmt = conn.prepareStatement(sql);
// 绑定参数
// 执行查询
ResultSet rs = pstmt.executeQuery()){
// 遍历结果集
while (rs.next()) {
Product product = new Product();
product.setProductid(rs.getString("productid"));
product.setCategory(rs.getString("category"));
product.setCname(rs.getString("cname"));
product.setEname(rs.getString("ename"));
product.setImage(rs.getString("image"));
product.setListprice(rs.getDouble("listprice"));
product.setUnitcost(rs.getDouble("unitcost"));
product.setDescn(rs.getString("descn"));
products.add(product);
}
}catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
return products;
}
@Override
public List<Product> findByCategory(String category) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Product> products = new ArrayList<Product>();
try {
connection = DBHelper.getConnection();
String sql = "select productid,category,cname,ename,image,listprice,unitcost,descn " +
"from product where category = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, category);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Product product = new Product();
product.setProductid(resultSet.getString("productid"));
product.setCategory(resultSet.getString("category"));
product.setCname(resultSet.getString("cname"));
product.setEname(resultSet.getString("ename"));
product.setImage(resultSet.getString("image"));
product.setListprice(resultSet.getDouble("listprice"));
product.setUnitcost(resultSet.getDouble("unitcost"));
product.setDescn(resultSet.getString("descn"));
products.add(product);
}
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
return products;
}
@Override
public Product findById(String productid) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBHelper.getConnection();
String sql = "select productid, category, cname, ename, image, descn, listprice, unitcost" +
" from product where productid = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, productid);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Product product = new Product();
product.setProductid(resultSet.getString("productid"));
product.setCategory(resultSet.getString("category"));
product.setCname(resultSet.getString("cname"));
product.setEname(resultSet.getString("ename"));
product.setImage(resultSet.getString("image"));
product.setListprice(resultSet.getDouble("listprice"));
product.setUnitcost(resultSet.getDouble("unitcost"));
product.setDescn(resultSet.getString("descn"));
return product;
}
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if(resultSet != null) {
try {
resultSet.close();
} catch (SQLException e2) {
// TODO: handle exception
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
return null;
}
@Override
public int create(Product product) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int modify(Product product) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int remove(Product product) {
// TODO Auto-generated method stub
return 0;
}
}
<file_sep>/PetStores/src/com/carillon/jpetstore/ui/CartTableModel.java
package com.carillon.jpetstore.ui;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class CartTableModel extends AbstractTableModel{
private String[] columnNames = {"商品编号", "商品名", "商品单价", "数量", "商品应付金额"};
private Object[][] data = null;
public CartTableModel(Object[][] data) {
// TODO Auto-generated constructor stub
this.data = data;
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return columnNames.length;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
if(columnIndex != 3) {
return;
}
try {
int quantity = new Integer((String) aValue);
if(quantity < 0) {
return;
}
data[rowIndex][3] = quantity;
double unitcost = (double)data[rowIndex][2];
double totalPrice = unitcost * quantity;
data[rowIndex][4] = new Double(totalPrice);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
return data[rowIndex][columnIndex];
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return data.length;
}
@Override
public String getColumnName(int columnIndex) {
// TODO Auto-generated method stub
return columnNames[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
if(columnIndex == 3) {
return true;
}
return false;
}
}
|
6c083dd8e3a33f8b36d33eb9e0ceba30f0293d2b
|
[
"Markdown",
"Java"
] | 14
|
Markdown
|
XWHQSJ/HardJava
|
0f85ad8c7ba595c8ef0a8cfe31b7a2509f3975e8
|
19e491cffb77dd471a1f3a70b227006c36810163
|
refs/heads/master
|
<file_sep>source ~/env/bin/py3/bin/activate
g++ -O3 -Wall -shared -std=c++11 -fPIC `python -m pybind11 --includes` cpp/arithmetic.cpp -o pipeg/arithmetic.cpython-36m-x86_64-linux-gnu.so `python3-config --ldflags` -I/usr/include/python3.6m/
python setup.py bdist_wheel
pip install dist/pipeg-0.0.1-py3-none-any.whl
python -c "import pipeg; print(pipeg.arithmetic.add(1,2))"
<file_sep>from . import arithmetic
# from ctypes import CDLL
# import os
# import pyexample
# lib_path = os.path.join(os.path.dirname(__file__), 'pyexample')
# lib = CDLL(lib_path)
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
#############################################
# File Name: setup.py
# Author: xingming
# Mail: <EMAIL>
# Created Time: 2015-12-11 01:25:34 AM
#############################################
from setuptools import setup, find_packages, Distribution
# class BinaryDistribution(Distribution):
# def has_ext_modules(foo):
# return True
setup(name="pipeg",
version="0.0.1",
packages=find_packages(),
package_dir={'': '.'},
package_data={'': ['arithmetic.cpython-36m-x86_64-linux-gnu.so']},
include_package_data=True,
platforms="any",
install_requires=[])
|
f04a8ab05dee560b3403e1abdd21546b82ab50af
|
[
"Python",
"Shell"
] | 3
|
Shell
|
glynpu/example_cpp_to_pip_whl
|
6c3ee10ab4080d26e06a89c11cb6d8d6d4ad6fd1
|
4ba96ba13734f25ea1cf71a37f74b4cf007e1e71
|
refs/heads/master
|
<file_sep>#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int LMS = 0;
int valorlido = 0;
void setup()
{
lcd.begin(16,2);
}
void loop()
{
valorlido = analogRead (LMS);
//lcd.setCursor(0, 0);
//lcd.print("Valor lido pelo sensor: ");
//lcd.setCursor(0, 1);
// lcd.print(valorlido);
if (valorlido < 100 )
{
lcd.setCursor(0, 0);
lcd.print("Esta Escuro !");
lcd.setCursor(0, 1);
lcd.print(valorlido);
}
else
{
lcd.setCursor(0, 0);
lcd.print("Esta Claro !");
lcd.setCursor(0, 1);
lcd.print(valorlido);
}
if (valorlido> 900)
{
lcd.setCursor(0, 0);
lcd.print("Esta muito claro");
}
delay (1000);
}
<file_sep># Arduino_Projects
some Arduino scketchs to beginers
<file_sep>const int Piezo = 9;
int Tempo = 1135;
void setup() {
pinMode(Piezo, OUTPUT);
}
void loop(){
//digitalWrite(Piezo, HIGH);
//delayMicroseconds(Tempo);
//digitalWrite(Piezo, LOW);
//delayMicroseconds(Tempo);
// essa e uma opsao para o que foi feito acima funciona da mesma forma
tone(Piezo, 440);
}
<file_sep>const int LM35 = 0;
float temperatura = 0;
int ADClido = 0;
const int LED[]={2,3,4,5,6,7,8,9,10,11};
void setup()
{
analogReference(INTERNAL);
for (int i=0; i<10; i++)
{
pinMode(LED[i], OUTPUT);
}
}
void loop()
{
ADClido = analogRead(LM35);
temperatura = ADClido* 0.1075268817204301;
if (temperatura > 10)
digitalWrite(LED[0], HIGH);
else
digitalWrite(LED[0], LOW);
if (temperatura > 11.5)
digitalWrite(LED[1], HIGH);
else
digitalWrite(LED[1], LOW);
if (temperatura > 12.5)
digitalWrite(LED[2], HIGH);
else
digitalWrite(LED[2], LOW);
if (temperatura > 13.5)
digitalWrite(LED[3], HIGH);
else
digitalWrite(LED[3], LOW);
if (temperatura > 20)
digitalWrite(LED[4], HIGH);
else
digitalWrite(LED[4], LOW);
if (temperatura > 23)
digitalWrite(LED[5], HIGH);
else
digitalWrite(LED[5], LOW);
if (temperatura > 25)
digitalWrite(LED[6], HIGH);
else
digitalWrite(LED[6], LOW);
if (temperatura > 30)
digitalWrite(LED[7], HIGH);
else
digitalWrite(LED[7], LOW);
if (temperatura > 35)
digitalWrite(LED[8], HIGH);
else
digitalWrite(LED[8], LOW);
if (temperatura > 35.5)
digitalWrite(LED[9], HIGH);
else
digitalWrite(LED[9], LOW);
if (temperatura > 40)
digitalWrite(LED[10], HIGH);
else
digitalWrite(LED[10], LOW);
delay(1000);
}
<file_sep>
const int led1= 13;
const int led2= 12;
const int led3= 11;
const int botao1 = 2;
const int botao2 = 3;
const int botao3 = 4;
const int buzzer = 10;
int estadobotao1 =0;
int estadobotao2 =0;
int estadobotao3 =0;
int Tom = 0;
void setup ()
{
pinMode(buzzer, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(botao1, INPUT);
pinMode(led2, OUTPUT);
pinMode(botao2, INPUT);
pinMode(led3, OUTPUT);
pinMode(botao3, INPUT);
}
void loop()
{
estadobotao1 = digitalRead(botao1);
estadobotao2 = digitalRead(botao2);
estadobotao3 = digitalRead(botao3);
if(estadobotao1 && !estadobotao2 && !estadobotao3)
{
Tom = 100;
digitalWrite(led1, HIGH);
}
if (estadobotao2 && !estadobotao1 && !estadobotao3)
{
Tom = 200;
digitalWrite(led2,HIGH);
}
if (estadobotao3 && !estadobotao2 && !estadobotao1)
{
Tom=300;
digitalWrite(led3, HIGH);
}
if(Tom > 0)
{
delayMicroseconds(Tom);
digitalWrite(buzzer, LOW);
delayMicroseconds(Tom);
Tom = 0;
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
}
}
|
65a3b7ef6c999cb92b5a989f96a3b221683481e7
|
[
"Markdown",
"C++"
] | 5
|
C++
|
iotondato/Arduino_Projects
|
55f41465e6475842c901b21caa43617905de6315
|
0aac218fcb0beb71edb29f212f39f8bda2ccfc93
|
refs/heads/master
|
<repo_name>18511084155/DeviceInfoHelper<file_sep>/DeviceSdk/src/main/java/com/woodys/devicelib/location/LocationGetter.java
package com.woodys.devicelib.location;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.telephony.CellInfo;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import com.woodys.devicelib.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import static com.woodys.devicelib.DeviceUtil.noSameName;
/**
* Created by lisiwei on 2018/2/12.
*/
public class LocationGetter extends SetterAndGetter implements LocationConstants {
private TelephonyManager tm;
private WifiManager wm;
public LocationGetter(Context context){
tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
public JSONObject getCellLocation(Context context) throws Exception {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
CellLocation cl = tm.getCellLocation();
JSONObject obj = new JSONObject();
if (null != cl) {
if (cl instanceof CdmaCellLocation) {
CdmaCellLocation ccl = (CdmaCellLocation) cl;
obj.put(CL_TYPE, CL_CDMACELLLOCATION);
obj.put(CL_BASESTATIONID, ccl.getBaseStationId());
obj.put(CL_BASESTATIONLATITUDE, ccl.getBaseStationLatitude());
obj.put(CL_BASESTATIONLONGTITUDE, ccl.getBaseStationLongitude());
obj.put(CL_NETWORKID, ccl.getNetworkId());
obj.put(CL_SYSTEMID, ccl.getSystemId());
} else if (cl instanceof GsmCellLocation) {
GsmCellLocation gcl = (GsmCellLocation) cl;
obj.put(CL_TYPE, CL_GSMCELLLOCATION);
obj.put(CL_GSMCID, gcl.getCid());
obj.put(CL_GSMLAC, gcl.getLac());
obj.put(CL_GSMPSC, gcl.getPsc());
}
}
return obj;
}
public JSONArray getNeighboringCellInfo(Context context) throws Exception {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
List<NeighboringCellInfo> nciList = tm.getNeighboringCellInfo();
JSONArray array = new JSONArray();
if (null != nciList && nciList.size() > 0) {
for (NeighboringCellInfo nci : nciList) {
JSONObject obj = new JSONObject();
Log.i("RRX", "CID: " + nci.getCid());
obj.put(NCI_CID, nci.getCid());
Log.i("RRX", "LAC: " + nci.getLac());
obj.put(NCI_LAC, nci.getLac());
Log.i("RRX", "NETWORKTYPE: " + nci.getNetworkType());
obj.put(NCI_NETWORKTYPE, nci.getNetworkType());
Log.i("RRX", "PSC: " + nci.getPsc());
obj.put(NCI_PSC, nci.getPsc());
Log.i("RRX", "RSSI: " + nci.getRssi());
obj.put(NCI_RSSI, nci.getRssi());
array.put(obj);
}
}
return array;
}
public JSONArray getAllCellInfo(Context context) throws Exception {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
List<CellInfo> ciList = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
ciList = tm.getAllCellInfo();
}
JSONArray array = new JSONArray();
Gson gson = new Gson();
Log.i("RRX", "getAllCellInfo");
if(null != ciList && ciList.size() > 0) {
for(CellInfo ci : ciList) {
if(null != ci){
String json = gson.toJson(ci);
JSONObject item = new JSONObject(json);
array.put(item);
}
}
}
return array;
}
public JSONObject getWifiConnectionInfo() throws Exception {
WifiInfo ci = wm.getConnectionInfo();
JSONObject obj = new JSONObject();
obj.put(CI_BSSID, ci.getBSSID());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
obj.put(CI_Frequency, ci.getFrequency());
}
obj.put(CI_HiddenSSID, ci.getHiddenSSID());
obj.put(CI_IpAddress, ci.getIpAddress());
obj.put(CI_LinkSpeed, ci.getLinkSpeed());
obj.put(CI_MacAddress, ci.getMacAddress());
obj.put(CI_NetworkId, ci.getNetworkId());
obj.put(CI_Rssi, ci.getRssi());
obj.put(CI_SSID, ci.getSSID());
obj.put(CI_SupplicantState, ci.getSupplicantState());
obj.put(CI_txBad, getFieldValueByNameLong(ci, "txBad"));
obj.put(CI_txRetries, getFieldValueByNameLong(ci, "txRetries"));
obj.put(CI_txSuccess, getFieldValueByNameLong(ci, "txSuccess"));
obj.put(CI_rxSuccess, getFieldValueByNameLong(ci, "rxSuccess"));
obj.put(CI_txBadRate, getFieldValueByNameDouble(ci, "txBadRate"));
obj.put(CI_txRetriesRate, getFieldValueByNameDouble(ci, "txRetriesRate"));
obj.put(CI_txSuccessRate, getFieldValueByNameDouble(ci, "txSuccessRate"));
obj.put(CI_rxSuccessRate, getFieldValueByNameDouble(ci, "rxSuccessRate"));
obj.put(CI_badRssiCount, getFieldValueByNameInt(ci, "badRssiCount"));
obj.put(CI_linkStuckCount, getFieldValueByNameInt(ci, "linkStuckCount"));
obj.put(CI_lowRssiCount, getFieldValueByNameInt(ci, "lowRssiCount"));
obj.put(CI_score, getFieldValueByNameInt(ci, "score"));
return obj;
}
public JSONArray getScanResults() throws Exception {
List<ScanResult> srList = noSameName(wm.getScanResults());
JSONArray array = new JSONArray();
if(null != srList && srList.size() > 0) {
for(ScanResult sr : srList) {
JSONObject obj = new JSONObject();
//wifiSsid = source.wifiSsid; parcelable TBD
obj.put(SR_BSSID, sr.BSSID);
obj.put(SR_SSID, getFieldValueByNameString(sr, SR_SSID));
obj.put(SR_hessid, getFieldValueByNameLong(sr, SR_hessid));
obj.put(SR_anqpDomainId, getFieldValueByNameInt(sr, SR_anqpDomainId));
//obj.put(SR_informationElements, getFieldValueByNameString(sr, SR_informationElements));
//obj.put(SR_anqpElements, getFieldValueByNameString(sr, SR_anqpElements));
obj.put(SR_capabilities, sr.capabilities);
obj.put(SR_level, sr.level);
obj.put(SR_frequency, sr.frequency);
obj.put(SR_channelWidth, getFieldValueByNameInt(sr, SR_channelWidth));
obj.put(SR_centerFreq0, getFieldValueByNameInt(sr, SR_centerFreq0));
obj.put(SR_centerFreq1, getFieldValueByNameInt(sr, SR_centerFreq1));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
obj.put(SR_timestamp, sr.timestamp);
}
obj.put(SR_distanceCm, getFieldValueByNameInt(sr, SR_distanceCm));
obj.put(SR_distanceSdCm, getFieldValueByNameInt(sr, SR_distanceSdCm));
obj.put(SR_seen, getFieldValueByNameLong(sr, SR_seen));
obj.put(SR_untrusted, getFieldValueByNameBoolean(sr, SR_untrusted));
obj.put(SR_numConnection, getFieldValueByNameInt(sr, SR_numConnection));
obj.put(SR_numUsage, getFieldValueByNameInt(sr, SR_numUsage));
obj.put(SR_numIpConfigFailures, getFieldValueByNameInt(sr, SR_numIpConfigFailures));
obj.put(SR_isAutoJoinCandidate, getFieldValueByNameInt(sr, SR_isAutoJoinCandidate));
obj.put(SR_flags, getFieldValueByNameLong(sr, SR_flags));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
obj.put(SR_venueName, sr.venueName.toString());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
obj.put(SR_operatorFriendlyName, sr.operatorFriendlyName.toString());
}
array.put(obj);
}
}
return array;
}
}
<file_sep>/DeviceSdk/src/main/java/com/woodys/devicelib/model/NeighboringStationInfo.java
package com.woodys.devicelib.model;
import java.io.Serializable;
/**
* Created by Zhao_xl on 17/5/26.
*/
public class NeighboringStationInfo implements Serializable{
public String cid;
public String lac;
public String rssi;
}
<file_sep>/settings.gradle
include ':app', ':DeviceSdk'
<file_sep>/DeviceSdk/nexus-push.gradle
apply plugin: 'com.github.dcendents.android-maven'
group = GROUP_ID
version = VERSION
android.libraryVariants.all { variant ->
println variant.javaCompile.classpath.files
if(variant.name == 'release') { //我们只需 release 的 javadoc
task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) {
// title = ''
// description = ''
source = variant.javaCompile.source
classpath = files(variant.javaCompile.classpath.files, project.android.getBootClasspath())
options {
encoding "utf-8"
links "http://docs.oracle.com/javase/7/docs/api/"
linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference"
}
exclude '**/BuildConfig.java'
exclude '**/R.java'
}
task("javadoc${variant.name.capitalize()}Jar", type: Jar, dependsOn: "generate${variant.name.capitalize()}Javadoc") {
classifier = 'javadoc'
from tasks.getByName("generate${variant.name.capitalize()}Javadoc").destinationDir
}
artifacts {
archives tasks.getByName("javadoc${variant.name.capitalize()}Jar")
}
}
}
task makeJar(type: Copy) {
delete 'build/libs/'+ARTIFACT_ID+'.jar'
from('build/intermediates/bundles/release/')
into('build/libs/')
include('classes.jar')
rename ('classes.jar', ARTIFACT_ID+'.jar')
}
task javadoc(type: Javadoc) {
//添加UTF-8编码否则注释可能JAVADOC文档可能生成不了
options{
encoding "UTF-8"
charSet 'UTF-8'
author true
version true
links "http://docs.oracle.com/javase/7/docs/api"
title "swipeJavaDoc"
}
source = android.sourceSets.main.java.srcDirs
options.linkSource true
classpath += project.files(project.android.getBootClasspath().join(File.pathSeparator))
failOnError false
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
task sourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.srcDirs
}
artifacts {
archives javadocJar
archives sourcesJar
}
uploadArchives {
configuration = configurations.archives
repositories {
mavenDeployer {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def userName = properties.getProperty("nexus.userName")
def password = <PASSWORD>("nexus.password")
def mavenUrl = properties.getProperty("nexus.mavenUrl")
//http://127.0.0.1:9999/nexus-zip/repository/maven-releases/" 仓库路径的url
repository(url: mavenUrl) {
authentication(userName: userName, password: <PASSWORD>) //账号,密码
}
pom.project {
//version:版本号
version VERSION
//artifactId:类似于项目名称
artifactId ARTIFACT_ID
//groupId:唯一标识符
groupId GROUP_ID
packaging POM_PACKAGING
description PROJECT_DESC
}
}
}
}<file_sep>/DeviceSdk/src/main/java/com/woodys/devicelib/model/AudioManagerInfo.java
package com.woodys.devicelib.model;
import java.io.Serializable;
/**
* Created by woodys on 2018/3/26.
*/
public class AudioManagerInfo implements Serializable {
//audioManager
public int streamVolume0;
public int streamVolume1;
public int streamVolume2;
public int streamVolume3;
public int streamVolume4;
}
<file_sep>/DeviceSdk/src/main/java/com/woodys/devicelib/callback/DeviceInfoListener.java
package com.woodys.devicelib.callback;
import org.json.JSONObject;
/**
* Created by woodys on 2018/3/26.
*/
public interface DeviceInfoListener {
public JSONObject run(JSONObject jsonObject);
}
<file_sep>/README.md
# DeviceInfoHelper
android获取设备信息<file_sep>/DeviceSdk/src/main/java/com/woodys/devicelib/model/SensorInfo.java
package com.woodys.devicelib.model;
import java.io.Serializable;
/**
* Created by Zhao_xl on 17/5/23.
*/
public class SensorInfo implements Serializable{
public String type;
public String name;
public String version;
public String vendor;
}
<file_sep>/DeviceSdk/src/main/java/com/woodys/devicelib/model/ConnectivityManagerInfo.java
package com.woodys.devicelib.model;
import java.io.Serializable;
/**
* Created by woodys on 2018/3/26.
*/
public class ConnectivityManagerInfo implements Serializable {
//connectivityManager
public String ExtraInfo;
public int Type;
public String TypeName;
public boolean isConnected;
}
|
b74dc973448c758a84ca401b6fee732d93e669ed
|
[
"Markdown",
"Java",
"Gradle"
] | 9
|
Java
|
18511084155/DeviceInfoHelper
|
ed2a3512a4a68851baf46e03e338b2a24a5736e9
|
46283afe82582c903a29aa7c5f9853a5f083ec4a
|
refs/heads/master
|
<repo_name>sunbaymax/workspace<file_sep>/leng/备份/leng9-29/access_token.php
<?php exit();?>{"expire_time":1505317107,"access_token":"<KEY>"}<file_sep>/weixinnew/backup/备份/运单查询/ITMS/logistics/access_token.php
<?php exit();?>{"expire_time":1512032817,"access_token":"<KEY>"}<file_sep>/weixinnew/Wxorder/js/order.js
$(function() {
toastr.options = {
timeOut: "3000",
positionClass: "toast-center-center"
};
function GetDateStr(AddDayCount) {
var dd = new Date();
dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
var y = dd.getFullYear();
var m = dd.getMonth() + 1; //获取当前月份的日期
var d = dd.getDate();
return y + "-" + m + "-" + d;
}
var date = [GetDateStr(0), GetDateStr(1), GetDateStr(2)];
var currtime = [];
var d = new Date();
var currhour = d.getHours();
if(currhour < 0 || currhour > 24) {
currtime = ['无效时间']
} else if(currhour >= 0 && currhour < 24) {
currtime = ['2小时上门', '8:30-10:30', '10:30-12:30', '12:30-14:30', '14:30-16:30', '16:30-17:30']
}
//else if(currhour >= 8 && currhour < 10) {
// currtime = ['2小时上门', '10:30-12:30', '12:30-14:30', '14:30-16:30', '16:30-17:30']
// } else if(currhour >= 10 && currhour < 12) {
// currtime = ['2小时上门', '12:30-14:30', '14:30-16:30', '16:30-17:30']
// } else if(currhour >= 12 && currhour < 14) {
// currtime = ['2小时上门', '14:30-16:30', '16:30-17:30']
// } else if(currhour >= 14 && currhour < 16) {
// currtime = ['2小时上门', '16:30-17:30']
// }
else {
currtime = ['非正常预约时间'];
}
$(".TimeType .TimeType-Ways .qi").each(function(key, index) {
$(this).text(date[key]);
});
$(currtime).each(function(key, index) {
let str = '<span class="ni">';
str += index;
str += '</span>';
$('.TimeType-datetime').append(str);
});
var telephone = sessionStorage.getItem('Telephone');
if(JSON.parse(sessionStorage.getItem('SendaddData'))) {
var _ChoseaddData = JSON.parse(sessionStorage.getItem('SendaddData'));
var _ChaddreType = sessionStorage.getItem('ChaddreType');
$(".Noexistsend").hide();
$(".existsend").show();
$('#send_username').text(_ChoseaddData.addressname);
$('#send_tel').text(_ChoseaddData.addresstel);
$('#send_address').text(_ChoseaddData.address);
}
if(JSON.parse(sessionStorage.getItem('getaddData'))) {
var _ChosogaddData = JSON.parse(sessionStorage.getItem('getaddData'));
var _ChaddreType = sessionStorage.getItem('ChaddreType');
$(".Noexistget").hide();
$(".existget").show();
$('#get_username').text(_ChosogaddData.addressname);
$('#get_tel').text(_ChosogaddData.addresstel);
$('#get_address').text(_ChosogaddData.address);
}
$('.clear').on('click', function() {
sessionStorage.clear();
})
//寄件人地址薄选择
$(".sendaddress").on("click", function() {
var _ChaddreType = 'send';
sessionStorage.setItem('ChaddreType', _ChaddreType);
$.ajax({
type: "post",
url: 'http://out.ccsc58.cc/DATA_PORT_WECHAT_1.01/AddressBook.php',
data: {
State: "show",
UserNumber: telephone
},
dataType: "json",
success: function(res) {
if(res.data.length > 0) {
location.href = 'addressbook.html';
} else {
location.href = 'Addsendress.html';
}
},
error: function(err) {
}
})
})
//收件人地址薄选择
$(".getaddress").on("click", function() {
var _ChaddreType = 'get';
sessionStorage.setItem('ChaddreType', _ChaddreType);
$.ajax({
type: "post",
url: 'http://out.ccsc58.cc/DATA_PORT_WECHAT_1.01/AddressBook.php',
data: {
State: "show",
UserNumber: telephone
},
dataType: "json",
success: function(res) {
if(res.data.length > 0) {
location.href = 'addressbook.html';
} else {
location.href = 'Addgetaddress.html';
}
},
error: function(err) {
}
})
})
//新增寄件人地址
$(".Noexistsend").on("click", function() {
location.href = 'Addsendress.html';
})
//新增收件人地址
$(".Noexistget").on("click", function() {
location.href = 'Addgetaddress.html';
})
$(".yin").on('click', function() {
$(".setbg").hide();
})
$(".closewindow").on('click', function() {
$(".setbg").hide();
})
//点击温度区间
$(".Tempqu").on('click', function() {
$('body,html').animate({
scrollTop: 0
}, 0);
$(".setbg").show();
$(".Temparea").show();
$(".BoxType").hide();
$(".TimeType").hide();
})
//点击箱型
$(".clickbox").on('click', function() {
$('body,html').animate({
scrollTop: 0
}, 0);
if($("#Temparea").text() == '请选择温区') {
toastr.error("请选择温度区间");
} else {
$(".setbg").show();
$(".Temparea").hide();
$(".BoxType").show();
$(".TimeType").hide();
}
})
//点击预约时间
var mytime = '';
$(".clickTime").on('click', function() {
// $('body,html').animate({
// scrollTop: 0
// }, 0);
// $(".setbg").show();
// $(".Temparea").hide();
// $(".BoxType").hide();
// $(".TimeType").show();
// pickuptime.init(0, function(data) {
// var arr = data.split(" ");
// var c = arr.join('');
// if(c.indexOf('今') != -1) {
// mytime = c.replace("今天", " ");
// } else if(c.indexOf('明') != -1) {
// mytime = c.replace("明天", " ");
// } else if(c.indexOf('后') != -1) {
// mytime = c.replace("后天", " ");
// } else {
// console.log(c)
// }
// console.log(mytime);
// $('#ChooseTimes').text(mytime)
// });
if($(".iDate.full").length > 0) {
$(".iDate.full").datetimepicker({
locale: "zh-cn",
format: "YYYY-MM-DD a hh:mm",
dayViewHeaderFormat: "YYYY年 MMMM"
});
}
})
$(".Temparea-Ways .Tempareac .ni").on('click', function() {
$(this).parents('.Temparea-Ways').find('.ni').removeClass('spanActive');
$(this).addClass('spanActive');
if($(this).parent().attr("class").indexOf("Dryice") != -1) {
$('.BoxTypef1 .ni').removeClass('disable');
$('.BoxTypef2 .ni').addClass('disable');
$('.BoxTypef2 .ni').removeClass('spanActive');
} else {
$('.BoxTypef1 .ni').addClass('disable');
$('.BoxTypef2 .ni').removeClass('disable');
$('.BoxTypef1 .ni').removeClass('spanActive');
}
});
var arrCbox = [];
$(".BoxType .ni").on('click', function() {
if($(this).attr('class').indexOf("spanActive") != -1) {
$(this).removeClass('spanActive')
} else {
$(this).addClass('spanActive');
}
});
$("body").on("click", "li .gw_num .add", function() {
var n = $(this).prev().val();
var num = parseInt(n) + 1;
if(num == 0) {
return;
}
$(this).prev().val(num);
});
//减的效果
$("body").on("click", "li .gw_num .jian", function() {
var n = $(this).next().val();
var num = parseInt(n) - 1;
if(num == 0) {
var delnumtext = $(this).prev().prev().text();
arrcBoxTxts.remove(delnumtext);
$(this).parents('.childbox').remove();
return
}
$(this).next().val(num);
});
//点击时间日期
$(".TimeType-Ways .TimeType-day .ni").on('click', function() {
$(this).siblings().removeClass('spanActive');
$(this).addClass('spanActive');
$(this).find('img').show();
$(this).siblings().find('img').hide();
if($(this).find('.ri').text() == '明日' || $(this).find('.ri').text() == '后日') {
$('.TimeType-datetime').empty();
let currtime = ['8:30-10:30', '10:30-12:30', '12:30-14:30', '14:30-16:30', '16:30-17:30']
$(currtime).each(function(key, index) {
let str = '<span class="ni">';
str += index;
str += '</span>';
$('.TimeType-datetime').append(str);
});
} else {
let currhour = d.getHours();
$('.TimeType-datetime').empty();
if(currhour < 0 || currhour > 24) {
currtime = ['无效时间']
} else if(currhour >= 6 && currhour < 17) {
currtime = ['2小时上门', '8:30-10:30', '10:30-12:30', '12:30-14:30', '14:30-16:30', '16:30-17:30']
} else {
currtime = ['非正常预约时间'];
}
$(currtime).each(function(key, index) {
let str = '';
if(currhour <= 8) {
str = '<span class="ni">';
str += index;
str += '</span>';
} else if(currhour >= 10 && currhour < 12) {
if(key == 1) {
str = '<span class="ni disable">';
str += index;
str += '</span>';
} else {
str = '<span class="ni">';
str += index;
str += '</span>';
}
} else if(currhour >= 12 && currhour < 14) {
if(key == 1 || key == 2) {
str = '<span class="ni disable">';
str += index;
str += '</span>';
} else {
str = '<span class="ni">';
str += index;
str += '</span>';
}
} else if(currhour >= 14 && currhour < 16) {
if(key >= 1 && key <= 3) {
str = '<span class="ni disable">';
str += index;
str += '</span>';
} else {
str = '<span class="ni">';
str += index;
str += '</span>';
}
} else {
str = '<span class="ni disable">';
str += index;
str += '</span>';
}
$('.TimeType-datetime').append(str);
});
}
});
//点击小时
$('body').on('click', ".TimeType-Ways .TimeType-datetime .ni", function() {
$(this).siblings().removeClass('spanActive');
$(this).addClass('spanActive');
});
var arrcBoxTxts = [];
$(".Temparea-btn").on('click', function() {
var chooseTempTxt = $('.Temparea .spanActive').text();
if(chooseTempTxt == '') {
toastr.error("请选择温度区间");
$("#Temparea").removeClass('chooseTemp');
$(".fatherbox .choosewenqu .gw_num").removeClass('hide');
} else {
$("#Temparea").text(chooseTempTxt);
$("#Temparea").addClass('chooseTemp');
$("#BoxType").text('请选择箱型');
$('.BoxType .BoxType-Ways .ni').removeClass('spanActive');
$(".fatherbox .choosewenqu p").addClass('hide');
$('.childbox').remove();
arrcBoxTxts = [];
$('.choosewenqu .gw_num input').val('1');
$(".setbg").hide();
$(".setbg").hide();
}
});
$(".BoxType-btn").on('click', function() {
var chooseBoxTxt = $('.BoxType .spanActive').text();
arrcBoxTxts = chooseBoxTxt.trim().split(/\s+/);
if(chooseBoxTxt == '') {
toastr.error("请选择箱型");
$("#BoxType").removeClass("chooseBox");
} else {
// $("#BoxType").text(chooseBoxTxt);
console.log(arrcBoxTxts)
if(arrcBoxTxts.length >= 2) {
$('.childbox').remove();
$('.fatherbox .choosewenqu .gw_num').removeClass('hide');
$(arrcBoxTxts).each(function(index, value) {
if(index != 0) {
let str = `<li class="childbox">
<div>
<img src="../img/box.png" class="img_temp" />
</div>
<div class="choosewenqu">
<label class="clickbox boxinput Cchildbox">${value}</label>
<img src="../img/delbox.png" class="delbox" />
<p class="gw_num">
<img src="../img/reduce.png" class="jian" />
<input type="text" value="1" class="num" readonly="readonly" />
<img src="../img/addbox.png" class="add" />
</p>
</div>
</li>`;
$('.fatherbox').after(str);
} else {
$(".fatherbox #BoxType").text(value)
}
});
} else {
$(".fatherbox #BoxType").text(chooseBoxTxt)
$('.fatherbox .choosewenqu .gw_num').removeClass('hide');
$('.childbox').each(function() {
$(this).remove();
});
}
$("#BoxType").addClass("chooseBox");
$(".setbg").hide();
}
});
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if(index > -1) {
this.splice(index, 1);
}
};
//删除选择的箱型
$("body").on("click", '.childbox .delbox', function() {
var deltext = $(this).prev().text();
arrcBoxTxts.remove(deltext);
$(this).parents('.childbox').remove();
})
$(".time-btn").on('click', function() {
var chooseDay = $('.TimeType-day .spanActive .qi').text();
var chooseTimeTxt = $('.TimeType-datetime .spanActive').text();
$("#ChooseTimes").text(chooseDay + ' ' + chooseTimeTxt);
$(".time .time-right label").addClass("chooseTimes");
$(".setbg").hide();
});
$('aside.slide-wrapper').on('touchstart', 'li', function(e) {
$(this).addClass('current').siblings('li').removeClass('current');
});
$('a.slide-menu').on('click', function(e) {
var wh = $('div.wrapper').height();
$('div.slide-mask').css('height', '100%').show();
$('aside.slide-wrapper').css('height', '100%').addClass('moved');
var tel = window.sessionStorage.getItem('Telephone')
$.ajax({
type: "post",
url: "http://out.ccsc58.cc/DATA_PORT_WECHAT_1.01/Center.php",
data: {
user: tel
},
dataType: "JSON",
success: function(res) {
console.log(res);
if(res.code == 300) {
toastr.error("请进行信息录入");
// setTimeout(function() {
// window.location.href = 'InfoInput.html';
// }, 1000);
$('.menu_footer .haveinfo').hide();
$('.menu_footer #editlogin').show();
}else{
$('.slide-wrapper .menu_footer img').attr("src",res.data.Picture);
$('.slide-wrapper .menu_footer .turename').text(res.data.NickName);
$('.slide-wrapper .menu_footer .turetel').text(res.data.UserNumber);
}
},
error: function(err) {
console.log(err)
}
})
});
$('div.slide-mask').on('click', function() {
$('div.slide-mask').hide();
$('aside.slide-wrapper').removeClass('moved');
});
$('.menu_top img').on('click', function() {
$('div.slide-mask').hide();
$('aside.slide-wrapper').removeClass('moved');
});
//提取汉字
function GetChinese(strValue) {
if(strValue != null && strValue != "") {
var reg = /[\u4e00-\u9fa5]/g;
return strValue.match(reg).join("");
}
else
return "";
}
//去掉汉字
function RemoveChinese(strValue) {
if(strValue != null && strValue != "") {
var reg = /[\u4e00-\u9fa5]/g;
return strValue.replace(reg, "");
}
else
return "";
}
function trimstart(v) { //去除字符串尾空白
if(typeof v == 'string') return v.replace(/^\s+/, '')
return v;
}
function replacepos(text, start, stop, replacetext) {
mystr = text.substring(0, stop - 1) + replacetext + text.substring(stop + 1);
return mystr;
}
$('.btndiv button').on('click', function() {
var choosetime = $('.iDate input').val();
var isAMPMtime = GetChinese(choosetime);
var jiequtime = RemoveChinese(choosetime);
var hour = jiequtime.substring(12, 14);
var t = '';
if(isAMPMtime == '下午' && hour != 12) {
t = parseInt(hour) + 12;
} else if(isAMPMtime == '凌晨' && hour == 12) {
t = '00';
} else if(isAMPMtime == '晚上') {
t = parseInt(hour) + 12;
} else {
t = hour;
}
if(parseInt(t) < 8 || parseInt(t) > 17) {
toastr.error("非取件时间,请于8点到17点之间下单");
}
var endstr = replacepos(jiequtime, 12, 13, t);
console.log(endstr.replace(" ", ""));
let timeok = endstr.replace(" ", "");
timeok = timeok.substring(0, 19);
timeok = timeok.replace(/-/g, '/');
console.log(timeok);
var timestamp = new Date(timeok).getTime() / 1000;
var timestamp1 = parseInt((new Date()).valueOf() / 1000);
console.log(timestamp1, '当前');
console.log(timestamp, '选择');
if(timestamp1 > timestamp) {
toastr.error("非取件时间,请选择大于当前时间");
}
//location.href = 'ordersuccess.html'
});
$('input').blur(function() {
$('body,html').animate({
scrollTop: 0
}, 0);
})
//点击头像跳转
$(".touxiang").on("click", function() {
location.href = 'person.html';
})
});<file_sep>/leng/备份/leng9-29/html/access_token.php
<?php exit();?>{"expire_time":1501152447,"access_token":"<KEY>"}<file_sep>/weixinnew/backup/备份/9.14/weixinnew/html/access_token.php
<?php exit();?>{"expire_time":1505386510,"access_token":"-<KEY>"}<file_sep>/README.md
# workspace
项目工作空间
<file_sep>/leng/备份/leng1-23/access_token.php
<?php exit();?>
{"expire_time":1506158486,"access_token":"<KEY>"}<file_sep>/weixinnew/backup/备份/9.14/weixinnew/access_token.php
<?php exit();?>
{"access_token":"<KEY>","expire_time":1505388298}
|
eece0bb7ff2b527e67cb717f2d9c1f5682e6eaed
|
[
"JavaScript",
"Markdown",
"PHP"
] | 8
|
PHP
|
sunbaymax/workspace
|
520710ebadc2412904e6cf4d16bec7283f76b0de
|
9463b22ea590698d3b4972b5ad6a47d54100b3b8
|
refs/heads/main
|
<repo_name>MdAkramKhanJehad/Wumpus-World-AI<file_sep>/gui.py
from tkinter import *
from agent import Agent
from world import World
from grid_label import Grid_Label
import time
from tkinter import messagebox
def solve_wumpus_world(master, world_file):
world = World()
world.generate_world(world_file)
label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
agent = Agent(world, label_grid)
while not agent.exited:
agent.explore(master)
if agent.found_gold:
print("Found gold")
break
agent.repaint_world()
agent.world_knowledge[agent.world.agent_row][agent.world.agent_col].remove('A')
time.sleep(1.5)
agent.repaint_world()
master = Tk()
master.title("Wumpus World")
# master.iconbitmap("icon.ico")
world = World()
world.generate_world("world_1.txt")
label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
world_1 = Button(master, text="PLAY", command=lambda: solve_wumpus_world(master, "world_1.txt"), width=8,
font="Helvetica 14 bold", bg="gray80", fg="blue", borderwidth=0, activeforeground="white",
activebackground="gray40")
exit_button = Button(master, text="Quit", command=master.destroy,font="Helvetica 14 bold", bg="gray80", fg="red", \
borderwidth=0, activeforeground="white",activebackground="gray40").grid(row=2, column=len(label_grid[0]))
world_1.grid(row=0, column=len(label_grid[0]))
mainloop()<file_sep>/README.md
# Wumpus-World-AI
2nd project of Artificial Intelligence course. <br>
### Run
To run the project, run the gui.py file.
<file_sep>/file_parser.py
class File_Parser:
def __init__(self, world_file):
self.row_col = []
self.agent = []
self.wumpus = []
self.gold = []
self.pits = [[]]
file = open(world_file, 'r')
self.row_col = file.readline()
self.row_col = self.row_col.rstrip('\r\n')
self.row_col = self.row_col.split(" ")
self.agent = file.readline()
self.agent = self.agent.rstrip('\r\n')
self.agent = self.agent.split(" ")
self.wumpus = file.readline()
self.wumpus = self.wumpus.rstrip('\r\n')
self.wumpus = self.wumpus.split(" ")
self.gold = file.readline()
self.gold = self.gold.rstrip('\r\n')
self.gold = self.gold.split(" ")
self.pits = []
while True:
pit = file.readline()
if len(pit) == 0:
break
pit = pit.rstrip('\r\n')
pit = pit.split(" ")
self.pits.append(pit)
<file_sep>/grid_label.py
from tkinter import *
class Grid_Label():
def __init__(self, master, i, j):
self.text = StringVar()
self.label = Label(master, textvariable=self.text, height=2, width=7, relief=RIDGE, bg="green", fg="white",
font="Helvetica 14 bold")
self.label.grid(row=i, column=j, sticky=W, pady=1)
self.row = i
self.col = j
def change_text(self, updated_text):
self.text.set(str(updated_text))
<file_sep>/agent.py
import time
from tkinter import messagebox
class Agent:
def __init__(self, world, label_grid):
self.world = world
self.world_knowledge = [[[] for i in range(self.world.num_cols)] for j in range(self.world.num_rows)]
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('A')
self.num_stenches = 0
self.path_out_of_cave = [[self.world.agent_row, self.world.agent_col]]
self.mark_tile_visited()
self.world.cave_entrance_row = self.world.agent_row
self.world.cave_entrance_col = self.world.agent_col
self.found_gold = False
self.took_gold = False
self.exited = False
self.label_grid = label_grid
self.repaint_world()
self.danger_probability = [[0 for i in range(self.world.num_cols)] for j in range(self.world.num_rows)]
self.in_dead_lock = False
def repaint_world(self):
for i in range(self.world.num_rows):
for j in range(self.world.num_cols):
updated_text = []
if 'A' in self.world_knowledge[i][j]:
updated_text.append('A')
if 'w' in self.world_knowledge[i][j]:
updated_text.append('W')
if 'p' in self.world_knowledge[i][j]:
updated_text.append('P')
if 'B' in self.world_knowledge[i][j]:
updated_text.append('B')
if 'S' in self.world_knowledge[i][j]:
updated_text.append('S')
if 'G' in self.world_knowledge[i][j]:
updated_text.append('G')
updated_str = ""
self.label_grid[i][j].change_text(updated_str.join(updated_text))
if '.' in self.world_knowledge[i][j]:
self.label_grid[i][j].label.config(bg="grey")
self.label_grid[i][j].label.update()
def go_back_one_tile(self):
if self.world.agent_row - 1 == self.path_out_of_cave[-1][0]:
self.move('u')
if self.world.agent_row + 1 == self.path_out_of_cave[-1][0]:
self.move('d')
if self.world.agent_col + 1 == self.path_out_of_cave[-1][1]:
self.move('r')
if self.world.agent_col - 1 == self.path_out_of_cave[-1][1]:
self.move('l')
def quit(self, master):
master.destroy()
def go_back_one_tile(self, master):
print("Path out cave len = ",len(self.path_out_of_cave))
# if len(self.path_out_of_cave) <= 1:
# self.in_dead_lock = True
# messagebox.showwarning("Warning", "You are in deadlock!")
# time.sleep(1)
# self.quit(master)
if self.world.agent_row - 1 == self.path_out_of_cave[-1][0]:
self.move('u')
if self.world.agent_row + 1 == self.path_out_of_cave[-1][0]:
self.move('d')
if self.world.agent_col + 1 == self.path_out_of_cave[-1][1]:
self.move('r')
if self.world.agent_col - 1 == self.path_out_of_cave[-1][1]:
self.move('l')
del self.path_out_of_cave[-1]
def leave_cave(self):
for tile in reversed(self.path_out_of_cave):
if self.world.agent_row - 1 == tile[0]:
self.move('u')
if self.world.agent_row + 1 == tile[0]:
self.move('d')
if self.world.agent_col + 1 == tile[1]:
self.move('r')
if self.world.agent_col - 1 == tile[1]:
self.move('l')
if self.world.cave_entrance_row == self.world.agent_row:
if self.world.cave_entrance_col == self.world.agent_col:
if self.found_gold == True:
self.exited = True
break
def explore(self,master):
already_moved = False
while (not self.found_gold) and (not self.in_dead_lock):
for index in range(self.world.num_rows):
for jndex in range(self.world.num_cols):
print(self.danger_probability[index][jndex], end="\t")
print("")
print("")
print("**********Current Agent Position:", self.world.agent_row, self.world.agent_col)
if self.found_gold:
break
if 'P' in self.world.world[self.world.agent_row][self.world.agent_col]:
messagebox.showwarning("Warning", "GAME OVER")
self.quit(master)
elif 'W' in self.world.world[self.world.agent_row][self.world.agent_col]:
messagebox.showwarning("Warning", "GAME OVER")
self.quit(master)
try:
if '.' not in self.world_knowledge[self.world.agent_row - 1][
self.world.agent_col] and self.is_safe_move(self.world.agent_row - 1, self.world.agent_col):
if not already_moved:
if self.move('u'):
already_moved = True
except IndexError:
pass
try:
if '.' not in self.world_knowledge[self.world.agent_row][
self.world.agent_col + 1] and self.is_safe_move(self.world.agent_row, self.world.agent_col + 1):
if not already_moved:
if self.move('r'):
already_moved = True
except IndexError:
pass
try:
if '.' not in self.world_knowledge[self.world.agent_row + 1][
self.world.agent_col] and self.is_safe_move(self.world.agent_row + 1, self.world.agent_col):
if not already_moved:
if self.move('d'):
already_moved = True
except IndexError:
pass
try:
if '.' not in self.world_knowledge[self.world.agent_row][
self.world.agent_col - 1] and self.is_safe_move(self.world.agent_row, self.world.agent_col - 1):
if not already_moved:
if self.move('l'):
already_moved = True
except IndexError:
pass
if not already_moved:
self.go_back_one_tile(master)
already_moved = False
def move(self, direction):
self.repaint_world()
if self.found_gold == True and self.took_gold == False:
self.took_gold == True
if 'G' in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.world_knowledge[self.world.agent_row][self.world.agent_col].remove('G')
successful_move = False
if direction == 'u':
if self.is_safe_move(self.world.agent_row - 1, self.world.agent_col):
successful_move = self.move_up()
if direction == 'r':
if self.is_safe_move(self.world.agent_row, self.world.agent_col + 1):
successful_move = self.move_right()
if direction == 'd':
if self.is_safe_move(self.world.agent_row + 1, self.world.agent_col):
successful_move = self.move_down()
if direction == 'l':
if self.is_safe_move(self.world.agent_row, self.world.agent_col - 1):
successful_move = self.move_left()
if successful_move:
self.add_indicators_to_knowledge()
self.predict_wumpus()
self.predict_pits()
self.mark_tile_visited()
self.clean_predictions()
self.confirm_wumpus_knowledge()
if 'G' in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.found_gold = True
if not self.found_gold:
self.path_out_of_cave.append([self.world.agent_row, self.world.agent_col])
time.sleep(0.9)
return successful_move
def add_indicators_to_knowledge(self):
if 'B' in self.world.world[self.world.agent_row][self.world.agent_col]:
if 'B' not in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('B')
if 'S' in self.world.world[self.world.agent_row][self.world.agent_col]:
if 'S' not in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('S')
if 'G' in self.world.world[self.world.agent_row][self.world.agent_col]:
if 'G' not in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('G')
if 'P' in self.world.world[self.world.agent_row][self.world.agent_col]:
if 'P' not in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('P')
if 'W' in self.world.world[self.world.agent_row][self.world.agent_col]:
if 'W' not in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('W')
def predict_pits(self):
try:
if 'B' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_row - 1 >= 0:
if '.' not in self.world.world[self.world.agent_row - 1][self.world.agent_col]:
# print(self.world.world[self.world.agent_row - 1][self.world.agent_col])
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col]:
self.danger_probability[self.world.agent_row - 1][self.world.agent_col] += 0.25
if 'p' not in self.world_knowledge[self.world.agent_row - 1][self.world.agent_col]:
self.world_knowledge[self.world.agent_row - 1][self.world.agent_col].append('p')
except IndexError:
pass
try:
if 'B' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_col + 1 < self.world.num_cols:
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col + 1]:
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col]:
self.danger_probability[self.world.agent_row][self.world.agent_col + 1] += 0.25
if 'p' not in self.world_knowledge[self.world.agent_row][self.world.agent_col + 1]:
self.world_knowledge[self.world.agent_row][self.world.agent_col + 1].append('p')
except IndexError:
pass
try:
if 'B' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_row + 1 < self.world.num_rows:
if '.' not in self.world.world[self.world.agent_row + 1][self.world.agent_col]:
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col]:
self.danger_probability[self.world.agent_row + 1][self.world.agent_col] += 0.25
if 'p' not in self.world_knowledge[self.world.agent_row + 1][self.world.agent_col]:
self.world_knowledge[self.world.agent_row + 1][self.world.agent_col].append('p')
except IndexError:
pass
try:
if 'B' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_col - 1 >= 0:
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col - 1]:
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col]:
self.danger_probability[self.world.agent_row][self.world.agent_col - 1] += 0.25
if 'p' not in self.world_knowledge[self.world.agent_row][self.world.agent_col - 1]:
self.world_knowledge[self.world.agent_row][self.world.agent_col - 1].append('p')
except IndexError:
pass
def predict_wumpus(self):
try:
if 'S' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_row - 1 >= 0:
if '.' not in self.world.world[self.world.agent_row - 1][self.world.agent_col]:
if 'w' not in self.world_knowledge[self.world.agent_row - 1][self.world.agent_col]:
self.world_knowledge[self.world.agent_row - 1][self.world.agent_col].append('w')
except IndexError:
pass
try:
if 'S' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_col + 1 < self.world.num_cols:
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col + 1]:
if 'w' not in self.world_knowledge[self.world.agent_row][self.world.agent_col + 1]:
self.world_knowledge[self.world.agent_row][self.world.agent_col + 1].append('w')
except IndexError:
pass
try:
if 'S' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_row + 1 < self.world.num_rows:
if '.' not in self.world.world[self.world.agent_row + 1][self.world.agent_col]:
if 'w' not in self.world_knowledge[self.world.agent_row + 1][self.world.agent_col]:
self.world_knowledge[self.world.agent_row + 1][self.world.agent_col].append('w')
except IndexError:
pass
try:
if 'S' in self.world.world[self.world.agent_row][self.world.agent_col]:
if self.world.agent_col - 1 >= 0:
if '.' not in self.world.world[self.world.agent_row][self.world.agent_col - 1]:
if 'w' not in self.world_knowledge[self.world.agent_row][self.world.agent_col - 1]:
self.world_knowledge[self.world.agent_row][self.world.agent_col - 1].append('w')
except IndexError:
pass
def clean_predictions(self):
self.num_stenches = 0
for i in range(self.world.num_rows):
for j in range(self.world.num_cols):
if 'S' in self.world_knowledge[i][j]:
self.num_stenches += 1
if 'w' in self.world_knowledge[i][j]:
try:
if i - 1 >= 0:
if '.' in self.world_knowledge[i - 1][j]:
if 'S' not in self.world_knowledge[i - 1][j]:
if 'w' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('w')
self.world_knowledge[i][j].append('nw')
except IndexError:
pass
try:
if j + 1 < self.world.num_cols:
if '.' in self.world_knowledge[i][j + 1]:
if 'S' not in self.world_knowledge[i][j + 1]:
if 'w' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('w')
self.world_knowledge[i][j].append('nw')
except IndexError:
pass
try:
if i + 1 < self.world.num_rows:
if '.' in self.world_knowledge[i + 1][j]:
if 'S' not in self.world_knowledge[i + 1][j]:
if 'w' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('w')
self.world_knowledge[i][j].append('nw')
except IndexError:
pass
try:
if j - 1 >= 0:
if '.' in self.world_knowledge[i][j - 1]:
if 'S' not in self.world_knowledge[i][j - 1]:
if 'w' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('w')
self.world_knowledge[i][j].append('nw')
except IndexError:
pass
if 'p' in self.world_knowledge[i][j]:
try:
if i - 1 >= 0:
if '.' in self.world_knowledge[i - 1][j]:
if 'B' not in self.world_knowledge[i - 1][j]:
print("i-1 = ", self.world_knowledge[i][j])
if 'p' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('p')
self.danger_probability[i][j] -= 0.25
self.world_knowledge[i][j].append('np')
except IndexError:
pass
try:
if j + 1 < self.world.num_cols:
if '.' in self.world_knowledge[i][j + 1]:
if 'B' not in self.world_knowledge[i][j + 1]:
print("j+1 = ", self.world_knowledge[i][j])
if 'p' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('p')
self.danger_probability[i][j] -= 0.25
self.world_knowledge[i][j].append('np')
except IndexError:
pass
try:
if i + 1 < self.world.num_rows:
if '.' in self.world_knowledge[i + 1][j]:
if 'B' not in self.world_knowledge[i + 1][j]:
print("i+1 = ", self.world_knowledge[i][j])
if 'p' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('p')
self.danger_probability[i][j] -= 0.25
self.world_knowledge[i][j].append('np')
except IndexError:
pass
try:
if j - 1 >= 0:
if '.' in self.world_knowledge[i][j - 1]:
if 'B' not in self.world_knowledge[i][j - 1]:
print("j-1 = ", self.world_knowledge[i][j])
if 'p' in self.world_knowledge[i][j]:
self.world_knowledge[i][j].remove('p')
self.danger_probability[i][j] -= 0.25
self.world_knowledge[i][j].append('np')
except IndexError:
pass
def confirm_wumpus_knowledge(self):
for i in range(self.world.num_rows):
for j in range(self.world.num_cols):
if 'w' in self.world_knowledge[i][j]:
stenches_around = 0
try:
if i - 1 >= 0:
if 'S' in self.world_knowledge[i - 1][j]:
stenches_around += 1
except IndexError:
pass
try:
if j + 1 < self.world.num_cols:
if 'S' in self.world_knowledge[i][j + 1]:
stenches_around += 1
except IndexError:
pass
try:
if i + 1 < self.world.num_rows:
if 'S' in self.world_knowledge[i + 1][j]:
stenches_around += 1
except IndexError:
pass
try:
if j - 1 >= 0:
if 'S' in self.world_knowledge[i][j - 1]:
stenches_around += 1
except IndexError:
pass
if stenches_around < self.num_stenches:
self.world_knowledge[i][j].remove('w')
self.world_knowledge[i][j].append('nw')
def move_up(self):
try:
if self.world.agent_row - 1 >= 0:
self.remove_agent()
self.world.agent_row -= 1
self.add_agent()
return True
else:
return False
except IndexError:
return False
def move_right(self):
try:
if self.world.agent_col + 1 < self.world.num_cols:
self.remove_agent()
self.world.agent_col += 1
self.add_agent()
return True
else:
return False
except IndexError:
return False
def move_down(self):
try:
if self.world.agent_row + 1 < self.world.num_rows:
self.remove_agent()
self.world.agent_row += 1
self.add_agent()
return True
else:
return False
except IndexError:
return False
def move_left(self):
try:
if self.world.agent_col - 1 >= 0:
self.remove_agent()
self.world.agent_col -= 1
self.add_agent()
return True
else:
return False
except IndexError:
return False
def remove_agent(self):
self.world.world[self.world.agent_row][self.world.agent_col].remove('A')
self.world_knowledge[self.world.agent_row][self.world.agent_col].remove('A')
def add_agent(self):
self.world.world[self.world.agent_row][self.world.agent_col].append('A')
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('A')
def mark_tile_visited(self):
if '.' not in self.world_knowledge[self.world.agent_row][self.world.agent_col]:
self.world.world[self.world.agent_row][self.world.agent_col].append('.')
self.world_knowledge[self.world.agent_row][self.world.agent_col].append('.')
def is_dead(self):
if 'W' in self.world.world[self.world.agent_row][self.world.agent_col]:
print("You have been slain by the Wumpus!")
return True
elif 'P' in self.world.world[self.world.agent_row][self.world.agent_col]:
print("You have fallen in a pit!")
return True
else:
return False
def is_safe_move(self, row, col):
try:
if 'w' in self.world_knowledge[row][col] or 'p' in self.world_knowledge[row][col] or 'W' in \
self.world_knowledge[row][col] or 'P' in self.world_knowledge[row][col]:
return False
except IndexError:
pass
return True
<file_sep>/world.py
from file_parser import File_Parser
class World:
def __init__(self):
self.world = [[]]
self.num_rows = 0
self.num_cols = 0
self.agent_row = 0
self.agent_col = 0
self.cave_entrance_row = 0
self.cave_entrance_col = 0
def generate_world(self, file_name):
file_parser = File_Parser(file_name)
self.num_rows = int(file_parser.row_col[0])
self.num_cols = int(file_parser.row_col[1])
self.world = [[[] for i in range(self.num_cols)] for j in range(self.num_rows)]
self.agent_row = int(file_parser.agent[1])
self.agent_col = int(file_parser.agent[2])
self.world[self.agent_row][self.agent_col].append('A')
self.world[int(file_parser.wumpus[1])][int(file_parser.wumpus[2])].append(file_parser.wumpus[0])
self.world[int(file_parser.gold[1])][int(file_parser.gold[2])].append(file_parser.gold[0])
for pit in file_parser.pits:
self.world[int(pit[1])][int(pit[2])].append(pit[0])
# print(DataFrame(self.world))
self.populate_indicators()
def populate_indicators(self):
for i in range(self.num_rows):
for j in range(self.num_cols):
for k in range(len(self.world[i][j])):
"""
if self.world[i][j][k] == 'A':
print("Agent at [" + str(i) + ", " + str(j) + "]")
"""
if self.world[i][j][k] == 'W':
# print("Wumpus at [" + str(i) + ", " + str(j) + "]")
try:
if i - 1 >= 0:
if 'S' not in self.world[i - 1][j]:
self.world[i - 1][j].append('S')
except IndexError:
pass
try:
if j + 1 < self.num_cols:
if 'S' not in self.world[i][j + 1]:
self.world[i][j + 1].append('S')
except IndexError:
pass
try:
if i + 1 < self.num_rows:
if 'S' not in self.world[i + 1][j]:
self.world[i + 1][j].append('S')
except IndexError:
pass
try:
if j - 1 >= 0:
if 'S' not in self.world[i][j - 1]:
self.world[i][j - 1].append('S')
except IndexError:
pass
"""
if self.world[i][j][k] == 'G':
print("Gold at [" + str(i) + ", " + str(j) + "]")
"""
if self.world[i][j][k] == 'P':
# print("Pit at [" + str(i) + ", " + str(j) + "]")
try:
if i - 1 >= 0:
if 'B' not in self.world[i - 1][j]:
self.world[i - 1][j].append('B')
except IndexError:
pass
try:
if j + 1 < self.num_cols:
if 'B' not in self.world[i][j + 1]:
self.world[i][j + 1].append('B')
except IndexError:
pass
try:
if i + 1 < self.num_rows:
if 'B' not in self.world[i + 1][j]:
self.world[i + 1][j].append('B')
except IndexError:
pass
try:
if j - 1 >= 0:
if 'B' not in self.world[i][j - 1]:
self.world[i][j - 1].append('B')
except IndexError:
pass
|
5c03f1f960614d27dcac283e2031c33f23eba4b5
|
[
"Markdown",
"Python"
] | 6
|
Python
|
MdAkramKhanJehad/Wumpus-World-AI
|
341f9510e7fa480e7984cb5ed2065b262940a639
|
a643d080913ec3c2599c729695f3981dd8655596
|
refs/heads/master
|
<repo_name>raessafathulalim/api-movie<file_sep>/app/Http/Controllers/MovielistController.php
<?php
namespace App\Http\Controllers;
use App\Movielist;
use Illuminate\Http\Request;
class MovielistController extends Controller
{
public function showAllMovies()
{
return response()->json(Movielist::paginate());
}
public function showOneMovie($id)
{
return response()->json(Movielist::find($id));
}
public function searchMovie(Request $request)
{
return response()->json(Movielist::where('title', 'like', '%' . $request->get('search') . '%')->get());
}
}<file_sep>/app/Movielist.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Movielist extends Model {
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table = 'movielist';
protected $fillable = [
'poster', 'title', 'year', 'imdbID', 'quality', 'sub', 'link'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [];
}
|
8750f2ccf1bee8d577910637f6d9efdf02917f9b
|
[
"PHP"
] | 2
|
PHP
|
raessafathulalim/api-movie
|
eb27f5b35d7a1090b861abfbb9d1afd8996a4597
|
bb558b88ee83d385b0364753fa32dfe017cb42e7
|
refs/heads/main
|
<file_sep>Para executar:
`dotnet run "caminho_para_produtos.txt" "caminho_para_vendas.txt"`
i.e.:
`dotnet run "./../Caso de teste 1/c1_produtos.txt" "./../Caso de teste 1/c1_vendas.txt"`
<file_sep>using System;
namespace W.Models
{
public class Sale
{
public Sale(string source, int line)
{
var split = source.Split(";");
Line = line;
ProductCode = Convert.ToInt32(split[0]);
Quantity = Convert.ToInt32(split[1]);
Status = (SaleStatus)Convert.ToInt32(split[2]);
Channel = (SaleChannel)Convert.ToInt32(split[3]);
}
public int Line { get; init; }
public int ProductCode { get; init; }
public int Quantity { get; init; }
public SaleStatus Status { get; init; }
public SaleChannel Channel { get; init; }
}
public enum SaleStatus
{
ConfirmedAndPaid = 100,
ConfirmedAndAwaitingPayment = 102,
Canceled = 135,
Unfinished = 190,
Error = 999
}
public enum SaleChannel
{
Representative = 1,
Website = 2,
AppAndroid = 3,
AppIOS = 4
}
}
<file_sep>using W.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace W
{
public class Program
{
private static List<Product> _products = new List<Product>();
private static List<Sale> _sales = new List<Sale>();
public static void Main(string[] args)
{
ReadProducts(args[0]);
ReadSales(args[1]);
ProcessTransfers();
ProcessDivergences();
ProcessSaleChannels();
}
private static void ProcessSaleChannels()
{
int representatives, website, android, ios;
representatives = website = android = ios = 0;
foreach (var sale in _sales)
{
if (sale.Status is (SaleStatus.ConfirmedAndPaid or SaleStatus.ConfirmedAndAwaitingPayment))
{
switch (sale.Channel)
{
case SaleChannel.AppAndroid:
android += sale.Quantity;
break;
case SaleChannel.AppIOS:
ios += sale.Quantity;
break;
case SaleChannel.Representative:
representatives += sale.Quantity;
break;
case SaleChannel.Website:
website += sale.Quantity;
break;
}
}
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Quantidades de Vendas por canal");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(string.Format("1 - Representantes\t\t{0}", representatives));
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(string.Format("2 - Website\t\t\t{0}", website));
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(string.Format("3 - App móvel Android\t\t{0}", android));
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(string.Format("4 - App móvel iPhone\t\t{0}", ios));
WriteToFile("./TOTCANAIS.TXT", stringBuilder.ToString());
}
private static void ProcessDivergences()
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var sale in _sales)
{
stringBuilder.Append(sale.Status switch
{
SaleStatus.Error => string.Format("Linha {0} - Erro desconhecido. Acionar equipe de TI", sale.Line),
SaleStatus.Canceled => string.Format("Linha {0} - Venda cancelada", sale.Line),
SaleStatus.Unfinished => string.Format("Linha {0} - Venda não finalizada", sale.Line),
_ => ""
});
if ((int)sale.Status >= 135)
{
stringBuilder.Append(Environment.NewLine);
continue;
}
// LINQ: products.Any(s => s.Id == sale.ProductId);
bool found = false;
foreach (var product in _products)
{
if (product.Id == sale.ProductCode)
{
found = true;
break;
}
}
if (!found)
{
stringBuilder.Append(string.Format("Linha {0} - Código de Produto não encontrado {1}", sale.Line, sale.ProductCode));
stringBuilder.Append(Environment.NewLine);
}
}
WriteToFile("./divergencias.txt", stringBuilder.ToString());
}
private static void ProcessTransfers()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Necessidade de Transferência Armazém para CO");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append("Produto\tQtCO\tQtMin\tQtVendas\tEstq.após\tNecess.\tTransf.\tde");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append("\t\t\t\t\tVendas\t\t\tArm p/ CO");
stringBuilder.Append(Environment.NewLine);
foreach (var product in _products)
{
int sales = SalesFor(product);
int postSalesStock = product.InStock - sales;
int neededForMinimum = product.OperationalMinimum - postSalesStock < 0 ? 0 : product.OperationalMinimum - postSalesStock;
int neededTransfered = neededForMinimum is (>= 1 and < 10) ? 10 : neededForMinimum;
stringBuilder.Append(
string.Format("{0}\t{1}\t{2}\t{3}\t\t{4}\t\t{5}\t\t{6}",
product.Id,
product.InStock,
product.OperationalMinimum,
sales,
postSalesStock,
neededForMinimum,
neededTransfered
));
stringBuilder.Append(Environment.NewLine);
WriteToFile("./transfere.txt", stringBuilder.ToString());
}
}
private static int SalesFor(Product product)
{
int sales = 0;
foreach (var sale in _sales)
{
if (sale.ProductCode == product.Id && sale.Status is SaleStatus.ConfirmedAndPaid or SaleStatus.ConfirmedAndAwaitingPayment)
sales += sale.Quantity;
}
return sales;
}
private static void ReadSales(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException(string.Format("O arquivo de vendas em \"{0}\" não pôde ser encontrado", path));
}
using (var streamReader = new StreamReader(path))
{
int line = 1;
while (streamReader.Peek() >= 0)
{
_sales.Add(new Sale(streamReader.ReadLine(), line));
line++;
}
}
}
private static void ReadProducts(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException(string.Format("O arquivo de produtos em \"{0}\" não pôde ser encontrado", path));
}
using (var streamReader = new StreamReader(path))
{
while (streamReader.Peek() >= 0)
{
_products.Add(new Product(streamReader.ReadLine()));
}
}
}
private static void WriteToFile(string path, string content)
{
using (var streamWritter = new StreamWriter(path))
{
streamWritter.Write(content);
}
}
}
}
<file_sep>using System;
namespace W.Models
{
public class Product
{
public Product(string source)
{
var split = source.Split(";");
Id = Convert.ToInt32(split[0]);
InStock = Convert.ToInt32(split[1]);
OperationalMinimum = Convert.ToInt32(split[2]);
}
public int Id { get; init; }
public int InStock { get; init; }
public int OperationalMinimum { get; init; }
}
}
|
89105b524a86c1a2511d76e9ece5b8acdf501258
|
[
"Markdown",
"C#"
] | 4
|
Markdown
|
WashingtonARamos/TesteTecnico
|
6c434d20a66af243345c97d52125cd9a944c9e06
|
c56c566632a48ae6f75ce18c1afc6cfd60b96a5c
|
refs/heads/master
|
<repo_name>GabrielBegun/ArduFire<file_sep>/AP_State.ino
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
void set_home_is_set(bool b)
{
// if no change, exit immediately
if( ap.home_is_set == b )
return;
ap.home_is_set = b;
if(b) {
Log_Write_Event(DATA_SET_HOME);
}
}
// ---------------------------------------------
void set_auto_armed(bool b)
{
// if no change, exit immediately
if( ap.auto_armed == b )
return;
ap.auto_armed = b;
if(b){
Log_Write_Event(DATA_AUTO_ARMED);
}
}
// ---------------------------------------------
void set_simple_mode(uint8_t b)
{
if(ap.simple_mode != b){
if(b == 0){
Log_Write_Event(DATA_SET_SIMPLE_OFF);
}else if(b == 1){
Log_Write_Event(DATA_SET_SIMPLE_ON);
}else{
// initialise super simple heading
update_super_simple_bearing(true);
Log_Write_Event(DATA_SET_SUPERSIMPLE_ON);
}
ap.simple_mode = b;
}
}
// ---------------------------------------------
static void set_failsafe_radio(bool b)
{
// only act on changes
// -------------------
if(failsafe.radio != b) {
// store the value so we don't trip the gate twice
// -----------------------------------------------
failsafe.radio = b;
if (failsafe.radio == false) {
// We've regained radio contact
// ----------------------------
failsafe_radio_off_event();
}else{
// We've lost radio contact
// ------------------------
failsafe_radio_on_event();
}
// update AP_Notify
AP_Notify::flags.failsafe_radio = b;
}
}
// ---------------------------------------------
void set_failsafe_battery(bool b)
{
failsafe.battery = b;
AP_Notify::flags.failsafe_battery = b;
}
// ---------------------------------------------
void set_takeoff_complete(bool b)
{
// if no change, exit immediately
if( ap.takeoff_complete == b )
return;
if(b){
Log_Write_Event(DATA_TAKEOFF);
}
ap.takeoff_complete = b;
}
// ---------------------------------------------
void set_land_complete(bool b)
{
// if no change, exit immediately
if( ap.land_complete == b )
return;
if(b){
Log_Write_Event(DATA_LAND_COMPLETE);
}else{
Log_Write_Event(DATA_NOT_LANDED);
}
ap.land_complete = b;
}
// ---------------------------------------------
void set_pre_arm_check(bool b)
{
if(ap.pre_arm_check != b) {
ap.pre_arm_check = b;
AP_Notify::flags.pre_arm_check = b;
}
}
void set_pre_arm_rc_check(bool b)
{
if(ap.pre_arm_rc_check != b) {
ap.pre_arm_rc_check = b;
}
}
<file_sep>/ArduFire.ino
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#define THISFIRMWARE "ArduCopter V3.1.2-rc1"
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ArduCopter Version 3.0
* Creator: <NAME>
* Lead Developer: <NAME>
* Lead Tester: <NAME>
* Based on code and ideas from the Arducopter team: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and more
* Thanks to: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
*
* Special Thanks to contributors (in alphabetical order by first name):
*
* <NAME> :Auto Compass Declination
* <NAME> :Camera mount library
* <NAME> :General development, Mavlink Support
* <NAME> :Alpha testing
* AndreasAntonopoulous:GeoFence
* <NAME> :DroidPlanner GCS
* <NAME> :Libraries
* <NAME> :Single Copter
* <NAME> :Alpha testing
* <NAME> :Release Management, Support
* <NAME> :V Octo Support
* <NAME> :DCM, Libraries, Control law advice
* <NAME> :Camera mount orientation math
* Guntars :Arming safety suggestion
* HappyKillmore :Mavlink GCS
* <NAME> :Octo Support, Heli Testing
* <NAME> :Control Law optimization
* <NAME> :Alpha testing
* <NAME> :Mavlink Support
* <NAME> :Testing feedback
* <NAME> :Auto Landing
* <NAME> :PPM Encoder
* <NAME> :Stabilization Control laws, MPU6k driver
* <NAME> :Pixhawk
* <NAME> :Inertial Navigation, CompassMot, Spin-When-Armed
* <NAME> :Andropilot GCS
* <NAME> :Tri Support, Graphics
* <NAME> :Flight Dynamics, Throttle, Loiter and Navigation Controllers
* <NAME> :Lead tester
* <NAME> :Mission Planner GCS
* <NAME> :Pixhawk driver, coding support
* <NAME> :PPM Encoder, piezo buzzer
* <NAME> :Hardware Abstraaction Layer (HAL)
* <NAME> :Heli Support, Copter LEDs
* <NAME> :Library testing, Porting to VRBrain
* <NAME> :Camera support, MinimOSD
* ..and many more.
*
* Code commit statistics can be found here: https://github.com/diydrones/ardupilot/graphs/contributors
* Wiki: http://copter.ardupilot.com/
* Requires modified version of Arduino, which can be found here: http://ardupilot.com/downloads/?category=6
*
*/
////////////////////////////////////////////////////////////////////////////////
// Header includes
////////////////////////////////////////////////////////////////////////////////
#include <math.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
// Common dependencies
#include <AP_Common.h>
#include <AP_Progmem.h>
#include <AP_Menu.h>
#include <AP_Param.h>
// AP_HAL
#include <AP_HAL.h>
#include <AP_HAL_AVR.h>
#include <AP_HAL_AVR_SITL.h>
#include <AP_HAL_PX4.h>
#include <AP_HAL_FLYMAPLE.h>
#include <AP_HAL_Linux.h>
#include <AP_HAL_Empty.h>
// Application dependencies
#include <AP_GPS.h> // ArduPilot GPS library
#include <AP_GPS_Glitch.h> // GPS glitch protection library
#include <DataFlash.h> // ArduPilot Mega Flash Memory Library
#include <AP_ADC.h> // ArduPilot Mega Analog to Digital Converter Library
#include <AP_ADC_AnalogSource.h>
#include <AP_Baro.h>
#include <AP_Compass.h> // ArduPilot Mega Magnetometer Library
#include <AP_Math.h> // ArduPilot Mega Vector/Matrix math Library
#include <AP_Curve.h> // Curve used to linearlise throttle pwm to thrust
#include <AP_InertialSensor.h> // ArduPilot Mega Inertial Sensor (accel & gyro) Library
#include <AP_AHRS.h>
#include <APM_PI.h> // PI library
#include <AC_PID.h> // PID library
#include <RC_Channel.h> // RC Channel Library
#include <AP_Motors.h> // AP Motors library
#include <AP_RangeFinder.h> // Range finder library
#include <AP_OpticalFlow.h> // Optical Flow library
#include <Filter.h> // Filter library
#include <AP_Buffer.h> // APM FIFO Buffer
#include <AP_Relay.h> // APM relay
#include <AP_ServoRelayEvents.h>
#include <AP_Airspeed.h> // needed for AHRS build
#include <AP_Vehicle.h> // needed for AHRS build
#include <AP_InertialNav.h> // ArduPilot Mega inertial navigation library
#include <AC_WPNav.h> // ArduCopter waypoint navigation library
#include <AP_Declination.h> // ArduPilot Mega Declination Helper Library
#include <SITL.h> // software in the loop support
#include <AP_Scheduler.h> // main loop scheduler
#include <AP_RCMapper.h> // RC input mapping library
#include <AP_Notify.h> // Notify library
#include <AP_BattMonitor.h> // Battery monitor library
#include <AP_BoardConfig.h> // board configuration library
#if SPRAYER == ENABLED
#include <AC_Sprayer.h> // crop sprayer library
#endif
#if EPM_ENABLED == ENABLED
#include <AP_EPM.h> // EPM cargo gripper stuff
#endif
// AP_HAL to Arduino compatibility layer
#include "compat.h"
// Configuration
#include "defines.h"
#include "config.h"
#include "config_channels.h"
// Local modules
#include "Parameters.h"
#include "GCS.h"
////////////////////////////////////////////////////////////////////////////////
// cliSerial
////////////////////////////////////////////////////////////////////////////////
// cliSerial isn't strictly necessary - it is an alias for hal.console. It may
// be deprecated in favor of hal.console in later releases.
static AP_HAL::BetterStream* cliSerial;
// N.B. we need to keep a static declaration which isn't guarded by macros
// at the top to cooperate with the prototype mangler.
////////////////////////////////////////////////////////////////////////////////
// AP_HAL instance
////////////////////////////////////////////////////////////////////////////////
const AP_HAL::HAL& hal = AP_HAL_BOARD_DRIVER;
////////////////////////////////////////////////////////////////////////////////
// Parameters
////////////////////////////////////////////////////////////////////////////////
//
// Global parameters are all contained within the 'g' class.
//
static Parameters g;
// main loop scheduler
static AP_Scheduler scheduler;
// AP_Notify instance
static AP_Notify notify;
////////////////////////////////////////////////////////////////////////////////
// prototypes
////////////////////////////////////////////////////////////////////////////////
static void update_events(void);
static void print_flight_mode(AP_HAL::BetterStream *port, uint8_t mode);
////////////////////////////////////////////////////////////////////////////////
// Dataflash
////////////////////////////////////////////////////////////////////////////////
#if CONFIG_HAL_BOARD == HAL_BOARD_APM2
static DataFlash_APM2 DataFlash;
#endif
////////////////////////////////////////////////////////////////////////////////
// the rate we run the main loop at
////////////////////////////////////////////////////////////////////////////////
static const AP_InertialSensor::Sample_rate ins_sample_rate = AP_InertialSensor::RATE_100HZ;
////////////////////////////////////////////////////////////////////////////////
// Sensors
////////////////////////////////////////////////////////////////////////////////
//
// There are three basic options related to flight sensor selection.
//
// - Normal flight mode. Real sensors are used.
// - HIL Attitude mode. Most sensors are disabled, as the HIL
// protocol supplies attitude information directly.
// - HIL Sensors mode. Synthetic sensors are configured that
// supply data from the simulation.
//
// All GPS access should be through this pointer.
static GPS *g_gps;
static GPS_Glitch gps_glitch(g_gps);
// flight modes convenience array
static AP_Int8 *flight_modes = &g.flight_mode1;
#if HIL_MODE == HIL_MODE_DISABLED
#if CONFIG_ADC == ENABLED
static AP_ADC_ADS7844 adc;
#endif
#if CONFIG_IMU_TYPE == CONFIG_IMU_MPU6000
static AP_InertialSensor_MPU6000 ins;
#elif CONFIG_IMU_TYPE == CONFIG_IMU_OILPAN
static AP_InertialSensor_Oilpan ins(&adc);
#elif CONFIG_IMU_TYPE == CONFIG_IMU_SITL
static AP_InertialSensor_HIL ins;
#elif CONFIG_IMU_TYPE == CONFIG_IMU_PX4
static AP_InertialSensor_PX4 ins;
#elif CONFIG_IMU_TYPE == CONFIG_IMU_FLYMAPLE
AP_InertialSensor_Flymaple ins;
#elif CONFIG_IMU_TYPE == CONFIG_IMU_L3G4200D
AP_InertialSensor_L3G4200D ins;
#endif
#if CONFIG_HAL_BOARD == HAL_BOARD_AVR_SITL
// When building for SITL we use the HIL barometer and compass drivers
static AP_Baro_HIL barometer;
static AP_Compass_HIL compass;
static SITL sitl;
#else
// Otherwise, instantiate a real barometer and compass driver
#if CONFIG_BARO == AP_BARO_BMP085
static AP_Baro_BMP085 barometer;
#elif CONFIG_BARO == AP_BARO_PX4
static AP_Baro_PX4 barometer;
#elif CONFIG_BARO == AP_BARO_MS5611
#if CONFIG_MS5611_SERIAL == AP_BARO_MS5611_SPI
static AP_Baro_MS5611 barometer(&AP_Baro_MS5611::spi);
#elif CONFIG_MS5611_SERIAL == AP_BARO_MS5611_I2C
static AP_Baro_MS5611 barometer(&AP_Baro_MS5611::i2c);
#else
#error Unrecognized CONFIG_MS5611_SERIAL setting.
#endif
#endif
static AP_Compass_HMC5843 compass;
#endif
// real GPS selection
#if GPS_PROTOCOL == GPS_PROTOCOL_NONE
AP_GPS_None g_gps_driver;
#else
#error Unrecognised GPS_PROTOCOL setting.
#endif // GPS PROTOCOL
static AP_AHRS_DCM ahrs(ins, g_gps);
#elif HIL_MODE == HIL_MODE_SENSORS
// sensor emulators
static AP_ADC_HIL adc;
static AP_Baro_HIL barometer;
static AP_Compass_HIL compass;
static AP_GPS_HIL g_gps_driver;
static AP_InertialSensor_HIL ins;
static AP_AHRS_DCM ahrs(ins, g_gps);
#elif HIL_MODE == HIL_MODE_ATTITUDE
static AP_ADC_HIL adc;
static AP_InertialSensor_HIL ins;
static AP_AHRS_HIL ahrs(ins, g_gps);
static AP_GPS_HIL g_gps_driver;
static AP_Compass_HIL compass; // never used
static AP_Baro_HIL barometer;
#else
#error Unrecognised HIL_MODE setting.
#endif // HIL MODE
////////////////////////////////////////////////////////////////////////////////
// SONAR selection
////////////////////////////////////////////////////////////////////////////////
//
ModeFilterInt16_Size3 sonar_mode_filter(1);
#if CONFIG_SONAR == ENABLED
static AP_HAL::AnalogSource *sonar_analog_source;
static AP_RangeFinder_MaxsonarXL *sonar;
#endif
////////////////////////////////////////////////////////////////////////////////
// User variables
////////////////////////////////////////////////////////////////////////////////
#ifdef USERHOOK_VARIABLES
#include USERHOOK_VARIABLES
#endif
////////////////////////////////////////////////////////////////////////////////
// Global variables
////////////////////////////////////////////////////////////////////////////////
/* Radio values
* Channel assignments
* 1 Ailerons (rudder if no ailerons)
* 2 Elevator
* 3 Throttle
* 4 Rudder (if we have ailerons)
* 5 Mode - 3 position switch
* 6 User assignable
* 7 trainer switch - sets throttle nominal (toggle switch), sets accels to Level (hold > 1 second)
* 8 TBD
* Each Aux channel can be configured to have any of the available auxiliary functions assigned to it.
* See libraries/RC_Channel/RC_Channel_aux.h for more information
*/
//Documentation of GLobals:
static union {
struct {
uint8_t home_is_set : 1; // 0
uint8_t simple_mode : 2; // 1,2 // This is the state of simple mode : 0 = disabled ; 1 = SIMPLE ; 2 = SUPERSIMPLE
uint8_t pre_arm_rc_check : 1; // 3 // true if rc input pre-arm checks have been completed successfully
uint8_t pre_arm_check : 1; // 4 // true if all pre-arm checks (rc, accel calibration, gps lock) have been performed
uint8_t auto_armed : 1; // 5 // stops auto missions from beginning until throttle is raised
uint8_t logging_started : 1; // 6 // true if dataflash logging has started
uint8_t do_flip : 1; // 7 // Used to enable flip code
uint8_t takeoff_complete : 1; // 8
uint8_t land_complete : 1; // 9 // true if we have detected a landing
uint8_t new_radio_frame : 1; // 10 // Set true if we have new PWM data to act on from the Radio
uint8_t CH7_flag : 2; // 11,12 // ch7 aux switch : 0 is low or false, 1 is center or true, 2 is high
uint8_t CH8_flag : 2; // 13,14 // ch8 aux switch : 0 is low or false, 1 is center or true, 2 is high
uint8_t usb_connected : 1; // 15 // true if APM is powered from USB connection
uint8_t yaw_stopped : 1; // 16 // Used to manage the Yaw hold capabilities
uint8_t disable_stab_rate_limit : 1; // 17 // disables limits rate request from the stability controller
uint8_t rc_receiver_present : 1; // 18 // true if we have an rc receiver present (i.e. if we've ever received an update
};
uint32_t value;
} ap;
////////////////////////////////////////////////////////////////////////////////
// Radio
////////////////////////////////////////////////////////////////////////////////
// This is the state of the flight control system
// There are multiple states defined such as STABILIZE, ACRO,
static int8_t control_mode = STABILIZE;
// Used to maintain the state of the previous control switch position
// This is set to -1 when we need to re-read the switch
static uint8_t oldSwitchPosition;
static RCMapper rcmap;
// board specific config
static AP_BoardConfig BoardConfig;
// receiver RSSI
static uint8_t receiver_rssi;
////////////////////////////////////////////////////////////////////////////////
// Failsafe
////////////////////////////////////////////////////////////////////////////////
static struct {
uint8_t rc_override_active : 1; // 0 // true if rc control are overwritten by ground station
uint8_t radio : 1; // 1 // A status flag for the radio failsafe
uint8_t battery : 1; // 2 // A status flag for the battery failsafe
int8_t radio_counter; // number of iterations with throttle below throttle_fs_value
uint32_t last_heartbeat_ms; // the time when the last HEARTBEAT message arrived from a GCS - used for triggering gcs failsafe
} failsafe;
////////////////////////////////////////////////////////////////////////////////
// Motor Output
////////////////////////////////////////////////////////////////////////////////
// Moved this to userVariables because of scope
// #define MOTOR_CLASS AP_MotorsQuad
//static MOTOR_CLASS motors(&g.rc_1, &g.rc_2, &g.rc_3, &g.rc_4);
////////////////////////////////////////////////////////////////////////////////
// PIDs
////////////////////////////////////////////////////////////////////////////////
// This is a convienience accessor for the IMU roll rates. It's currently the raw IMU rates
// and not the adjusted omega rates, but the name is stuck
static Vector3f omega;
// This is used to hold radio tuning values for in-flight CH6 tuning
float tuning_value;
// A LOT OF STUFF THAT WAS HERE WAS MOVED TO USER SPACE
////////////////////////////////////////////////////////////////////////////////
// Performance monitoring
////////////////////////////////////////////////////////////////////////////////
static int16_t pmTest1;
// System Timers
// --------------
// Time in microseconds of main control loop
static uint32_t fast_loopTimer;
// Counter of main loop executions. Used for performance monitoring and failsafe processing
static uint16_t mainLoop_count;
// Loiter timer - Records how long we have been in loiter
static uint32_t rtl_loiter_start_time;
// Used to exit the roll and pitch auto trim function
static uint8_t auto_trim_counter;
// Reference to the relay object (APM1 -> PORTL 2) (APM2 -> PORTB 7)
static AP_Relay relay;
// handle repeated servo and relay events
static AP_ServoRelayEvents ServoRelayEvents(relay);
// a pin for reading the receiver RSSI voltage.
static AP_HAL::AnalogSource* rssi_analog_source;
// Input sources for battery voltage, battery current, board vcc
static AP_HAL::AnalogSource* board_vcc_analog_source;
#if CLI_ENABLED == ENABLED
static int8_t setup_show (uint8_t argc, const Menu::arg *argv);
#endif
// Camera/Antenna mount tracking and stabilisation stuff
// --------------------------------------
////////////////////////////////////////////////////////////////////////////////
// Crop Sprayer
////////////////////////////////////////////////////////////////////////////////
#if SPRAYER == ENABLED
static AC_Sprayer sprayer(&inertial_nav);
#endif
////////////////////////////////////////////////////////////////////////////////
// EPM Cargo Griper
////////////////////////////////////////////////////////////////////////////////
#if EPM_ENABLED == ENABLED
static AP_EPM epm;
#endif
////////////////////////////////////////////////////////////////////////////////
// function definitions to keep compiler from complaining about undeclared functions
////////////////////////////////////////////////////////////////////////////////
void get_throttle_althold(int32_t target_alt, int16_t min_climb_rate, int16_t max_climb_rate);
static void pre_arm_checks(bool display_failure);
////////////////////////////////////////////////////////////////////////////////
// Top-level logic
////////////////////////////////////////////////////////////////////////////////
// setup the var_info table
AP_Param param_loader(var_info, WP_START_BYTE);
/*
scheduler table - all regular tasks apart from the fast_loop()
should be listed here, along with how often they should be called
(in 10ms units) and the maximum time they are expected to take (in
microseconds)
*/
static const AP_Scheduler::Task scheduler_tasks[] PROGMEM = {
{ throttle_loop, 2, 450 },
// { update_nav_mode, 1, 400 },
{ update_batt_compass, 10, 720 },
// { read_aux_switches, 10, 50 },
{ arm_motors_check, 10, 10 },
{ auto_trim, 10, 140 }, // CHECK
{ update_altitude, 10, 1000 },
// { run_nav_updates, 10, 800 },
{ three_hz_loop, 33, 90 },
{ compass_accumulate, 2, 420 },
{ barometer_accumulate, 2, 250 },
{ update_notify, 2, 100 },
{ one_hz_loop, 100, 420 },
{ crash_check, 10, 20 },
// { ten_hz_logging_loop, 10, 300 },
// { fifty_hz_logging_loop, 2, 220 },
{ perf_update, 1000, 200 },
// { read_receiver_rssi, 10, 50 },
#ifdef USERHOOK_FASTLOOP
{ userhook_FastLoop, 1, 100 },
#endif
#ifdef USERHOOK_50HZLOOP
{ userhook_50Hz, 2, 100 },
#endif
#ifdef USERHOOK_MEDIUMLOOP
{ userhook_MediumLoop, 10, 1000 },
#endif
#ifdef USERHOOK_SLOWLOOP
{ userhook_SlowLoop, 30, 100 },
#endif
#ifdef USERHOOK_SUPERSLOWLOOP
{ userhook_SuperSlowLoop,101, 1000 },
#endif
};
/// COPY HERERERERE
void setup()
{
cliSerial = hal.console;
// Load the default values of variables listed in var_info[]s
AP_Param::setup_sketch_defaults();
init_ardupilot();
// initialise the main loop scheduler
scheduler.init(&scheduler_tasks[0], sizeof(scheduler_tasks)/sizeof(scheduler_tasks[0]));
}
/*
if the compass is enabled then try to accumulate a reading
*/
static void compass_accumulate(void)
{
if (g.compass_enabled) {
compass.accumulate();
}
}
/*
try to accumulate a baro reading
*/
static void barometer_accumulate(void)
{
barometer.accumulate();
}
static void perf_update(void)
{
if (g.log_bitmask & MASK_LOG_PM)
Log_Write_Performance();
if (scheduler.debug()) {
cliSerial->printf_P(PSTR("PERF: %u/%u %lu\n"),
(unsigned)perf_info_get_num_long_running(),
(unsigned)perf_info_get_num_loops(),
(unsigned long)perf_info_get_max_time());
}
perf_info_reset();
pmTest1 = 0;
}
void loop()
{
// wait for an INS sample
if (!ins.wait_for_sample(1000)) {
Log_Write_Error(ERROR_SUBSYSTEM_MAIN, ERROR_CODE_MAIN_INS_DELAY);
return;
}
uint32_t timer = micros();
// check loop time
perf_info_check_loop_time(timer - fast_loopTimer);
// used by PI Loops
G_Dt = (float)(timer - fast_loopTimer) / 1000000.f;
fast_loopTimer = timer;
// for mainloop failure monitoring
mainLoop_count++;
// Execute the fast loop
// ---------------------
fast_loop();
// tell the scheduler one tick has passed
scheduler.tick();
// run all the tasks that are due to run. Note that we only
// have to call this once per loop, as the tasks are scheduled
// in multiples of the main loop tick. So if they don't run on
// the first call to the scheduler they won't run on a later
// call until scheduler.tick() is called again
uint32_t time_available = (timer + 10000) - micros();
scheduler.run(time_available - 300);
}
// Main loop - 100hz
static void fast_loop()
{
// IMU DCM Algorithm
// Reads internal sensors (?)
// --------------------
read_AHRS();
// reads all of the necessary trig functions for cameras, throttle, etc.
// --------------------------------------------------------------------
update_trig();
// Acrobatic control
if (ap.do_flip) {
if(abs(g.rc_1.control_in) < 4000) {
// calling roll_flip will override the desired roll rate and throttle output
roll_flip();
}else{
// force an exit from the loop if we are not hands off sticks.
ap.do_flip = false;
Log_Write_Event(DATA_EXIT_FLIP);
}
}
// run low level rate controllers that only require IMU data
run_rate_controllers();
// write out the servo PWM values
// ------------------------------
set_servos_4();
// Inertial Nav
// --------------------
read_inertia();
// Read radio and 3-position switch on radio
// -----------------------------------------
read_radio();
//read_control_switch();
// update mode according to RC controller // custom
update_mode();
//readUartB();
// custom code/exceptions for flight modes
// ---------------------------------------
update_yaw_mode();
update_roll_pitch_mode();
// update targets to rate controllers
update_rate_contoller_targets();
}
// throttle_loop - should be run at 50 hz
// ---------------------------
static void throttle_loop()
{
// get altitude and climb rate from inertial lib
read_inertial_altitude();
// Update the throttle ouput
// -------------------------
update_throttle_mode();
// check if we've landed
update_land_detector();
// check auto_armed status
update_auto_armed();
}
// update_mount - update camera mount position
// should be run at 50hz
static void update_mount()
{
}
// update_batt_compass - read battery and compass
// should be called at 10hz
static void update_batt_compass(void)
{
// read battery before compass because it may be used for motor interference compensation
read_battery();
#if HIL_MODE != HIL_MODE_ATTITUDE // don't execute in HIL mode
if(g.compass_enabled) {
if (compass.read()) {
compass.null_offsets();
}
// log compass information
if (g.log_bitmask & MASK_LOG_COMPASS) {
Log_Write_Compass();
}
}
#endif
// record throttle output
throttle_integrator += g.rc_3.servo_out;
}
// three_hz_loop - 3.3hz loop
static void three_hz_loop()
{
#if SPRAYER == ENABLED
sprayer.update();
#endif
update_events();
if(g.radio_tuning > 0)
tuning();
}
// one_hz_loop - runs at 1Hz
static void one_hz_loop()
{
if (g.log_bitmask != 0) {
Log_Write_Data(DATA_AP_STATE, ap.value);
}
// pass latest alt hold kP value to navigation controller
wp_nav.set_althold_kP(g.pi_alt_hold.kP());
// update latest lean angle to navigation controller
wp_nav.set_lean_angle_max(g.angle_max);
// log battery info to the dataflash
if (g.log_bitmask & MASK_LOG_CURRENT) {
Log_Write_Current();
}
// perform pre-arm checks & display failures every 30 seconds
static uint8_t pre_arm_display_counter = 15;
pre_arm_display_counter++;
if (pre_arm_display_counter >= 30) {
pre_arm_checks(true);
pre_arm_display_counter = 0;
}else{
pre_arm_checks(false);
}
// auto disarm checks
// auto_disarm_check();
// CHECK
if (!motors.armed()) {
// make it possible to change ahrs orientation at runtime during initial config
ahrs.set_orientation();
// check the user hasn't updated the frame orientation
motors.set_frame_orientation(g.frame_orientation);
}
// update assigned functions and enable auxiliar servos
aux_servos_update_fn();
enable_aux_servos();
check_usb_mux();
}
// called at 100hz but data from sensor only arrives at 20 Hz
static void update_optical_flow(void)
{
}
// called at 50hz
static void update_GPS(void)
{
return;
}
// set_yaw_mode - update yaw mode and initialise any variables required
bool set_yaw_mode(uint8_t new_yaw_mode)
{
// boolean to ensure proper initialisation of throttle modes
bool yaw_initialised = false;
// return immediately if no change
if( new_yaw_mode == yaw_mode ) {
return true;
}
switch( new_yaw_mode ) {
case YAW_HOLD:
yaw_initialised = true;
break;
case YAW_ACRO:
yaw_initialised = true;
acro_yaw_rate = 0;
break;
case YAW_LOOK_AT_NEXT_WP:
if( ap.home_is_set ) {
yaw_initialised = true;
}
break;
case YAW_LOOK_AT_LOCATION:
if( ap.home_is_set ) {
// update bearing - assumes yaw_look_at_WP has been intialised before set_yaw_mode was called
yaw_look_at_WP_bearing = pv_get_bearing_cd(inertial_nav.get_position(), yaw_look_at_WP);
yaw_initialised = true;
}
break;
case YAW_CIRCLE:
if( ap.home_is_set ) {
// set yaw to point to center of circle
yaw_look_at_WP = circle_center;
// initialise bearing to current heading
yaw_look_at_WP_bearing = ahrs.yaw_sensor;
yaw_initialised = true;
}
break;
case YAW_LOOK_AT_HEADING:
yaw_initialised = true;
break;
case YAW_LOOK_AT_HOME:
if( ap.home_is_set ) {
yaw_initialised = true;
}
break;
case YAW_LOOK_AHEAD:
if( ap.home_is_set ) {
yaw_initialised = true;
}
break;
case YAW_DRIFT:
yaw_initialised = true;
break;
case YAW_RESETTOARMEDYAW:
control_yaw = ahrs.yaw_sensor; // store current yaw so we can start rotating back to correct one
yaw_initialised = true;
break;
}
// if initialisation has been successful update the yaw mode
if( yaw_initialised ) {
yaw_mode = new_yaw_mode;
}
// return success or failure
return yaw_initialised;
}
// update_yaw_mode - run high level yaw controllers
// 100hz update rate
void update_yaw_mode(void)
{
int16_t pilot_yaw;
if(flymode == auto_mode){
pilot_yaw = receivedCommands.yaw;
//yaw_mode = YAW_HOLD;
//receivedCommands.yaw = 0;
} else {
pilot_yaw = g.rc_4.control_in;
}
// do not process pilot's yaw input during radio failsafe
if (failsafe.radio) {
pilot_yaw = 0;
}
switch(yaw_mode) {
case YAW_HOLD:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}
// heading hold at heading held in control_yaw but allow input from pilot
get_yaw_rate_stabilized_ef(pilot_yaw);
break;
case YAW_ACRO:
// pilot controlled yaw using rate controller
get_yaw_rate_stabilized_bf(pilot_yaw);
break;
case YAW_LOOK_AT_NEXT_WP:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}else{
// point towards next waypoint (no pilot input accepted)
// we don't use wp_bearing because we don't want the copter to turn too much during flight
control_yaw = get_yaw_slew(control_yaw, original_wp_bearing, AUTO_YAW_SLEW_RATE);
}
get_stabilize_yaw(control_yaw);
// if there is any pilot input, switch to YAW_HOLD mode for the next iteration
if (pilot_yaw != 0) {
set_yaw_mode(YAW_HOLD);
}
break;
case YAW_LOOK_AT_LOCATION:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}
// point towards a location held in yaw_look_at_WP
get_look_at_yaw();
// if there is any pilot input, switch to YAW_HOLD mode for the next iteration
if (pilot_yaw != 0) {
set_yaw_mode(YAW_HOLD);
}
break;
case YAW_CIRCLE:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}
// points toward the center of the circle or does a panorama
get_circle_yaw();
// if there is any pilot input, switch to YAW_HOLD mode for the next iteration
if (pilot_yaw != 0) {
set_yaw_mode(YAW_HOLD);
}
break;
case YAW_LOOK_AT_HOME:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}else{
// keep heading always pointing at home with no pilot input allowed
control_yaw = get_yaw_slew(control_yaw, home_bearing, AUTO_YAW_SLEW_RATE);
}
get_stabilize_yaw(control_yaw);
// if there is any pilot input, switch to YAW_HOLD mode for the next iteration
if (pilot_yaw != 0) {
set_yaw_mode(YAW_HOLD);
}
break;
case YAW_LOOK_AT_HEADING:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}else{
// keep heading pointing in the direction held in yaw_look_at_heading with no pilot input allowed
control_yaw = get_yaw_slew(control_yaw, yaw_look_at_heading, yaw_look_at_heading_slew);
}
get_stabilize_yaw(control_yaw);
break;
case YAW_LOOK_AHEAD:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}
// Commanded Yaw to automatically look ahead.
get_look_ahead_yaw(pilot_yaw);
break;
case YAW_DRIFT:
// if we have landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}
get_yaw_drift();
break;
case YAW_RESETTOARMEDYAW:
// if we are landed reset yaw target to current heading
if (ap.land_complete) {
control_yaw = ahrs.yaw_sensor;
}else{
// changes yaw to be same as when quad was armed
control_yaw = get_yaw_slew(control_yaw, initial_armed_bearing, AUTO_YAW_SLEW_RATE);
}
get_stabilize_yaw(control_yaw);
// if there is any pilot input, switch to YAW_HOLD mode for the next iteration
if (pilot_yaw != 0) {
set_yaw_mode(YAW_HOLD);
}
break;
}
}
// get yaw mode based on WP_YAW_BEHAVIOR parameter
// set rtl parameter to true if this is during an RTL
uint8_t get_wp_yaw_mode(bool rtl)
{
switch (g.wp_yaw_behavior) {
case WP_YAW_BEHAVIOR_LOOK_AT_NEXT_WP:
return YAW_LOOK_AT_NEXT_WP;
break;
case WP_YAW_BEHAVIOR_LOOK_AT_NEXT_WP_EXCEPT_RTL:
if( rtl ) {
return YAW_HOLD;
}else{
return YAW_LOOK_AT_NEXT_WP;
}
break;
case WP_YAW_BEHAVIOR_LOOK_AHEAD:
return YAW_LOOK_AHEAD;
break;
default:
return YAW_HOLD;
break;
}
}
// set_roll_pitch_mode - update roll/pitch mode and initialise any variables as required
bool set_roll_pitch_mode(uint8_t new_roll_pitch_mode)
{
// boolean to ensure proper initialisation of throttle modes
bool roll_pitch_initialised = false;
// return immediately if no change
if( new_roll_pitch_mode == roll_pitch_mode ) {
return true;
}
switch( new_roll_pitch_mode ) {
case ROLL_PITCH_STABLE:
roll_pitch_initialised = true;
break;
case ROLL_PITCH_ACRO:
// reset acro level rates
acro_roll_rate = 0;
acro_pitch_rate = 0;
roll_pitch_initialised = true;
break;
case ROLL_PITCH_AUTO:
case ROLL_PITCH_STABLE_OF:
case ROLL_PITCH_DRIFT:
case ROLL_PITCH_LOITER:
case ROLL_PITCH_SPORT:
roll_pitch_initialised = true;
break;
#if AUTOTUNE == ENABLED
case ROLL_PITCH_AUTOTUNE:
// only enter autotune mode from stabilized roll-pitch mode when armed and flying
if (roll_pitch_mode == ROLL_PITCH_STABLE && motors.armed() && !ap.land_complete) {
// auto_tune_start returns true if it wants the roll-pitch mode changed to autotune
roll_pitch_initialised = auto_tune_start();
}
break;
#endif
}
// if initialisation has been successful update the yaw mode
if( roll_pitch_initialised ) {
exit_roll_pitch_mode(roll_pitch_mode);
roll_pitch_mode = new_roll_pitch_mode;
}
// return success or failure
return roll_pitch_initialised;
}
// exit_roll_pitch_mode - peforms any code required when exiting the current roll-pitch mode
void exit_roll_pitch_mode(uint8_t old_roll_pitch_mode)
{
#if AUTOTUNE == ENABLED
if (old_roll_pitch_mode == ROLL_PITCH_AUTOTUNE) {
auto_tune_stop();
}
#endif
}
// update_roll_pitch_mode - run high level roll and pitch controllers
// 100hz update rate
void update_roll_pitch_mode(void)
{
switch(roll_pitch_mode) {
case ROLL_PITCH_ACRO:
// copy user input for reporting purposes
/*if(flymode == auto_mode){
control_roll = receivedCommands.roll;
control_pitch = receivedCommands.pitch;
receivedCommands.roll = 0;
receivedCommands.pitch = 0;
} else {*/
control_roll = g.rc_1.control_in;
control_pitch = g.rc_1.control_in;
//}
acro_level_mix = constrain_float(1-max(max(abs(g.rc_1.control_in), abs(g.rc_2.control_in)), abs(g.rc_4.control_in))/4500.0, 0, 1)*cos_pitch_x;
get_roll_rate_stabilized_bf(g.rc_1.control_in);
get_pitch_rate_stabilized_bf(g.rc_2.control_in);
get_acro_level_rates();
break;
case ROLL_PITCH_STABLE:
// apply SIMPLE mode transform
update_simple_mode();
// convert pilot input to lean angles
get_pilot_desired_lean_angles(g.rc_1.control_in, g.rc_2.control_in, control_roll, control_pitch);
// pass desired roll, pitch to stabilize attitude controllers
get_stabilize_roll(control_roll);
get_stabilize_pitch(control_pitch);
break;
case ROLL_PITCH_AUTO:
// copy latest output from nav controller to stabilize controller
control_roll = wp_nav.get_desired_roll();
control_pitch = wp_nav.get_desired_pitch();
get_stabilize_roll(control_roll);
get_stabilize_pitch(control_pitch);
break;
case ROLL_PITCH_STABLE_OF:
// apply SIMPLE mode transform
update_simple_mode();
// convert pilot input to lean angles
get_pilot_desired_lean_angles(g.rc_1.control_in, g.rc_2.control_in, control_roll, control_pitch);
// mix in user control with optical flow
control_roll = get_of_roll(control_roll);
control_pitch = get_of_pitch(control_pitch);
// call stabilize controller
get_stabilize_roll(control_roll);
get_stabilize_pitch(control_pitch);
break;
case ROLL_PITCH_DRIFT:
get_roll_pitch_drift();
break;
case ROLL_PITCH_LOITER:
// apply SIMPLE mode transform
update_simple_mode();
// update loiter target from user controls
wp_nav.move_loiter_target(g.rc_1.control_in, g.rc_2.control_in, 0.01f);
// copy latest output from nav controller to stabilize controller
control_roll = wp_nav.get_desired_roll();
control_pitch = wp_nav.get_desired_pitch();
get_stabilize_roll(control_roll);
get_stabilize_pitch(control_pitch);
break;
case ROLL_PITCH_SPORT:
// apply SIMPLE mode transform
update_simple_mode();
// copy user input for reporting purposes
control_roll = g.rc_1.control_in;
control_pitch = g.rc_2.control_in;
get_roll_rate_stabilized_ef(g.rc_1.control_in);
get_pitch_rate_stabilized_ef(g.rc_2.control_in);
break;
#if AUTOTUNE == ENABLED
case ROLL_PITCH_AUTOTUNE:
// apply SIMPLE mode transform
if(ap.simple_mode && ap.new_radio_frame) {
update_simple_mode();
}
// convert pilot input to lean angles
get_pilot_desired_lean_angles(g.rc_1.control_in, g.rc_2.control_in, control_roll, control_pitch);
// pass desired roll, pitch to stabilize attitude controllers
get_stabilize_roll(control_roll);
get_stabilize_pitch(control_pitch);
// copy user input for reporting purposes
get_autotune_roll_pitch_controller(g.rc_1.control_in, g.rc_2.control_in, g.rc_4.control_in);
break;
#endif
}
#if FRAME_CONFIG != HELI_FRAME
if(g.rc_3.control_in == 0 && control_mode <= ACRO) {
reset_rate_I();
}
#endif //HELI_FRAME
if(ap.new_radio_frame) {
// clear new radio frame info
ap.new_radio_frame = false;
}
}
static void
init_simple_bearing()
{
// capture current cos_yaw and sin_yaw values
simple_cos_yaw = cos_yaw;
simple_sin_yaw = sin_yaw;
// initialise super simple heading (i.e. heading towards home) to be 180 deg from simple mode heading
super_simple_last_bearing = wrap_360_cd(ahrs.yaw_sensor+18000);
super_simple_cos_yaw = simple_cos_yaw;
super_simple_sin_yaw = simple_sin_yaw;
// log the simple bearing to dataflash
if (g.log_bitmask != 0) {
Log_Write_Data(DATA_INIT_SIMPLE_BEARING, ahrs.yaw_sensor);
}
}
// update_simple_mode - rotates pilot input if we are in simple mode
void update_simple_mode(void)
{
float rollx, pitchx;
// exit immediately if no new radio frame or not in simple mode
if (ap.simple_mode == 0 || !ap.new_radio_frame) {
return;
}
if (ap.simple_mode == 1) {
// rotate roll, pitch input by -initial simple heading (i.e. north facing)
rollx = g.rc_1.control_in*simple_cos_yaw - g.rc_2.control_in*simple_sin_yaw;
pitchx = g.rc_1.control_in*simple_sin_yaw + g.rc_2.control_in*simple_cos_yaw;
}else{
// rotate roll, pitch input by -super simple heading (reverse of heading to home)
rollx = g.rc_1.control_in*super_simple_cos_yaw - g.rc_2.control_in*super_simple_sin_yaw;
pitchx = g.rc_1.control_in*super_simple_sin_yaw + g.rc_2.control_in*super_simple_cos_yaw;
}
// rotate roll, pitch input from north facing to vehicle's perspective
g.rc_1.control_in = rollx*cos_yaw + pitchx*sin_yaw;
g.rc_2.control_in = -rollx*sin_yaw + pitchx*cos_yaw;
}
// update_super_simple_bearing - adjusts simple bearing based on location
// should be called after home_bearing has been updated
void update_super_simple_bearing(bool force_update)
{
// check if we are in super simple mode and at least 10m from home
if(force_update || (ap.simple_mode == 2 && home_distance > SUPER_SIMPLE_RADIUS)) {
// check the bearing to home has changed by at least 5 degrees
if (labs(super_simple_last_bearing - home_bearing) > 500) {
super_simple_last_bearing = home_bearing;
float angle_rad = radians((super_simple_last_bearing+18000)/100);
super_simple_cos_yaw = cosf(angle_rad);
super_simple_sin_yaw = sinf(angle_rad);
}
}
}
// throttle_mode_manual - returns true if the throttle is directly controlled by the pilot
bool throttle_mode_manual(uint8_t thr_mode)
{
return (thr_mode == THROTTLE_MANUAL || thr_mode == THROTTLE_MANUAL_TILT_COMPENSATED || thr_mode == THROTTLE_MANUAL_HELI);
}
// set_throttle_mode - sets the throttle mode and initialises any variables as required
bool set_throttle_mode( uint8_t new_throttle_mode )
{
// boolean to ensure proper initialisation of throttle modes
bool throttle_initialised = false;
// return immediately if no change
if( new_throttle_mode == throttle_mode ) {
return true;
}
// initialise any variables required for the new throttle mode
switch(new_throttle_mode) {
case THROTTLE_MANUAL:
case THROTTLE_MANUAL_TILT_COMPENSATED:
throttle_accel_deactivate(); // this controller does not use accel based throttle controller
altitude_error = 0; // clear altitude error reported to GCS
throttle_initialised = true;
break;
case THROTTLE_HOLD:
case THROTTLE_AUTO:
if(flymode == auto_mode)
controller_desired_alt = receivedCommands.targetHeight;
else
controller_desired_alt = get_initial_alt_hold(current_loc.alt, climb_rate); // reset controller desired altitude to current altitude
wp_nav.set_desired_alt(controller_desired_alt); // same as above but for loiter controller
if (throttle_mode_manual(throttle_mode)) { // reset the alt hold I terms if previous throttle mode was manual
reset_throttle_I();
set_accel_throttle_I_from_pilot_throttle(get_pilot_desired_throttle(g.rc_3.control_in));
}
throttle_initialised = true;
break;
case THROTTLE_LAND:
reset_land_detector(); // initialise land detector
controller_desired_alt = get_initial_alt_hold(current_loc.alt, climb_rate); // reset controller desired altitude to current altitude
throttle_initialised = true;
break;
}
// update the throttle mode
if( throttle_initialised ) {
throttle_mode = new_throttle_mode;
// reset some variables used for logging
desired_climb_rate = 0;
nav_throttle = 0;
}
// return success or failure
return throttle_initialised;
}
// update_throttle_mode - run high level throttle controllers
// 50 hz update rate
void update_throttle_mode(void)
{
int16_t pilot_climb_rate;
int16_t pilot_throttle_scaled;
if(ap.do_flip) // this is pretty bad but needed to flip in AP modes.
return;
#if FRAME_CONFIG != HELI_FRAME
// do not run throttle controllers if motors disarmed
if( !motors.armed() ) {
set_throttle_out(0, false);
throttle_accel_deactivate(); // do not allow the accel based throttle to override our command
set_target_alt_for_reporting(0);
return;
}
#endif // FRAME_CONFIG != HELI_FRAME
/* if(flymode == auto_mode){
// custom
// Same idea as Throttle Manual
//hal.uartB->printf("Auto Throttle %d\n", receivedCommands.throttle);
//set_throttle_out(receivedCommands.throttle, false);
//update_throttle_cruise(receivedCommands.throttle);
//send pilot's output directly to motors
pilot_throttle_scaled = get_pilot_desired_throttle(receivedCommands.throttle);
set_throttle_out(pilot_throttle_scaled, false);
// check if we've taken off yet
if (!ap.takeoff_complete && motors.armed()) {
if (pilot_throttle_scaled > g.throttle_cruise) {
// we must be in the air by now
set_takeoff_complete(true); // this function logs takeoff and landing
}
}
set_target_alt_for_reporting(0);
} else{
//hal.uartB->printf("Manual Throttle %d\n", get_pilot_desired_throttle(g.rc_3.control_in));
*/
switch(throttle_mode) {
case THROTTLE_MANUAL:
// completely manual throttle
if(g.rc_3.control_in <= 0){
set_throttle_out(0, false);
}else{
// send pilot's output directly to motors
pilot_throttle_scaled = get_pilot_desired_throttle(g.rc_3.control_in);
set_throttle_out(pilot_throttle_scaled, false);
// update estimate of throttle cruise
update_throttle_cruise(pilot_throttle_scaled);
// check if we've taken off yet
if (!ap.takeoff_complete && motors.armed()) {
if (pilot_throttle_scaled > g.throttle_cruise) {
// we must be in the air by now
set_takeoff_complete(true); // this function logs takeoff and landing
}
}
}
set_target_alt_for_reporting(0);
break;
case THROTTLE_MANUAL_TILT_COMPENSATED:
// manual throttle but with angle boost
if (g.rc_3.control_in <= 0) {
set_throttle_out(0, false); // no need for angle boost with zero throttle
}else{
pilot_throttle_scaled = get_pilot_desired_throttle(g.rc_3.control_in);
set_throttle_out(pilot_throttle_scaled, true);
// update estimate of throttle cruise
update_throttle_cruise(pilot_throttle_scaled);
if (!ap.takeoff_complete && motors.armed()) {
if (pilot_throttle_scaled > g.throttle_cruise) {
// we must be in the air by now
set_takeoff_complete(true);
}
}
}
set_target_alt_for_reporting(0);
break;
case THROTTLE_HOLD:
if(ap.auto_armed) {
// alt hold plus pilot input of climb rate
pilot_climb_rate = get_pilot_desired_climb_rate(g.rc_3.control_in);
// special handling if we have landed
if (ap.land_complete) {
if (pilot_climb_rate > 0) {
// indicate we are taking off
set_land_complete(false);
// clear i term when we're taking off
set_throttle_takeoff();
}else{
// move throttle to minimum to keep us on the ground
set_throttle_out(0, false);
// deactivate accel based throttle controller (it will be automatically re-enabled when alt-hold controller next runs)
throttle_accel_deactivate();
}
}
// check land_complete flag again in case it was changed above
if (!ap.land_complete) {
if( sonar_alt_health >= SONAR_ALT_HEALTH_MAX ) {
// if sonar is ok, use surface tracking
get_throttle_surface_tracking(pilot_climb_rate); // this function calls set_target_alt_for_reporting for us
}else{
// if no sonar fall back stabilize rate controller
get_throttle_rate_stabilized(pilot_climb_rate); // this function calls set_target_alt_for_reporting for us
}
}
}else{
// pilot's throttle must be at zero so keep motors off
set_throttle_out(0, false);
// deactivate accel based throttle controller
throttle_accel_deactivate();
set_target_alt_for_reporting(0);
}
break;
case THROTTLE_AUTO:
// auto pilot altitude controller with target altitude held in wp_nav.get_desired_alt()
if(ap.auto_armed) {
// special handling if we are just taking off
if (ap.land_complete) {
// tell motors to do a slow start.
motors.slow_start(true);
}
get_throttle_althold_with_slew(wp_nav.get_desired_alt(), -wp_nav.get_descent_velocity(), wp_nav.get_climb_velocity());
set_target_alt_for_reporting(wp_nav.get_desired_alt()); // To-Do: return get_destination_alt if we are flying to a waypoint
}else{
// pilot's throttle must be at zero so keep motors off
set_throttle_out(0, false);
// deactivate accel based throttle controller
throttle_accel_deactivate();
set_target_alt_for_reporting(0);
}
break;
case THROTTLE_LAND:
// landing throttle controller
get_throttle_land();
set_target_alt_for_reporting(0);
break;
}
// } // TEMP for if statement on flymode
}
// set_target_alt_for_reporting - set target altitude in cm for reporting purposes (logs and gcs)
static void set_target_alt_for_reporting(float alt_cm)
{
target_alt_for_reporting = alt_cm;
}
// get_target_alt_for_reporting - returns target altitude in cm for reporting purposes (logs and gcs)
static float get_target_alt_for_reporting()
{
return target_alt_for_reporting;
}
static void read_AHRS(void)
{
// Perform IMU calculations and get attitude info
//-----------------------------------------------
#if HIL_MODE != HIL_MODE_DISABLED
// update hil before ahrs update
gcs_check_input();
#endif
ahrs.update();
omega = ins.get_gyro();
}
static void update_trig(void){
Vector2f yawvector;
const Matrix3f &temp = ahrs.get_dcm_matrix();
yawvector.x = temp.a.x; // sin
yawvector.y = temp.b.x; // cos
yawvector.normalize();
cos_pitch_x = safe_sqrt(1 - (temp.c.x * temp.c.x)); // level = 1
cos_roll_x = temp.c.z / cos_pitch_x; // level = 1
cos_pitch_x = constrain_float(cos_pitch_x, 0, 1.0);
// this relies on constrain_float() of infinity doing the right thing,
// which it does do in avr-libc
cos_roll_x = constrain_float(cos_roll_x, -1.0, 1.0);
sin_yaw = constrain_float(yawvector.y, -1.0, 1.0);
cos_yaw = constrain_float(yawvector.x, -1.0, 1.0);
// added to convert earth frame to body frame for rate controllers
sin_pitch = -temp.c.x;
sin_roll = temp.c.y / cos_pitch_x;
// update wp_nav controller with trig values
wp_nav.set_cos_sin_yaw(cos_yaw, sin_yaw, cos_pitch_x);
//flat:
// 0 ° = cos_yaw: 1.00, sin_yaw: 0.00,
// 90° = cos_yaw: 0.00, sin_yaw: 1.00,
// 180 = cos_yaw: -1.00, sin_yaw: 0.00,
// 270 = cos_yaw: 0.00, sin_yaw: -1.00,
}
// read baro and sonar altitude at 20hz
static void update_altitude()
{
#if HIL_MODE == HIL_MODE_ATTITUDE
// we are in the SIM, fake out the baro and Sonar
baro_alt = g_gps->altitude_cm;
if(g.sonar_enabled) {
sonar_alt = baro_alt;
}
#else
// read in baro altitude
baro_alt = read_barometer();
// read in sonar altitude
sonar_alt = read_sonar();
#endif // HIL_MODE == HIL_MODE_ATTITUDE
// write altitude info to dataflash logs
if (g.log_bitmask & MASK_LOG_CTUN) {
Log_Write_Control_Tuning();
}
}
static void tuning(){
// exit immediately when radio failsafe is invoked so tuning values are not set to zero
if (failsafe.radio || failsafe.radio_counter != 0) {
return;
}
tuning_value = (float)g.rc_6.control_in / 1000.0f;
g.rc_6.set_range(g.radio_tuning_low,g.radio_tuning_high); // 0 to 1
switch(g.radio_tuning) {
// Roll, Pitch tuning
case CH6_STABILIZE_ROLL_PITCH_KP:
g.pi_stabilize_roll.kP(tuning_value);
g.pi_stabilize_pitch.kP(tuning_value);
break;
case CH6_RATE_ROLL_PITCH_KP:
g.pid_rate_roll.kP(tuning_value);
g.pid_rate_pitch.kP(tuning_value);
break;
case CH6_RATE_ROLL_PITCH_KI:
g.pid_rate_roll.kI(tuning_value);
g.pid_rate_pitch.kI(tuning_value);
break;
case CH6_RATE_ROLL_PITCH_KD:
g.pid_rate_roll.kD(tuning_value);
g.pid_rate_pitch.kD(tuning_value);
break;
// Yaw tuning
case CH6_STABILIZE_YAW_KP:
g.pi_stabilize_yaw.kP(tuning_value);
break;
case CH6_YAW_RATE_KP:
g.pid_rate_yaw.kP(tuning_value);
break;
case CH6_YAW_RATE_KD:
g.pid_rate_yaw.kD(tuning_value);
break;
// Altitude and throttle tuning
case CH6_ALTITUDE_HOLD_KP:
g.pi_alt_hold.kP(tuning_value);
break;
case CH6_THROTTLE_RATE_KP:
g.pid_throttle_rate.kP(tuning_value);
break;
case CH6_THROTTLE_RATE_KD:
g.pid_throttle_rate.kD(tuning_value);
break;
case CH6_THROTTLE_ACCEL_KP:
g.pid_throttle_accel.kP(tuning_value);
break;
case CH6_THROTTLE_ACCEL_KI:
g.pid_throttle_accel.kI(tuning_value);
break;
case CH6_THROTTLE_ACCEL_KD:
g.pid_throttle_accel.kD(tuning_value);
break;
// Loiter and navigation tuning
case CH6_LOITER_POSITION_KP:
g.pi_loiter_lat.kP(tuning_value);
g.pi_loiter_lon.kP(tuning_value);
break;
case CH6_LOITER_RATE_KP:
g.pid_loiter_rate_lon.kP(tuning_value);
g.pid_loiter_rate_lat.kP(tuning_value);
break;
case CH6_LOITER_RATE_KI:
g.pid_loiter_rate_lon.kI(tuning_value);
g.pid_loiter_rate_lat.kI(tuning_value);
break;
case CH6_LOITER_RATE_KD:
g.pid_loiter_rate_lon.kD(tuning_value);
g.pid_loiter_rate_lat.kD(tuning_value);
break;
case CH6_WP_SPEED:
// set waypoint navigation horizontal speed to 0 ~ 1000 cm/s
wp_nav.set_horizontal_velocity(g.rc_6.control_in);
break;
// Acro roll pitch gain
case CH6_ACRO_RP_KP:
g.acro_rp_p = tuning_value;
break;
// Acro yaw gain
case CH6_ACRO_YAW_KP:
g.acro_yaw_p = tuning_value;
break;
case CH6_RELAY:
if (g.rc_6.control_in > 525) relay.on(0);
if (g.rc_6.control_in < 475) relay.off(0);
break;
case CH6_OPTFLOW_KP:
g.pid_optflow_roll.kP(tuning_value);
g.pid_optflow_pitch.kP(tuning_value);
break;
case CH6_OPTFLOW_KI:
g.pid_optflow_roll.kI(tuning_value);
g.pid_optflow_pitch.kI(tuning_value);
break;
case CH6_OPTFLOW_KD:
g.pid_optflow_roll.kD(tuning_value);
g.pid_optflow_pitch.kD(tuning_value);
break;
#if HIL_MODE != HIL_MODE_ATTITUDE // do not allow modifying _kp or _kp_yaw gains in HIL mode
case CH6_AHRS_YAW_KP:
ahrs._kp_yaw.set(tuning_value);
break;
case CH6_AHRS_KP:
ahrs._kp.set(tuning_value);
break;
#endif
case CH6_INAV_TC:
// To-Do: allowing tuning TC for xy and z separately
inertial_nav.set_time_constant_xy(tuning_value);
inertial_nav.set_time_constant_z(tuning_value);
break;
case CH6_DECLINATION:
// set declination to +-20degrees
compass.set_declination(ToRad((2.0f * g.rc_6.control_in - g.radio_tuning_high)/100.0f), false); // 2nd parameter is false because we do not want to save to eeprom because this would have a performance impact
break;
case CH6_CIRCLE_RATE:
// set circle rate
g.circle_rate.set(g.rc_6.control_in/25-20); // allow approximately 45 degree turn rate in either direction
break;
case CH6_SONAR_GAIN:
// set sonar gain
g.sonar_gain.set(tuning_value);
break;
case CH6_LOIT_SPEED:
// set max loiter speed to 0 ~ 1000 cm/s
wp_nav.set_loiter_velocity(g.rc_6.control_in);
break;
}
}
AP_HAL_MAIN();
<file_sep>/GCS_Mavlink.ino
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
// default sensors are present and healthy: gyro, accelerometer, barometer, rate_control, attitude_stabilization, yaw_position, altitude control, x/y position control, motor_control
#define MAVLINK_SENSOR_PRESENT_DEFAULT (MAV_SYS_STATUS_SENSOR_3D_GYRO | MAV_SYS_STATUS_SENSOR_3D_ACCEL | MAV_SYS_STATUS_SENSOR_ABSOLUTE_PRESSURE | MAV_SYS_STATUS_SENSOR_ANGULAR_RATE_CONTROL | MAV_SYS_STATUS_SENSOR_ATTITUDE_STABILIZATION | MAV_SYS_STATUS_SENSOR_YAW_POSITION | MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL | MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL | MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS)
// use this to prevent recursion during sensor init
static bool in_mavlink_delay;
// true when we have received at least 1 MAVLink packet
static bool mavlink_active;
// true if we are out of time in our event timeslice
static bool gcs_out_of_time;
// check if a message will fit in the payload space available
#define CHECK_PAYLOAD_SIZE(id) if (payload_space < MAVLINK_MSG_ID_ ## id ## _LEN) return false
// prototype this for use inside the GCS class
static void gcs_send_text_fmt(const prog_char_t *fmt, ...);
static void gcs_send_heartbeat(void)
{
gcs_send_message(MSG_HEARTBEAT);
}
static void gcs_send_deferred(void)
{
gcs_send_message(MSG_RETRY_DEFERRED);
}
/*
* !!NOTE!!
*
* the use of NOINLINE separate functions for each message type avoids
* a compiler bug in gcc that would cause it to use far more stack
* space than is needed. Without the NOINLINE we use the sum of the
* stack needed for each message type. Please be careful to follow the
* pattern below when adding any new messages
*/
static NOINLINE void send_heartbeat(mavlink_channel_t chan)
{
uint8_t base_mode = MAV_MODE_FLAG_CUSTOM_MODE_ENABLED;
uint8_t system_status = ap.land_complete ? MAV_STATE_STANDBY : MAV_STATE_ACTIVE;
uint32_t custom_mode = control_mode;
// set system as critical if any failsafe have triggered
if (failsafe.radio || failsafe.battery ) {
system_status = MAV_STATE_CRITICAL;
}
// work out the base_mode. This value is not very useful
// for APM, but we calculate it as best we can so a generic
// MAVLink enabled ground station can work out something about
// what the MAV is up to. The actual bit values are highly
// ambiguous for most of the APM flight modes. In practice, you
// only get useful information from the custom_mode, which maps to
// the APM flight mode and has a well defined meaning in the
// ArduPlane documentation
base_mode = MAV_MODE_FLAG_STABILIZE_ENABLED;
switch (control_mode) {
case AUTO:
case RTL:
case LOITER:
case GUIDED:
case CIRCLE:
base_mode |= MAV_MODE_FLAG_GUIDED_ENABLED;
// note that MAV_MODE_FLAG_AUTO_ENABLED does not match what
// APM does in any mode, as that is defined as "system finds its own goal
// positions", which APM does not currently do
break;
}
// all modes except INITIALISING have some form of manual
// override if stick mixing is enabled
base_mode |= MAV_MODE_FLAG_MANUAL_INPUT_ENABLED;
#if HIL_MODE != HIL_MODE_DISABLED
base_mode |= MAV_MODE_FLAG_HIL_ENABLED;
#endif
// we are armed if we are not initialising
if (motors.armed()) {
base_mode |= MAV_MODE_FLAG_SAFETY_ARMED;
}
// indicate we have set a custom mode
base_mode |= MAV_MODE_FLAG_CUSTOM_MODE_ENABLED;
mavlink_msg_heartbeat_send(
chan,
MAV_TYPE_QUADROTOR,
MAV_AUTOPILOT_ARDUPILOTMEGA,
base_mode,
custom_mode,
system_status);
}
static NOINLINE void send_attitude(mavlink_channel_t chan)
{
mavlink_msg_attitude_send(
chan,
millis(),
ahrs.roll,
ahrs.pitch,
ahrs.yaw,
omega.x,
omega.y,
omega.z);
}
static NOINLINE void send_extended_status1(mavlink_channel_t chan, uint16_t packet_drops)
{
uint32_t control_sensors_present;
uint32_t control_sensors_enabled;
uint32_t control_sensors_health;
// default sensors present
control_sensors_present = MAVLINK_SENSOR_PRESENT_DEFAULT;
// first what sensors/controllers we have
if (g.compass_enabled) {
control_sensors_present |= MAV_SYS_STATUS_SENSOR_3D_MAG; // compass present
}
if (g_gps != NULL && g_gps->status() > GPS::NO_GPS) {
control_sensors_present |= MAV_SYS_STATUS_SENSOR_GPS;
}
if (ap.rc_receiver_present) {
control_sensors_present |= MAV_SYS_STATUS_SENSOR_RC_RECEIVER;
}
// all present sensors enabled by default except altitude and position control which we will set individually
control_sensors_enabled = control_sensors_present & (~MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL & ~MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL);
switch (control_mode) {
case ALT_HOLD:
case AUTO:
case GUIDED:
case LOITER:
case RTL:
case CIRCLE:
case LAND:
case OF_LOITER:
control_sensors_enabled |= MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL;
control_sensors_enabled |= MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL;
break;
case POSITION:
control_sensors_enabled |= MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL;
break;
case SPORT:
control_sensors_enabled |= MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL;
break;
}
// default to all healthy except compass, gps and receiver which we set individually
control_sensors_health = control_sensors_present & (~MAV_SYS_STATUS_SENSOR_3D_MAG & ~MAV_SYS_STATUS_SENSOR_GPS & ~MAV_SYS_STATUS_SENSOR_RC_RECEIVER);
if (g.compass_enabled && compass.healthy() && ahrs.use_compass()) {
control_sensors_health |= MAV_SYS_STATUS_SENSOR_3D_MAG;
}
if (g_gps != NULL && g_gps->status() > GPS::NO_GPS && !gps_glitch.glitching()) {
control_sensors_health |= MAV_SYS_STATUS_SENSOR_GPS;
}
if (ap.rc_receiver_present && !failsafe.radio) {
control_sensors_health |= MAV_SYS_STATUS_SENSOR_RC_RECEIVER;
}
if (!ins.healthy()) {
control_sensors_health &= ~(MAV_SYS_STATUS_SENSOR_3D_GYRO | MAV_SYS_STATUS_SENSOR_3D_ACCEL);
}
int16_t battery_current = -1;
int8_t battery_remaining = -1;
if (battery.monitoring() == AP_BATT_MONITOR_VOLTAGE_AND_CURRENT) {
battery_remaining = battery.capacity_remaining_pct();
battery_current = battery.current_amps() * 100;
}
mavlink_msg_sys_status_send(
chan,
control_sensors_present,
control_sensors_enabled,
control_sensors_health,
(uint16_t)(scheduler.load_average(10000) * 1000),
battery.voltage() * 1000, // mV
battery_current, // in 10mA units
battery_remaining, // in %
0, // comm drops %,
0, // comm drops in pkts,
0, 0, 0, 0);
}
static void NOINLINE send_location(mavlink_channel_t chan)
{
uint32_t fix_time;
// if we have a GPS fix, take the time as the last fix time. That
// allows us to correctly calculate velocities and extrapolate
// positions.
// If we don't have a GPS fix then we are dead reckoning, and will
// use the current boot time as the fix time.
if (g_gps->status() >= GPS::GPS_OK_FIX_2D) {
fix_time = g_gps->last_fix_time;
} else {
fix_time = millis();
}
mavlink_msg_global_position_int_send(
chan,
fix_time,
current_loc.lat, // in 1E7 degrees
current_loc.lng, // in 1E7 degrees
g_gps->altitude_cm * 10, // millimeters above sea level
(current_loc.alt - home.alt) * 10, // millimeters above ground
g_gps->velocity_north() * 100, // X speed cm/s (+ve North)
g_gps->velocity_east() * 100, // Y speed cm/s (+ve East)
g_gps->velocity_down() * -100, // Z speed cm/s (+ve up)
ahrs.yaw_sensor); // compass heading in 1/100 degree
}
static void NOINLINE send_nav_controller_output(mavlink_channel_t chan)
{
mavlink_msg_nav_controller_output_send(
chan,
control_roll / 1.0e2f,
control_pitch / 1.0e2f,
control_yaw / 1.0e2f,
wp_bearing / 1.0e2f,
wp_distance / 1.0e2f,
altitude_error / 1.0e2f,
0,
0);
}
static void NOINLINE send_ahrs(mavlink_channel_t chan)
{
const Vector3f &omega_I = ahrs.get_gyro_drift();
mavlink_msg_ahrs_send(
chan,
omega_I.x,
omega_I.y,
omega_I.z,
1,
0,
ahrs.get_error_rp(),
ahrs.get_error_yaw());
}
// report simulator state
static void NOINLINE send_simstate(mavlink_channel_t chan)
{
}
static void NOINLINE send_hwstatus(mavlink_channel_t chan)
{
mavlink_msg_hwstatus_send(
chan,
board_voltage(),
hal.i2c->lockup_count());
}
static void NOINLINE send_gps_raw(mavlink_channel_t chan)
{
mavlink_msg_gps_raw_int_send(
chan,
g_gps->last_fix_time*(uint64_t)1000,
g_gps->status(),
g_gps->latitude, // in 1E7 degrees
g_gps->longitude, // in 1E7 degrees
g_gps->altitude_cm * 10, // in mm
g_gps->hdop,
65535,
g_gps->ground_speed_cm, // cm/s
g_gps->ground_course_cd, // 1/100 degrees,
g_gps->num_sats);
}
static void NOINLINE send_system_time(mavlink_channel_t chan)
{
mavlink_msg_system_time_send(
chan,
g_gps->time_epoch_usec(),
hal.scheduler->millis());
}
#if HIL_MODE != HIL_MODE_DISABLED
static void NOINLINE send_servo_out(mavlink_channel_t chan)
{
// normalized values scaled to -10000 to 10000
// This is used for HIL. Do not change without discussing with HIL maintainers
#if X_PLANE == ENABLED
/* update by JLN for X-Plane HIL */
if(motors.armed() && ap.auto_armed) {
mavlink_msg_rc_channels_scaled_send(
chan,
millis(),
0, // port 0
g.rc_1.servo_out,
g.rc_2.servo_out,
10000 * g.rc_3.norm_output(),
g.rc_4.servo_out,
10000 * g.rc_1.norm_output(),
10000 * g.rc_2.norm_output(),
10000 * g.rc_3.norm_output(),
10000 * g.rc_4.norm_output(),
receiver_rssi);
}else{
mavlink_msg_rc_channels_scaled_send(
chan,
millis(),
0, // port 0
0,
0,
-10000,
0,
10000 * g.rc_1.norm_output(),
10000 * g.rc_2.norm_output(),
10000 * g.rc_3.norm_output(),
10000 * g.rc_4.norm_output(),
receiver_rssi);
}
#else
mavlink_msg_rc_channels_scaled_send(
chan,
millis(),
0, // port 0
g.rc_1.servo_out,
g.rc_2.servo_out,
g.rc_3.radio_out,
g.rc_4.servo_out,
10000 * g.rc_1.norm_output(),
10000 * g.rc_2.norm_output(),
10000 * g.rc_3.norm_output(),
10000 * g.rc_4.norm_output(),
receiver_rssi);
#endif
}
#endif // HIL_MODE
static void NOINLINE send_radio_in(mavlink_channel_t chan)
{
mavlink_msg_rc_channels_raw_send(
chan,
millis(),
0, // port
g.rc_1.radio_in,
g.rc_2.radio_in,
g.rc_3.radio_in,
g.rc_4.radio_in,
g.rc_5.radio_in,
g.rc_6.radio_in,
g.rc_7.radio_in,
g.rc_8.radio_in,
receiver_rssi);
}
static void NOINLINE send_radio_out(mavlink_channel_t chan)
{
uint8_t i;
uint16_t rcout[8];
hal.rcout->read(rcout,8);
// clear out unreasonable values
for (i=0; i<8; i++) {
if (rcout[i] > 10000) {
rcout[i] = 0;
}
}
mavlink_msg_servo_output_raw_send(
chan,
micros(),
0, // port
rcout[0],
rcout[1],
rcout[2],
rcout[3],
rcout[4],
rcout[5],
rcout[6],
rcout[7]);
}
static void NOINLINE send_vfr_hud(mavlink_channel_t chan)
{
mavlink_msg_vfr_hud_send(
chan,
(float)g_gps->ground_speed_cm / 100.0f,
(float)g_gps->ground_speed_cm / 100.0f,
(ahrs.yaw_sensor / 100) % 360,
g.rc_3.servo_out/10,
current_loc.alt / 100.0f,
climb_rate / 100.0f);
}
static void NOINLINE send_raw_imu1(mavlink_channel_t chan)
{
const Vector3f &accel = ins.get_accel();
const Vector3f &gyro = ins.get_gyro();
const Vector3f &mag = compass.get_field();
mavlink_msg_raw_imu_send(
chan,
micros(),
accel.x * 1000.0f / GRAVITY_MSS,
accel.y * 1000.0f / GRAVITY_MSS,
accel.z * 1000.0f / GRAVITY_MSS,
gyro.x * 1000.0f,
gyro.y * 1000.0f,
gyro.z * 1000.0f,
mag.x,
mag.y,
mag.z);
if (ins.get_gyro_count() <= 1 &&
ins.get_accel_count() <= 1 &&
compass.get_count() <= 1) {
return;
}
const Vector3f &accel2 = ins.get_accel(1);
const Vector3f &gyro2 = ins.get_gyro(1);
const Vector3f &mag2 = compass.get_field(1);
mavlink_msg_scaled_imu2_send(
chan,
millis(),
accel2.x * 1000.0f / GRAVITY_MSS,
accel2.y * 1000.0f / GRAVITY_MSS,
accel2.z * 1000.0f / GRAVITY_MSS,
gyro2.x * 1000.0f,
gyro2.y * 1000.0f,
gyro2.z * 1000.0f,
mag2.x,
mag2.y,
mag2.z);
}
static void NOINLINE send_raw_imu2(mavlink_channel_t chan)
{
}
static void NOINLINE send_raw_imu3(mavlink_channel_t chan)
{
const Vector3f &mag_offsets = compass.get_offsets();
const Vector3f &accel_offsets = ins.get_accel_offsets();
const Vector3f &gyro_offsets = ins.get_gyro_offsets();
mavlink_msg_sensor_offsets_send(chan,
mag_offsets.x,
mag_offsets.y,
mag_offsets.z,
compass.get_declination(),
barometer.get_pressure(),
barometer.get_temperature()*100,
gyro_offsets.x,
gyro_offsets.y,
gyro_offsets.z,
accel_offsets.x,
accel_offsets.y,
accel_offsets.z);
}
static void NOINLINE send_current_waypoint(mavlink_channel_t chan)
{
}
static void NOINLINE send_statustext(mavlink_channel_t chan)
{
}
// are we still delaying telemetry to try to avoid Xbee bricking?
static bool telemetry_delayed(mavlink_channel_t chan)
{
uint32_t tnow = millis() >> 10;
if (tnow > (uint32_t)g.telem_delay) {
return false;
}
if (chan == MAVLINK_COMM_0 && hal.gpio->usb_connected()) {
// this is USB telemetry, so won't be an Xbee
return false;
}
// we're either on the 2nd UART, or no USB cable is connected
// we need to delay telemetry by the TELEM_DELAY time
return true;
}
// try to send a message, return false if it won't fit in the serial tx buffer
static bool mavlink_try_send_message(mavlink_channel_t chan, enum ap_message id, uint16_t packet_drops)
{
return true;
}
#define MAX_DEFERRED_MESSAGES MSG_RETRY_DEFERRED
static struct mavlink_queue {
enum ap_message deferred_messages[MAX_DEFERRED_MESSAGES];
uint8_t next_deferred_message;
uint8_t num_deferred_messages;
} mavlink_queue[MAVLINK_COMM_NUM_BUFFERS];
// send a message using mavlink
static void mavlink_send_message(mavlink_channel_t chan, enum ap_message id, uint16_t packet_drops)
{
uint8_t i, nextid;
struct mavlink_queue *q = &mavlink_queue[(uint8_t)chan];
// see if we can send the deferred messages, if any
while (q->num_deferred_messages != 0) {
if (!mavlink_try_send_message(chan,
q->deferred_messages[q->next_deferred_message],
packet_drops)) {
break;
}
q->next_deferred_message++;
if (q->next_deferred_message == MAX_DEFERRED_MESSAGES) {
q->next_deferred_message = 0;
}
q->num_deferred_messages--;
}
if (id == MSG_RETRY_DEFERRED) {
return;
}
// this message id might already be deferred
for (i=0, nextid = q->next_deferred_message; i < q->num_deferred_messages; i++) {
if (q->deferred_messages[nextid] == id) {
// its already deferred, discard
return;
}
nextid++;
if (nextid == MAX_DEFERRED_MESSAGES) {
nextid = 0;
}
}
if (q->num_deferred_messages != 0 ||
!mavlink_try_send_message(chan, id, packet_drops)) {
// can't send it now, so defer it
if (q->num_deferred_messages == MAX_DEFERRED_MESSAGES) {
// the defer buffer is full, discard
return;
}
nextid = q->next_deferred_message + q->num_deferred_messages;
if (nextid >= MAX_DEFERRED_MESSAGES) {
nextid -= MAX_DEFERRED_MESSAGES;
}
q->deferred_messages[nextid] = id;
q->num_deferred_messages++;
}
}
void mavlink_send_text(mavlink_channel_t chan, gcs_severity severity, const char *str)
{
}
const AP_Param::GroupInfo GCS_MAVLINK::var_info[] PROGMEM = {
// @Param: RAW_SENS
// @DisplayName: Raw sensor stream rate
// @Description: Raw sensor stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("RAW_SENS", 0, GCS_MAVLINK, streamRates[0], 0),
// @Param: EXT_STAT
// @DisplayName: Extended status stream rate to ground station
// @Description: Extended status stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("EXT_STAT", 1, GCS_MAVLINK, streamRates[1], 0),
// @Param: RC_CHAN
// @DisplayName: RC Channel stream rate to ground station
// @Description: RC Channel stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("RC_CHAN", 2, GCS_MAVLINK, streamRates[2], 0),
// @Param: RAW_CTRL
// @DisplayName: Raw Control stream rate to ground station
// @Description: Raw Control stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("RAW_CTRL", 3, GCS_MAVLINK, streamRates[3], 0),
// @Param: POSITION
// @DisplayName: Position stream rate to ground station
// @Description: Position stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("POSITION", 4, GCS_MAVLINK, streamRates[4], 0),
// @Param: EXTRA1
// @DisplayName: Extra data type 1 stream rate to ground station
// @Description: Extra data type 1 stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("EXTRA1", 5, GCS_MAVLINK, streamRates[5], 0),
// @Param: EXTRA2
// @DisplayName: Extra data type 2 stream rate to ground station
// @Description: Extra data type 2 stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("EXTRA2", 6, GCS_MAVLINK, streamRates[6], 0),
// @Param: EXTRA3
// @DisplayName: Extra data type 3 stream rate to ground station
// @Description: Extra data type 3 stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("EXTRA3", 7, GCS_MAVLINK, streamRates[7], 0),
// @Param: PARAMS
// @DisplayName: Parameter stream rate to ground station
// @Description: Parameter stream rate to ground station
// @Units: Hz
// @Range: 0 10
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("PARAMS", 8, GCS_MAVLINK, streamRates[8], 0),
AP_GROUPEND
};
void
GCS_MAVLINK::update(void)
{
// receive new packets
mavlink_message_t msg;
mavlink_status_t status;
status.packet_rx_drop_count = 0;
// process received bytes
uint16_t nbytes = comm_get_available(chan);
for (uint16_t i=0; i<nbytes; i++)
{
uint8_t c = comm_receive_ch(chan);
#if CLI_ENABLED == ENABLED
/* allow CLI to be started by hitting enter 3 times, if no
* heartbeat packets have been received */
if (mavlink_active == 0 && (millis() - _cli_timeout) < 20000 &&
!motors.armed() && comm_is_idle(chan)) {
if (c == '\n' || c == '\r') {
crlf_count++;
} else {
crlf_count = 0;
}
if (crlf_count == 3) {
run_cli(_port);
}
}
#endif
// Try to get a new message
if (mavlink_parse_char(chan, c, &msg, &status)) {
// we exclude radio packets to make it possible to use the
// CLI over the radio
if (msg.msgid != MAVLINK_MSG_ID_RADIO && msg.msgid != MAVLINK_MSG_ID_RADIO_STATUS) {
mavlink_active = true;
}
handleMessage(&msg);
}
}
// Update packet drops counter
packet_drops += status.packet_rx_drop_count;
if (!waypoint_receiving) {
return;
}
uint32_t tnow = millis();
if (waypoint_receiving &&
waypoint_request_i <= waypoint_request_last &&
tnow > waypoint_timelast_request + 500 + (stream_slowdown*20)) {
waypoint_timelast_request = tnow;
send_message(MSG_NEXT_WAYPOINT);
}
// stop waypoint receiving if timeout
if (waypoint_receiving && (tnow - waypoint_timelast_receive) > waypoint_receive_timeout) {
waypoint_receiving = false;
}
}
// see if we should send a stream now. Called at 50Hz
bool GCS_MAVLINK::stream_trigger(enum streams stream_num)
{
if (stream_num >= NUM_STREAMS) {
return false;
}
float rate = (uint8_t)streamRates[stream_num].get();
// send at a much lower rate while handling waypoints and
// parameter sends
if ((stream_num != STREAM_PARAMS) &&
(waypoint_receiving || _queued_parameter != NULL)) {
rate *= 0.25;
}
if (rate <= 0) {
return false;
}
if (stream_ticks[stream_num] == 0) {
// we're triggering now, setup the next trigger point
if (rate > 50) {
rate = 50;
}
stream_ticks[stream_num] = (50 / rate) + stream_slowdown;
return true;
}
// count down at 50Hz
stream_ticks[stream_num]--;
return false;
}
void
GCS_MAVLINK::data_stream_send(void)
{
if (waypoint_receiving) {
// don't interfere with mission transfer
return;
}
if (!in_mavlink_delay && !motors.armed()) {
handle_log_send(DataFlash);
}
gcs_out_of_time = false;
if (_queued_parameter != NULL) {
if (streamRates[STREAM_PARAMS].get() <= 0) {
streamRates[STREAM_PARAMS].set(10);
}
if (stream_trigger(STREAM_PARAMS)) {
send_message(MSG_NEXT_PARAM);
}
// don't send anything else at the same time as parameters
return;
}
if (gcs_out_of_time) return;
if (in_mavlink_delay) {
// don't send any other stream types while in the delay callback
return;
}
if (stream_trigger(STREAM_RAW_SENSORS)) {
send_message(MSG_RAW_IMU1);
send_message(MSG_RAW_IMU2);
send_message(MSG_RAW_IMU3);
}
if (gcs_out_of_time) return;
if (stream_trigger(STREAM_EXTENDED_STATUS)) {
send_message(MSG_EXTENDED_STATUS1);
send_message(MSG_EXTENDED_STATUS2);
send_message(MSG_CURRENT_WAYPOINT);
send_message(MSG_GPS_RAW);
send_message(MSG_NAV_CONTROLLER_OUTPUT);
send_message(MSG_LIMITS_STATUS);
}
if (gcs_out_of_time) return;
if (stream_trigger(STREAM_POSITION)) {
send_message(MSG_LOCATION);
}
if (gcs_out_of_time) return;
if (stream_trigger(STREAM_RAW_CONTROLLER)) {
send_message(MSG_SERVO_OUT);
}
if (gcs_out_of_time) return;
if (stream_trigger(STREAM_RC_CHANNELS)) {
send_message(MSG_RADIO_OUT);
send_message(MSG_RADIO_IN);
}
if (gcs_out_of_time) return;
if (stream_trigger(STREAM_EXTRA1)) {
send_message(MSG_ATTITUDE);
send_message(MSG_SIMSTATE);
}
if (gcs_out_of_time) return;
if (stream_trigger(STREAM_EXTRA2)) {
send_message(MSG_VFR_HUD);
}
if (gcs_out_of_time) return;
if (stream_trigger(STREAM_EXTRA3)) {
send_message(MSG_AHRS);
send_message(MSG_HWSTATUS);
send_message(MSG_SYSTEM_TIME);
}
}
void
GCS_MAVLINK::send_message(enum ap_message id)
{
mavlink_send_message(chan,id, packet_drops);
}
void
GCS_MAVLINK::send_text_P(gcs_severity severity, const prog_char_t *str)
{
mavlink_statustext_t m;
uint8_t i;
for (i=0; i<sizeof(m.text); i++) {
m.text[i] = pgm_read_byte((const prog_char *)(str++));
if (m.text[i] == '\0') {
break;
}
}
if (i < sizeof(m.text)) m.text[i] = 0;
mavlink_send_text(chan, severity, (const char *)m.text);
}
void GCS_MAVLINK::handleMessage(mavlink_message_t* msg)
{}
/*
* a delay() callback that processes MAVLink packets. We set this as the
* callback in long running library initialisation routines to allow
* MAVLink to process packets while waiting for the initialisation to
* complete
*/
static void mavlink_delay_cb()
{
}
/*
* send a message on both GCS links
*/
static void gcs_send_message(enum ap_message id)
{
}
/*
* send data streams in the given rate range on both links
*/
static void gcs_data_stream_send(void)
{
}
/*
* look for incoming commands on the GCS links
*/
static void gcs_check_input(void)
{
}
static void gcs_send_text_P(gcs_severity severity, const prog_char_t *str)
{
}
/*
* send a low priority formatted message to the GCS
* only one fits in the queue, so if you send more than one before the
* last one gets into the serial buffer then the old one will be lost
*/
void gcs_send_text_fmt(const prog_char_t *fmt, ...)
{
}
<file_sep>/UserVariables.h
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
// user defined variables
// example variables used in Wii camera testing - replace with your own
// variables
#ifdef USERHOOK_VARIABLES
//////////////////////////////////
// static variables and defines //
//////////////////////////////////
// These were originally in ArduFire but I moved them here because of scope
#define MOTOR_CLASS AP_MotorsQuad
static MOTOR_CLASS motors(&g.rc_1, &g.rc_2, &g.rc_3, &g.rc_4);
static AP_BattMonitor battery;
//////////////// STARTS
////////////////////////////////////////////////////////////////////////////////
// GPS variables
////////////////////////////////////////////////////////////////////////////////
// This is used to scale GPS values for EEPROM storage
// 10^7 times Decimal GPS means 1 == 1cm
// This approximation makes calculations integer and it's easy to read
static const float t7 = 10000000.0;
// We use atan2 and other trig techniques to calaculate angles
// We need to scale the longitude up to make these calcs work
// to account for decreasing distance between lines of longitude away from the equator
static float scaleLongUp = 1;
// Sometimes we need to remove the scaling for distance calcs
static float scaleLongDown = 1;
////////////////////////////////////////////////////////////////////////////////
// Location & Navigation
////////////////////////////////////////////////////////////////////////////////
// This is the angle from the copter to the next waypoint in centi-degrees
static int32_t wp_bearing;
// The original bearing to the next waypoint. used to point the nose of the copter at the next waypoint
static int32_t original_wp_bearing;
// The location of home in relation to the copter in centi-degrees
static int32_t home_bearing;
// distance between plane and home in cm
static int32_t home_distance;
// distance between plane and next waypoint in cm.
static uint32_t wp_distance;
// navigation mode - options include NAV_NONE, NAV_LOITER, NAV_CIRCLE, NAV_WP
static uint8_t nav_mode;
// Register containing the index of the current navigation command in the mission script
static int16_t command_nav_index;
// Register containing the index of the previous navigation command in the mission script
// Used to manage the execution of conditional commands
static uint8_t prev_nav_index;
// Register containing the index of the current conditional command in the mission script
static uint8_t command_cond_index;
// Used to track the required WP navigation information
// options include
// NAV_ALTITUDE - have we reached the desired altitude?
// NAV_LOCATION - have we reached the desired location?
// NAV_DELAY - have we waited at the waypoint the desired time?
static float lon_error, lat_error; // Used to report how many cm we are from the next waypoint or loiter target position
static int16_t control_roll; // desired roll angle of copter in centi-degrees
static int16_t control_pitch; // desired pitch angle of copter in centi-degrees
static uint8_t rtl_state; // records state of rtl (initial climb, returning home, etc)
static uint8_t land_state; // records state of land (flying to location, descending)
////////////////////////////////////////////////////////////////////////////////
// Orientation
////////////////////////////////////////////////////////////////////////////////
// Convienience accessors for commonly used trig functions. These values are generated
// by the DCM through a few simple equations. They are used throughout the code where cos and sin
// would normally be used.
// The cos values are defaulted to 1 to get a decent initial value for a level state
static float cos_roll_x = 1.0;
static float cos_pitch_x = 1.0;
static float cos_yaw = 1.0;
static float sin_yaw;
static float sin_roll;
static float sin_pitch;
////////////////////////////////////////////////////////////////////////////////
// SIMPLE Mode
////////////////////////////////////////////////////////////////////////////////
// Used to track the orientation of the copter for Simple mode. This value is reset at each arming
// or in SuperSimple mode when the copter leaves a 20m radius from home.
static float simple_cos_yaw = 1.0;
static float simple_sin_yaw;
static int32_t super_simple_last_bearing;
static float super_simple_cos_yaw = 1.0;
static float super_simple_sin_yaw;
// Stores initial bearing when armed - initial simple bearing is modified in super simple mode so not suitable
static int32_t initial_armed_bearing;
////////////////////////////////////////////////////////////////////////////////
// Rate contoller targets
////////////////////////////////////////////////////////////////////////////////
// Moved to user space
////////////////////////////////////////////////////////////////////////////////
// Throttle variables
////////////////////////////////////////////////////////////////////////////////
static int16_t throttle_accel_target_ef; // earth frame throttle acceleration target
static bool throttle_accel_controller_active; // true when accel based throttle controller is active, false when higher level throttle controllers are providing throttle output directly
static float throttle_avg; // g.throttle_cruise as a float
static int16_t desired_climb_rate; // pilot desired climb rate - for logging purposes only
static float target_alt_for_reporting; // target altitude in cm for reporting (logs and ground station)
////////////////////////////////////////////////////////////////////////////////
// ACRO Mode
////////////////////////////////////////////////////////////////////////////////
// Used to control Axis lock
static int32_t acro_roll; // desired roll angle while sport mode
static int32_t acro_roll_rate; // desired roll rate while in acro mode
static int32_t acro_pitch; // desired pitch angle while sport mode
static int32_t acro_pitch_rate; // desired pitch rate while acro mode
static int32_t acro_yaw_rate; // desired yaw rate while acro mode
static float acro_level_mix; // scales back roll, pitch and yaw inversely proportional to input from pilot
////////////////////////////////////////////////////////////////////////////////
// Circle Mode / Loiter control
////////////////////////////////////////////////////////////////////////////////
Vector3f circle_center; // circle position expressed in cm from home location. x = lat, y = lon
// angle from the circle center to the copter's desired location. Incremented at circle_rate / second
static float circle_angle;
// the total angle (in radians) travelled
static float circle_angle_total;
// deg : how many times to circle as specified by mission command
static uint8_t circle_desired_rotations;
static float circle_angular_acceleration; // circle mode's angular acceleration
static float circle_angular_velocity; // circle mode's angular velocity
static float circle_angular_velocity_max; // circle mode's max angular velocity
// How long we should stay in Loiter Mode for mission scripting (time in seconds)
static uint16_t loiter_time_max;
// How long have we been loitering - The start time in millis
static uint32_t loiter_time;
////////////////////////////////////////////////////////////////////////////////
// CH7 and CH8 save waypoint control
////////////////////////////////////////////////////////////////////////////////
// This register tracks the current Mission Command index when writing
// a mission using Ch7 or Ch8 aux switches in flight
static int8_t aux_switch_wp_index;
////////////////////////////////////////////////////////////////////////////////
// Battery Sensors
////////////////////////////////////////////////////////////////////////////////
// Moved to user Variables
////////////////////////////////////////////////////////////////////////////////
// Altitude
////////////////////////////////////////////////////////////////////////////////
// The (throttle) controller desired altitude in cm
static float controller_desired_alt;
// The cm we are off in altitude from next_WP.alt – Positive value means we are below the WP
static int32_t altitude_error;
// The cm/s we are moving up or down based on filtered data - Positive = UP
static int16_t climb_rate;
// The altitude as reported by Sonar in cm – Values are 20 to 700 generally.
static int16_t sonar_alt;
static uint8_t sonar_alt_health; // true if we can trust the altitude from the sonar
static float target_sonar_alt; // desired altitude in cm above the ground
// The altitude as reported by Baro in cm – Values can be quite high
static int32_t baro_alt;
////////////////////////////////////////////////////////////////////////////////
// flight modes
////////////////////////////////////////////////////////////////////////////////
// Flight modes are combinations of Roll/Pitch, Yaw and Throttle control modes
// Each Flight mode is a unique combination of these modes
//
// The current desired control scheme for Yaw
static uint8_t yaw_mode = STABILIZE_YAW;
// The current desired control scheme for roll and pitch / navigation
static uint8_t roll_pitch_mode = STABILIZE_RP;
// The current desired control scheme for altitude hold
static uint8_t throttle_mode = STABILIZE_THR;
////////////////////////////////////////////////////////////////////////////////
// flight specific
////////////////////////////////////////////////////////////////////////////////
// An additional throttle added to keep the copter at the same altitude when banking
static int16_t angle_boost;
// counter to verify landings
static uint16_t land_detector;
////////////////////////////////////////////////////////////////////////////////
// 3D Location vectors
////////////////////////////////////////////////////////////////////////////////
// home location is stored when we have a good GPS lock and arm the copter
// Can be reset each the copter is re-armed
static struct Location home;
// Current location of the copter
static struct Location current_loc;
// Holds the current loaded command from the EEPROM for navigation
static struct Location command_nav_queue;
// Holds the current loaded command from the EEPROM for conditional scripts
static struct Location command_cond_queue;
////////////////////////////////////////////////////////////////////////////////
// Navigation Roll/Pitch functions
////////////////////////////////////////////////////////////////////////////////
// The Commanded ROll from the autopilot based on optical flow sensor.
static int32_t of_roll;
// The Commanded pitch from the autopilot based on optical flow sensor. negative Pitch means go forward.
static int32_t of_pitch;
////////////////////////////////////////////////////////////////////////////////
// Navigation Throttle control
////////////////////////////////////////////////////////////////////////////////
// The Commanded Throttle from the autopilot.
static int16_t nav_throttle; // 0-1000 for throttle control
// This is a simple counter to track the amount of throttle used during flight
// This could be useful later in determining and debuging current usage and predicting battery life
static uint32_t throttle_integrator;
////////////////////////////////////////////////////////////////////////////////
// Navigation Yaw control
////////////////////////////////////////////////////////////////////////////////
// The Commanded Yaw from the autopilot.
static int32_t control_yaw;
// Yaw will point at this location if yaw_mode is set to YAW_LOOK_AT_LOCATION
static Vector3f yaw_look_at_WP;
// bearing from current location to the yaw_look_at_WP
static int32_t yaw_look_at_WP_bearing;
// yaw used for YAW_LOOK_AT_HEADING yaw_mode
static int32_t yaw_look_at_heading;
// Deg/s we should turn
static int16_t yaw_look_at_heading_slew;
////////////////////////////////////////////////////////////////////////////////
// Delay Mission Scripting Command
////////////////////////////////////////////////////////////////////////////////
static int32_t condition_value; // used in condition commands (eg delay, change alt, etc.)
static uint32_t condition_start;
////////////////////////////////////////////////////////////////////////////////
// IMU variables
////////////////////////////////////////////////////////////////////////////////
// Integration time (in seconds) for the gyros (DCM algorithm)
// Updated with the fast loop
static float G_Dt = 0.02;
////////////////////////////////////////////////////////////////////////////////
// Inertial Navigation
////////////////////////////////////////////////////////////////////////////////
static AP_InertialNav inertial_nav(&ahrs, &barometer, g_gps, gps_glitch);
////////////////////////////////////////////////////////////////////////////////
// Waypoint navigation object
// To-Do: move inertial nav up or other navigation variables down here
////////////////////////////////////////////////////////////////////////////////
static AC_WPNav wp_nav(&inertial_nav, &ahrs, &g.pi_loiter_lat, &g.pi_loiter_lon, &g.pid_loiter_rate_lat, &g.pid_loiter_rate_lon);
//////////////////////////////////// ENDS
static uint8_t rate_targets_frame = EARTH_FRAME; // indicates whether rate targets provided in earth or body frame
static int32_t roll_rate_target_ef;
static int32_t pitch_rate_target_ef;
static int32_t yaw_rate_target_ef;
static int32_t roll_rate_target_bf; // body frame roll rate target
static int32_t pitch_rate_target_bf; // body frame pitch rate target
static int32_t yaw_rate_target_bf; // body frame yaw rate target
// LED PINS
#define AN5 59 // Fly mode. One means user
#define AN6 60 // armed
#define AN7 61 // BBB communication
#define AN8 62
#define OUTPUT GPIO_OUTPUT
#define INPUT GPIO_INPUT
#define HIGH 1
#define LOW 0
#define THROTTLEMAX 500
#define PITCHMAX 50
#define ROLLMAX 50
#define YAWMAX 50
//////////////////////////
// Small Util functions //
//////////////////////////
int isNumber(char s){
if(s >= '0' && s <= '9') return 1;
else return 0;
}
int isValid(char data){
if((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) return 1;
else return 0;
}
//////////////
// Fly Mode //
//////////////
// Fly mode, enum, global variable and update
enum FlyMode {
auto_mode = 0,
user_mode = 1
};
//* Read info from BBB */
static struct {
int armMotors;
int pitch;
int yaw;
int roll;
int throttle;
int targetHeight;
int powerOff;
} receivedCommands;
FlyMode flymode = user_mode; // default, global variable
void update_mode(){
if(g.rc_5.radio_in > 1400) flymode = user_mode;
else flymode = auto_mode;
if(flymode == user_mode){
hal.gpio->write(AN5,HIGH);
failsafe_disable();
set_throttle_mode(AUTO_THR);
set_auto_armed(true);
} else {
hal.gpio->write(AN5,LOW);
failsafe_enable();
set_throttle_mode(STABILIZE_THR);
set_auto_armed(false);
}
/*
// auto_mode can only be set when the motors are disarmed
if(motors.armed())
if(flymode == user_mode) return;
else if(g.rc_5.radio_in > 1400) flymode = user_mode;
else
if(g.rc_5.radio_in > 1400) flymode = user_mode;
else flymode = auto_mode;*/
}
//////////////////////////
// uartB communications //
//////////////////////////
void prepareUartB(){
hal.uartB->begin(9600);
receivedCommands.armMotors = 0;
receivedCommands.pitch = 0;
receivedCommands.yaw = 0;
//receivedCommands.throttle = 0;
receivedCommands.powerOff = 0;
//receivedCommands.targetHeight = 0;
}
// Process the command in a switch statement. Returns 0 if processing fails
int processCommand(char * command){
char key = command[0];
int value = (command[1]-'0') * 1000 + (command[2]-'0') * 100 + (command[3]-'0') * 10 + (command[4]-'0') * 1;
switch(key){
case 'a':
case 'A':
//hal.uartB->printf("Changing armMotors to %d\n", value);
receivedCommands.armMotors = value;
if(flymode == auto_mode) {
if(value != 0) {
/*receivedCommands.pitch = 0;
receivedCommands.yaw = 0;
receivedCommands.throttle = 0;
receivedCommands.targetHeight = 0;
receivedCommands.powerOff = 0;
init_arm_motors(); */
//set_land_complete(false);
//wp_nav.set_destination(Vector3f(0,0,0));
} else {
init_disarm_motors();
reset_land_detector();
}
}
return 1;
break;
case 'h':
case 'H':
receivedCommands.targetHeight = value;
//wp_nav.set_destination(Vector3f(0,0,value));
break;
case 'p':
case 'P':
//hal.uartB->printf("Changing Pitch to %d\n", value);
if(value > PITCHMAX || value < -PITCHMAX) value = 0;
receivedCommands.pitch = value;
return 1;
break;
case 'r':
case 'R':
//hal.uartB->printf("Changing Roll to %d\n", value);
if(value > ROLLMAX || value < -ROLLMAX) value = 0;
receivedCommands.roll = value;
return 1;
break;
case 'y':
case 'Y':
//hal.uartB->printf("Changing Yaw to %d\n", value);
if(value > YAWMAX || value < -YAWMAX) value = 0;
receivedCommands.yaw = value;
return 1;
break;
case 't':
case 'T':
//hal.uartB->printf("Changing Throttle to %d\n", value);
if(value > THROTTLEMAX) value = 0;
receivedCommands.throttle = value;
return 1;
break;
case 'z':
case 'Z':
//hal.uartB->printf("Changing PowerOff to %d\n", value);
// TODO
receivedCommands.powerOff = value;
if(value != 0 && flymode == auto_mode) {
receivedCommands.pitch = 0;
receivedCommands.yaw = 0;
receivedCommands.throttle = 0;
receivedCommands.armMotors = 0;
init_disarm_motors();
}
return 1;
break;
default:
hal.uartB->printf("Unknown command %c %d\n", key, value);
return 0;
break;
}
return 1;
}
/* Receives a message in the format S03 T1000 Y0000 R1234 */
#define WHILELOOPFAILSAFE_MAX 10000 // error check stuff
void receiveMessage(void){
char start[3];
char command[5];
uint8_t data;
int num_commands = 0;
int whileLoopFailsafe = 0;
//hal.uartB->flush();
for(int ii = 0; ii < 5; ii++){
command[ii] = 'a';
}
//hal.uartB->printf("Message Received \n");
//hal.gpio->write(AN7,HIGH);
for(int ii = 0; ii < 3; ii++){
data = hal.uartB->read();
while(!isValid( (char) data) && (whileLoopFailsafe++) <= WHILELOOPFAILSAFE_MAX){ data = hal.uartB->read(); }
start[ii] = (char) data;
}
if(start[0] == 's'){
if(isNumber(start[1])) num_commands = (start[1] - '0') * 10;
else { return; }
if(isNumber(start[2])) num_commands += (start[2] - '0');
else { return; }
} else { return; }
/* if(start[0] == 's'){
if(isNumber(start[1])) num_commands = (start[1] - '0') * 10;
else { hal.uartB->printf("Error in first command [1] \n"); return; }
if(isNumber(start[2])) num_commands += (start[2] - '0');
else { hal.uartB->printf("Error in first command [2] \n"); return; }
//hal.uartB->printf("Ready to receive %d commands. \n", num_commands);
} else {
hal.uartB->printf("Error in first command [0]. Got %s\n", start);
return;
}*/
// Receve the rest of the commands
while((num_commands--) && (whileLoopFailsafe++) <= WHILELOOPFAILSAFE_MAX){
while(hal.uartB->available() == 0 && (whileLoopFailsafe++) <= WHILELOOPFAILSAFE_MAX) {} // wait for new data. TODO - add exit strategy to avoid infinit loops
for(int ii = 0; ii < 5; ii++){
data = hal.uartB->read();
while(!isValid( (char) data) && (whileLoopFailsafe++) <= WHILELOOPFAILSAFE_MAX) { data = hal.uartB->read(); }
command[ii] = (char) data;
}
//hal.uartB->printf("Command %d: %s \n", num_commands, command);
//hal.uartA->printf("Command %d: %s \n", num_commands, command);
if(processCommand(command) == 0) return; //hal.uartB->printf("Error parsing command!\n");
}
}
void sendMessageReply(void){
// float b_voltage = battery.voltage();
// float b_current = battery.current_amps();
// float b_current_mah = battery.current_total_mah();
// hal.uartB->printf("bv%f,bc%f,bm%f,\n", b_voltage, b_current, b_current_mah);
// Vector3f gyro = ins.get_gyro();
// hal.uartB->printf("gx%f,gy%f,gz%f,\n",gyro.x, gyro.y, gyro.z);
// Vector3f accel = ins.get_accel();
// hal.uartB->printf("ax%f,ay%f,az%f,\n",accel.x, accel.y, accel.z);
// const Vector3f &mag_offsets = compass.get_offsets();
// hal.uartB->printf("cox%f,coy%f,coz%f\n",mag_offsets.x, mag_offsets.y, mag_offsets.z);
// const Vector3f &compass_field = compass.get_field();
// hal.uartB->printf("cx%f,cy%f,cz%f,\n", compass_field.x, compass_field.y, compass_field.z);
// float yaw_target_body = yaw_rate_target_bf;
// float yaw_target_earth = yaw_rate_target_ef;
// hal.uartB->printf("yb%f,ye%f\n", yaw_target_body, yaw_target_earth);
// hal.uartB->printf("mo%d,ar%d,\n",flymode,motors.armed());
hal.uartB->printf("TH %d, TT %d\n", receivedCommands.targetHeight, receivedCommands.throttle);
}
int send_next_status = 0;
Vector3f temp_vec3;
void sendMessageStatus(void){
switch(send_next_status++ %5) {
case 0:
hal.uartB->printf("mo%d,ar%d,\n",flymode,motors.armed());
break;
case 1:
hal.uartB->printf("bv%f,bc%f,bm%f,\n", battery.voltage(), battery.current_amps(), battery.current_total_mah());
break;
case 2:
temp_vec3 = ins.get_gyro();
hal.uartB->printf("gx%f,gy%f,gz%f,\n",temp_vec3.x, temp_vec3.y, temp_vec3.z);
break;
case 3:
temp_vec3 = ins.get_accel();
hal.uartB->printf("ax%f,ay%f,az%f,\n",temp_vec3.x, temp_vec3.y, temp_vec3.z);
break;
case 4:
float yaw_target_body = yaw_rate_target_bf;
float yaw_target_earth = yaw_rate_target_ef;
hal.uartB->printf("yb%f,ye%f\n", yaw_target_body, yaw_target_earth);
break;
}
}
// Used for testing
void printStatustoUart(void){
//hal.uartB->printf("Status: Armed %d, Pitch %d, Yaw %d, Roll %d, Throttle %d, PowerOff %d\n", receivedCommands.armMotors, receivedCommands.pitch, receivedCommands.yaw, receivedCommands.roll, receivedCommands.throttle, receivedCommands.powerOff);
hal.uartA->printf("Status: Armed %d, Pitch %d, Yaw %d, Roll %d, Throttle %d, PowerOff %d\n", receivedCommands.armMotors, receivedCommands.pitch, receivedCommands.yaw, receivedCommands.roll, receivedCommands.throttle, receivedCommands.powerOff);
}
int flush_count = 0;
void sync_uart(void){
int num = hal.uartB->available();
if(num > 0) {
if(hal.uartB->read() == 's') {
//hal.uartA->printf("Got something!");
hal.gpio->write(AN7,HIGH);
receiveMessage();
sendMessageReply();
//printStatustoUart();
}
} else {
//if(flush_count % 30) { hal.uartB->flush(); flush_count++; }
// hal.uartB->flush();
hal.gpio->write(AN7,LOW);
}
}
//////////
// MISC //
//////////
void arm_LED(){
if(motors.armed()) hal.gpio->write(AN6, HIGH); // Change to motors.armed()
else hal.gpio->write(AN6, LOW);
}
#endif // USERHOOK_VARIABLES
<file_sep>/test.ino
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#if CLI_ENABLED == ENABLED
// These are function definitions so the Menu can be constructed before the functions
// are defined below. Order matters to the compiler.
#if HIL_MODE != HIL_MODE_ATTITUDE && HIL_MODE != HIL_MODE_SENSORS
static int8_t test_baro(uint8_t argc, const Menu::arg *argv);
#endif
static int8_t test_compass(uint8_t argc, const Menu::arg *argv);
static int8_t test_ins(uint8_t argc, const Menu::arg *argv);
static int8_t test_logging(uint8_t argc, const Menu::arg *argv);
static int8_t test_motors(uint8_t argc, const Menu::arg *argv);
static int8_t test_motorsync(uint8_t argc, const Menu::arg *argv);
static int8_t test_optflow(uint8_t argc, const Menu::arg *argv);
static int8_t test_radio_pwm(uint8_t argc, const Menu::arg *argv);
static int8_t test_radio(uint8_t argc, const Menu::arg *argv);
static int8_t test_relay(uint8_t argc, const Menu::arg *argv);
#if HIL_MODE != HIL_MODE_ATTITUDE && HIL_MODE != HIL_MODE_SENSORS
static int8_t test_sonar(uint8_t argc, const Menu::arg *argv);
#endif
// Creates a constant array of structs representing menu options
// and stores them in Flash memory, not RAM.
// User enters the string in the console to call the functions on the right.
// See class Menu in AP_Coommon for implementation details
const struct Menu::command test_menu_commands[] PROGMEM = {
#if HIL_MODE != HIL_MODE_ATTITUDE && HIL_MODE != HIL_MODE_SENSORS
{"baro", test_baro},
#endif
{"compass", test_compass},
{"ins", test_ins},
{"logging", test_logging},
{"motors", test_motors},
{"motorsync", test_motorsync},
{"optflow", test_optflow},
{"pwm", test_radio_pwm},
{"radio", test_radio},
{"relay", test_relay},
#if HIL_MODE != HIL_MODE_ATTITUDE && HIL_MODE != HIL_MODE_SENSORS
{"sonar", test_sonar},
#endif
};
// A Macro to create the Menu
MENU(test_menu, "test", test_menu_commands);
static int8_t
test_mode(uint8_t argc, const Menu::arg *argv)
{
test_menu.run();
return 0;
}
#if HIL_MODE != HIL_MODE_ATTITUDE && HIL_MODE != HIL_MODE_SENSORS
static int8_t
test_baro(uint8_t argc, const Menu::arg *argv)
{
int32_t alt;
print_hit_enter();
init_barometer(true);
while(1) {
delay(100);
alt = read_barometer();
if (!barometer.healthy) {
cliSerial->println_P(PSTR("not healthy"));
} else {
cliSerial->printf_P(PSTR("Alt: %0.2fm, Raw: %f Temperature: %.1f\n"),
alt / 100.0,
barometer.get_pressure(),
barometer.get_temperature());
}
if(cliSerial->available() > 0) {
return (0);
}
}
return 0;
}
#endif
static int8_t
test_compass(uint8_t argc, const Menu::arg *argv)
{
uint8_t delta_ms_fast_loop;
uint8_t medium_loopCounter = 0;
if (!g.compass_enabled) {
cliSerial->printf_P(PSTR("Compass: "));
print_enabled(false);
return (0);
}
if (!compass.init()) {
cliSerial->println_P(PSTR("Compass initialisation failed!"));
return 0;
}
ahrs.init();
ahrs.set_fly_forward(true);
ahrs.set_compass(&compass);
report_compass();
// we need the AHRS initialised for this test
ins.init(AP_InertialSensor::COLD_START,
ins_sample_rate);
ahrs.reset();
int16_t counter = 0;
float heading = 0;
print_hit_enter();
while(1) {
delay(20);
if (millis() - fast_loopTimer > 19) {
delta_ms_fast_loop = millis() - fast_loopTimer;
G_Dt = (float)delta_ms_fast_loop / 1000.f; // used by DCM integrator
fast_loopTimer = millis();
// INS
// ---
ahrs.update();
medium_loopCounter++;
if(medium_loopCounter == 5) {
if (compass.read()) {
// Calculate heading
const Matrix3f &m = ahrs.get_dcm_matrix();
heading = compass.calculate_heading(m);
compass.null_offsets();
}
medium_loopCounter = 0;
}
counter++;
if (counter>20) {
if (compass.healthy()) {
const Vector3f &mag_ofs = compass.get_offsets();
const Vector3f &mag = compass.get_field();
cliSerial->printf_P(PSTR("Heading: %ld, XYZ: %.0f, %.0f, %.0f,\tXYZoff: %6.2f, %6.2f, %6.2f\n"),
(wrap_360_cd(ToDeg(heading) * 100)) /100,
mag.x,
mag.y,
mag.z,
mag_ofs.x,
mag_ofs.y,
mag_ofs.z);
} else {
cliSerial->println_P(PSTR("compass not healthy"));
}
counter=0;
}
}
if (cliSerial->available() > 0) {
break;
}
}
// save offsets. This allows you to get sane offset values using
// the CLI before you go flying.
cliSerial->println_P(PSTR("saving offsets"));
compass.save_offsets();
return (0);
}
static int8_t
test_ins(uint8_t argc, const Menu::arg *argv)
{
Vector3f gyro, accel;
print_hit_enter();
cliSerial->printf_P(PSTR("INS\n"));
delay(1000);
ahrs.init();
ins.init(AP_InertialSensor::COLD_START,
ins_sample_rate);
cliSerial->printf_P(PSTR("...done\n"));
delay(50);
while(1) {
ins.update();
gyro = ins.get_gyro();
accel = ins.get_accel();
float test = accel.length() / GRAVITY_MSS;
cliSerial->printf_P(PSTR("a %7.4f %7.4f %7.4f g %7.4f %7.4f %7.4f t %7.4f \n"),
accel.x, accel.y, accel.z,
gyro.x, gyro.y, gyro.z,
test);
delay(40);
if(cliSerial->available() > 0) {
return (0);
}
}
}
/*
* test the dataflash is working
*/
static int8_t
test_logging(uint8_t argc, const Menu::arg *argv)
{
cliSerial->println_P(PSTR("Testing dataflash logging"));
DataFlash.ShowDeviceInfo(cliSerial);
return 0;
}
static int8_t
test_motors(uint8_t argc, const Menu::arg *argv)
{
cliSerial->printf_P(PSTR(
"Connect battery for this test.\n"
"Motors will spin by frame position order.\n"
"Front (& right of centerline) motor first, then in clockwise order around frame.\n"
"Remember to disconnect battery after this test.\n"
"Any key to exit.\n"));
// ensure all values have been sent to motors
motors.set_update_rate(g.rc_speed);
motors.set_frame_orientation(g.frame_orientation);
motors.set_min_throttle(g.throttle_min);
motors.set_mid_throttle(g.throttle_mid);
// enable motors
init_rc_out();
while(1) {
delay(20);
read_radio();
motors.output_test();
if(cliSerial->available() > 0) {
g.esc_calibrate.set_and_save(0);
return(0);
}
}
}
// test_motorsync - suddenly increases pwm output to motors to test if ESC loses sync
static int8_t
test_motorsync(uint8_t argc, const Menu::arg *argv)
{
bool test_complete = false;
bool spin_motors = false;
uint32_t spin_start_time = 0;
uint32_t last_run_time;
int16_t last_throttle = 0;
int16_t c;
// check if radio is calibration
pre_arm_rc_checks();
if (!ap.pre_arm_rc_check) {
cliSerial->print_P(PSTR("radio not calibrated\n"));
return 0;
}
// print warning that motors will spin
// ask user to raise throttle
// inform how to stop test
cliSerial->print_P(PSTR("This sends sudden outputs to the motors based on the pilot's throttle to test for ESC loss of sync. Motors will spin so mount props up-side-down!\n Hold throttle low, then raise throttle stick to desired level and press A. Motors will spin for 2 sec and then return to low.\nPress any key to exit.\n"));
// clear out user input
while (cliSerial->available()) {
cliSerial->read();
}
// disable throttle and battery failsafe
g.failsafe_throttle = FS_THR_DISABLED;
g.failsafe_battery_enabled = FS_BATT_DISABLED;
// read radio
read_radio();
// exit immediately if throttle is not zero
if( g.rc_3.control_in != 0 ) {
cliSerial->print_P(PSTR("throttle not zero\n"));
return 0;
}
// clear out any user input
while (cliSerial->available()) {
cliSerial->read();
}
// enable motors and pass through throttle
init_rc_out();
output_min();
motors.armed(true);
// initialise run time
last_run_time = millis();
// main run while the test is not complete
while(!test_complete) {
// 50hz loop
if( millis() - last_run_time > 20 ) {
last_run_time = millis();
// read radio input
read_radio();
// display throttle value
if (abs(g.rc_3.control_in-last_throttle) > 10) {
cliSerial->printf_P(PSTR("\nThr:%d"),g.rc_3.control_in);
last_throttle = g.rc_3.control_in;
}
// decode user input
if (cliSerial->available()) {
c = cliSerial->read();
if (c == 'a' || c == 'A') {
spin_motors = true;
spin_start_time = millis();
// display user's throttle level
cliSerial->printf_P(PSTR("\nSpin motors at:%d"),(int)g.rc_3.control_in);
// clear out any other use input queued up
while (cliSerial->available()) {
cliSerial->read();
}
}else{
// any other input ends the test
test_complete = true;
motors.armed(false);
}
}
// check if time to stop motors
if (spin_motors) {
if ((millis() - spin_start_time) > 2000) {
spin_motors = false;
cliSerial->printf_P(PSTR("\nMotors stopped"));
}
}
// output to motors
if (spin_motors) {
// pass pilot throttle through to motors
motors.throttle_pass_through();
}else{
// spin motors at minimum
output_min();
}
}
}
// stop motors
motors.output_min();
motors.armed(false);
// clear out any user input
while( cliSerial->available() ) {
cliSerial->read();
}
// display completion message
cliSerial->printf_P(PSTR("\nTest complete\n"));
return 0;
}
static int8_t
test_optflow(uint8_t argc, const Menu::arg *argv)
{
return (0);
}
static int8_t
test_radio_pwm(uint8_t argc, const Menu::arg *argv)
{
print_hit_enter();
delay(1000);
while(1) {
delay(20);
// Filters radio input - adjust filters in the radio.pde file
// ----------------------------------------------------------
read_radio();
// servo Yaw
//APM_RC.OutputCh(CH_7, g.rc_4.radio_out);
cliSerial->printf_P(PSTR("IN: 1: %d\t2: %d\t3: %d\t4: %d\t5: %d\t6: %d\t7: %d\t8: %d\n"),
g.rc_1.radio_in,
g.rc_2.radio_in,
g.rc_3.radio_in,
g.rc_4.radio_in,
g.rc_5.radio_in,
g.rc_6.radio_in,
g.rc_7.radio_in,
g.rc_8.radio_in);
if(cliSerial->available() > 0) {
return (0);
}
}
}
static int8_t
test_radio(uint8_t argc, const Menu::arg *argv)
{
print_hit_enter();
delay(1000);
while(1) {
delay(20);
read_radio();
cliSerial->printf_P(PSTR("IN 1: %d\t2: %d\t3: %d\t4: %d\t5: %d\t6: %d\t7: %d\n"),
g.rc_1.control_in,
g.rc_2.control_in,
g.rc_3.control_in,
g.rc_4.control_in,
g.rc_5.control_in,
g.rc_6.control_in,
g.rc_7.control_in);
if(cliSerial->available() > 0) {
return (0);
}
}
}
static int8_t test_relay(uint8_t argc, const Menu::arg *argv)
{
print_hit_enter();
delay(1000);
while(1) {
cliSerial->printf_P(PSTR("Relay on\n"));
relay.on(0);
delay(3000);
if(cliSerial->available() > 0) {
return (0);
}
cliSerial->printf_P(PSTR("Relay off\n"));
relay.off(0);
delay(3000);
if(cliSerial->available() > 0) {
return (0);
}
}
}
#if HIL_MODE != HIL_MODE_ATTITUDE && HIL_MODE != HIL_MODE_SENSORS
/*
* test the sonar
*/
static int8_t
test_sonar(uint8_t argc, const Menu::arg *argv)
{
#if CONFIG_SONAR == ENABLED
if(g.sonar_enabled == false) {
cliSerial->printf_P(PSTR("Sonar disabled\n"));
return (0);
}
// make sure sonar is initialised
init_sonar();
print_hit_enter();
while(1) {
delay(100);
cliSerial->printf_P(PSTR("Sonar: %d cm\n"), sonar->read());
if(cliSerial->available() > 0) {
return (0);
}
}
#endif
return (0);
}
#endif
static void print_hit_enter()
{
cliSerial->printf_P(PSTR("Hit Enter to exit.\n\n"));
}
#endif // CLI_ENABLED
<file_sep>/events.ino
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
/*
* This event will be called when the failsafe changes
* boolean failsafe reflects the current state
*/
static void failsafe_radio_on_event()
{
// if motors are not armed there is nothing to do
if( !motors.armed() ) {
return;
}
// This is how to handle a failsafe.
switch(control_mode) {
case STABILIZE:
case ACRO:
case SPORT:
// if throttle is zero disarm motors
/*if (g.rc_3.control_in == 0) {
init_disarm_motors();
}else if(g.failsafe_throttle == FS_THR_ENABLED_ALWAYS_LAND) {
// if failsafe_throttle is 3 (i.e. FS_THR_ENABLED_ALWAYS_LAND) land immediately
set_mode(LAND);
}else if(home_distance > wp_nav.get_waypoint_radius()) {
if (!set_mode(RTL)) {
set_mode(LAND);
}
}else{ */
// We have no GPS or are very close to home so we will land
set_mode(LAND);
//}
break;
case AUTO:
// failsafe_throttle is 1 do RTL, 2 means continue with the mission
if (g.failsafe_throttle == FS_THR_ENABLED_ALWAYS_RTL) {
if(home_distance > wp_nav.get_waypoint_radius()) {
if (!set_mode(RTL)) {
set_mode(LAND);
}
}else{
// We are very close to home so we will land
set_mode(LAND);
}
}else if(g.failsafe_throttle == FS_THR_ENABLED_ALWAYS_LAND) {
// if failsafe_throttle is 3 (i.e. FS_THR_ENABLED_ALWAYS_LAND) land immediately
set_mode(LAND);
}
// if failsafe_throttle is 2 (i.e. FS_THR_ENABLED_CONTINUE_MISSION) no need to do anything
break;
case LOITER:
case ALT_HOLD:
// if landed with throttle at zero disarm, otherwise do the regular thing
if (g.rc_3.control_in == 0 && ap.land_complete) {
init_disarm_motors();
}else if(g.failsafe_throttle == FS_THR_ENABLED_ALWAYS_LAND) {
// if failsafe_throttle is 3 (i.e. FS_THR_ENABLED_ALWAYS_LAND) land immediately
set_mode(LAND);
}else if(home_distance > wp_nav.get_waypoint_radius()) {
if (!set_mode(RTL)) {
set_mode(LAND);
}
}else{
// We have no GPS or are very close to home so we will land
set_mode(LAND);
}
break;
case LAND:
// continue to land if battery failsafe is also active otherwise fall through to default handling
if (g.failsafe_battery_enabled == FS_BATT_LAND && failsafe.battery) {
break;
}
default:
if(g.failsafe_throttle == FS_THR_ENABLED_ALWAYS_LAND) {
// if failsafe_throttle is 3 (i.e. FS_THR_ENABLED_ALWAYS_LAND) land immediately
set_mode(LAND);
}else if(home_distance > wp_nav.get_waypoint_radius()) {
if (!set_mode(RTL)){
set_mode(LAND);
}
}else{
// We have no GPS or are very close to home so we will land
set_mode(LAND);
}
break;
}
// log the error to the dataflash
Log_Write_Error(ERROR_SUBSYSTEM_FAILSAFE_RADIO, ERROR_CODE_FAILSAFE_OCCURRED);
}
// failsafe_off_event - respond to radio contact being regained
// we must be in AUTO, LAND or RTL modes
// or Stabilize or ACRO mode but with motors disarmed
static void failsafe_radio_off_event()
{
// no need to do anything except log the error as resolved
// user can now override roll, pitch, yaw and throttle and even use flight mode switch to restore previous flight mode
Log_Write_Error(ERROR_SUBSYSTEM_FAILSAFE_RADIO, ERROR_CODE_FAILSAFE_RESOLVED);
}
static void failsafe_battery_event(void)
{
// return immediately if low battery event has already been triggered
if (failsafe.battery) {
return;
}
// failsafe check
if (g.failsafe_battery_enabled != FS_BATT_DISABLED && motors.armed()) {
switch(control_mode) {
case STABILIZE:
case ACRO:
case SPORT:
// if throttle is zero disarm motors
if (g.rc_3.control_in == 0) {
init_disarm_motors();
}else{
// set mode to RTL or LAND
if (g.failsafe_battery_enabled == FS_BATT_RTL && home_distance > wp_nav.get_waypoint_radius()) {
if (!set_mode(RTL)) {
set_mode(LAND);
}
}else{
set_mode(LAND);
}
}
break;
case AUTO:
// set mode to RTL or LAND
if (home_distance > wp_nav.get_waypoint_radius()) {
if (!set_mode(RTL)) {
set_mode(LAND);
}
}else{
set_mode(LAND);
}
break;
case LOITER:
case ALT_HOLD:
// if landed with throttle at zero disarm, otherwise fall through to default handling
if (g.rc_3.control_in == 0 && ap.land_complete) {
init_disarm_motors();
break;
}
default:
// set mode to RTL or LAND
if (g.failsafe_battery_enabled == FS_BATT_RTL && home_distance > wp_nav.get_waypoint_radius()) {
if (!set_mode(RTL)) {
set_mode(LAND);
}
}else{
set_mode(LAND);
}
break;
}
}
// set the low battery flag
set_failsafe_battery(true);
// warn the ground station and log to dataflash
gcs_send_text_P(SEVERITY_LOW,PSTR("Low Battery!"));
Log_Write_Error(ERROR_SUBSYSTEM_FAILSAFE_BATT, ERROR_CODE_FAILSAFE_OCCURRED);
}
static void update_events()
{
ServoRelayEvents.update_events();
}
<file_sep>/UserCode.ino
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#ifdef USERHOOK_INIT
void userhook_init()
{
hal.gpio->pinMode(AN5, OUTPUT);
hal.gpio->pinMode(AN6, OUTPUT);
hal.gpio->pinMode(AN7, OUTPUT);
hal.gpio->pinMode(AN8, OUTPUT);
prepareUartB();
battery.set_monitoring(AP_BATT_MONITOR_VOLTAGE_AND_CURRENT);
//hal.uartA->begin(9600);
}
#endif
#ifdef USERHOOK_FASTLOOP
void userhook_FastLoop()
{
// put your 100Hz code here
}
#endif
#ifdef USERHOOK_50HZLOOP
void userhook_50Hz()
{
// put your 50Hz code here
}
#endif
#ifdef USERHOOK_MEDIUMLOOP
void userhook_MediumLoop()
{
// put your 10Hz code here
sync_uart();
arm_LED();
}
#endif
#ifdef USERHOOK_SLOWLOOP
void userhook_SlowLoop()
{
// put your 3.3Hz code here
}
#endif
#ifdef USERHOOK_SUPERSLOWLOOP
void userhook_SuperSlowLoop()
{
static int count = 0;
if(count++ %2 == 0){
sendMessageStatus();
}
}
#endif
<file_sep>/heli.ino
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
// Traditional helicopter variables and functions
|
d2422303f82302908bdeb0293446e7fd680cc897
|
[
"C",
"C++"
] | 8
|
C++
|
GabrielBegun/ArduFire
|
16d5ff65bd68700b97a9bdd355c2dad28c8751ea
|
f01ea099e9c8f7a8c84e79d98f5272498e1319aa
|
refs/heads/master
|
<file_sep>// Rome 0.7.0
// ==========
// "Opinions are good, only when I agree with them." This is Rome's entire philosophy to development.
// If you want to actually work on Rome here are some things you should keep in mind.
// - If it could be done differently it should be exposed to others
// - Rome should make as few assumptions as possible, but still build a good OOBE
// - Smaller, sleeker code is better, but don't completely sacrifice performance
// - Functional programming is highly approved, but keep the previous point in mind
// - Rome should have no dependencies, if possible, unless the library is small enough one could embed or it is so popular it is a "standard"
(function () {
var self = this,
jQueryCompat = self.jQuery || self.Zepto,
body,
// Currently even IE8 supports our use of querySelectorAll, so we'll use this internally instead
$ = function (selector, context) {
context = (context || body || (body = document.body));
if (!context.querySelectorAll) return [];
var nodeList = context.querySelectorAll(selector);
// Convert NodeList to a real array to make operations easier.
// Based on http://jsperf.com/nodelist-to-array/24 - Terse While new Array
var len = nodeList.length,
arr = new Array(len);
while (len--) {
arr[len] = nodeList[len]
}
return arr;
};
function nope() { }
function Rome() { }
//Potential for supporting multiple registries within Rome?
function Registry() {
this.componentsLookup = {};
}
// `NodeList.forEach` doesn't work, so might as well make our own more efficient forEach
function each(arr, cb) {
for (var i = 0, len = arr.length; i < len; ++i) {
cb(arr[i]);
}
}
function eachReverse(arr, cb) {
for (var i = arr.length - 1; i >= 0; --i) {
cb(arr[i]);
}
}
// Should be a reference to the window object for now
Registry.prototype = {
// Used during `Rome.erect` to get the planned component
findComponent: function (name) {
return this.componentsLookup[name];
},
addComponent: function (base, component, mixins) {
var name = component._name;
if (this.componentsLookup[name]) return;
this.componentsLookup[name] = { base: base, mixins: mixins };
},
findInstance: function (root) {
return root._rome;
},
addInstance: function (root, componentName, instance) {
root._rome = { component: instance };
}
};
var reg = Rome.Registry = new Registry();
function getInstance(obj) {
var romeData = obj._rome;
return romeData.mixins ? obj : romeData.component;
}
// Strategies are a minimal abstraction/transformation layer
// that will allow users to replace the OOBE of Rome.
var strats = Rome.Strategies = {
mixin: function (obj, mixin) {
mixin(obj);
},
// These are mixins that get added to all components
autoMixins: [],
// Handles all DOM changes as to automatically wire-up and destroy components
domObserver: function () {
function erect(node) {
node = node.target || node;
// The node may not be a component, but it may contain other components
var children = $('[data-rome]', node);
if (node.getAttribute && node.getAttribute('data-rome')) {
children = children.concat(node);
}
erectInstances(children);
}
function destroy(node) {
var domRomeData = (node.target || node)._rome;
domRomeData && domRomeData.component.destroy({ domObserved: true })
}
var MutationObserver = self.MutationObserver || self.WebKitMutationObserver;
if (MutationObserver) {
var observer = new MutationObserver(function (mutations) {
eachReverse(mutations, function (mutation) {
eachReverse(mutation.addedNodes, erect);
eachReverse(mutation.removedNodes, destroy);
});
});
observer.observe(document.body, { subtree: true, childList: true });
}
else {
//@TODO: Throttle calls as to pass a single array of nodes once
document.body.addEventListener('DOMNodeInserted', erect, false);
document.body.addEventListener('DOMNodeRemoved', destroy, false);
}
},
destruct: function (obj) {
//Instance can either be a DOM element or a Rome Component instance
obj = getInstance(obj);
//@TODO: Add in recursive mixin walking
// All components can provide a destructor, which is modeled after C++/C# `~ComponentName`
each(obj._rome.mixins, function (mixin) {
var destructorName = '~' + mixin._name;
obj[destructorName] && obj[destructorName]();
});
},
construct: function (obj) {
//Instance can either be a DOM element or a Rome Component instance
obj = getInstance(obj);
//@TODO: Add in recursive mixin walking
// Executes each mixin's constructor function, if one exists, which is based on the mixin's name
eachReverse(obj._rome.mixins, function (mixin) {
var constructorName = mixin._name;
obj[constructorName] && obj[constructorName]();
});
}
};
// The foundation for all components provided by Rome.
// Allows users to provide a new foundation for functionality they want baked in.
Rome.Foundation = (function () {
var destroy = function (state) {
state = state || {};
var root = this.root;
// Component is manually handling itself, at least for now
if (root._rome.isExiled) return;
// All child components should be cleaned up along with the parent
eachReverse($('[data-rome]', root).concat(root), strats.destruct);
// If a domObserver picked up the removal there is no need to remove the node again
!state.domObserved && root.parentNode.removeChild(root);
};
var exile = function (isExiled) { Rome.exile(this, isExiled); };
function Foundation(obj) {
var proto = obj.prototype;
proto.destroy = destroy;
proto.exile = exile;
};
Foundation._name = 'Foundation';
return Foundation;
})();
// Before you can erect a component you must plan for it.
// `baseComponent` is what Rome will be creating instances of via `[data-rome]`.
// The `mixins` is an array of all the functionality you want in a component.
// `name` is what you want your component known as.
// This must be provided if `baseComponent._name` is not set.
// Unforuntately, minification might mangle the function name, so we had to resort to being explicit
Rome.plan = function (baseComponent, mixins, name) {
// An anonymous function to merge all mixins into, so that the baseComponent
// can be the last mixin merged into the base
var base = function () { };
// We store the component name as a static to always make it easily accessible
base._name = baseComponent._name || (baseComponent._name = name);
mixins = (mixins || []).concat(strats.autoMixins);
// We always add Rome.Foundation for common functionality in components
// and let the baseComponent reign supreme
mixins.unshift(baseComponent, Rome.Foundation);
eachReverse(mixins, function (mixin) {
mixin = typeof mixin != 'string' ? mixin : reg.findComponent(mixin);
strats.mixin(base, mixin);
});
reg.addComponent(base, baseComponent, mixins);
return base;
};
function erectInstances(components) {
eachReverse(components, Rome.erect);
}
var wasRomeBuilt = false;
// After you're done planning all your components or simply want to start erecting your components.
Rome.build = function () {
// Rome can only be built once, so bail if it is accidentally called again
if (wasRomeBuilt) return;
//@TODO: Remove DOM dependency - perhaps some sort of dependency analysis instead?
//Configurable selector would be useful + configurable data attributes
erectInstances($('[data-rome]'));
strats.domObserver();
wasRomeBuilt = true;
};
//Should this even be publicly exposed?
Rome.erect = function (root) {
if (root._rome) return;
var romeComponentName = root.getAttribute('data-rome'),
storedComponent = reg.findComponent(romeComponentName);
if (!storedComponent.cachedComponent) {
function Component(root) {
this.root = root;
// We support jQuery-like libraries to allow for "advanced" manipulation of the dom
jQueryCompat && (this.$root = jQueryCompat(root));
strats.construct(this);
}
// Finally adds in everything from the base component's `prototype` before creating a new component instance
Component.prototype = storedComponent.base.prototype;
// Makes looking up a component's mixins easy and we don't want to duplicate the mixins list on each instance
Component.prototype._rome = { mixins: storedComponent.mixins };
// Cache this Rome.Component, so that creating numerous instances doesn't require recreating the function
storedComponent.cachedComponent = Component;
}
//Need mixin initialization strategy?
reg.addInstance(root, romeComponentName, new storedComponent.cachedComponent(root));
};
Rome.exile = function (component, isExiled) {
component.root._rome.isExiled = typeof isExiled == 'undefined' ? true : isExiled
};
//@TODO: Global PubSub?
Rome.Empire;
//@TODO: Routing?
Rome.Roads;
//@TODO: Binding? Use Event Delegation? Copy Derby?
Rome.Allegiance
//@TODO Alias elements? https://github.com/tenbits/mask-compo
//@TODO support AMD/Common
this.Rome = Rome;
})();
|
9ea31880cfdf5a7232d07ecb296851a1a5aeaad7
|
[
"JavaScript"
] | 1
|
JavaScript
|
Akkuma/Rome
|
e446a5d4f9ca2c5150b33c67cc9bb6c3621922e6
|
1682b4240751e9f24a01561f06a94c94ebb5a141
|
refs/heads/master
|
<repo_name>ningtangla/invertedPendulum<file_sep>/src/policyGradientContinuous.py
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import functools as ft
#import env
import cartpole_env
import reward
import dataSave
def approximatePolicy(stateBatch, model):
graph = model.graph
state_ = graph.get_tensor_by_name('inputs/state_:0')
actionSample_ = graph.get_tensor_by_name('outputs/actionSample_:0')
actionBatch = model.run(actionSample_, feed_dict = {state_ : stateBatch})
return actionBatch
class SampleTrajectory():
def __init__(self, maxTimeStep, transitionFunction, isTerminal, reset):
self.maxTimeStep = maxTimeStep
self.transitionFunction = transitionFunction
self.isTerminal = isTerminal
self.reset = reset
def __call__(self, policy):
oldState = self.reset()
trajectory = []
for time in range(self.maxTimeStep):
oldStateBatch = oldState.reshape(1, -1)
actionBatch = policy(oldStateBatch)
action = actionBatch[0]
# actionBatch shape: batch * action Dimension; only need action Dimention
newState = self.transitionFunction(oldState, action)
trajectory.append((oldState, action))
terminal = self.isTerminal(newState)
if terminal:
break
oldState = newState
return trajectory
class AccumulateRewards():
def __init__(self, decay, rewardFunction):
self.decay = decay
self.rewardFunction = rewardFunction
def __call__(self, trajectory):
rewards = [self.rewardFunction(state, action) for state, action in trajectory]
accumulateReward = lambda accumulatedReward, reward: self.decay * accumulatedReward + reward
accumulatedRewards = np.array([ft.reduce(accumulateReward, reversed(rewards[TimeT: ])) for TimeT in range(len(rewards))])
return accumulatedRewards
def normalize(accumulatedRewards):
normalizedAccumulatedRewards = (accumulatedRewards - np.mean(accumulatedRewards)) / np.std(accumulatedRewards)
return normalizedAccumulatedRewards
class TrainTensorflow():
def __init__(self, summaryWriter):
self.summaryWriter = summaryWriter
def __call__(self, episode, episodeIndex, normalizedAccumulatedRewardsEpisode, model):
mergedEpisode = np.concatenate(episode)
stateEpisode, actionEpisode = list(zip(*mergedEpisode))
stateBatch, actionBatch = np.vstack(stateEpisode), np.vstack(actionEpisode)
mergedAccumulatedRewardsEpisode = np.concatenate(normalizedAccumulatedRewardsEpisode)
graph = model.graph
state_ = graph.get_tensor_by_name('inputs/state_:0')
action_ = graph.get_tensor_by_name('inputs/action_:0')
accumulatedRewards_ = graph.get_tensor_by_name('inputs/accumulatedRewards_:0')
loss_ = graph.get_tensor_by_name('outputs/loss_:0')
trainOpt_ = graph.get_operation_by_name('train/adamOpt_')
lossSummary = graph.get_tensor_by_name('outputs/Loss:0')
loss, summary, trainOpt = model.run([loss_, lossSummary, trainOpt_], feed_dict = {state_ : np.vstack(stateBatch),
action_ : np.vstack(actionBatch),
accumulatedRewards_ : mergedAccumulatedRewardsEpisode
})
self.summaryWriter.add_summary(summary, episodeIndex)
self.summaryWriter.flush()
return loss, model
class PolicyGradient():
def __init__(self, numTrajectory, maxEpisode):
self.numTrajectory = numTrajectory
self.maxEpisode = maxEpisode
def __call__(self, model, approximatePolicy, sampleTrajectory, accumulateRewards, train):
for episodeIndex in range(self.maxEpisode):
policy = lambda state: approximatePolicy(state, model)
episode = [sampleTrajectory(policy) for index in range(self.numTrajectory)]
normalizedAccumulatedRewardsEpisode = [normalize(accumulateRewards(trajectory)) for trajectory in episode]
loss, model = train(episode, episodeIndex, normalizedAccumulatedRewardsEpisode, model)
print(np.mean([len(episode[index]) for index in range(self.numTrajectory)]))
return model
def main():
# tf.set_random_seed(123)
# np.random.seed(123)
numActionSpace = 1
numStateSpace = 4
actionLow = -2
actionHigh = 2
actionRatio = (actionHigh - actionLow) / 2.
envModelName = 'inverted_pendulum'
renderOn = False
maxTimeStep = 200
maxQPos = 0.2
qPosInitNoise = 0.001
qVelInitNoise = 0.001
aliveBouns = 1
rewardDecay = 1
numTrajectory = 1000
maxEpisode = 8
learningRate = 0.01
summaryPath = 'tensorBoard/1'
savePath = 'data/tmpModelGaussian.ckpt'
with tf.name_scope("inputs"):
state_ = tf.placeholder(tf.float32, [None, numStateSpace], name="state_")
action_ = tf.placeholder(tf.float32, [None, numActionSpace], name="action_")
accumulatedRewards_ = tf.placeholder(tf.float32, [None, ], name="accumulatedRewards_")
with tf.name_scope("hidden"):
fullyConnected1_ = tf.layers.dense(inputs = state_, units = 30, activation = tf.nn.relu)
fullyConnected2_ = tf.layers.dense(inputs = fullyConnected1_, units = 20, activation = tf.nn.relu)
actionMean_ = tf.layers.dense(inputs = fullyConnected2_, units = numActionSpace, activation = tf.nn.tanh)
actionVariance_ = tf.layers.dense(inputs = fullyConnected2_, units = numActionSpace, activation = tf.nn.softplus)
with tf.name_scope("outputs"):
actionDistribution_ = tfp.distributions.MultivariateNormalDiag(actionMean_ * actionRatio, actionVariance_ + 1e-8, name = 'actionDistribution_')
actionSample_ = tf.clip_by_value(actionDistribution_.sample(), actionLow, actionHigh, name = 'actionSample_')
negLogProb_ = - actionDistribution_.log_prob(action_, name = 'negLogProb_')
loss_ = tf.reduce_sum(tf.multiply(negLogProb_, accumulatedRewards_), name = 'loss_')
tf.summary.scalar("Loss", loss_)
with tf.name_scope("train"):
trainOpt_ = tf.train.AdamOptimizer(learningRate, name = 'adamOpt_').minimize(loss_)
mergedSummary = tf.summary.merge_all()
model = tf.Session()
model.run(tf.global_variables_initializer())
summaryWriter = tf.summary.FileWriter(summaryPath, graph = model.graph)
"""
transitionFunction = env.TransitionFunction(envModelName, renderOn)
isTerminal = env.IsTerminal(maxQPos)
reset = env.Reset(envModelName, qPosInitNoise, qVelInitNoise)
"""
transitionFunction = cartpole_env.Cartpole_continuous_action_transition_function(renderOn = False)
isTerminal = cartpole_env.cartpole_done_function
reset = cartpole_env.cartpole_get_initial_state
sampleTrajectory = SampleTrajectory(maxTimeStep, transitionFunction, isTerminal, reset)
rewardFunction = reward.RewardFunction(aliveBouns)
accumulateRewards = AccumulateRewards(rewardDecay, rewardFunction)
train = TrainTensorflow(summaryWriter)
policyGradient = PolicyGradient(numTrajectory, maxEpisode)
trainedModel = policyGradient(model, approximatePolicy, sampleTrajectory, accumulateRewards, train)
saveModel = dataSave.SaveModel(savePath)
modelSave = saveModel(model)
transitionPlay = cartpole_env.Cartpole_continuous_action_transition_function(renderOn = False)
samplePlay = SampleTrajectory(maxTimeStep, transitionPlay, isTerminal, reset)
policy = lambda state: approximatePolicy(state, model)
playEpisode = [samplePlay(policy) for index in range(5)]
print(np.mean([len(playEpisode[index]) for index in range(5)]))
if __name__ == "__main__":
main()
<file_sep>/src/cartpole_env.py
import numpy as np
import math
from gym.envs.classic_control import CartPoleEnv
env = CartPoleEnv()
#env.seed(123)
#np.random.seed(123)
class Cartpole_transition_function():
def __init__(self, renderOn):
self.renderOn = renderOn
def __call__(self, state, action):
# copied from gym src code
assert env.action_space.contains(action), "%r (%s) invalid"%(action, type(action))
x, x_dot, theta, theta_dot = state
force = env.force_mag if action==1 else -env.force_mag
costheta = math.cos(theta)
sintheta = math.sin(theta)
temp = (force + env.polemass_length * theta_dot * theta_dot * sintheta) / env.total_mass
thetaacc = (env.gravity * sintheta - costheta* temp) / (env.length * (4.0/3.0 - env.masspole * costheta * costheta / env.total_mass))
xacc = temp - env.polemass_length * thetaacc * costheta / env.total_mass
if env.kinematics_integrator == 'euler':
x = x + env.tau * x_dot
x_dot = x_dot + env.tau * xacc
theta = theta + env.tau * theta_dot
theta_dot = theta_dot + env.tau * thetaacc
else: # semi-implicit euler
x_dot = x_dot + env.tau * xacc
x = x + env.tau * x_dot
theta_dot = theta_dot + env.tau * thetaacc
theta = theta + env.tau * theta_dot
state = np.array([x,x_dot,theta,theta_dot])
if self.renderOn: cartpole_render(state)
return state
class Cartpole_continuous_action_transition_function():
def __init__(self, renderOn):
self.renderOn = renderOn
def __call__(self, state, action):
# copied from gym src code
actionValue = action[0]
x, x_dot, theta, theta_dot = state
#force = env.force_mag if action==1 else -env.force_mag
force = (actionValue)*env.force_mag
costheta = math.cos(theta)
sintheta = math.sin(theta)
temp = (force + env.polemass_length * theta_dot * theta_dot * sintheta) / env.total_mass
thetaacc = (env.gravity * sintheta - costheta* temp) / (env.length * (4.0/3.0 - env.masspole * costheta * costheta / env.total_mass))
xacc = temp - env.polemass_length * thetaacc * costheta / env.total_mass
if env.kinematics_integrator == 'euler':
x = x + env.tau * x_dot
x_dot = x_dot + env.tau * xacc
theta = theta + env.tau * theta_dot
theta_dot = theta_dot + env.tau * thetaacc
else: # semi-implicit euler
x_dot = x_dot + env.tau * xacc
x = x + env.tau * x_dot
theta_dot = theta_dot + env.tau * thetaacc
theta = theta + env.tau * theta_dot
state = np.array([x,x_dot,theta,theta_dot])
if self.renderOn: cartpole_render(state)
return state
def cartpole_reward_function(state, action, next_state):
reward = 1.0
return reward
def cartpole_get_initial_state():
return np.array(env.reset())
def cartpole_done_function(state):
# copied from gym src code
x, x_dot, theta, theta_dot = state
done = x < -env.x_threshold \
or x > env.x_threshold \
or theta < -env.theta_threshold_radians \
or theta > env.theta_threshold_radians
done = bool(done)
return done
def cartpole_render(state):
env.reset()
env.state = np.array(state)
# copied from gym src code
mode = 'human'
screen_width = 600
screen_height = 400
world_width = env.x_threshold*2
scale = screen_width/world_width
carty = 100 # TOP OF CART
polewidth = 10.0
polelen = scale * (2 * env.length)
cartwidth = 50.0
cartheight = 30.0
if env.viewer is None:
from gym.envs.classic_control import rendering
env.viewer = rendering.Viewer(screen_width, screen_height)
l,r,t,b = -cartwidth/2, cartwidth/2, cartheight/2, -cartheight/2
axleoffset =cartheight/4.0
cart = rendering.FilledPolygon([(l,b), (l,t), (r,t), (r,b)])
env.carttrans = rendering.Transform()
cart.add_attr(env.carttrans)
env.viewer.add_geom(cart)
l,r,t,b = -polewidth/2,polewidth/2,polelen-polewidth/2,-polewidth/2
pole = rendering.FilledPolygon([(l,b), (l,t), (r,t), (r,b)])
pole.set_color(.8,.6,.4)
env.poletrans = rendering.Transform(translation=(0, axleoffset))
pole.add_attr(env.poletrans)
pole.add_attr(env.carttrans)
env.viewer.add_geom(pole)
env.axle = rendering.make_circle(polewidth/2)
env.axle.add_attr(env.poletrans)
env.axle.add_attr(env.carttrans)
env.axle.set_color(.5,.5,.8)
env.viewer.add_geom(env.axle)
env.track = rendering.Line((0,carty), (screen_width,carty))
env.track.set_color(0,0,0)
env.viewer.add_geom(env.track)
env._pole_geom = pole
if env.state is None: return None
# Edit the pole polygon vertex
pole = env._pole_geom
l,r,t,b = -polewidth/2,polewidth/2,polelen-polewidth/2,-polewidth/2
pole.v = [(l,b), (l,t), (r,t), (r,b)]
x = env.state
cartx = x[0]*scale+screen_width/2.0 # MIDDLE OF CART
env.carttrans.set_translation(cartx, carty)
env.poletrans.set_rotation(-x[2])
return env.viewer.render(return_rgb_array = mode=='rgb_array')
<file_sep>/src/reward.py
import numpy as np
class RewardFunction():
def __init__(self, aliveBouns):
self.aliveBouns = aliveBouns
def __call__(self, state, action):
reward = self.aliveBouns
return reward
class CartpoleRewardFunction():
def __init__(self, aliveBouns):
self.aliveBouns = aliveBouns
def __call__(self, state, action):
distanceBonus = (0.21 - abs(state[2])) / 0.21 + (2.4 - abs(state[0])) / 2.4
reward = self.aliveBouns + distanceBonus
return reward
<file_sep>/src/env.py
import mujoco_py as mujoco
import os
import numpy as np
class Reset():
def __init__(self, modelName, qPosInitNoise, qVelInitNoise):
model = mujoco.load_model_from_path('xmls/' + modelName + '.xml')
self.simulation = mujoco.MjSim(model)
self.qPosInitNoise = qPosInitNoise
self.qVelInitNoise = qVelInitNoise
def __call__(self):
qPos = self.simulation.data.qpos + np.random.uniform(low = -self.qPosInitNoise, high = self.qPosInitNoise, size = len(self.simulation.data.qpos))
qVel = self.simulation.data.qvel + np.random.uniform(low = -self.qVelInitNoise, high = self.qVelInitNoise, size = len(self.simulation.data.qvel))
self.simulation.data.qpos[:] = qPos
self.simulation.data.qpos[:] = qVel
self.simulation.forward()
startState = np.concatenate([qPos, qVel])
return startState
class TransitionFunction():
def __init__(self, modelName, renderOn):
model = mujoco.load_model_from_path('xmls/' + modelName + '.xml')
self.simulation = mujoco.MjSim(model)
self.numQPos = len(self.simulation.data.qpos)
self.numQVel = len(self.simulation.data.qvel)
self.renderOn = renderOn
if self.renderOn:
self.viewer = mujoco.MjViewer(self.simulation)
def __call__(self, oldState, action, renderOpen = False, numSimulationFrames = 1):
oldQPos = oldState[0 : self.numQPos]
oldQVel = oldState[self.numQPos : self.numQPos + self.numQVel]
self.simulation.data.qpos[:] = oldQPos
self.simulation.data.qvel[:] = oldQVel
self.simulation.data.ctrl[:] = action
for i in range(numSimulationFrames):
self.simulation.step()
if self.renderOn:
self.viewer.render()
newQPos, newQVel = self.simulation.data.qpos, self.simulation.data.qvel
newState = np.concatenate([newQPos, newQVel])
return newState
class IsTerminal():
def __init__(self, maxQPos):
self.maxQPos = maxQPos
def __call__(self, state):
terminal = not (np.isfinite(state).all() and np.abs(state[1]) <= self.maxQPos)
return terminal
if __name__ == '__main__':
#transite = TransitionFunction('inverted_pendulum')
#aa = transite([np.zeros(2), np.zeros(2), np.array([0, 0, -0.6]), np.zeros(3)], 0.001)
reset = Reset('inverted_pendulum', 0.001, 0.001)
bb = reset()
|
fadaafa3d3669b53b285f9e2705aa215b7df4c70
|
[
"Python"
] | 4
|
Python
|
ningtangla/invertedPendulum
|
1b646e769b6026f4c8d6ef5d250406fa7846b41f
|
0fe7bd8564fd9661d322bc8656de15770bd3f5ad
|
refs/heads/master
|
<file_sep>package svlt;
public class Acct {
String acctNo;
String acctName;
double balance;
String acctStatus;
public Acct() {
// TODO Auto-generated constructor stub
}
public Acct(String acctNo, String acctName, double balance, String acctStatus) {
this.acctNo = acctNo;
this.acctName = acctName;
this.balance = balance;
this.acctStatus = acctStatus;
}
public String getAcctNo() {
return acctNo;
}
public void setAcctNo(String acctNo) {
this.acctNo = acctNo;
}
public String getAcctName() {
return acctName;
}
public void setAcctName(String acctName) {
this.acctName = acctName;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getAcctStatus() {
return acctStatus;
}
public void setAcctStatus(String acctStatus) {
this.acctStatus = acctStatus;
}
@Override
public String toString() {
return "Acct [acctNo=" + acctNo + ", acctName=" + acctName + ", balance=" + balance + ", acctStatus="
+ acctStatus + "]";
}
}
<file_sep>package svlt;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class UserHandler {
Map<String, String> users;
Map<String, String> usersInfo;
List<User> usersInfos;
public UserHandler() {
// 给users赋初值
users = new HashMap<String, String>();
users.put("qbq", "123456");
users.put("bqb", "123");
users.put("bbq", "1234");
usersInfo = new HashMap<String, String>();
usersInfo.put("钱兵桥", "24岁,软件工程师");
usersInfo.put("qbq", "22岁,Enigneer");
usersInfo.put("bqb", "26岁,Doctor");
usersInfos = new ArrayList<User>();
usersInfos.add(new User("钱兵桥", "24岁", "软件工程师"));
usersInfos.add(new User("qbq", "22岁", "Enigneer"));
usersInfos.add(new User("bqb", "26岁", "Doctor"));
}
public Map<String, String> getUsers() {
return users;
}
public void setUsers(Map<String, String> users) {
this.users = users;
}
/**
*
* @param user
* @param password
* @return
*/
public boolean doLogin(String user, String password) {
if (user == null || password == null) {
return false;
}
Set<Entry<String, String>> map = users.entrySet();
for (Map.Entry<String, String> entrys : map) {
if (user.equals(entrys.getKey()) && password.equals(entrys.getValue())) {
return true;
}
}
// if(users.containsKey(user) && password.equals(users.get(user))){
// return true;
// }
return false;
}
public boolean queryUserInfo(String userName) {
if (usersInfo.containsKey(userName)) {
return true;
}
return false;
}
/**
* 根据Map<K,V> 针对K来查询
*
* @param userName
* @return
*/
public String getUserInfo(String userName) {
String info = "";
info = userName + "," + usersInfo.get(userName);
return info;
}
/**
* 查询全部
*
* @return
*/
public List<User> getAllUser() {
List<User> list = new ArrayList<User>();
User users = null;
for (User user : usersInfos) {
users = new User();
users.setName(user.getName());
users.setAge(user.getAge());
user.setGander(user.getGander());
list.add(user);
}
return list;
}
}
<file_sep>package svlt;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.qbq.utils.DBUtity;
public class AcctManager {
Connection con = null;
public AcctManager() {
}
/**
* 查询全部
*
* @return
*/
public List<Acct> acctQueryAll() {
List<Acct> accts = new ArrayList<Acct>();
try {
con = DBUtity.openConnection();
String sql = "select * from acct";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs == null)
return accts;
while (rs.next()) {
String acctNo = rs.getString("acct_no");
String acctName = rs.getString("acct_name");
double balance = rs.getDouble("balance");
String acctStatus = rs.getString("acct_status");
Acct acct = new Acct(acctNo, acctName, balance, acctStatus);
accts.add(acct);
}
if (ps != null) {
ps.close();
}
DBUtity.closeConnection(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accts;
}
/**
* 精确查询
*
* @param acct_no
* @return
*/
public List<Acct> selectAcctByno(Acct acct) {
List<Acct> accts = new ArrayList<Acct>();
try {
con = DBUtity.openConnection();
String sql = "select * from acct";
String cdt = " where 1=1 ";
// acctNo条件
if (!acct.getAcctNo().equals(""))
cdt += " and acct_no = '" + acct.getAcctNo() + "'";
// acctName条件
if (!acct.getAcctName().equals(""))
cdt += " and acct_name = '" + acct.getAcctName() + "'";
// 余额balance
if (acct.getBalance() > 0.00000001)
cdt += " and balance = " + acct.getBalance();
// 账户状态
if (!acct.getAcctStatus().equals(""))
cdt += " and acct_status = '" + acct.getAcctStatus() + "'";
sql += cdt;
System.out.println("sql语句:" + sql);
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs == null)
return accts;
while (rs.next()) {
String acctNo = rs.getString("acct_no");
String acctName = rs.getString("acct_name");
double balance = rs.getDouble("balance");
String acctStatus = rs.getString("acct_status");
Acct acctnum = new Acct(acctNo, acctName, balance, acctStatus);
accts.add(acctnum);
}
if (ps != null) {
ps.close();
}
DBUtity.closeConnection(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accts;
}
/**
*
* @param a
* @return
*/
public List<Acct> queryHazy(Acct acct) {
List<Acct> accts = new ArrayList<Acct>();
try {
con = DBUtity.openConnection();
String sql = "select * from acct";
String cdt = " where 1=1 ";
// acctNo条件
if (!acct.getAcctNo().equals(""))
cdt += " and acct_no like '%" + acct.getAcctNo() + "%'";
// acctName条件
if (!acct.getAcctName().equals(""))
cdt += " and acct_name like '%" + acct.getAcctName() + "%'";
sql += cdt;
System.out.println("sql语句:" + sql);
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs == null)
return accts;
while (rs.next()) {
String acctNo = rs.getString("acct_no");
String acctName = rs.getString("acct_name");
double balance = rs.getDouble("balance");
String acctStatus = rs.getString("acct_status");
Acct acct_num = new Acct(acctNo, acctName, balance, acctStatus);
accts.add(acct_num);
}
if (ps != null) {
ps.close();
}
DBUtity.closeConnection(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accts;
}
/**
* 添加
*
* @param acct
* @return int
* @throws SQLException
*/
public int addAcct(Acct acct) throws SQLException {
con = DBUtity.openConnection();
String sql = "insert into acct values (?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, acct.getAcctNo());
ps.setString(2, acct.getAcctName());
ps.setString(3, acct.getAcctStatus());
ps.setString(4, "2017-06-20");
ps.setDouble(5, acct.getBalance());
System.out.println("sql语句:" + sql);
System.out.println(acct.toString());
int rs = ps.executeUpdate();
System.out.println("sql ------------");
if (rs != 0) {
return rs;
}
if (ps != null) {
ps.close();
}
DBUtity.closeConnection(con);
return rs;
}
/**
* 删除
* @param acct
* @return
* @throws SQLException
*/
public int addDelete(Acct acct) throws SQLException {
con = DBUtity.openConnection();
String sql = "delete from acct where acct_no=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, acct.getAcctNo());
System.out.println("sql语句:" + sql);
System.out.println(acct.toString());
int rs = ps.executeUpdate();
System.out.println("sql ------------");
if (rs != 0) {
return rs;
}
if (ps != null) {
ps.close();
}
DBUtity.closeConnection(con);
return rs;
}
/**
* 修改
* @param acct
* @return
* @throws SQLException
*/
public int updateAcct(Acct acct) throws SQLException {
con = DBUtity.openConnection();
String sql = "update acct set acct_name=?,acct_status=?,balance=? where acct_no=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, acct.getAcctName());
ps.setString(2, acct.getAcctStatus());
ps.setDouble(3, acct.getBalance());
ps.setString(4, acct.getAcctNo());
System.out.println("sql语句:" + sql);
System.out.println(acct.toString());
int rs = ps.executeUpdate();
System.out.println("sql ------------");
if (rs != 0) {
return rs;
}
if (ps != null) {
ps.close();
}
DBUtity.closeConnection(con);
return rs;
}
}
<file_sep>package svlt;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloWorld extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("Learn14.HelloWorld.init()");
}
public HelloWorld() {
super();
System.out.println("Learn14.HelloWorld.HelloWorld()");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Learn14.HelloWorld.doPost()");
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Learn14.HelloWorld.doPut()");
}
@Override
public void destroy() {
System.out.println("Learn14.HelloWorld.destroy()");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // TODO Auto-generated method stub
// System.out.println("Learn14.HelloWorld.service()");
PrintWriter out = resp.getWriter();
// // doPut(req, resp);
// // doPost(req, resp);
// // resp.sendRedirect("http://www.baidu.com");
// Cookie[] ck = req.getCookies();
// if(ck != null){
// for(Cookie c:ck){
// System.out.println("name :" +c.getName() +"values :" +c.getValue());
// }
// }
//
// System.out.println("tag:----------------------------");
//// int times = 0;
//// if (ck != null) {
//// for (Cookie c : ck) {
//// if (c.getName().equals("currentTimes")) {
//// times = Integer.parseInt(c.getValue());
//// times++;
//// c.setValue(String.valueOf(times));
//// resp.addCookie(c);//!!
//// System.out.println(times + "");
//// }
//// }
//// }
// Cookie c = new Cookie("name", "qbq");
// Cookie c1 = new Cookie("isLogin", "true");
// c.setMaxAge(10);
// c1.setMaxAge(10);
//// if (times == 0) {
//// Cookie c2 = new Cookie("currentTimes", "1");
//// resp.addCookie(c2);
//// }
// resp.addCookie(c);
// resp.addCookie(c1);
//获取请求数据
String content = "test!!!!";
//保存到request
req.setAttribute("content","Content: "+content);
//转发
System.out.println("keyizhuanfa ");
req.getRequestDispatcher("META-INF/test.jsp").forward(req,resp);
// out.println("<h1><a href=\"hello\"/>Hello World</h1>");
}
// @Override
// protected void service(HttpServletRequest req, HttpServletResponse reqs)
// throws ServletException, IOException {
// // TODO Auto-generated method stub
// ServletOutputStream out=reqs.getOutputStream();
//// out.println("<html>");
//// out.println("<body>");
//// out.println("<h1>Hello,World!</h1>");
//// out.println("<h2>I am a boy!</h2>");
//// out.println("</body>");
//// out.println("</html>");
// out.println("Hello,World!");
// }
}
<file_sep>package com.qbq.packagescan;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Logger;
public class PackageScanUtils {
public Set<Class<?>> getClassesInPackage(String pack, boolean scanjar)
{
Set classesSet = new LinkedHashSet();
if ((pack == null) || ("".equals(pack.trim()))) {
lwlException("the package [ " + pack + " ] not exists");
return classesSet;
}
boolean recursive = true;
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
try
{
Enumeration dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
if (!dirs.hasMoreElements()) {
lwlException("the package [ " + pack + " ] not exists");
return classesSet;
}
while (dirs.hasMoreElements())
{
URL url = (URL)dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
Logger.getLogger("lwl").info("file(class) type to be scanned");
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classesSet);
} else if (("jar".equals(protocol)) && (scanjar))
{
Logger.getLogger("lwl").info("jar type to be scanned");
JarFile jar = ((JarURLConnection)url.openConnection()).getJarFile();
Enumeration entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry entry = (JarEntry)entries.nextElement();
String name = entry.getName();
if (name.charAt(0) == '/') {
name = name.substring(1);
}
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
if (idx != -1) {
packageName = name.substring(0, idx).replace('/', '.');
}
if ((idx != -1) || (recursive))
{
if ((name.endsWith(".class")) && (!entry.isDirectory()))
{
String className = name.substring(packageName.length() + 1, name.length() - 6);
classesSet.add(Thread.currentThread().getContextClassLoader()
.loadClass(packageName + '.' + className));
}
}
}
}
}
}
}
catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return classesSet;
}
private void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes)
{
File dir = new File(packagePath);
if ((!dir.exists()) || (!dir.isDirectory())) {
Logger.getLogger("lwl").info("异常信息 Exception " + packageName + " 可能不存在");
return;
}
File[] dirfiles = dir.listFiles(new FileFilter()
{
public boolean accept(File file)
{
return ((recursive) && (file.isDirectory())) ||
(file.getName().endsWith(".class"));
}
});
try
{
for (File file : dirfiles)
{
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(
packageName + "." + file.getName(),
file.getAbsolutePath(), recursive, classes);
}
else {
String className = file.getName().substring(0, file.getName().length() - 6);
classes.add(Thread.currentThread().getContextClassLoader()
.loadClass(packageName + '.' + className));
}
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
private void lwlException(String dec)
{
try {
throw new Exception(dec);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package svlt;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "AcctManagerSvlt", urlPatterns = {"/acct"})
public class AcctManagerSvlt extends HttpServlet {
/**
* trans_code:query 精确查询 add 添加 del 删除 edit 修改
*/
private static final long serialVersionUID = -5115091395802691609L;
AcctManager acctmng = null;
/**
* 空参数构造
*
*/
public AcctManagerSvlt() {
acctmng = new AcctManager();
}
/**
* doGet()方法
*
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 准备数据
/**
* trans_code:query 精确查询 add 添加 del 删除 edit 修改
*/
String transCode = req.getParameter("trans");
if (transCode == null || "".equals(transCode)) {
RequestDispatcher dispatcher = req.getRequestDispatcher("Err.jsp");
dispatcher.forward(req, resp);
return;
}
if (transCode.equals("add")) {
System.out.println("add...");
doAdd(req, resp);
} else if (transCode.equals("del")) {
doDel(req, resp);
} else if (transCode.equals("edit")) {
doEdit(req, resp);
} else if (transCode.equals("query")) {
String query_type = req.getParameter("hazys");
if (query_type == null)
query_type = "";
if (query_type.equals("on")) {
doHazyQuery(req, resp);
} else {
doQuery(req, resp);
}
} else {
RequestDispatcher dispatcher = req.getRequestDispatcher("Err.jsp");
dispatcher.forward(req, resp);
return;
}
}
/**
*
* doPost()方法
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
/**
* 模糊查询
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void doHazyQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String acctNo = req.getParameter("acctNo");
String acctName = req.getParameter("acctName");
String balance = req.getParameter("balance");
String acctStatus = req.getParameter("acctStatus");
if (acctNo == null)
acctNo = "";
if (acctName == null)
acctName = "";
if (balance == null)
balance = "";
if (acctStatus == null)
acctStatus = "";
Double Bal = (!balance.equals("")) ? Double.parseDouble(balance) : 0.00;
Acct a = new Acct(acctNo, acctName, Bal, acctStatus);
List<Acct> accts = acctmng.queryHazy(a);
req.setAttribute("accts", accts);
// 实现转发
RequestDispatcher dispatcher = req.getRequestDispatcher("/AcctMain.jsp");
dispatcher.forward(req, resp);
}
/**
* 精确查询
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void doQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String acctNo = req.getParameter("acctNo");
String acctName = req.getParameter("acctName");
String balance = req.getParameter("balance");
String acctStatus = req.getParameter("acctStatus");
if (acctNo == null)
acctNo = "";
if (acctName == null)
acctName = "";
if (balance == null)
balance = "";
if (acctStatus == null)
acctStatus = "";
Double Bal = (!balance.equals("")) ? Double.parseDouble(balance) : 0.00;
Acct a = new Acct(acctNo, acctName, Bal, acctStatus);
List<Acct> accts = acctmng.selectAcctByno(a);
req.setAttribute("accts", accts);
// req.setAttribute("accts", acctInfo);
// 实现转发
RequestDispatcher dispatcher = req.getRequestDispatcher("AcctMain.jsp");
dispatcher.forward(req, resp);
}
/**
* 添加
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String acctNo = req.getParameter("acctNo");
String acctName = req.getParameter("acctName");
String balance = req.getParameter("balance");
String acctStatus = req.getParameter("acctStatus");
if (acctNo == null)
acctNo = "";
if (acctName == null)
acctName = "";
if (balance == null)
balance = "";
if (acctStatus == null)
acctStatus = "";
Double Bal = (!balance.equals("")) ? Double.parseDouble(balance) : 0.00;
Acct a = new Acct(acctNo, acctName, Bal, acctStatus);
try {
int rs = acctmng.addAcct(a);
// 实现转发
String url = "";
if (rs > 0)
url = "AcctMain.jsp";
else
url = "Err.jsp";
req.getRequestDispatcher(url).forward(req, resp);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* delete 删除
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void doDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String acctNo = req.getParameter("acctNo");
if (acctNo == null)
acctNo = "";
Acct a = new Acct(acctNo, "", 0.00, "");
try {
int rs = acctmng.addDelete(a);
// 实现转发
String url = "";
if (rs > 0)
url = "AcctMain.jsp";
else
url = "Err.jsp";
req.getRequestDispatcher(url).forward(req, resp);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 修改
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void doEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String acctNo = req.getParameter("acctNo");
String acctName = req.getParameter("acctName");
String balance = req.getParameter("balance");
String acctStatus = req.getParameter("acctStatus");
if (acctNo == null)
acctNo = "";
if (acctName == null)
acctName = "";
if (balance == null)
balance = "";
if (acctStatus == null)
acctStatus = "";
Double Bal = (!balance.equals("")) ? Double.parseDouble(balance) : 0.00;
Acct a = new Acct(acctNo, acctName, Bal, acctStatus);
try {
int rs = acctmng.updateAcct(a);
// 实现转发
String url = "";
if (rs > 0)
url = "AcctMain.jsp";
else
url = "Err.jsp";
req.getRequestDispatcher(url).forward(req, resp);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
16cd475400fb73707684543967fe8a6186749517
|
[
"Java"
] | 6
|
Java
|
QianBingqiao/jspServlet
|
21ffbb520ca3b307fb5da631d5b91dcbce9f2047
|
d52e9491b8709897931db8cb16e6bb32cae1745b
|
refs/heads/master
|
<repo_name>lixuanye1994/Minecraft-Plugin<file_sep>/README.md
# Minecraft-Plugin
服务端插件开发学习 </br>
文件结构:</br>
...</br>
-src</br>
-Testplugin.java //主类</br>
-EventHandle.java //监听事件</br>
...
<file_sep>/EventHandle.java
package codetest;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
/**
* EventHandle 接口为 Listener 用于监听服务器玩家情况
* @author lee
*/
public class EventHandle implements Listener {
//将主程序Testplugin.java设置成插件,实例化
private final Testplugin plugin;
public EventHandle(Testplugin instance) {
plugin = instance;
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
// 监听玩家加入游戏后服务端执行操作
//游戏界面
event.setJoinMessage(event.getPlayer().getName()+"进入游戏了,快跑吧!");
//后台日志
plugin.getLogger().info(event.getPlayer().getName() + " 进入游戏了,快跑吧 :D");
}
}
|
3a5c2967f4e7eb03950ba69a1aed47966d640805
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
lixuanye1994/Minecraft-Plugin
|
e9fa005e7c1d646d7217e5bfcf61de95c31d5b24
|
799395ba19b18f3c600919786bbf467ee794eb9a
|
refs/heads/main
|
<file_sep>#include <iostream>
#include "CBofCB.h"
using namespace std;
CBofCB::CBofCB()
{
//m_obCapacity == 7
//m_buffers[7] = {};
m_buffers[0] = new InnerCB(10);
m_obSize = 1;
m_oldest = 0; //start
m_newest = 0; //end
}
/*
CBOfCB::CBofCB(const CBofCB& other)
{
}
*/
CBofCB::~CBofCB()
{
/*
for (int i = 0; i < m_obCapacity ; i++)
{
delete m_buffers[i];
}
delete [] m_buffers;
*/
}
void CBofCB::enqueue(int data)
{
//Adds an object to the currently pointed array.
if (isFull())
{
//throw "Congrats, you literally created more arrays than God.";
}
if (m_buffers[m_newest]->isFull())
{
m_newest++;
if (m_newest >= m_obCapacity) //NOTE!!!: May be m_obCapacity - 1. Check back
{
m_newest = 0;
m_buffers[m_newest] = new InnerCB(2*(m_buffers[m_obCapacity-1]->capacity()));
}
else{
m_buffers[m_newest] = new InnerCB(2*(m_buffers[m_newest-1]->capacity()));
}
m_obSize++;
}
else {
//m_newest++;
}
m_buffers[m_newest]->enqueue(data);
}
int CBofCB::dequeue()
{
int returnable = -1;
if (isEmpty())
{
throw "Error: Something goofed. (ERR_CODE 13370)";
}
else {
//m_oldest++;
/*
if (m_buffers[m_oldest]->isEmpty())
{
m_oldest++;
if (m_oldest >= m_obCapacity) //NOTE!!!: Check here, too.
{
m_oldest = 0;
delete m_buffers[m_obCapacity];
}
else {
delete m_buffers[m_oldest-1];
}
m_obSize--;
}
else {
//m_oldest++;
}
*/
if (m_buffers[m_oldest]->size() == 1)
{
returnable = m_buffers[m_oldest]->dequeue();
m_oldest++;
if (m_oldest >= m_obCapacity) //NOTE!!!: Check here, too.
{
m_oldest = 0;
delete m_buffers[m_obCapacity];
}
else {
delete m_buffers[m_oldest-1];
}
m_obSize--;
return returnable;
}
}
returnable = m_buffers[m_oldest]->dequeue();
return returnable;
}
bool CBofCB::isFull()
{
if (m_obSize >= m_obCapacity)
{
return true;
}
else {
return false;
}
}
bool CBofCB::isEmpty()
{
if (m_obSize == 0)
{
return true;
}
else {
return false;
}
}
int CBofCB::size()
{
//idea: subtract max. amount from c whenever it overflows
int totesSize = 0;
if (m_oldest <= m_newest)
{
for (int c = m_oldest; c <= m_newest; c++) //ha, c++. how meta.
{
totesSize = totesSize + m_buffers[c]->size();
}
}
if (m_oldest > m_newest)
{
int c = m_oldest;
do
{
totesSize = totesSize + m_buffers[c]->size();
c++;
if (c >= m_obCapacity)
{
c = 0;
}
}while (c != m_newest+1);
}
return totesSize;
}
void CBofCB::dump()
{
if (m_oldest <= m_newest)
{
for (int c = m_oldest; c <= m_newest; c++)
{
cout << "array " << c << ":" << endl;
m_buffers[c]->dump();
cout << endl;
}
}
if (m_oldest > m_newest)
{
int c = m_oldest;
while (c != m_newest)
{
cout << "array " << c << ":" << endl;
m_buffers[c]->dump();
cout << endl;
c++;
if (c >= m_obCapacity)
{
c = 0;
}
}
}
}
<file_sep>#include <iostream>
#include "InnerCB.h"
using namespace std;
InnerCB::InnerCB(int n)
{
m_buffer = new int [n]; //makes the array!
m_size = 0; //current number of elements in queue
m_start = 0; //start of the queue. Pop values from here.
m_end = -1; //end of the queue. New values go here.
m_capacity = n; //size of the array/ largest size of the queue
}
InnerCB::InnerCB(const InnerCB& other)
{
m_buffer = other.m_buffer;
m_size = other.m_size;
m_start = other.m_start;
m_end = other.m_end;
m_capacity = other.m_capacity;
}
InnerCB::~InnerCB()
{
//delete [] m_buffer;
}
void InnerCB::enqueue (int data)
{
//if(isEmpty())
// m_start++;
if (isFull())
{
}
//throw "Error: Something goofed. (ERR_CODE 60025)";
if (m_end == m_capacity -1)
{
m_end = 0;
}
else {
m_end++;
}
m_buffer[m_end] = data;
m_size++;
//cout << "Adding [" << m_buffer[m_end] << "] to the queue." << endl;
}
int InnerCB::dequeue ()
{
if (isEmpty())
{
throw "ERR: Cannot remove the empty queue!";
}
//throw "Error: Something goofed. (ERR_CODE 95483)";
int returnable = m_buffer[m_start];
// m_start++;
if (m_start == m_capacity-1)
{
m_start = 0;
}
else {
m_start++;
}
m_size--;
//cout << "Removing [" << returnable << "] from the queue." << endl;
return returnable;
}
bool InnerCB::isFull ()
{
if (m_size == m_capacity)
return true;
return false;
}
bool InnerCB::isEmpty ()
{
if (m_size == 0)
return true;
return false;
}
int InnerCB::capacity ()
{
return m_capacity;
}
int InnerCB::size ()
{
return m_size;
}
//const InnerCB& operator=(const InnerCB& rhs)
//{
//come back to this
//}
void InnerCB::dump ()
{
/*
cout << "Your face is a dump." << endl;
cout << "OHHHHHH! YOU JUST GOT TOLD" << endl;
*/
//cout << "\"BEGIN\"" << endl;
for (int ct = 0; ct < m_capacity; ct++)
{
if (ct == m_start)
cout << " (ST)";
if (ct == m_end)
cout << " (EN)";
cout << "[" << ct << "] " << m_buffer[ct] << " || ";
}
cout << endl;
}
<file_sep><h2> cmsc341-proj1 </h2>
<h3> CMSC 341 Data Structures - Project #1 </h3>
Fall 2018 UMBC CMSC 341 Data Structures:
Project #1
`Insert Brief Desc. Here`
|
f952fbacfd6823a44af78cac287f51d36e2179d2
|
[
"Markdown",
"C++"
] | 3
|
C++
|
dywaza/cmsc341-proj1
|
9bf69b1474f5f4b3eebea051340d48e0115478e1
|
3fd0e135353cc8efaafe46d52d172d03e24a10d9
|
refs/heads/main
|
<repo_name>Magnetar111/project-0<file_sep>/index.php
<?php
if (array_key_exists("getotp",$_POST)) {
// echo "Ready for otp";
if (!$_POST["email"]) {
$eerror="Email is required";
}else{ $code=rand();
session_start();
$_SESSION[$vcode] =$code;
$emailTo=$_POST['email'];
$Subject="Email OTP";
$body="Your One Time Password is: ".$code;
$header="Verify your email";
if(mail($emailTo,$Subject,$body,$header)){
$success='mail sent sucessfully.';
}
else{
$error='mail did not sent';
}
}
}
if(array_key_exists("submit",$_POST)){
// echo "Ready for verify otp";
if (!$_POST["email"]) {
$eerror="Email is required";
}
if (!$_POST["otp"]) {
$oerror="Fill the OTP";
}else{
// echo "Email Verified successfully";
session_start();
$code=$_SESSION[$vcode];
if ($_POST["otp"]==$code) {
$success="Mail verfied";
}else{
$oerror= "Your otp is invalid";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>email_otp_verification</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style type="text/css">
.error{
color:red;
font-weight:bold;
}
.success{
color:green;
font-weight:bold;
}
</style>
</head>
<body>
<div class="container">
<form method="post">
<h2>Email verification form</h2>
<div class="success"><?php echo $success; ?></div>
<div class="error"><?php echo $eerror; ?></div>
<div class="align" id="email">
<label>Email Id</label>
<input type="email" name="email" class="input" placeholder="your email id" value="<?php echo $_POST['email'] ?>">
</div>
<div class="error"><?php echo $oerror; ?></div>
<div class="align" id="otp">
<label>Enter OT P</label>
<input type="text" name="otp" class="input" placeholder="enter your otp here">
</div>
<button type="submit" name="getotp">Get OTP</button>
<div class="btn" id="submit-div">
<input type="submit" name="submit" class="btni">
</div>
</form>
</div>
</body>
</html>
|
9d0367414276b17504569d0f2af9b7dcdd2d2f03
|
[
"PHP"
] | 1
|
PHP
|
Magnetar111/project-0
|
71f3b3b7b0d511774bb3241375a8c592b26b45e2
|
daccf29d38bcd1c99f3e474409349ad7a7e91117
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <list>
#include <time.h>
#define MAXNUM 99
bool PrimeNum(std::list<int> prime, int v){
std::list<int>::iterator ito = prime.begin();
while ((*ito) <= v){
if (ito == prime.end()){ return false; }
if ((*ito) < v){ ito++; }
else if ((*ito) == v){ return true; }
}
return false;
}
bool TwoAddNumNotPrime(std::list<int> prime, int num){
std::list<int>::iterator ito = prime.begin();
for (;; ito++){
int v = num - (*ito);
if (v < (*ito)){ return true; }
if (PrimeNum(prime, v)){ return false; }
}
}
bool JudgeNumInList(std::list<int> &listnum, int v){
std::list<int>::iterator ito = listnum.begin();
while (ito != listnum.end()){
if ((*ito) == v){
return true;
}
else if ((*ito) > v){
return false;
}
ito++;
}
return false;
}
void delete2prime(std::list<int> &addnum, std::list<int>&mulnum, std::list<int> &prime){
std::list<int> TwoPrimeAdd;
std::list<int> TwoPrimeMul;
for (std::list<int>::iterator ito1 = prime.begin(); (*ito1) < MAXNUM; ito1++){
for (std::list<int>::iterator ito2 = ito1; (*ito2) < MAXNUM; ito2++){
TwoPrimeAdd.push_back((*ito1) + (*ito2));
TwoPrimeMul.push_back((*ito1) * (*ito2));
}
}
TwoPrimeAdd.sort();
TwoPrimeAdd.unique();
std::list<int>::iterator twomul;
for (int num1 = 2; num1 < MAXNUM; num1++){
/*bool pri = JudgeNumInList(prime, num1);
if (pri){
for (int num2 = num1 + 1; num2 < MAXNUM; num2 ++){
if (!JudgeNumInList(prime, num2)){
mulnum.push_back(num1 * num2);
}
}
}
else{
for (int num2 = num1; num2 < MAXNUM; num2++){
mulnum.push_back(num2 * num1);
}
}*/
twomul = TwoPrimeMul.begin();
for (int num2 = num1; num2 < MAXNUM; num2++){
if (twomul == TwoPrimeMul.end()){ twomul--; }
else if ((num1*num2) == (*twomul)){ twomul++; continue; }
else if ((num1*num2)>(*twomul)){ twomul++; num2--; }
else{ mulnum.push_back((num1*num2)); }
}
}
mulnum.sort();
std::list<int>::iterator twoadd = TwoPrimeAdd.begin();
for (int num = 4; num < 2 * MAXNUM; num++){
if (twoadd == TwoPrimeAdd.end()){ twoadd--; }
if (num == (*twoadd)){ twoadd++; continue; }
else{ addnum.push_back(num); }
}
std::list<int> AllPrimePos;
twoadd = TwoPrimeAdd.begin();
while (twoadd != TwoPrimeAdd.end()){
for (int v1 = (*twoadd)/2; v1 > 1; v1--){
int v2 = *twoadd - v1;
if (v2 > MAXNUM){ break; }
AllPrimePos.push_back(v2*v1);
}
twoadd++;
}
AllPrimePos.sort();
std::list<int>::iterator alp = AllPrimePos.begin();
for (twomul = mulnum.begin(); twomul != mulnum.end();){
if (alp == AllPrimePos.end()){ break; }
if ((*twomul) < (*alp)){ twomul++; }
else if ((*twomul)>(*alp)){ alp++; }
else
{
twomul = mulnum.erase(twomul);
alp++;
}
}
for (std::list<int>::iterator ito1 = mulnum.begin(); ito1 != mulnum.end(); ){
std::list<int>::iterator ito2 = ito1;
ito2++;
if (ito2 == mulnum.end()){ break; }
bool same = false;
while ((*ito1) == (*ito2)){ ito2 = mulnum.erase(ito2); same = true;}
if (same){ ito1 = mulnum.erase(ito1); }
else{ ito1++; }
}
}
void OnlyOnePosInAdd(std::list<int> &addnum, std::list<int>&mulnum, std::list<int> &prime){
std::list<int>::iterator ito = addnum.begin();
while (ito != addnum.end()){
int c = 0;
int mi, ma;
for (int i = 2; i < (*ito) / 2; i++){
int j = (*ito) - i;
if (JudgeNumInList(mulnum, i*j)){
c++;
if (c > 1){ break; }
mi = i < j ? i : j;
ma = i < j ? j : i;
}
}
if (c == 1){ std::cout << mi << " " << ma << " " << std::endl; }
if (c != 1){ ito = addnum.erase(ito); }
else{ ito++; }
}
}
int main(){
int s[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
std::list<int> prime;
std::list<int> addnum;
std::list<int> mulnum;
for (int i = 0; i < 10; i++){ prime.push_back(s[i]); }
/*for (int i = 4; i < 2 * MAXNUM; i++){ addnum.push_back(i); }
for (int i = 2; i < MAXNUM; i++){
for (int j = i; j < MAXNUM; j++){
mulnum.push_back(i*j);
}
}
mulnum.sort();
mulnum.unique();*/
long st, en;
st = clock();
for (int num = 31; num < MAXNUM*MAXNUM; num++){
std::list<int>::iterator ito = prime.begin();
bool pri = true;
while (ito!=prime.end())
{
int ne = num / (*ito);
if (ne < (*ito)){ break; }
if (ne * (*ito) == num){
pri = false;
break;
}
ito++;
}
if (pri){ prime.push_back(num); }
}
en = clock();
std::cout << "prime:" << en - st << std::endl;
st = clock();
//first sentence
delete2prime(addnum, mulnum, prime);
en = clock();
std::cout << "p1:" << en - st << std::endl;
//st = clock();
////second sentence
//OnlyOnePossible(addnum, mulnum, prime);
//en = clock();
//std::cout << "p2:" << en - st << std::endl;
st = clock();
//third sentence
OnlyOnePosInAdd(addnum, mulnum, prime);
en = clock();
std::cout << "p3:" << en - st << std::endl;
/*std::list<int> first;
first = FirstAlgothm(prime);
std::list<int> second;
second = SecondAlgothm(prime);
std::list<int>::iterator ito1 = first.begin();
std::list<int>::iterator ito2 = second.begin();
for (int i = 4; i < MAXNUM; i++){
if (TwoMulNumOnlyOnePos(prime, i)){
std::cout << i << " " << std::endl;
}
}*/
return 0;
}
<file_sep>//@author ccyyhlg
#define NORMAL_TYPE 0 //正常牌型
#define THREEFLUSH 1 //三同花
#define THREESTRIGHT 2 //三顺子
#define SIXPAIRS 3 //6对
#define FIVEPAIRSANDTHREE 4 //5对3条
#define FOUR_THREE 5 //4组三条
#define ALLSAMECOLOR 6 //凑一色
#define ALLLOW 7 //全小
#define ALLHIGH 8 //全大
#define THREE_BOMB 9 //三分天下(4个炸)
#define THREE_STRIGHTFLUSH 10 //三同花顺
#define ROYALCARD 11 //十二皇族
#define LOWDRAGON 12 //一条龙
#define BLACKDRAGON 13 //青龙
#define CT_INVALIDCARD 0x00 //相公
#define CT_HIGHCARD 0x01 //乌龙
#define CT_ONEPAIR 0x02 //对子
#define CT_TWOPAIRS 0x03 //两对
#define CT_THREE 0x04 //三张
#define CT_STRIGHT 0x05 //顺子
#define CT_FLUSH 0x06 //同花
#define CT_FULLHOUSE 0x07 //葫芦
#define CT_FOUR 0x08 //铁支(炸)
#define CT_FLUSHSTRIGHT 0x09 //同花顺
#define CT_THREE_FIRST 0x0a //三冲
#define CT_FULLHOUSE_MID 0x0b //中墩葫芦
#define SELECTTHREE(st) for(int va1=14;va1>1;va1--){ \
for (int j = 0; j < 4; j++){\
if ((h[va1] & C34[j]) == C34[j]){\
int alco = C34[j]; \
std::list<BYTE> ust; \
int col = 0; \
while (alco){\
if (alco % 2 != 0){ ust.push_back((col << 4) + (va1 == 14 ? 1 : va1)); } \
col++; \
alco = alco >> 1; \
} \
DeleteUsedCards(card, ust, CurSeq, Layer, st);
#define ENDSELECTTHREE(st) RecallCards(card,ust,CurSeq, Layer, st);}}}
#define SELECTPAIR(st) for(int va2=14;va2>1;va2--){ \
for (int y = 0; y < 6; y++){\
if ((h[va2] & C24[y]) == C24[y] && va2 != va1){\
int allco = C24[y]; \
std::list<BYTE> ustw; \
int co = 0; \
while (allco){\
if (allco % 2 != 0){ ustw.push_back((co << 4) + (va2 == 14 ? 1 : va2)); } \
co++; \
allco = allco >> 1; \
} \
DeleteUsedCards(card, ustw, CurSeq, Layer, st);
#define ENDSELECTPAIR(st) RecallCards(card,ustw,CurSeq, Layer, st);}}}
void DeleteUsedCards(std::list<BYTE> &cards, std::list<BYTE> us, BYTE Cur[], int La, int ha){
int st = 0;
if (La == 1){ st = 8; }
else if (La == 2){ st = 3; }
else { st = 0; }
int i = st + ha;
for (std::list<BYTE>::iterator ui = us.begin(); ui != us.end(); ui++){
cards.remove(*ui);
Cur[i++] = *ui;
}
for (; i < (La == 3 ? st + 3 : st + 5);){
Cur[i++] = 0;
}
}
void RecallCards(std::list<BYTE> &cards, std::list<BYTE> us, BYTE Cur[], int La, int ha){
for (std::list<BYTE>::iterator ui = us.begin(); ui != us.end(); ui++){
cards.push_back(*ui);
}
int st = 0;
if (La == 1){ st = 8; }
else if (La == 2){ st = 3; }
else { st = 0; }
st += ha;
memset(Cur + st, 0, (La < 3 ? 5 - ha : 3 - ha));
}
void CGameLogic::BestSequence(std::list<BYTE> &card, unsigned int We[], int Layer, int type, BYTE CurSeq[], BYTE BestSeq[], unsigned int BestWe[]){
int TexPos[] = { 15873, 7936, 3968, 1984, 992, 496, 248, 124, 62, 8223 };
std::list<BYTE>::iterator ic = card.begin();
int Str[4];
memset(Str, 0, sizeof(int)* 4);
int ExStr = 0;
int h[15];
memset(h, 0, sizeof(int)* 15);
int C34[] = { 7, 11, 13, 14 };
int C24[] = { 3, 5, 6, 9, 10, 12 };
for (; ic != card.end(); ic++){
int col = *ic >> 4;
int val = *ic % 16;
if (val == 1){ val = 14; }
h[val] += 1 << col;
if (val == 14){ h[1] += 1 << col; }
Str[col] += 1 << (val - 1);
if (val == 14){ Str[col] += 1; }
if ((ExStr & (1 << (val - 1))) == 0){
ExStr += 1 << (val - 1);
if (val == 14){ ExStr++; }
}
}
//同花顺
if (type > 8 && Layer < 3){
for (int i = 0; i < 4; i++){
for (int j = 0; j < 10; j++){
if ((Str[i] & TexPos[j]) == TexPos[j]){
std::list<BYTE> us;
for (int v = 14 - j; v > 14 - j - 5; v--){
us.push_back((i << 4) + (v == 14 ? 1 : v));
}
DeleteUsedCards(card, us, CurSeq, Layer, 0);
BestSequence(card, We, Layer + 1, 9, CurSeq, BestSeq, BestWe);
return;
}
}
}
}
//铁支
if (type > 7 && Layer < 3){
for (int i = 14; i > 1; i--){
if (h[i] == 15){
std::list<BYTE> us;
for (int c = 0; c < 4; c++){
us.push_back((c << 4) + i);
}
DeleteUsedCards(card, us, CurSeq, Layer, 0);
BestSequence(card, We, Layer + 1, 8, CurSeq, BestSeq, BestWe);
return;
}
}
}
//葫芦
if (type > 6 && Layer < 3){
SELECTTHREE(0)
SELECTPAIR(3)
BestSequence(card, We, Layer + 1, 7, CurSeq, BestSeq, BestWe);
ENDSELECTPAIR(3)
ENDSELECTTHREE(0)
}
//同花
if (type > 5 && Layer < 3){
for (int i = 0; i < 4; i++){
if (GetCount(Str[i]) >= 5){
int cm = Str[i] % (1 << 13);
BYTE sscards[10] {};
int cc = 1;
int k = 0;
while (cm){
if (cm % 2 != 0){ sscards[k++] = (i << 4) + cc; }
cm = cm >> 1;
cc++;
}
int in[5] {0, 1, 2, 3, 4};
std::list<BYTE> us;
while (in[4] < k){
if (in[0] == in[1]){
in[0] = 0;
in[1]++;
}
if (in[1] == in[2]){
in[1] = 1;
in[2]++;
}
if (in[2] == in[3]){
in[2] = 2;
in[3]++;
}
if (in[3] == in[4]){
in[3] = 3;
in[4]++;
if (in[4] == k){ break; }
}
us.clear();
for (int ii = 0; ii < 5; ii++){
us.push_back(sscards[in[ii]]);
}
DeleteUsedCards(card, us, CurSeq, Layer, 0);
BestSequence(card, We, Layer + 1, 6, CurSeq, BestSeq, BestWe);
RecallCards(card, us, CurSeq, Layer, 0);
in[0]++;
}
}
}
}
//顺子
if (type > 4 && Layer < 3){
for (int j = 0; j < 10; j++){
if ((ExStr & TexPos[j]) == TexPos[j]){
int v = 14 - j;
BYTE stcards[5][3] {};
int Count = 1;
//设置卡
for (int i = 0; i < 5; i++){
int cc = 0;
for (int k = 0; k < 4; k++){
if (((1 << k) & h[v - i]) == (1 << k)){
stcards[i][cc++] = (k << 4) + ((v - i) == 14 ? 1 : v - i);
}
}
}
int in[5] {};
std::list<BYTE> us;
while (stcards[0][in[0]] != 0){
if (stcards[4][in[4]] == 0){
in[4] = 0;
in[3]++;
}
if (stcards[3][in[3]] == 0){
in[3] = 0;
in[2]++;
}
if (stcards[2][in[2]] == 0){
in[2] = 0;
in[1]++;
}
if (stcards[1][in[1]] == 0){
in[1] = 0;
in[0]++;
}
if (stcards[0][in[0]] == 0){
break;
}
us.clear();
for (int ii = 0; ii < 5; ii++){
us.push_back(stcards[ii][in[ii]]);
}
DeleteUsedCards(card, us, CurSeq, Layer, 0);
BestSequence(card, We, Layer + 1, 5, CurSeq, BestSeq, BestWe);
RecallCards(card, us, CurSeq, Layer, 0);
in[4]++;
}
return;
}
}
}
//三张
if (type > 3){
SELECTTHREE(0)
BestSequence(card, We, Layer + 1, 4, CurSeq, BestSeq, BestWe);
RecallCards(card, ust, CurSeq, Layer, 0);
return;
}
}}
}
//两对
if (type > 2 && Layer < 3){
for (int i = 14; i > 1; i--){
for (int j = 0; j < 6; j++){
if (h[i] == C24[j]){
std::list<BYTE> us;
int cc = 0;
int cm = C24[j];
while (cm){
if (cm % 2 != 0){
us.push_back((cc << 4) + (i == 14 ? 1 : i));
}
cc++;
cm = cm >> 1;
}
for (int x = 2; x < i; x++){
for (int y = 0; y < 6; y++){
if (h[x] == C24[y]){
int cc2 = 0;
int cm2 = C24[y];
while (cm2){
if (cm2 % 2){
us.push_back((cc2 << 4) + (x == 14 ? 1 : x));
}
cc2++;
cm2 = cm2 >> 1;
}
DeleteUsedCards(card, us, CurSeq, Layer, 0);
BestSequence(card, We, Layer + 1, 3, CurSeq, BestSeq, BestWe);
RecallCards(card, us, CurSeq, Layer, 0);
return;
}
}
}
}
}
}
}
//对子
if (type > 1 && Layer < 4){
int va1 = 1;
SELECTPAIR(0)
BestSequence(card, We, Layer + 1, 2, CurSeq, BestSeq, BestWe);
RecallCards(card, ustw, CurSeq, Layer, 0);
return;
}}}
}
card.sort();
std::list<BYTE> us;
int inde[10] {};
int k = 0;
int sp = Layer;
while (sp < 4){
int st = 0;
if (sp == 2){ st = 3; }
std::list<BYTE>::iterator ito = card.begin();
BYTE inc = 0;
int v2 = 0;
for (; ito != card.end(); ito++){
int v1 = *ito & 0x0f;
if (v1 == 1){ v1 = 14; }
if (v1 > v2){
inc = *ito;
v2 = v1;
}
}
CurSeq[st] = inc;
card.remove(inc);
us.push_back(inc);
inde[k++] = st;
sp++;
}
for (int i = 0; i < 13; i++){
std::list<BYTE>::iterator ito = card.begin();
BYTE inc = 15;
int v2 = 15;
for (; ito != card.end(); ito++){
int v1 = *ito & 0x0f;
if (v1 == 1){ v1 = 14; }
if (v1 < v2){
inc = *ito;
v2 = v1;
}
}
if (CurSeq[i] == 0){
card.remove(inc);
us.push_back(inc);
CurSeq[i] = inc;
inde[k++] = i;
}
}
unsigned int Cur[3]{};
Cur[0] = CalcWeight(CurSeq, 3);
Cur[1] = CalcWeight(CurSeq + 3, 5);
Cur[2] = CalcWeight(CurSeq + 8, 5);
if ((Cur[0] + Cur[1] + Cur[2] > BestWe[0] + BestWe[1] + BestWe[2]) && JudgeOrder(Cur)){
memcpy(BestWe, Cur, sizeof(unsigned int)* 3);
memcpy(BestSeq, CurSeq, 13);
}
int xx = 0;
for (std::list<BYTE>::iterator ito = us.begin(); ito != us.end(); ito++, xx++){
card.push_back(*ito);
CurSeq[inde[xx]] = 0;
}
}
void CGameLogic::ForceSelectCard(BYTE cards[], unsigned int we[]){
std::list<BYTE> card;
BYTE BestSeq[13] {};
BYTE CurSeq[13] {};
for (int i = 0; i < 13; i++){
card.push_back(cards[i]);
}
memset(we, 0, sizeof(unsigned int)* 3);
BestSequence(card, we, 1, 9, CurSeq, BestSeq, we);
memcpy(cards, BestSeq, 13);
}
bool GetBitCount(int x,int pos[],int req){
int count = 0, index = 0;
int in = 0;
while (x){
if (x % 2 == 1){
count++;
pos[in++] = index;
}
x = x >> 1;
index++;
if (count == req && x > 0){ return false; }
}
if (count == req){ return true; }
return false;
}
void CGameLogic::VeryForceSelectCard(BYTE bCards[], unsigned int we[]){
BYTE copy[13];
memcpy(copy, bCards, 13);
int t1[285], t2[1287];
unsigned int CurWe3[285], CurWe5[1287];
int BestValSeq[3] = { 0, 0, 0 };
unsigned int BestWe = 0;
BYTE BestSeq[13];
memset(BestSeq, 0, 13);
//force t1,t2
int in = 0;
for (int i = 7; i < 0x1b01; i++){
int pos[3] {};
BYTE Se3[3] {};
if (GetBitCount(i, pos, 3)){
Se3[0] = copy[pos[0]];
Se3[1] = copy[pos[1]];
Se3[2] = copy[pos[2]];
t1[in] = i;
CurWe3[in++] = CalcWeight(Se3, 3);
}
}
in = 0;
for (int i = 31; i < 0x1f01; i++){
int pos[5];
BYTE Se5[5];
if (GetBitCount(i, pos, 5)){
Se5[0] = copy[pos[0]];
Se5[1] = copy[pos[1]];
Se5[2] = copy[pos[2]];
Se5[3] = copy[pos[3]];
Se5[4] = copy[pos[4]];
t2[in] = i;
CurWe5[in++] = CalcWeight(Se5, 5);
}
}
//not force
//-------------------------------------------------------------------------------------------------
//思路适用于任何组合问题(括号)
//思路2:pos 2 > 1即可 allva=0x1fff- t1[i] x[10]= {all pos} int va2=1<<x[i](i>4),va1=1<<x[i](i<5);
//int cc[5]={0,1,2,3,4};
//选5个位置 :while(va2>va1)
//if(cc[i]==cc[i+1])(i=0,1,2,3,4顺序) cc[i]=i; cc[i+1]++;
//va1+=1<<x[cc[i]];(i=0,1,2,3,4)
//va2=allva-va1;
//-------------------------------------------------------------------------------------------------
for (int i = 0; i < 285; i++){
int calccount = 0;
for (int j = 0; j < 1287; j++){
if ((t1[i] & t2[j]) == 0){
calccount++;
int va = 0x1fff - t1[i] - t2[j];
int k = 0;
for (int left = 0, right = 1286, mid = (left + right) / 2;; mid = (left + right) / 2){
if (va == t2[mid]){
k = mid;
break;
}
else if (va == t2[left]){
k = left;
break;
}
else if (va == t2[right]){
k = right;
break;
}
else if (va < t2[mid]){
right = mid;
}
else{
left = mid;
}
}
int timesj = 1, timesk = 1;
if ((CurWe5[j] >> 24) > 7){
timesj= 2;
}
if ((CurWe5[k] >> 24) > 7){
timesk = 2;
}
unsigned int CountWe = CurWe5[j] * timesj + CurWe5[k] * timesk + CurWe3[i];
if (CurWe5[j]>CurWe3[i] && CurWe5[k] > CurWe3[i] && CountWe > BestWe){
BestWe = CountWe;
BestValSeq[0] = t1[i];
if (CurWe5[j] > CurWe5[k]){
BestValSeq[1] = t2[k];
BestValSeq[2] = t2[j];
}
else{
BestValSeq[1] = t2[j];
BestValSeq[2] = t2[k];
}
}
}
if (calccount == 126){
break;
}
}
}
int val1 = 0, val2 = 3, val3 = 8;
for (int i = 0; i < 13; i++){
if (((1 << i)&BestValSeq[0]) != 0){
BestSeq[val1++] = copy[i];
}
else if (((1 << i)&BestValSeq[1]) != 0){
BestSeq[val2++] = copy[i];
}
else if (((1 << i)&BestValSeq[2]) != 0){
BestSeq[val3++] = copy[i];
}
}
we[0] = CalcWeight(BestSeq, 3);
we[1] = CalcWeight(BestSeq + 3, 5);
we[2] = CalcWeight(BestSeq + 8, 5);
memcpy(bCards, BestSeq, 13);
}
<file_sep>bool JudgeLegal(int iCard[], int in[], int now){
bool com = true;
for (int i = 0; i <= now; i++){
iCard[in[i]]--;
if (iCard[in[i]] < 0){ com = false; }
}
for (int i = 0; i <= now; i++){
iCard[in[i]]++;
}
return com;
}
int Times(int a, int b){
//a==1时自己是炸 早已返回
if (a == 2 && b == 1){ return 2; }
if (a == 3 && b == 1){ return 3; }
if (a == 4 && b == 1){ return 4; }
if (a == 2 && b == 2){ return 1; }
if (a == 3 && b == 2){ return 3; }
if (a == 4 && b == 2){ return 6; }
if (a == 3 && b == 3){ return 1; }
if (a == 4 && b == 3){ return 3; }
if (a == 4 && b == 4){ return 1; }
return 0;
}
int AIPlayer::GetTimes(int iCards[], int in[]){
int index1 = 1, index2 = 1;
if (in[0] == in[1]){ index1 = 2; }
if (in[0] == in[2]){ index1 = 3; index2 = iCards[in[0]]; }
if (in[1] == in[2]){ index2 = 2; }
if (index1 != 1 || index2 != 1){ return Times(iCards[in[0]], index1)*Times(iCards[in[2]], index2); }
int ti = Times(iCards[in[0]], 1)*Times(iCards[in[1]], 1)*Times(iCards[in[2]], 1);
//2 3 4 3 3 3
if (ti == 24 || ti == 27){ ti = ti - 4 + m_iColCount; }
//2 4 4 /2种同花
else if (ti == 32){ ti -= 2; }
//3 3 4
else if (ti == 36){
if (m_iColCount == 1){ ti -= 1; }
else if (m_iColCount == 3){ ti -= 2; }
else { ti -= 2; m_iMinus++; }
}
//3 4 4
else if (ti == 48){ ti -= 1; }
//4 4 4
else { ti -= 4; }
return ti;
}
void AIPlayer::OtherPosWeightCount(int Weight, int count){
int type = Weight >> 12;
int maxcard = (Weight >> 8) % 16;
OtherPlayer op = FirstTime;
if (type == 2 && maxcard <= 10){}
else if (type == 2 && maxcard <= 14){ op = Over10; }
else if (type == 3 && maxcard < 5){ op = OverA; }
else if (type == 3 && maxcard <= 13){ op = Pair5; }
else { op = PairK; }
for (int i = op + 1; i < AllPos; i++){
m_iOtherCount[i] += count;
}
}
//回溯 容斥原理
int AIPlayer::GetCount(int iCards[], int in[], int now){
int Count = 0;
if (now == 0){ in[now] = 1; }
else{ in[now] = in[now - 1]; }
for (; in[now] < 14; in[now]++){
if (JudgeLegal(iCards, in, now)){
if (now == 2){
BYTE possi[3];
possi[0] = 0x00 + in[0];
possi[1] = 0x10 + in[1];
possi[2] = 0x20 + in[2];
int TemWeight = m_logic.CalcWeight(possi);
int a = GetTimes(iCards, in);
OtherPosWeightCount(TemWeight, a);
if (TemWeight < m_iWeight){
Count += a;
}
}
else{
Count += GetCount(iCards, in, now + 1);
}
}
}
return Count;
}
int AIPlayer::GetCount(bool bCards[4][14], int in[], int now, int col){
int Count = 0;
if (now == 0){ in[now] = 1; }
else{ in[now] = in[now - 1] + 1; }
for (; in[now] < 14; in[now]++){
if (bCards[col][in[now]]){
if (now == 2){
BYTE possi[3];
possi[0] = (col << 4) + in[0];
possi[1] = (col << 4) + in[1];
possi[2] = (col << 4) + in[2];
if (m_logic.CalcWeight(possi) < m_iWeight){
Count++;
}
}
else{
Count += GetCount(bCards, in, now + 1, col);
}
}
}
return Count;
}
int AIPlayer::CalcAIWinCount(){
int count = 0;
m_iMinus = 0;
//可以先处理本身为豹子的情况
if (m_iWeight > (CT_FOUR << 12)){
int val = (m_iWeight >> 8) % 16;
count = (14 - val) * 4;
return MAXCOUNT - (count + 60);
}
//两种数据形式
//同花需要的数据结构
bool bCards[4][14];
memset(bCards, 1, 56);
int iCards[14];
iCards[0] = 0;
for (int i = 1; i < 14; i++){
iCards[i] = 4;
}
//DeleteAIHoleData
for (int i = 0; i < 3; i++){
int col = m_bHoleCards[i] >> 4;
int val = m_bHoleCards[i] & 0x0f;
bCards[col][val] = 0;
iCards[val]--;
}
//Calc HoleCards ColCount
m_iColCount = 3;
if ((m_bHoleCards[0] >> 4) == (m_bHoleCards[1] >> 4) ||
(m_bHoleCards[0] >> 4) == (m_bHoleCards[2] >> 4) ||
(m_bHoleCards[1] >> 4) == (m_bHoleCards[2] >> 4)){
m_iColCount = 2;
}
else if ((m_bHoleCards[0] >> 4) == (m_bHoleCards[1] >> 4) &&
(m_bHoleCards[0] >> 4) == (m_bHoleCards[2] >> 4)){
m_iColCount = 1;
}
int in[3];
//GetFlushCount
in[0] = in[1] = in[2] = 1;
if (m_iWeight > (CT_FLUSH << 12)){
for (int co = 0; co < 4; co++){
count += GetCount(bCards, in, 0, co);
}
}
//GetOtherCount
in[0] = in[1] = in[2] = 1;
count += GetCount(iCards, in, 0);
count += (m_iMinus / 3);
return count;
}
<file_sep># algorithm-of-some-poker-game
some poker game's algorithm.
|
368a26b1a4a50ac2d4ab2f95a1ef86c1a7262e81
|
[
"Markdown",
"C++"
] | 4
|
C++
|
ccyyhlg/algorithm-of-some-poker-game
|
d56f58cce61cc6cdc0ebefd115483f188cfe2018
|
7f00f937154ccf17ee48095482937e69b29491c8
|
refs/heads/master
|
<repo_name>RomanYemelyanenko/VKMusic<file_sep>/VKMusicProject/VKMusic/src/main/java/ListTools/InflaterBase.java
package listtools;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by Superman on 11/18/13.
*/
public abstract class InflaterBase<T> implements IInflater<T> {
protected Context _context;
protected LayoutInflater getLayoutInflater() { return LayoutInflater.from(_context); };
public InflaterBase(Context context)
{
_context = context;
}
public ViewHolder<T> getViewHolder(View view) { return (ViewHolder<T>)view.getTag(); }
public abstract View inflateView();
public abstract ViewHolder<T> createViewHolder();
public abstract void refill(View convertView, T item, ViewHolder<T> viewHolder);
}
<file_sep>/VKMusicProject/VKMusic/src/main/java/com/vkmusic/UserProfileFragment.java
package com.vkmusic;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class UserProfileFragment extends Fragment {
private boolean isLogined()
{ return false; }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(isLogined())
return inflater.inflate(R.layout.layout_user_profile,null);
else
{
View view = inflater.inflate(R.layout.layout_login, null);
View selectedView = view.findViewById(R.id.login_button);
return view;
}
}
}<file_sep>/VKMusicProject/VKMusic/src/main/java/com/vkmusic/AudioListDrawerFragment.java
package com.vkmusic;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.sql.Array;
import java.util.ArrayList;
import DAL.AudioDescriptor;
import adapters.AudioListAdapter;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class AudioListDrawerFragment extends Fragment {
private ArrayAdapter<String> _audioListAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<AudioDescriptor> dataList = new ArrayList<AudioDescriptor>();
for(int i = 0; i < 100; i++)
{
AudioDescriptor descriptor = new AudioDescriptor("Audio: "+i);
dataList.add(descriptor);
}
View view =inflater.inflate(R.layout.layout_audio_list, container, false);
ListView list = (ListView)view.findViewById(R.id.audio_list);
AudioListAdapter adapter = new AudioListAdapter(getActivity(),dataList);
list.setAdapter(adapter);
return view;
}
}
<file_sep>/VKMusicProject/settings.gradle
include ':VKMusic'
<file_sep>/README.md
VKMusic
=======
VKMusic
<file_sep>/VKMusicProject/VKMusic/src/main/java/ListTools/ViewHolder.java
package listtools;
import android.view.View;
/**
* Created by Superman on 11/18/13.
*/
public abstract class ViewHolder<T> {
public T Item;
public ViewHolder(View view, T item)
{
Item = item;
}
}
<file_sep>/VKMusicProject/VKMusic/src/main/java/ListTools/IInflater.java
package listtools;
import android.view.View;
/**
* Created by Superman on 11/18/13.
*/
public interface IInflater<T> {
View inflateView();
ViewHolder<T> createViewHolder(View view, T item);
ViewHolder<T> getViewHolder(View view);
void refill(View convertView, T item, ViewHolder<T> viewHolder);
}
|
8fead923cf4c6a6b0738911d074571326ec431b9
|
[
"Markdown",
"Java",
"Gradle"
] | 7
|
Java
|
RomanYemelyanenko/VKMusic
|
2755d26976764f487e8b0081ccab1845283c67d5
|
f2d0650f24ade2919ce761420bc7050faa767bbc
|
refs/heads/master
|
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('contato');
});
Route::get('/usuarios-view','App\Http\Controllers\UsuarioController@exibirUsuarios');
Route::get('/usuarios-view/{id}','App\Http\Controllers\UsuarioController@destroy');
Route::post('/usuario/inserir','App\Http\Controllers\UsuarioController@store');
Route::get('/usuarios-editar/{id}/editar','App\Http\Controllers\UsuarioController@edit');
Route::post('/usuarios-alterar/{id}','App\Http\Controllers\UsuarioController@update');<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UsuarioModel extends Model
{
use HasFactory;
protected $table = "mensagem";
public $timestamps=false;
protected $fillable =['nome','email','telefone','assunto','mensagem'];
protected $primaryKey = 'id';
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\UsuarioModel;
class UsuarioController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$mensagem = UsuarioModel::all();
foreach($mensagem as $m){
echo $m->id . " ";
echo $m->nome . "<br />";
}
}
public function exibirUsuarios(){
$mensagem = UsuarioModel::where('id','>=',1)->orderBy('nome','asc')->get();
return view('usuariosView',compact('mensagem'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$mensagem = new UsuarioModel();
$mensagem->nome = $request->txNome;
$mensagem->email = $request->txEmail;
$mensagem->telefone = $request->txTel;
$mensagem->assunto = $request->txAssunto;
$mensagem->mensagem = $request->txMsg;
$mensagem->save();
return redirect()->action('App\Http\Controllers\UsuarioController@exibirUsuarios');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$mensagem = UsuarioModel::find($id);
$title = "Editar Usuário . {$mensagem->nome}";
$title = "Editar Usuário . {$mensagem->email}";
$title = "Editar Usuário . {$mensagem->telefone}";
$title = "Editar Usuário . {$mensagem->assunto}";
$title = "Editar Usuário . {$mensagem->mensagem}";
return view ('UsuariosEditar',compact('title','mensagem'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$mensagem = UsuarioModel::find($id);
$mensagem->update(['nome'=>$request->txNome]);
$mensagem->update(['email'=>$request->txEmail]);
$mensagem->update(['telefone'=>$request->txTel]);
$mensagem->update(['assunto'=>$request->txAssunto]);
$mensagem->update(['mensagem'=>$request->txMsg]);
return redirect()->action('App\Http\Controllers\UsuarioController@exibirUsuarios');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$mensagem = UsuarioModel::where('id',$id)->delete();
return redirect()->action('App\Http\Controllers\UsuarioController@exibirUsuarios');
}
}
|
4293d7270fab4088cd2f0b6500f9253713ed8347
|
[
"PHP"
] | 3
|
PHP
|
Brunorodrigues0955/Projetos_Laravel
|
8b02153610db4ab57e7790fa027b815629036b9b
|
9867e848bb4d276b5b8e26bd0a82dd94a499f34d
|
refs/heads/master
|
<file_sep>module.exports = function(app, Router, routes, React)
{
//----------------------------------------------------------------------------------------------------------------------
// Dining Room
//----------------------------------------------------------------------------------------------------------------------
app.get('/level-0/diningRoom', function (req, res)
{
var urlData = req.query;
var session = req.session;
var userData = {};
Router.run(routes, req.url, Handler => {
// Client-side variables.
var props = {userData: userData};
let content = React.renderToString(<Handler userData={userData}/>);
res.render('index', { content: content,
props: JSON.stringify(props),
title: "Kafka Alpha - Dining Room"});
});
});
}
<file_sep>import React from "react";
var Doorway = require('../../generics/doorway');
var blk = {
image: "blackdrop"
};
var flr = {
image: "floor.png"
};
var wal = {
image: "wall"
};
exports.layout = [
[wal, flr, flr, flr, flr, flr, flr, wal],
[wal, flr, flr, flr, flr, flr, flr, wal],
[flr, flr, flr, flr, flr, flr, flr, flr],
[flr, flr, flr, flr, flr, flr, flr, wal]
];
var upstairsDoorComponent = <Doorway description="A staircase leading upstairs." image="door.png" destination="/level-0/upstairs/" />;
var upstairsDoor = {
posX: 1,
posY: 0,
component: upstairsDoorComponent
};
var denDoorComponent = <Doorway description="Doorway to the den." image="door.png" destination="/level-0/den/" />;
var denDoor = {
posX: 7,
posY: 2,
component: denDoorComponent
};
exports.gameObjects = [upstairsDoor, denDoor];
<file_sep>import React from "react";
var Doorway = require('../../generics/doorway');
var blk = {
image: "blackdrop"
};
var flr = {
image: "floor.png"
};
var wal = {
image: "wall"
};
exports.layout = [
[wal, flr, flr, flr, flr, flr, flr, wal],
[flr, flr, flr, flr, flr, flr, flr, flr],
[wal, flr, flr, flr, flr, flr, flr, wal],
[wal, flr, flr, flr, flr, flr, flr, wal]
];
var diningRoomDoorComponent = <Doorway description="Doorway to Dining Room." image="door.png" destination="/level-0/diningRoom/" />;
var diningRoomDoor = {
posX: 0,
posY: 1,
component: diningRoomDoorComponent
};
var bedroomDoorComponent = <Doorway description="Doorway to bedroom." image="door.png" destination="/level-0/bedroom/" />;
var bedroomDoor = {
posX: 7,
posY: 1,
component: bedroomDoorComponent
};
exports.gameObjects = [diningRoomDoor, bedroomDoor];
<file_sep>
import React from "react";
import {RouteHandler} from "react-router";
export default class AppHandler extends React.Component {
render() {
return <RouteHandler urlData={this.props.urlData}
loginData={this.props.loginData}
errorData={this.props.errorData} />;
}
}
<file_sep># KafkaAlpha
==========
TO DO LIST
==========
Tier 1
- Fix the slight alignment issue on tiles with objects
- Add missing objects
- Add missing background images
Tier 2
- Look into upgrading the current React-Router version
- Add functional minimap
Tier 3
- Get inventory working
- Get (more) interactable objects working
- Get MISC player details working
Tier 4
- Get page transitions working
- Get player flags working
Tier 5
- Get Father 'cutscene' working
- Get/Create custom art assets
Tier 6
- Look into other multimedia assets
<file_sep>import React from "react";
import cookie from 'react-cookie';
var res = require("resources");
var playerStats = React.createClass(
{
getInitialState: function()
{
if (typeof(window) == 'undefined')
{
global.window = new Object();
}
var itemsString = cookie.load('items');
var items = [];
if(itemsString != null)
{
items = JSON.parse(itemsString);
}
return {items: items};
},
render()
{
return <div className="inventory">
<span className="inventoryPage">
<span className="inventoryItem">
</span>
</span>
</div>;
}
});
module.exports = playerStats;
<file_sep>/*
* Component: React
* Module: routes.js
* Author: <NAME>
*
* Notes: Packages the React webpage into a handler for rendering by server.js
*/
import { Route, DefaultRoute } from "react-router";
import React from "react";
import AppRouter from "./components/AppRouter";
import splashHandler from "./components/splashHandler";
import levelHandler from "./components/levelHandler";
import basementHandler from "./components/level-0/basement";
import bedroomHandler from "./components/level-0/bedroom";
import denHandler from "./components/level-0/den";
import diningRoomHandler from "./components/level-0/diningRoom";
import kitchenHandler from "./components/level-0/kitchen";
import upstairsHandler from "./components/level-0/upstairs";
export default (
<Route name="root" handler={ AppRouter } path="/">
<DefaultRoute handler={ splashHandler } />
<Route name="level-0" handler={ levelHandler } path="level-0/">
<Route name="basement" handler={ basementHandler } path="basement/" />
<Route name="bedroom" handler={ bedroomHandler } path="bedroom/" />
<Route name="den" handler={ denHandler } path="den/" />
<Route name="diningRoom" handler={ diningRoomHandler } path="diningRoom/" />
<Route name="kitchen" handler={ kitchenHandler } path="kitchen/" />
<Route name="upstairs" handler={ upstairsHandler } path="upstairs/" />
</Route>
</Route>
);
<file_sep>import React from "react";
var Doorway = require('../../generics/doorway');
var blk = {
image: "blackdrop"
};
var flr = {
image: "floor.png"
};
var wal = {
image: "wall"
};
exports.layout = [
[flr, flr, flr, wal, flr, flr, flr, flr],
[flr, flr, flr, wal, flr, flr, flr, flr],
[flr, flr, flr, wal, flr, flr, flr, flr],
[flr, flr, flr, flr, flr, wal, wal, wal],
[flr, flr, flr, flr, flr, flr, wal, wal],
[flr, flr, flr, flr, flr, wal, wal, wal],
[flr, flr, flr, flr, flr, flr, flr, flr],
[flr, flr, flr, flr, flr, wal, flr, flr]
];
var diningRoomDoorComponent = <Doorway description="Staircase leading to the dining room" image="door.png" destination="/level-0/diningRoom/" />;
var diningRoomDoor = {
posX: 4,
posY: 7,
component: diningRoomDoorComponent
};
exports.gameObjects = [diningRoomDoor];
<file_sep>import React from "react";
import {Link} from 'react-router';
import cookie from 'react-cookie';
var splashBody = React.createClass(
{
getInitialState: function()
{
var lastPage = cookie.load("continue", {path: "KafkaAlpha"});
var cont = (lastPage != null);
console.log("Last Page: " + lastPage);
return {continue: cont,
lastPage: lastPage};
},
render: function()
{
var continueButton = null;
if(this.state.continue)
{
continueButton = <a className="StartButton" href={this.state.lastPage}>{"Continue"}</a>;
}
return <div>
<div className="Title">{"Kafka Alpha"}</div>
<div className="StartButtonContainer">
<Link className="StartButton" to="/level-0/bedroom/">{"Start"}</Link>
{continueButton}
</div>
</div>;
}
});
module.exports = splashBody;
<file_sep>import React from "react";
var resources = require('resources');
/**
* props:
* backgroundLayout - 8x8 grid which specifies the background tileset to use for each tile in the roomBuilder
* gameObjects - a list of objects. All objects have the following parameters, with interactable objects having
* additional properties defined elsewhere.
* posX - The object's horizontal position on the grid, from 0 to 9
* posY - The object's vertical position on the grid, from 0 to 9
* component - The actual gameobject component
*/
var roomBuilder = React.createClass(
{
getInitialState: function()
{
if (typeof(window) == 'undefined')
{
global.window = new Object();
}
return {};
},
render: function()
{
return <span className="room">
{this.renderRows()}
</span>;
},
renderRows: function()
{
var rows = [];
for(var i = 0; i < this.props.backgroundLayout.length; ++i)
{
rows.push(<span key={i} className="roomTileRow">{this.renderRow(i)}</span>);
}
return rows;
},
renderRow: function(index)
{
var tiles = [];
for(var i = 0; i < this.props.backgroundLayout[index].length; ++i)
{
tiles.push(<span key={i} className="roomTile" style={this.renderTile(index, i)}>{this.renderObject(index, i)}</span>);
}
return tiles;
},
renderTile: function(posy, posx)
{
return {"backgroundImage": "url(/" + resources.IMAGE_DIR + this.props.backgroundLayout[posy][posx].image + ")"};
},
renderObject: function(posy, posx)
{
for(var i = 0; i < this.props.gameObjects.length; ++i)
{
if(this.props.gameObjects[i].posX == posx && this.props.gameObjects[i].posY == posy)
{
return this.props.gameObjects[i].component;
}
}
return null;
}
});
module.exports = roomBuilder;
<file_sep>var resources = require('resources');
// Checks whether an object is an array or an instance and iterates through it accordingly.
exports.addArrayOrItem = function(object, callback) {
if(object.constructor === Array) {
for(var i = 0; i < object.length; ++i) {
callback(object[i]);
}
} else {
callback(object);
}
}
// Returns the number of properties within an object.
exports.getListSize = function(list) {
var size = 0;
for(var prop in list) {
size += 1;
}
return size;
}
<file_sep>
import React from "react";
var roomLayout = require('./upstairs/layout');
var RoomBuilder = require('../roomBuilder');
export default class AppHandler extends React.Component
{
render()
{
return <div id="container">
<RoomBuilder backgroundLayout={roomLayout.layout} gameObjects={roomLayout.gameObjects} />
</div>;
}
}
<file_sep>import React from "react";
import cookie from 'react-cookie';
var res = require("resources");
var playerStats = React.createClass(
{
getInitialState: function()
{
if (typeof(window) == 'undefined')
{
global.window = new Object();
}
return {};
},
render: function()
{
return <span className="map">
<span className="mapInterior">
</span>
</span>;
}
});
module.exports = playerStats;
<file_sep>import express from "express";
// Express Middle-Ware Modules
var session = require("express-session");
import React from "react";
import Router from "react-router";
import routes from "../shared/routes";
const app = express();
// set up Jade
// Folder containing HTML templates
app.set('views', './view/');
app.set('view engine', 'jade');
// Server Modules
var basement = require('./level-0/basement');
var bedroom = require('./level-0/bedroom');
var den = require('./level-0/den');
var diningRoom = require('./level-0/diningRoom');
var kitchen = require('./level-0/kitchen');
var upstairs = require('./level-0/upstairs');
var resources = require('resources');
// Server Modules
//var User = require('./User');
// Setting up public directory
app.use(express.static(__dirname + resources.RELATIVE_PUBLIC_DIR));
// Set up Session variable handling
app.use(session({ secret: 'test session',
resave: false,
saveUninitialized: true}));
//----------------------------------------------------------------------------------------------------------------------
// Index
//----------------------------------------------------------------------------------------------------------------------
app.get('/', function(req, res)
{
var urlData = req.query;
var session = req.session;
var userData = {};
Router.run(routes, req.url, Handler => {
// Client-side variables.
var props = {userData: userData};
let content = React.renderToString(<Handler userData={userData}/>);
res.render('index', { content: content,
props: JSON.stringify(props),
title: "Kafka Alpha"});
});
});
//----------------------------------------------------------------------------------------------------------------------
// User Pages
//----------------------------------------------------------------------------------------------------------------------
basement(app, Router, routes, React);
bedroom(app, Router, routes, React);
den(app, Router, routes, React);
diningRoom(app, Router, routes, React);
kitchen(app, Router, routes, React);
upstairs(app, Router, routes, React);
// Redirect to Index Page on linking to a page which does not exist.
/*app.use(function(req, res, next)
{
res.redirect("/");
});*/
var server = app.listen(process.env.PORT, function ()
{
var port = server.address().port;
console.log('Collab-OnePage listening at port %s', port);
});
<file_sep>import React from "react";
import {Link} from 'react-router';
var GameObject = require('./gameObject');
var resources = require('resources');
/**
* props:
* description - A description to of the object to be displayed to the player on click
* image - What the object should look like
* actions - a list of actions. All actions have the following properties:
* image - the sprite rendered for the action's button
* conditions - (optional) Any requirements which must be met before the action can be used. All conditions have the following properties:
* cName - the variable name against which the condition will be checked
* op - The type of varification. (valid values: 'equal', '!equal', 'greater', 'less')
* val - The value against which the cookie variable will be checked.
* result - a function that is run when the action is used
* destination - the destination to which this doorway leads
*/
var doorway = React.createClass(
{
contextTypes: {
history: React.PropTypes.object
},
getInitialState: function()
{
if (typeof(window) == 'undefined')
{
global.window = new Object();
}
var actions = [];
if(this.props.actions != null)
{
actions = this.props.actions;
}
var link = {
image: "doorAction.png",
result: this.linkRoom
};
actions.push(link);
return {actions: actions};
},
render: function()
{
return <GameObject description={this.props.description} image={this.props.image} actions={this.state.actions} />;
},
linkRoom: function(event)
{
event.preventDefault();
window.location = this.props.destination;
}
});
module.exports = doorway;
<file_sep>import cookie from 'react-cookie';
var resources = require('resources');
/* Truncates large numbers into a more human-readable format
*
* number - The number to be truncated
*/
exports.truncateNumber = function(number)
{
if(number > 1000000)
{
return "" + (number / 1000000).toPrecision(3) + "M";
} else if(number >= 10000)
{
return "" + (number / 1000).toPrecision(3) + "K";
}
return number;
}
// Must have window defined
exports.setContinuePoint = function()
{
if (typeof(document) != 'undefined')
{
console.log("Saving room progress");
cookie.save("continue", document.URL, {path: "KafkaAlpha"});
}
}
<file_sep>
import React from "react";
var SplashBody = require('./splashBody');
export default class AppHandler extends React.Component
{
render()
{
return <div id="content">
<SplashBody />
</div>
}
}
<file_sep>import React from "react";
var Doorway = require('../../generics/doorway');
var blk = {
image: "blackdrop"
};
var flr = {
image: "floor.png"
};
var wal = {
image: "wall"
};
exports.layout = [
[blk, blk, blk, blk, blk, blk, blk, blk],
[blk, blk, blk, blk, blk, blk, blk, blk],
[blk, blk, flr, flr, flr, flr, blk, blk],
[blk, blk, wal, flr, flr, flr, blk, blk],
[blk, blk, wal, flr, flr, flr, blk, blk],
[blk, blk, wal, wal, flr, flr, blk, blk],
[blk, blk, blk, blk, blk, blk, blk, blk],
[blk, blk, blk, blk, blk, blk, blk, blk]
];
var bedroomDoorComponent = <Doorway description="Doorway to bedroom." image="door.png" destination="/level-0/bedroom/" />;
var bedroomDoor = {
posX: 2,
posY: 2,
component: bedroomDoorComponent
};
exports.gameObjects = [bedroomDoor];
|
2537d5d1a9084a58b0095ca9137b3ea43b5d7d79
|
[
"JavaScript",
"Markdown"
] | 18
|
JavaScript
|
JohnPayment/KafkaAlpha
|
d3d37a7f026e56374214b6d5276ebc637e4ca997
|
842238bc02cde2adc0710494b1d1a15357aa5545
|
refs/heads/master
|
<repo_name>HussainHaider/Freecodecamp-FELibraries-Projects<file_sep>/drum-machine/src/components/Button/Button.js
import React,{Component} from 'react'
import classes from './Button.css'
class button extends Component {
componentDidMount() {
document.addEventListener('keydown', this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyPress);
}
handleKeyPress = (e) => {
if (e.keyCode === this.props.keyCode) {
this.handleClick();
}
};
handleClick = () => {
this.audio.play();
this.audio.currentTime = 0;
this.props.handleDisplay(this.props.id);
};
render() {
return (<div className={ classes.btn }
id={this.props.id}
onClick={this.handleClick}
>
<audio
className="clip"
id={this.props.value}
src={this.props.src}
ref={ref => this.audio = ref}/>
{this.props.value}
</div>
);
}
};
export default button;
<file_sep>/drum-machine/src/components/Screen/Screen.js
import React from 'react'
import classes from './Screen.css';
const screen = ( props ) => {
return (<div className={classes.display}>
<p id="display">{props.value}</p>
</div>);
};
export default screen;
<file_sep>/calculator/build/precache-manifest.e3335b129c80c51ae16fc173445e4111.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "8bf0223224844a01fcd85282ffe16cc6",
"url": "/calculator/index.html"
},
{
"revision": "459074c7563ad4914738",
"url": "/calculator/static/css/main.6c91efd3.chunk.css"
},
{
"revision": "5cb1b548c7a48975ec0e",
"url": "/calculator/static/js/2.0278f759.chunk.js"
},
{
"revision": "459074c7563ad4914738",
"url": "/calculator/static/js/main.da439104.chunk.js"
},
{
"revision": "4ceda9192a4fdcfdf689",
"url": "/calculator/static/js/runtime-main.001727de.js"
}
]);<file_sep>/markdown-previewer/src/Component/Toolbar/Toolbar.js
import React from "react";
import classes from './Toolbar.css';
const Toolbar = (props) => {
return (
<div className={classes.toolbar}>
<i title="no-stack-dub-sack" className="fab fa-free-code-camp"/>
{props.text}
</div>
)
};
export default Toolbar;
<file_sep>/pomodoro-clock/src/components/Timer/timer.js
import React from "react";
import classes from "./timer.css";
import Button from "../Button/Button";
const Timer = (props) => {
return (
<div className="break">
<p id={props.label_ID}>{props.timerType}</p>
<div>
<Button id={props.decrement_ID} icon="fas fa-minus" clickHandler = {props.decrementHandler} />
<p className={classes.text} id={props.timer_ID}>{props.time}</p>
<Button id={props.increment_ID} icon="fas fa-plus" clickHandler = {props.incrementHandler} />
</div>
</div>
);
};
export default Timer;
<file_sep>/calculator/src/containers/buttonList/buttonList.js
import React,{ Component } from 'react'
import classes from './buttonList.css';
import Button from '../../components/Button/Button'
import {connect} from 'react-redux'
import * as actionTypes from '../../store/action'
class ButtonList extends Component {
state = {
buttonList : [
{
id:'clear',
value:'AC',
class:'blue',
action:actionTypes.ALL_CLEAR
},
{
id:'power',
value:'^',
class:'',
action:actionTypes.POWER
},
{
id:'percentage',
value:'%',
class:'',
action:actionTypes.PERCENTAGE
},
{
id:'divide',
value:'/',
class:'yellow',
action:actionTypes.DIVIDE
},
{
id:'seven',
value:'7',
class:'',
action:actionTypes.SEVEN
},
{
id:'eight',
value:'8',
class:'',
action:actionTypes.EIGHT
},
{
id:'nine',
value:'9',
class:'',
action:actionTypes.NINE
},
{
id:'add',
value:'+',
class:'yellow',
action:actionTypes.ADD
},
{
id:'four',
value:'4',
class:'',
action:actionTypes.FOUR
},
{
id:'five',
value:'5',
class:'',
action:actionTypes.FIVE
},
{
id:'six',
value:'6',
class:'',
action:actionTypes.SIX
},
{
id:'subtract',
value:'-',
class:'yellow',
action:actionTypes.SUBTRACT
},
{
id:'one',
value:'1',
class:'',
action:actionTypes.ONE
},
{
id:'two',
value:'2',
class:'',
action:actionTypes.TWO
},
{
id:'three',
value:'3',
class:'',
action:actionTypes.THREE
},
{
id:'multiply',
value:'*',
class:'yellow',
action:actionTypes.MULTIPLY
},
{
id:'zero',
value:'0',
class:'',
action:actionTypes.ZERO
},
{
id:'decimal',
value:'.',
class:'',
action:actionTypes.DECIMAL
},
{
id:'delete',
value:'C',
class:'red',
action:actionTypes.CLEAR
},
{
id:'equals',
value:'=',
class:'green',
action:actionTypes.EQUAL
}
]
};
render() {
const list = this.state.buttonList.map((obj,index) => (
<Button
id={obj.id}
key={obj.id}
value={obj.value}
class={obj.class}
clicked={() => this.props.calcNumbers(obj.action)}/>
));
console.log(list);
return (
<div className={classes.buttons}>
{list}
{/*<div className={classes.row}>*/}
{/* <Button id="clear" value="AC" class="blue" clicked={() => this.props.calcNumbers(actionTypes.ALL_CLEAR)}/>*/}
{/* <Button id="power" value="^" clicked={() => this.props.calcNumbers(actionTypes.POWER)}/>*/}
{/* <Button id="percentage" value="%" clicked={() => this.props.calcNumbers(actionTypes.PERCENTAGE)}/>*/}
{/* <Button id="divide" value="/" class="yellow" clicked={() => this.props.calcNumbers(actionTypes.DIVIDE)}/>*/}
{/*</div>*/}
{/*<div className={classes.row}>*/}
{/* <Button id="seven" value="7" clicked={() => this.props.calcNumbers(actionTypes.SEVEN)}/>*/}
{/* <Button id="eight" value="8" clicked={() => this.props.calcNumbers(actionTypes.EIGHT)}/>*/}
{/* <Button id="nine" value="9" clicked={() => this.props.calcNumbers(actionTypes.NINE)}/>*/}
{/* <Button id="add" value="+" class="yellow" clicked={() => this.props.calcNumbers(actionTypes.ADD)}/>*/}
{/*</div>*/}
{/*<div className={classes.row}>*/}
{/* <Button id="four" value="4" clicked={() => this.props.calcNumbers(actionTypes.FOUR)}/>*/}
{/* <Button id="five" value="5" clicked={() => this.props.calcNumbers(actionTypes.FIVE)}/>*/}
{/* <Button id="six" value="6" clicked={() => this.props.calcNumbers(actionTypes.SIX)}/>*/}
{/* <Button id="subtract" value="-" class="yellow" clicked={() => this.props.calcNumbers(actionTypes.SUBTRACT)}/>*/}
{/*</div>*/}
{/*<div className={classes.row}>*/}
{/* <Button id="one" value="1" clicked={() => this.props.calcNumbers(actionTypes.ONE)}/>*/}
{/* <Button id="two" value="2" clicked={() => this.props.calcNumbers(actionTypes.TWO)}/>*/}
{/* <Button id="three" value="3" clicked={() => this.props.calcNumbers(actionTypes.THREE)}/>*/}
{/* <Button id="multiply" value="*" class="yellow" clicked={() => this.props.calcNumbers(actionTypes.MULTIPLY)}/>*/}
{/*</div>*/}
{/*<div className={classes.row}>*/}
{/* <Button id="zero" value="0" clicked={() => this.props.calcNumbers(actionTypes.ZERO)}/>*/}
{/* <Button id="decimal" value="." clicked={() => this.props.calcNumbers(actionTypes.DECIMAL)}/>*/}
{/* <Button id="delete" value="C" class="red" clicked={() => this.props.calcNumbers(actionTypes.CLEAR)}/>*/}
{/* <Button id="equals" value="=" class="green" clicked={() => this.props.calcNumbers(actionTypes.EQUAL)}/>*/}
{/*</div>*/}
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
calcNumbers: (number) => dispatch({type:number})
}
};
export default connect(null,mapDispatchToProps)(ButtonList);
<file_sep>/pomodoro-clock/src/App.js
import React from 'react';
import './App.css';
import Clock from "./containers/Clock/clock";
function App() {
return (<Clock/>);
}
export default App;
<file_sep>/calculator/src/components/Button/Button.js
import React from 'react'
import classes from './Button.css'
const button = ( props ) => {
// let style = {};
// if (props.value==='=') {
// style['color'] = '#0CB999';
// }
return (<input type="button"
id={props.id}
value={props.value}
onClick={props.clicked} className={classes[props.class]} />);
};
export default button;
<file_sep>/drum-machine/src/containers/Drum/drum.js
import React,{ Component } from 'react'
import Screen from '../../components/Screen/Screen'
import classes from './drum.css';
import DrumPad from "../DrumPad/drumPad";
class Drum extends Component {
constructor(props){
super(props);
this.state = {
display: 'Click or Press a Key'
}
}
handleDisplay = display => {
this.setState({display});
console.log('Change state!!!');
};
render() {
return (
<>
<h1>Drum Machine</h1>
<div id="drum-machine" className={classes.container}>
<Screen value={this.state.display} />
<DrumPad handleDisplay={this.handleDisplay}/>
</div>
<p className={classes.poweredBy}>Developed in React by <a href="#"><NAME></a></p>
</>
);
}
}
export default Drum;
|
7339932b8461445ef2db7693444d8202bf65e330
|
[
"JavaScript"
] | 9
|
JavaScript
|
HussainHaider/Freecodecamp-FELibraries-Projects
|
8f0f6941dbd2f209824ffcc1e905f3b502102eb8
|
64fef0fc85a37977d12eb2b962cbd07c52bbbe1f
|
refs/heads/master
|
<repo_name>nicovalentini03/Sconti2<file_sep>/Sconti2/Program.cs
using System;
namespace Sconti2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("inserisci il totale della spesa");
double tot = double.Parse(Console.ReadLine());
double sconto = (tot * 10) / 100;
double sconto2 = (tot * 20) / 100;
if (tot <= 500)
{
double importo = tot - sconto;
Console.WriteLine($"l'importo totale è {importo:c}");
}
if (tot > 500)
{
double importo = tot - sconto2;
Console.WriteLine($"l'importo totale è {importo:c}");
}
Console.ReadLine();
}
}
}
|
52dfb5d4de96931b82803f11258189ce52601baa
|
[
"C#"
] | 1
|
C#
|
nicovalentini03/Sconti2
|
7b8b455cd18df7dc232cc6d662884dedb18785d7
|
d3bbb408965bfe4d72bf23c97fd3e00eb273b5c3
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
#使用上の注意点
'''
sudo apt-get install oauth2を予めコマンドラインで打っておいてください
動作確認環境 raspbian = Debian
分からないことがあればtwitter @yurisi0212まで
'''
import time
import oauth2 as oauth
from urllib import urlencode
#いずれもdev.twitter.comで取得したkeyを入力
# |
#\/
consumer_key="consumerkey"
consumer_secret="comsecret"
access_token_key="accesstokenkey"
access_token_secret="accesstokensecret"
client = oauth.Client(
oauth.Consumer(key=consumer_key, secret=consumer_secret),
oauth.Token(access_token_key, access_token_secret)
)
while True:
message=""#発言したいメッセージの追加
message2=""#追加可能。
message3=""
#message4=""
#メッセージ1の投稿処理
client.request(
'https://t.co/xdz9ClfP96',
'POST',
urlencode({
'status': message
}),
)
time.sleep(3600.0)#秒単位で次のツイートを投稿する時間の設定
#メッセージ2の投稿処理
client.request(
'https://t.co/xdz9ClfP96',
'POST',
urlencode({
'status': message2
}),
)
time.sleep(3600.0)
#メッセージ3の投稿処理
client.request(
'https://t.co/xdz9ClfP96',
'POST',
urlencode({
'status': message3
}),
)
#もしmessage4のシャープを外し中にメッセージを代入したらここのシャープを消して実行できる状態にする
#time.sleep(3600.0)
#client.request(
#'https://t.co/xdz9ClfP96',
#'POST',
#urlencode({
#'status' : mesaage4
#}),
#)
|
505ac3c71ea8e1a9f11046e784b79277b3e0caab
|
[
"Python"
] | 1
|
Python
|
yurisi/auto_tweet_bot
|
3b7498cb8f26ed2c34edfdb3f0720a4d2533febc
|
4d114bd7bbc999df0d3686b039b0a5cd60a5c413
|
refs/heads/master
|
<file_sep>var clickedArticleId = "";
$(function() {
$("#search")
.on("keyup", function(e) {
if (e.which == 13 || e.which == 27) {
$(e.target).val('');
}
var value = $(e.target).val();
$("menu > li").each(function() {
if ($(this).text().toLowerCase().search(value.toLowerCase()) > -1) {
$(this).show();
}
else {
$(this).hide();
}
});
});
});
function clickUser(id){
destroyPHPSession();
if(setPHPSession(id)){
reLoadWindow();
showUserAccountBalance();
}
}
function destroyPHPSession(){
var isDestroyed = false;
$.ajax({
url: 'php_scripts/login.php?destroySessionRequested=1',
success: function(html) {
var obj = JSON.parse(html);
isDestroyed = obj.isSessionDestroyed;
}
});
return isDestroyed;
}
function setPHPSession(userId){
var sessionCreated = 0;
$.ajax({
url: 'php_scripts/login.php?user_id='+userId+'&password=0',//TODO : set password if required
async: false,
success: function(html) {
var obj = JSON.parse(html);
sessionCreated = obj.isSessionCreated;
}
});
return sessionCreated;
}
function clickArticle(articleId){
var modal = document.getElementById('myModal');
modal.style.display = "block";
clickedArticleId = articleId;
setSelectedArticleNameInPopupWindow(articleId);
}
window.onclick = function(event) {
var targetId = event.target.id;
if(targetId == "productConfirmationBtn" || targetId == "productCancelationBtn"){
document.getElementById('myModal').style.display = "none";
reLoadWindow();
showUserAccountBalance();
}
}
function showUserAccountBalance() {
var amound = 0;
$.ajax({
url: 'php_scripts/dbutility.php?accountBalanceRequested=1',
async: true,
success: function(html) {
var obj = JSON.parse(html);
var afterCommaLength = obj.toString().split(".")[1].length;
if(afterCommaLength > 3){
var indexToCut = obj.indexOf(".") + 3;
amound = obj.substr(0, indexToCut);
}
document.getElementById('accountBalance').innerHTML = amound+' €';
if(obj.account_balance < 0){
document.getElementById('accountBalance').style.backgroundColor = "red";
}
}
});
}
function closeAdminSite(){
$.ajax({
url: 'php_scripts/login.php?logoutRequested=1',
success: function(html) {
var obj = JSON.parse(html);
reLoadWindow();
}
});
}
function sendSelectedProductForUser(){
$.ajax({
url: 'php_scripts/dbutility.php?selectedArticleId='+clickedArticleId+'&articleBoughtRequsted=1',
success: function(html) {
var obj = JSON.parse(html);
showUserAccountBalance();
}
});
}
function setSelectedArticleNameInPopupWindow(articleId){
$.ajax({
url: 'php_scripts/dbArticle.php?id='+articleId,
success: function(html) {
var obj = JSON.parse(html);
//var selectedArticleName = document.getElementById('selectedProductName');
selectedProductName.innerHTML = obj["name"];
selectedProductName.style.fontWeight = 'bold';
}
});
}
function reLoadWindow(){
window.location.reload();
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(150);
};
reader.readAsDataURL(input.files[0]);
}
}
var inputs = document.querySelectorAll( '.upload-picture-btn' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
console.log('hi');
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});<file_sep><h2>This app is implemented for managing of drinks in work. Users and Products should be inserted</h2>
<h1>REQUIREMENTS</h1>
<ul>
<li> 1. PHP > 5</li>
<li> 2. python > 3</li>
<li> 3. MySQL > 5.5</li>
</ul>
<h1>INSTALLATION</h1>
<li>1. Install MySQL
<li>2. Create your database "flex_kitchen" (for customized database name look step 3)
<li>3. Open file sql_queries.sql and adjust your database name and admin user (email and password). with this admin user you can manage product and Users
<ul>
<li>3.1 With Admin user you will redirected to admin page wehere you can manage product and users</li>
</ul>
<li>4. Execute sql_queries.sql on your database (if you want to use customized database name then you can open sql_queries.sql file and change database name)</li>
<li>5. copy all files from app directory (flex_kitchen) to your domain (on directory where your domain referenced)</li>
<li>6. open file /php_scripts/dbConnector.php and adjust your database user if your customized database user in sql_queries.sql file</li>
<h1>FEATURES</h1>
<ul>
<li>Users</li>
<li>Products</li>
<li>Add/remove user and product</li>
<li>Admin page</li>
<li>Manager user and product in admin page</li>
<li>Notify User per email if user a product purchased</li>
<li>Notify user every month with account state and purchased product number (for this you shuld make crone job (linux) or windows task (windows)</li>
<li>show user history (purchased products and payments)</li>
</ul>
<file_sep>
<?php
include ("php_script.php");
include ("php_scripts/login.php");
?>
<?php
$functions = new functions();
echo '
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script type="text/javascript" src="function.js"></script>
<script type="text/javascript" src="./js/administration.js"></script>
<link rel="stylesheet" href="./css/style.css">
<script type="text/javascript">
function checkCookie(){
if('.hasSession().'){
if('.isAdmin().'){
window.location.href = "admin.php";
}else{
setLoggedUser('.getSessionUserId().');
}
}else{
window.location.href = "index.php";
}
}
</script>
</head>
<body onLoad="checkCookie();">
<div class="flex-container">
<header>
<!-- Header: first column -->
<div class="header_first_column">
<div id="loggedUserImg" style="width:60px;height:60px;float:left; background-image:url(\'img/default_user_img.png\');background-repeat:no-repeat;background-size: cover"></div>
<div style="float:left"> <p id="loggedUserName"></p></div>
</div>
<!-- Header: first column End-->
<!-- Header: second column -->
<div class="header_second_column">'. $functions->getUserAccountBalance().'</div>
<!-- Header: second column End-->
<!-- Header: third column -->
<div class="header_third_column">
<div style="float:right"><img style="width:50px; float:right;" src="logout.ico" href="#" onclick="closeAdminSite()"></img></div>
<div style="float:right"><form class="search_form"><input class="search" type="text" id="search" onkeyup="myFunction()" placeholder="Search for article.." title="Type in a name"></form></div>
</div>
<!-- Header: third column End-->
</header>
<div class="content">
<menu>'.$functions->getArticleLIs().'</menu>
</div>'.$functions->getFooter();
echo '<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<table style="font-size:3em">
<tr><td colspan="2">Sie haben</td></tr>
<tr><td colspan="2" id="selectedProductName"><NAME></td></tr>
<tr><td colspan="2"> ausgewählt</td></tr>
<tr>
<td><button class="popupButton" id="productConfirmationBtn" style="background-image:url(\'img/ok_btn.png\')" onclick="sendSelectedProductForUser()"></button> </td>
<td><button class="popupButton" id="productCancelationBtn" style="background-image:url(\'img/x_btn.png\')"></button></td>
</tr>
</table>
</div>
</div>';
?>
<file_sep><?php
if(isset($_REQUEST['userRequested'])){
echo getUserDivsInAdminPage();
}
if(isset($_REQUEST['adminHomeRequested'])){
require("content_script.php");
echo getAdminPageContent();
}
if(isset($_REQUEST['productsRequested'])){
echo getProductDivsInAdminPage();
}
if(isset($_REQUEST['userHirstoryPageRequested']) && isset($_REQUEST['personId'])){
$personId = $_REQUEST['personId'];
echo getUserHistoryPage($personId);
}
if(isset($_REQUEST['userHistoryRequested']) && isset($_REQUEST['personId']) && isset($_REQUEST['since'])){
$personId = $_REQUEST['personId'];
$since = $_REQUEST['since'];
echo getUserHistory($personId, $since);
}
function getUserDivsInAdminPage(){
require("../php_script.php");
$script = new FunctionScript();
$persons = $script->getAllPersonFromDB();
$result = "";
if($persons->num_rows >0){
while($row = $persons->fetch_assoc()){
//pass user if it is admin
if($row["is_admin"] == "1") continue;
$user = $row["firstname"].' '.$row["lastname"];
$id = $row["id"];
$accountBalance = $row["account_balance"];
$payButtonId = 'payButton'.$id;
$inputPayment = 'inputPayment'.$id;
$fetchedData = $script->getLastPurchasedArticle($id);
$lastPurchase =$fetchedData;
$src = $script->createUserImagePath($row["img_path"]);
$result = $result.'<div class="column">
<div class="box1"><img src='.$src.' alt="user image"></div>
<div class="box2">
<div>Name: <span id="loggedUserName">'.$user.'</span></div>
<div>Kontostand: <span id="accountBalance'.$id.'">'.$accountBalance.' €</span></div>
<div>Letzter Kauf: <span id="lastBuy">'.$lastPurchase["name"].' ('.$lastPurchase["buy_date"].')</span></div>
</div>
<div class="box3">
<div class="input_in_grid">
<input class="payment_input" id="'.$inputPayment.'" placeholder="e.g. 2.50" onkeyup="checkInputForNumber(\''.$inputPayment.'\',\''.$payButtonId.'\')" type="text">
</div>
<div class="payment_button_in_grid">
<button id="'.$payButtonId.'" class="button" onclick="updateUserAmount(\''.$id.'\',\''.$inputPayment.'\');">Bezahlen</button>
</div>
<div class="remove_user_in_grid">
<img class="icon_image" id="'.$payButtonId.'" src="img/remove_user_icon.png" onclick="confirmUserDeleting(\''.$user.'\',\''.$id.'\');"/>
</div>
<div class="user_history_in_grid">
<img class="icon_image" style="margin-top:3px;" src="img/user-history.png" onclick="goToUserHistoryPage(\''.$id.'\');"/>
</div>
</div>
</div>';
}
}
return $result;
}
function getProductDivsInAdminPage(){
require("../php_script.php");
$script = new FunctionScript();
$products = $script->getAllFromTable("article");
$categories = $script->getCategoriesFromDB();
if($products->num_rows >0){
$result = "";
while($row = $products->fetch_assoc()){
$productName = $row["name"];
$productId = $row["id"];
$NumOfProducts = $row["count"];
$price = $row["price"];
$categoryId = $row["category"];
$categoryName = $categories[$categoryId];
$image = $row["img_path"];
$payButtonId = 'payButton'.$productId;
$inputPayment = 'inputPayment'.$productId;
$result = $result.'<div class="column">
<div class="box1"><img src="img/'.$image.'" alt="product image"></div>
<div class="box2">
<div>Name: <span id="loggedUserName">'.$productName.'</span></div>
<div>Preis: <span id="price'.$price.'">'.$price.' €</span></div>
<div>Anzahl: <span id="numOfProduct'.$productId.'">'.$NumOfProducts.' Stück</span></div>
<div>Kategorie: <span id="category'.$productId.'">'.$categoryName.'</span></div>
</div>
<div class="box3">
<div class="input_in_grid">
<input class="payment_input" id="'.$inputPayment.'" onkeyup="checkInputForNumber(\''.$inputPayment.'\',\''.$payButtonId.'\')" type="text">
</div>
<div class="payment_button_in_grid">
<button id="'.$payButtonId.'" class="button" style="width:100%;" onclick="updateProductNumber(\''.$productId.'\',\''.$inputPayment.'\');">Einlagern</button>
</div>
<div class="remove_user_in_grid">
<img class="icon_image" style="margin-top:3px;" id="'.$payButtonId.'" src="img/remove_product_icon.png" onclick="confirmProductDeleting(\''.$productName.'\',\''.$productId.'\');"/>
</div>
</div>
</div>';
}
}
return $result;
}
function getUserHistoryPage($personId){
require("../php_script.php");
$script = new FunctionScript();
$person = json_decode($script->getPersonById($personId));
$userName = $person->firstname.' '.$person->lastname;
$accountBalance = $person->account_balance;
$accountBalanceColor = intval($accountBalance) < 0? "red":"black";
$src = $script->createUserImagePath($person->img_path);
$result = "";
$result = $result.'<div class="column">
<div class="box1"><img src='.$src.'></div>
<div class="box2">
<div>Name: <span id="loggedUserName">'.$userName.'</span></div>
<div>Kontostand: <span style="color:'.$accountBalanceColor.'">'.$accountBalance.' €</span></div>
</div>
<div class="box3">
<div class="input_in_grid">
<input type="range" min="1" max="11" value="1" class="slider" id="myRange" onchange="showUserHistory(this.value, '.$personId.');">
<p><b><span id="sinceXMonth">1</span></b> Monat(e)</p>
</div>
<div class="payment_button_in_grid">
</div>
</div>
</div>
<div class="user_history_area">
<div id="user_products_history_area" class="purchased_history history_area"><table><tr><th>Produktname</th><th>Kaufdatum</th></tr></table></div>
<div id="user_payments_history_area" class="payment_history history_area"><table><tr><th>Bezahlte Betrag</th><th>Zahlungsdatum</th></tr></table></div>
</div>';
return $result;
}
function getUserHistory($personId, $since){
require("../php_script.php");
$script = new FunctionScript();
$productsByDate = $script->getAllPurchasedArticlesByDate($personId, $since);
$productAsList = "<table><tr><th>Produktname</th><th>Kaufdatum</th></tr>";
if($productsByDate != -1){
foreach ($productsByDate as $key => $value) {
$productAsList = $productAsList."<tr><td>".$value["article_name"]."</td><td>".$value["buy_date"]."</td></tr>";
}
}
$productAsList = $productAsList."</table>";
$response["productList"] = $productAsList;
$paymentByDate = $script->getUserPaymentByDate($personId, $since);
$paymentAsList = "<table><tr><th>Bezahlte Betrag</th><th>Zahlungsdatum</th></tr>";
if($paymentByDate != -1){
foreach ($paymentByDate as $key => $value) {
$paymentAsList = $paymentAsList."<tr><td>".$value["amount"]." €</td><td>".$value["pay_date"]."</td></tr>";
}
}
$paymentAsList = $paymentAsList."</table>";
$response["payments"] = $paymentAsList;
return json_encode($response);
}
?>
<file_sep>
<?php
include ("php_script.php");
include ("php_scripts/login.php");
include ("add_product_form.php");
include ("add_customer_form.php");
?>
<?php
$functions = new functions();
echo '
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script type="text/javascript" src="function.js"></script>
<script type="text/javascript" src="./js/administration.js"></script>
<link rel="stylesheet" href="./css/style.css">
<head>
<style>
.product_count {
width: 60px;
height: 40px;
padding: 1px;
border: none;
border: 1px solid #555;
font-weight: bold;
}
</style>
<script>
function searchUserInAdminPage(){
var value = document.getElementById("searchInAdminPage").value;
$(".column").each(function() {
if ($(this).text().toLowerCase().search(value.toLowerCase()) > -1) {
$(this).show();
}
else {
$(this).hide();
}
});
}
function checkInputForNumber(inputPayment,buttonId)
{
var input = document.getElementById(inputPayment);
var payButton = document.getElementById(buttonId);
//input.style.backgroundColor="#FFF";
var x=input.value;
if (!isInputedAmoundValid(x) && x !="")
{
input.style.backgroundColor="#FF0000";
}else{
input.style.backgroundColor="#FFF";
}
}
function updateUserAmound(userId, inputFieldId){
var input = document.getElementById(inputFieldId);
var amound = input.value;
if(isInputedAmoundValid(amound)){
$.ajax({
url: \'php_scripts/dbutility.php?id=\'+userId+\'&amound=\'+amound,
success: function(html) {
var obj = JSON.parse(html);
var idOfBalanceToBeUpdated = "accountBalance"+userId;
document.getElementById(idOfBalanceToBeUpdated).innerHTML = obj["newBalance"]+" €";
input.value = "";
}
});
}
}
function updateProductNumber(productId, inputFieldId){
var input = document.getElementById(inputFieldId);
var productNumber = input.value;
if (isInteger(productNumber)){
$.ajax({
url: \'php_scripts/dbutility.php?productId=\'+productId+\'&productNumber=\'+productNumber,
success: function(html) {
var obj = JSON.parse(html);
var idOfBalanceToBeUpdated = "numOfProduct"+productId;
var numberOfProduct = obj["newCount"];
document.getElementById(idOfBalanceToBeUpdated).innerHTML = numberOfProduct+" Stück";
input.value = "";
}
});
}
}
function isInteger(x) {
return x % 1 === 0;
}
function isInputedAmoundValid(value){
var regex=/^\-?([1-9]\d*|0)(\.\d?[1-9])?$/;
if(value=="" || !value.match(regex)) {
return false;
}
else{
return true;
}
}
</script>
</head>
<body>
<div class="flex-container">
<header>
<div class="header_first_column">
<div style="width: 50px; height: 50px; float: left"> FLEX KITCHEN</div>
</div>
<div class="header_second_column" style="background-color:yellow;color:black"><h4> Aministration Bereich</h4></div>
<div class="header_third_column">
<form class="search_form">
<div style="float:right"><img style=" width:50px; float:right;" src="img/adminLogginImg.png" href="#" onclick="closeAdminSite()"></img></div>
<div style="float:right"><img style=" height:60px;float:right;" src="img/home.png" href="#" onclick="goToAdminHome()"></img></div>
<div style="float:right"> <input type="text" class="search" id="searchInAdminPage" onkeyup="searchUserInAdminPage()" placeholder="Search for names.." title="Type in a name"></div>
</form>
</div>
</header>
<div class="content" id="contentInAdminPage">
<menu id="admin_home_manu" style="padding-left:0px">';
$functions->getAdminPageContent();
echo '</menu>
</div>';
$functions->getFooter();
?>
<file_sep><?php
session_start();
$errorMessage="";
// Remove Session
if(isset($_GET['destroySessionRequested']) && $_GET['destroySessionRequested'] ==1){
$response['isSessionDestroyed'] = true;
echo json_encode($response);
}
// Create Session
if(isset($_GET['user_id'])){
$userId = $_GET['user_id'];
$succes = setSession("id", $userId);
$response['isSessionCreated'] = $succes;
echo json_encode($response);
}
if(isset($_GET['logoutRequested'])){
session_unset();
session_destroy();
$response['logout'] = 1;
echo json_encode($response);
}
// Login requested
if(isset($_GET['admin_login_requested'])) {
if(!isset($_REQUEST['email'])){
echo json_encode("Email missing!");
exit;
}
$email = $_REQUEST['email'];
$sessionCreated = setSession("email", "\"".$email."\"");
if($sessionCreated){
$errorMessage="Login success!";
$host = $_SERVER['HTTP_HOST'];
$extra = 'index.php';
//Hacy only for localtest
if(strpos($host, 'localhost') !== false){
$extra = "flex_kitchen/".$extra;
}
header("Location: http://$host/$extra");
} else {
$errorMessage = "E-Mail oder Passwort war ungültig<br>";
}
echo json_encode($errorMessage);
}
function setSession($attributeName, $attributeValue){
require_once("./dbConnector.php");
$db = new dbConnector();
$conn = $db->getDBConnection();
session_unset();
$sql = 'SELECT * FROM person WHERE '.$attributeName.'='.$attributeValue;
$result = $conn->query($sql);
if ($result->num_rows > 0 ) {
while($row = $result->fetch_assoc()) {
//TODO activate here if password re
if(md5($_REQUEST['password']) != $row['user_pw']){
$errorMessage ="wrong password";
return 0;
}
$errorMessage = "session is created";
$_SESSION['userid'] = $row["id"];
$_SESSION['isAdmin'] = $row['is_admin'];
$_SESSION['userName'] = $row['firstname'].' '.$row['lastname'];
$_SESSION['imagePath'] = $row['img_path'];
}
return 1;
} else {
return 0;
}
$conn->close();
}
function hasSession(){
if(count($_SESSION) > 0){
return 1;
}
else{
return 0;
}
}
function isAdmin(){
if(hasSession()){
if($_SESSION["isAdmin"] == 0){
return 0;
}else{
return 1;
}
}else{
return 0;
}
}
function getSessionUserId(){
return $_SESSION['userid'];;
}
function getCurrentUserName(){
return $_SESSION['userName'];
}
function getCurrentUserImagePath(){
$imagePath = $_SESSION['imagePath'];
if($imagePath == ""){
return 'img/default_user_img.png';
}
return $imagePath;
}
?>
<file_sep><?php
if(isset($_REQUEST["sendMonthlyEmail"])){
require_once("send_email.php");
sendMonthlyEmails();
}
?>
<file_sep>#!/usr/bin/python3
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys
import json
def send_email(sender, receiver, subject, content):
try:
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
html_body = MIMEText(content, 'html')
msg.attach(html_body)
try:
server = smtplib.SMTP('smtp.gmail.com',587)
server.sendmail(sender,receiver,msg.as_string())
server.quit()
return True
except smtplib.SMTPException as ex:
print(ex)
return False
except smtplib.SMTPException as err:
return err
if __name__ == "__main__":
json_file = sys.argv[1]
contentAsJson = {}
with open(json_file) as f:
contentAsJson = json.load(f)
for k,v in contentAsJson.items():
receiver = k
subject = ""
content = ""
for k2,v2 in v.items():
if k2 == "subject":
subject = v2
if k2 == "content":
content = v2
send_email("<EMAIL>", "<EMAIL>", subject, content)
<file_sep><?php
if(isset($_GET["paymentRequested"])){
if(!isset($_GET["id"]) || !isset($_GET["amount"])){
return;
}
$script = getPHPScript();
$id=$_GET["id"];
$amound = $_GET["amount"];
$response = $script->updateAccountBalanceOfUser($id, $amound);
echo json_encode($response);
}
if(isset($_GET["productId"]) && isset($_GET["productNumber"])){
$script = getPHPScript();
$id=$_GET["productId"];
$number = $_GET["productNumber"];
$response = $script->updateProductNumber($id, $number);
echo json_encode($response);
}
if(isset($_GET['accountBalanceRequested'])){
$script = getPHPScript();
$response = $script->getAccountBalanceOfCurrentUser();
echo json_encode($response);
}
if(isset($_REQUEST["first_name"]) && isset($_REQUEST["last_name"]) &&isset($_REQUEST["email"]) && isset($_REQUEST["customer_img"])){
$firstname = $_REQUEST["first_name"];
$lastname = $_REQUEST["last_name"];
$email = $_REQUEST["email"];
$telefon = $_REQUEST["telefon"];
$imaga_name = $_REQUEST["customer_img"];
$script = getPHPScript();
$userInserted = $script->insertUser($firstname, $lastname, $email, $telefon, $imaga_name);
}
if(isset($_REQUEST["articleBoughtRequsted"])){
require_once("login.php");
include("dbConnector.php");
$db = new dbConnector();
$conn = $db->getDBConnection();
if(!isset($_REQUEST["selectedArticleId"])){
echo json_encode("No article selected to buy");
exit;
}
$selectedArticleId = $_REQUEST["selectedArticleId"];
$personId = getSessionUserId();
$sql = 'INSERT INTO person_article_matrix (person_id, article_id, count, buy_date) VALUES ('.$personId.','.$selectedArticleId.',1,now())';
$result = mysqli_query($conn, $sql);
if ($result === TRUE) {
echo "New record created successfully";
//Send email on user
notifyUserForPurchasedArticle($personId, $selectedArticleId);
} else {
echo "Error: ". $sql . "<br>" . $conn->error;
}
$conn->close();
}
$errorByInsertedUser ="success";
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
$script = getPHPScript();
define ('SITE_ROOT', realpath(dirname(__DIR__)));
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0 && $_REQUEST["first_name"] && $_REQUEST["last_name"] && $_REQUEST["email"] && $_REQUEST["telefon"]){
$firstname = $_REQUEST["first_name"];
$lastname = $_REQUEST["last_name"];
$email = $_REQUEST["email"];
$tel = $_REQUEST["telefon"];
$filename = $_FILES["photo"]["name"];
$userInserted = $script->insertUser($firstname, $lastname, $email, $tel, $filename);
//error_log("[dbUtility] user inserted: ".$userInserted, 0);
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png","PNG" => "image/PNG");
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)){
$errorByInsertedUser = "Error: Please select a valid file format.";
}
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize){
$errorByInsertedUser ="Error: File size is larger than the allowed limit.";
}
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
if(file_exists("img/" . $filename)){
$errorByInsertedUser = $filename . " is already exists.";
} else{
if($userInserted == TRUE){
move_uploaded_file($_FILES["photo"]["tmp_name"], SITE_ROOT.'/img/' . $filename);
$errorByInsertedUser = "User and picture inserting successfully";
}
}
} else{
$errorByInsertedUser = "Error: There was a problem uploading your file. Please try again.";
error_log("Error by user image upload : ".$errorByInsertedUser, 0);
}
} else{
$errorByInsertedUser = "Error: " . $_FILES["photo"]["error"];
error_log("Error user insert : ".$errorByInsertedUser, 0);
}
echo json_encode($errorByInsertedUser);
header("Refresh:0; url=../index.php");
}
function notifyUserForPurchasedArticle($personId, $selectedArticleId){
require_once("send_email.php");
$script = getPHPScript();
$email = 'email';
$firstname = 'firstname';
$articleName = 'name';
$personToNotify = json_decode($script->getPersonById($personId));
//error_log("email : ".$personToNotify->$email, 0);
$articleObject = json_decode($script->getArticleById($selectedArticleId));
$date = date('Y/m/d H:i:s');
$htmlContent = '
<html>
<head>
<title>Flex Kitchen</title>
</head>
<body>
<div>
<p>Hallo '.$personToNotify->$firstname.',</p>
<p>Du hast gerade ein(e) '.$articleObject->$articleName.' gekauft</p><br/>
<p>Dies ist eine automatisch erstellte E-Mail. Bitte ANTWORTE NICHT auf diese Mail</p>
<p> Der Kauf wurde vom PC (<b>'.$_SERVER["REMOTE_ADDR"].'</b>) durchgeführt</p>
</div>
<br/>
<p>Viele Grüße </p>
<p>Flex Kitchen </p>
</body>
</html>';
$subject = "Du hast eine Getränke am ".$date." gekauft";
sendEmailToCustomer($personToNotify->$email, $htmlContent, $subject);
}
if(isset($_GET['setUserInActive'])){
$personId=$_GET["personId"];
$script = getPHPScript();
$response = $script->setUserInActive($personId);
echo json_encode($response);
}
if(isset($_GET['setUserInActive'])){
$personId=$_GET["personId"];
$script = getPHPScript();
$response = $script->setUserInActive($personId);
echo json_encode($response);
}
if(isset($_GET['deleteProductRequested'])){
$personId=$_GET["productId"];
$script = getPHPScript();
$response = $script->setUserInActive($personId);
echo json_encode($response);
}
function getPHPScript(){
require_once("../php_script.php");
return new FunctionScript();
}
?>
<file_sep><?php
// Create connection
class dbConnector{
public function __construct(){
}
public function getDBConnection(){
$conn = mysqli_connect("localhost", "flex_user", "cxz6KNEQn8YJe0UN", "flex_kitchen");
return $conn;
}
}
?><file_sep><?php
class FunctionScript{
public function getAccountBalanceOfCurrentUser(){
require_once("login.php");
//$currentUserId = $this->getSessionUserId();
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->getAccountBalanceOfCurrentUser();
return $result;
}
public function updateAccountBalanceOfUser($userId, $amount){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->updateAccountBalanceOfUser($userId, $amount);
return $result;
}
function updateProductNumber($productId, $productNumber){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->updateProductNumber($productId, $productNumber);
return $result;
}
public function getPersonById($personId){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->getPersonById($personId);
return $result;
}
public function getArticleById($articleId){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->getArticleById($articleId);
return $result;
}
public function getAllFromTable($tableName){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->getAllFromTable($tableName);
return $result;
}
public function getAllPersonFromDB(){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->getAllPersonFromDB();
return $result;
}
public function getCategoriesFromDB(){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->getCategoriesFromDB();
return $result;
}
public function insertUser($firstname, $lastname, $email, $telefon, $img_path){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->insertUser($firstname, $lastname, $email, $telefon, $img_path);
return $result;
}
public function insertArticle($articleName, $category, $price, $filename){
$fetchDataFromDB = $this->getDBFacadeScript();
$result = $fetchDataFromDB->insertArticle($articleName, $category, $price, $filename);
return $result;
}
public function getUserLIs(){
$persons = $this->getAllPersonFromDB();
$result = "<h2>No User found... :'(</h2>";
if($persons->num_rows >0){
$result = "";
while($row = $persons->fetch_assoc()){
//don't show admin in index page
if($row["is_admin"] == "1") continue;
$user = $row["firstname"]." ".$row["lastname"];
$id = $row["id"];
$src = $this->createUserImagePath($row["img_path"]);
$result = $result.'<li class="user_div" id="'.$id.'">
<div class="user_img" style="background-image: url(\''.$src.'\');" href="#" onclick="clickUser(\''.$id.'\')"></div>
<span class="name_label_span">'.$user.'</span></li>';
}
}
return $result;
}
public function getArticleLIs(){
$persons = $this -> getAllFromTable("article");
$result = "<h2>No Article found... :'(</h2>";
if($persons->num_rows >0){
$result = "";
while($row = $persons->fetch_assoc()){
$id = $row["id"];
$imgUrl = $this->createUserImagePath($row["img_path"]);
$result = $result.'<li class="article_li" style="width:fil-content">
<div class="article_li_div" id="'.$id.'">
<div class="notify-badge"><strong>'.$row["price"].' €</strong></div>
<div class="article_li_img" style="background-image: url(\''.$imgUrl.'\');" href="#" onclick="clickArticle(\''.$id.'\')"></div>
<span class="name_label_span">'.$row["name"].'</span>
</div>
</li>';
}
}
return $result;
}
public function getAllPurchasedArticlesForPersonSince($personId, $sinceXMonth){
$dbFacadaScript = $this->getDBFacadeScript();
$purchasedArticlesByIds = $fetchDataFromDB-> getAllPurchasedArticlesForPersonFromDB($personId, $sinceXMonth);
return $purchasedArticlesByIds;
}
public function getAllPurchasedArticlesByDate($personId, $sinceXMonth){
$dbFacadaScript = $this->getDBFacadeScript();
$purchasedArticlesByDate = $dbFacadaScript->getAllPurchasedArticlesByDate($personId, $sinceXMonth);
return $purchasedArticlesByDate;
}
public function getUserPaymentByDate($personId, $sinceXMonth){
$dbFacadaScript = $this->getDBFacadeScript();
$userPaymentByDate = $dbFacadaScript->getUserPaymentByDate($personId, $sinceXMonth);
return $userPaymentByDate;
}
public function getLastPurchasedArticle($personId){
$fetchDataFromDB = $this->getDBFacadeScript();
$purchasedArticle = $fetchDataFromDB-> getLastPurchases($personId);
return $purchasedArticle;
}
public function setUserInActive($personId){
$fetchDataFromDB = $this->getDBFacadeScript();
$userInActiveSuccess = $fetchDataFromDB->setUserInActive($personId);
return $userInActiveSuccess;
}
public function createUserImagePath($image_path){
if(strpos($image_path, 'http') !== false){
return $image_path;
}else{
return 'img/'.str_replace(" ","%20",$image_path);
}
}
function getDBFacadeScript(){
require_once("php_scripts/dbFetchDataFromDB.php");
return new fetchDataFromDB();
}
}
?>
<file_sep><?php
/**
*
* @author <NAME>
*/
class fetchDataFromDB {
public function __construct(){
}
function getDBConnection(){
require_once("dbConnector.php");
$db = new dbConnector();
$conn = $db->getDBConnection();
return $conn;
}
public function getLastPurchases($personId){
$conn = $this->getDBConnection();
$sql = 'SELECT a.name as name, pam.person_id as person_id, pam.buy_date as buy_date
FROM article a, person_article_matrix pam
WHERE a.id = pam.article_id AND pam.person_id = '.$personId.' ORDER BY pam.id DESC LIMIT 1';
$result = $conn->query($sql);
$response['name'] = "Noch nichts gekauft";
$response['id'] = -1;
$response['person_id'] = -1;
$response['buy_date'] = "00.00.00.00";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['name'] = $row["name"];
$response['person_id'] = $row["person_id"];
$response['buy_date'] = $row["buy_date"];
}
}else{
error_log("[dbFechDataFromDB -> getLastPurchases] no last purchases article found");
}
$conn->close();
return $response;
}
public function getAllPurchasedArticlesForPersonFromDB($personId, $sinceXMonth){
$conn = $this->getDBConnection();
$sql = 'SELECT article_id, sum(count) as sum
FROM person_article_matrix
WHERE person_id = '.$personId.' && buy_date > DATE_ADD(CURDATE(), INTERVAL -'.$sinceXMonth.' MONTH) GROUP BY article_id ORDER BY buy_date DESC';
$result = $conn->query($sql);
$purchasedArticlesByArticleId;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['article_id'] = $row["article_id"];
$response['sum'] = $row["sum"];
$purchasedArticlesByArticleId[$row["article_id"]] = $response;
}
}else{
error_log("[dbFechDataFromDB -> getAllPurchasedArticlesForPersonFromDB] no purchases articles found");
return -1;
}
$conn->close();
return json_encode($purchasedArticlesByArticleId);
}
public function getAllPurchasedArticlesByDate($personId, $sinceXMonth){
$conn = $this->getDBConnection();
$sql = 'SELECT a.name as article_name, pam.buy_date as buy_date
FROM person_article_matrix pam, article a
WHERE pam.person_id = '.$personId.' && pam.buy_date > DATE_ADD(CURDATE(), INTERVAL -'.$sinceXMonth.' MONTH) &&
pam.article_id = a.id ORDER BY buy_date DESC';
$result = $conn->query($sql);
$purchasedArticlesByArticleId;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['article_name'] = $row["article_name"];
$response['buy_date'] = $row["buy_date"];
$purchasedArticlesByArticleId[$row["buy_date"]] = $response;
}
}else{
error_log("[dbFechDataFromDB -> getAllPurchasedArticlesForPersonFromDB] no purchases articles found");
return -1;
}
$conn->close();
return $purchasedArticlesByArticleId;
}
public function getAllPurchasedArticlesHistoryByPerson($personId, $sinceXMonth){
$conn = $this->getDBConnection();
$sql = 'SELECT a.name as action_desc, pam.buy_date as action_date, pam.price as amount, pam.account_balance
FROM person_article_matrix pam, article a
WHERE pam.person_id = '.$personId.' && pam.buy_date > DATE_ADD(CURDATE(), INTERVAL -'.$sinceXMonth.' MONTH) &&
pam.article_id = a.id ORDER BY buy_date DESC';
error_log($sql);
$result = $conn->query($sql);
$personHistory;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['action_desc'] = $row["action_desc"];
$response['action_date'] = $row["action_date"];
$response['amount'] = $row["amount"];
$response['account_balance'] = $row["account_balance"];
$personHistory[$row["action_date"]] = $response;
}
}else{
error_log("[dbFechDataFromDB -> getAllPurchasedArticlesForPersonFromDB] no purchases articles found");
return -1;
}
$conn->close();
return $personHistory;
}
public function getUserPaymentByDate($personId, $sinceXMonth){
$conn = $this->getDBConnection();
$sql = 'SELECT amount, pay_date as action_date, account_balance_state as account_balance
FROM person_payment_matrix
WHERE person_id = '.$personId.' && pay_date > DATE_ADD(CURDATE(), INTERVAL -'.$sinceXMonth.' MONTH)';
$result = $conn->query($sql);
$paymentByDate = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['action_date'] = $row["action_date"];
$response['action_desc'] = "EINZAHLUNG";
$response['amount'] = $row["amount"];
$response['account_balance'] = $row["account_balance"];
$paymentByDate[$row["action_date"]] = $response;
}
}else{
error_log("[dbFechDataFromDB -> getUserPaymentByDate] no payment found for user id ".$personId);
}
$conn->close();
$personHistory = $this->getAllPurchasedArticlesHistoryByPerson($personId, $sinceXMonth);
//$dateTime = strtotime($row["action_date"])
$result = array_merge($paymentByDate,$personHistory);
//ksort($result);
krsort($result);
return $result;
}
public function getAllPersonsFromDB(){
$conn = $this->getDBConnection();
$sql = 'SELECT * FROM person WHERE is_admin="0" AND is_active="1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$counter = 0;
$customers;
while($row = $result->fetch_assoc()) {
$response['id'] = $row["id"];
$response['firstname'] = $row["firstname"];
$response['lastname'] =$row["lastname"];
$response['email'] = $row["email"];
$response['img_path'] = $row["img_path"];
$response['account_balance'] = $row["account_balance"];
$customers[$counter] = $response;
$counter++;
}
$conn->close();
return json_encode($customers);
} else {
error_log("[dbFechDataFromDB -> getAllPersonsFromDB] no person found from db");
return json_encode("-1");
}
}
function getPersonById($personId){
$conn = $this->getDBConnection();
$sql = 'SELECT * FROM person WHERE id ='.$personId.' AND is_admin="0" AND is_active=1';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$person;
while($row = $result->fetch_assoc()) {
$person['id'] = $row["id"];
$person['firstname'] = $row["firstname"];
$person['lastname'] =$row["lastname"];
$person['email'] = $row["email"];
$person['img_path'] = $row["img_path"];
$person['account_balance'] = $row["account_balance"];
}
$conn->close();
return json_encode($person);
} else {
error_log("[dbFechDataFromDB -> getPersonById] no person found for id ".$personId);
return json_encode("-1");
}
}
function getArticleById($articleId){
$conn = $this->getDBConnection();
$sql = 'SELECT * FROM article WHERE id ='.$articleId;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$person;
while($row = $result->fetch_assoc()) {
$person['id'] = $row["id"];
$person['name'] = $row["name"];
$person['price'] =$row["price"];
$person['count'] = $row["count"];
$person['category'] = $row["category"];
$person['img_path'] = $row["img_path"];
}
$conn->close();
return json_encode($person);
} else {
error_log("[dbFechDataFromDB -> getArticleById] no article found for id ".$articleId);
return json_encode("-1");
}
}
function getArticleFromDB($productId){
$conn = $this->getDBConnection();
$sql = 'SELECT * FROM article WHERE id ='.$productId;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$article['id'] = $row["id"];
$article['name'] = $row["name"];
$article['price'] = $row["price"];
$article['count'] = $row["count"];
$article['category'] = $row["category"];
$article['img_path'] = $row["img_path"];
}
return $article;
} else {
error_log("[dbFechDataFromDB -> getArticleFromDB] no article found for id ".$productId);
return "-1";
}
$conn->close();
}
public function getAllFromTable($tableName){
$conn = $this->getDBConnection();
if (!$conn) {
die('database connectin fails: ' . mysql_error());
}
$sql = "SELECT DISTINCT * FROM ".$tableName;
$result = $conn->query($sql);
$conn->close();
return $result;
}
public function getAllPersonFromDB(){
$conn = $this->getDBConnection();
if (!$conn) {
die('database connectin fails: ' . mysql_error());
}
$sql = "SELECT DISTINCT * FROM person WHERE is_active = 1";
$result = $conn->query($sql);
$conn->close();
return $result;
}
public function getAccountBalanceOfCurrentUser(){
require_once("login.php");
$conn = $this->getDBConnection();
$userId = getSessionUserId();
$person = json_decode($this->getPersonById($userId));
$account_balance = "account_balance";
$oldAccountBalance = floatval($person->$account_balance);
$conn->close();
return $oldAccountBalance;
}
public function updateAccountBalanceOfUser ($userId, $amount){
$conn = $this->getDBConnection();
$person = json_decode($this->getPersonById($userId));
$account_balance = 'account_balance';
$oldAccountBalance = floatval($person->$account_balance);
$newAccountBalance = $oldAccountBalance + floatval($amount);
$response = "";
$sql = 'UPDATE person SET account_balance = '.$newAccountBalance.' WHERE id ='.$userId;
if ($conn->query($sql) === FALSE) {
$response = "Error updating record: " . $conn->error;
}else{
$response = array('newBalance'=>(string)$newAccountBalance);
}
$conn->close();
$this->userPaid($userId, $amount);
return $response;
}
public function userPaid($personId, $amount){
$person = json_decode($this->getPersonById($personId));
$account_balance = 'account_balance';
$personAccountState = floatval($person->$account_balance);
$conn = $this->getDBConnection();
$sql = 'INSERT INTO person_payment_matrix(person_id, amount, pay_date,account_balance_state) VALUES ('.$personId.' , '.$amount.', now(),'.$personAccountState.')';
if ($conn->query($sql) === FALSE) {
error_log("Error occoured while payment process :".$conn->error);
}
$conn->close();
}
public function updateProductNumber($productId, $productNumber){
$conn = $this->getDBConnection();
$article = json_decode($this->getArticleById($productId));
$count = 'count';
$oldAccountBalance = floatval($article->$count);
$newAccountBalance = $oldAccountBalance + $productNumber;
$response = "";
$sql = 'UPDATE article SET count = '.$newAccountBalance.' WHERE id ='.$productId;
if ($conn->query($sql) === FALSE) {
$response = "Error updating record: " . $conn->error;
}else{
$response = array('newCount'=>(string)$newAccountBalance);
}
$conn->close();
return $response;
}
function getCategoriesFromDB(){
$conn = $this->getDBConnection();
$sql = 'SELECT * FROM category';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$row["id"]] = $row["name"];
}
return $response;
} else {
error_log("[dbFechDataFromDB -> getCategoriesFromDB] no categories found ");
return "-1";
}
$conn->close();
}
public function insertUser($firstname, $lastname, $email, $telefon, $img_path){
$conn = $this->getDBConnection();
$imaga_name = $img_path;
$response = "not inserted";
$sql = 'INSERT INTO person (firstname, lastname, email, tel_no, img_path, account_balance, is_admin, user_pw, is_active)
VALUES ("'.$firstname.'","'.$lastname.'","'.$email.'", "'.$telefon.'","'.$imaga_name.'", 0, 0,"cfcd208495d565ef66e7dff9f98764da",1)';
$result = $conn->query($sql);
if($result){
$response = "Records added successfully.";
} else{
$response = "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
$conn->close();
return $response;
}
public function insertArticle($articleName, $category, $price, $filename){
$conn = $this->getDBConnection();
$response = "not inserted";
$sql = 'INSERT INTO article (name, price, count, category, img_path) VALUES ("'.$articleName.'",'.$price.',0,'.$category.',"'.$filename.'")';
$result = $conn->query($sql);
if($result){
$response = "Records added successfully.";
} else{
$response = "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
$conn->close();
return $response;
}
public function setUserInActive($personId){
$conn = $this->getDBConnection();
$response = 1;
$sql = 'UPDATE person SET is_active = 0 WHERE id ='.$personId;
if ($conn->query($sql) === FALSE) {
error_log("[dbFechDataFromDB -> setUserInActive] can not set person inactive");
$response = 0;
}
$conn->close();
return $response;
}
}
<file_sep><?php
include("dbConnector.php");
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
require_once("../php_script.php");
$script = new FunctionScript();
define ('SITE_ROOT', realpath(dirname(__DIR__)));
$articleInserted ="success";
// Check if file was uploaded without errors
if(isset($_FILES["product_img"]) && $_FILES["product_img"]["error"] == 0 && $_REQUEST["product_name"] && $_REQUEST["product_category"] && $_REQUEST["product_price"]){
$articleName = $_REQUEST["product_name"];
$category = $_REQUEST["product_category"];
$price = $_REQUEST["product_price"];
$filename = $_FILES["product_img"]["name"];
$articleInserted = $script->insertArticle($articleName, $category, $price, $filename);
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png","PNG" => "image/PNG");
$filetype = $_FILES["product_img"]["type"];
$filesize = $_FILES["product_img"]["size"];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)){
$articleInserted = "Error: Please select a valid file format.";
}
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize){
$articleInserted ="Error: File size is larger than the allowed limit.";
}
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
if(file_exists("img/" . $filename)){
$articleInserted = $filename . " is already exists.";
} else{
if($articleInserted == TRUE){
move_uploaded_file($_FILES["product_img"]["tmp_name"], SITE_ROOT.'/img/' . $filename);
$articleInserted = "User and picture inserting successfully";
}
}
} else{
$articleInserted = "Error: There was a problem uploading your file. Please try again.";
}
} else{
$articleInserted = "Error: " . $_FILES["product_img"]["error"];
}
echo json_encode($articleInserted);
header("Refresh:0; url=../index.php");
}
if(isset($_GET["id"])){
$id = $_GET["id"];
$db = new dbConnector();
$conn = $db->getDBConnection();
$sql = 'SELECT * FROM article WHERE id ='.$id;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['id'] = $row["id"];
$response['name'] = $row["name"];
$response['price'] =$row["price"];
$response['img_path'] = $row["img_path"];
}
echo json_encode($response);
} else {
echo "Error: ". $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<file_sep><?php
function sendMonthlyEmails(){
$all_emails = array();
$allPersons = json_decode(getAllPersons());
foreach($allPersons as $customer){
$lastMonth= getMonthInGerman(date("M", strtotime("last month")));
$purchasedArticlesJSON = getAllPurchasedArticlesForCustomer($customer->id, 1);
if($purchasedArticlesJSON == "-1") continue;
$purchasedArticles = json_decode($purchasedArticlesJSON);
$row='';
$totalAmound = 0;
foreach($purchasedArticles as $purchasedArticle){
$articleObject = getArticle($purchasedArticle->article_id);
$articleName = $articleObject["name"];
$articlePrice = $articleObject["price"];
$numberOfPurchasedArticle = $purchasedArticle->sum;
$price = $numberOfPurchasedArticle * $articlePrice;
$row= $row.' <tr style="background-color: #e0e0e0;height:20">
<td>'.$articleName.'</td><td>'.$numberOfPurchasedArticle.'</td><td>'.$price.' €</td>
</tr>';
$totalAmound = $totalAmound + $price;
}
$accountBalance = $customer->account_balance;
$customerMsg = '<p>Bitte bezahle den Betrag vom <strong><span style="background-color:red">'.$accountBalance.' €</span></strong> bei zuständigen Person!</p>';
if($customer->account_balance >= 0){
$customerMsg = '<p>Du hast noch einen Guthaben vom <strong><span style="background-color:#00800075">'.$accountBalance.' € </span></strong> daher musst Du nix bezahlen!</p>';
}
$htmlContent = '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div>
<p>Hallo '.$customer->firstname.',</p>
<p>Im folgenden erhaltest Du eine Getränkeliste und Abrechnung für den Monat <strong>'.$lastMonth.' '.date('Y').'.</strong></p>
</div>
<div>
<table style="width: 100%; max-width:800px;border: 1px slid #FB4314; padding-right:10px;">
<tr style="background-color: #808080;height:20">
<th>Getränk</th> <th>Anzahl</th> <th>Preis</th>
'.$row.'
<tr style="border:2;height:20">
<td></td><td></td><td>Gesamtbetrag: <strong>'.$totalAmound.' € </strong></td>
</tr>
</table>
</div>
<table>
'.$customerMsg.'
<p>Dies ist eine automatisch erstellte E-Mail. Bitte ANTWORTE NICHT auf diese Mail</p>
</table>
<br/>
<p>Viele Grüße </p>
<p>Flex Kitchen </p>
</div>
</body>
</html>';
$lastMonth= getMonthInGerman(date("M", strtotime("last month")));
$subject = 'Die Getränkeabrechnung '.$lastMonth.' '.date('Y');
$email = array();
$email["subject"] = $subject;
$email["content"] = $htmlContent;
//$all_emails[$customer->email] = $email;
$all_emails["<EMAIL>"] = $email;
}
// open tem file to write email
sendEmail($all_emails);
}
function sendEmail($emails){
$fileName = "temp_email_file.json";
$fp = fopen($fileName, 'w');
fwrite($fp, json_encode($emails));
fclose($fp);
if(empty($emails)){
error_log("No Emails to send");
return;
}
echo shell_exec("python3 send_email.py ".$fileName." 2>&1");
}
function sendEmailToCustomer($to, $htmlContent, $subject){
$all_emails = array();
$email = array();
$email["subject"] = $subject;
$email["content"] = $htmlContent;
$all_emails[$to] = $email;
sendEmail($all_emails);
}
function getAllPersons(){
require_once("dbFetchDataFromDB.php");
$fetchDataFromDB = new fetchDataFromDB();
$result = $fetchDataFromDB->getAllPersonsFromDB();
return $result;
}
function getAllPurchasedArticlesForCustomer($personId, $sinceXMonth){
require_once("dbFetchDataFromDB.php");
$fetchDataFromDB = new fetchDataFromDB();
$result = $fetchDataFromDB->getAllPurchasedArticlesForPersonFromDB($personId,$sinceXMonth);
return $result;
}
function getArticle($articleId){
require_once("dbFetchDataFromDB.php");
$fetchDataFromDB = new fetchDataFromDB();
$article = $fetchDataFromDB->getArticleFromDB($articleId);
return $article;
}
function getMonthInGerman($month){
$months=array(
"January"=>"Januar",
"February"=>"Februar",
"March"=>"März",
"April"=>"April",
"May"=>"Mai",
"June"=>"Juni",
"July"=>"Juli",
"August"=>"August",
"September"=>"September",
"October"=>"Oktober",
"November"=>"November",
"December"=>"Dezember",
//
"Jan" => "Januar",
"Feb"=>"Februar",
"Mar"=>"März",
"Apr"=>"April",
"May"=>"Mai",
"Jun"=>"Juni",
"Jul"=>"Juli",
"Aug"=>"August",
"Sep" => "September",
"Oct"=>"Oktober",
"Nov"=>"November",
"Dec"=>"Dezember",
);
return $months[$month];
}
?>
<file_sep>
<?php
echo'
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/window_style.css">
<div id="add_customer_form" class="login_modal">
<form class="login_modal-content login_animate login_form" action="php_scripts/dbutility.php?" method="POST" enctype="multipart/form-data">
<div class="imgcontainer">
<h4>ADD NEW CUSTOMER</h4>
<div onclick="document.getElementById(\'add_customer_form\').style.display=\'none\'" class="login_close" title="Close Modal">×</div>
</div>
<div class="login_container">
<label><b>First Name</b></label>
<input class="login_input" type="text" placeholder="Enter firstname" name="first_name" required>
<label><b>Last Name</b></label>
<input class="login_input" type="text" placeholder="Enter lastname" name="last_name" required>
<label><b>Email</b></label>
<input class="login_input" type="email" placeholder="e.g. <EMAIL>" name="email" required>
<label><b>Telefon</b></label>
<input class="login_input" type="tel" name="telefon" required>
<label><b>Select picture</b></label>
<input type="file" name="photo" id="user_photo" required>
</div>
<div style="text-align: center; margin-bottom:10px"><button class="button" type="submit">Save</button></div>
</form>
</div>
<script>
// Get the modal
var login_modal = document.getElementById(\'id01\');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == login_modal) {
modal.style.display = "none";
}
}
</script>';
?><file_sep>
<?php
include ("php_script.php");
include ('php_scripts/content_script.php');
echo getCurrentPageContent();
?>
<file_sep>
<?php
echo'
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/window_style.css">
<div id="add_product_form" class="login_modal">
<form class="login_modal-content login_animate login_form" action="php_scripts/dbArticle.php?" method="POST">
<div class="imgcontainer">
<h4>ADD NEW PRODUCT</h4>
<div onclick="document.getElementById(\'add_product_form\').style.display=\'none\'" class="login_close" title="Close Modal">×</div>
</div>
<div class="login_container">
<label><b>Produkt Name</b></label>
<input class="login_input" type="text" placeholder="Enter Name" name="product_name" required>
<label><b>Select Category</b></label>
<div><select name="product_category">
'.getCategoryOptionsElement().'
</select></div><br/>
<label><b>Price</b></label>
<input class="login_input" type="text" placeholder="Enter price e.g. 1.0" name="product_price" required>
<label><b>Enter picture name</b></label>
<input class="login_input" type="text" placeholder="e.g. test.png" name="product_img" required>
</div>
<div style="text-align: center; margin-bottom:10px"><button class="button" type="submit">Save</button></div>
</form>
</div>
<script>
// Get the modal
var login_modal = document.getElementById(\'id01\');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == login_modal) {
modal.style.display = "none";
}
}
</script>';
function getCategoryOptionsElement(){
require("php_scripts/dbutility.php");
$categories = getCategoriesFromDB();
$result = "";
foreach ($categories as $key => $value) {
$result = $result."<option value=".$key.">".$value."</option>";
}
return $result;
}
?><file_sep>function login(){
var loginWindow = document.getElementById("admin_login_Window");
loginWindow.style.display = "block";
}
function getUsersInAdminPage(){
$.ajax({
url: 'php_scripts/adminPageContent.php?userRequested=1',
success: function(html) {
document.getElementById('admin_home_manu').innerHTML = html;
document.getElementById('toggle-button').innerHTML = '<img class="icon_image" src="img/add_user_icon.png" onclick="add_new_customer()"/>';
document.getElementById('toggle-button').classList.add('header-btn-container');
}
});
}
function getProducts(){
$.ajax({
url: 'php_scripts/adminPageContent.php?productsRequested=1',
success: function(html) {
document.getElementById('admin_home_manu').innerHTML = html;
document.getElementById('toggle-button').innerHTML = '<img class="icon_image" src="img/add_product_icon.png" onclick="add_new_product()"/>';
document.getElementById('toggle-button').classList.add('header-btn-container');
}
});
}
function goToAdminHome(){
$.ajax({
url: 'php_scripts/adminPageContent.php?adminHomeRequested=1',
success: function(html) {
document.getElementById('admin_home_manu').innerHTML = html;
document.getElementById('toggle-button').innerHTML = "";
document.getElementById('toggle-button').classList.remove('header-btn-container');
}
});
}
function goToUserHistoryPage(personId){
$.ajax({
url: 'php_scripts/adminPageContent.php?userHirstoryPageRequested=1&personId='+personId,
success: function(html) {
document.getElementById('admin_home_manu').innerHTML = html;
document.getElementById('toggle-button').innerHTML = '<img class="icon_image" src="img/go-back-arrow.png" onclick="getUsersInAdminPage()"/>';
document.getElementById('toggle-button').classList.add('header-btn-container');
}
});
}
function add_new_product(){
var loginWindow = document.getElementById("add_product_form");
loginWindow.style.display = "block";
}
function add_new_customer(){
var addNewEmployeeWindow = document.getElementById("add_customer_form");
addNewEmployeeWindow.style.display = "block";
}
function showUserHistory(since, personId){
var slider = document.getElementById("myRange");
var output = document.getElementById("sinceXMonth");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
$.ajax({
url: 'php_scripts/adminPageContent.php?userHistoryRequested=1&since='+since+"&personId="+personId,
success: function(html) {
let response = JSON.parse(html);
document.getElementById('user_products_history_area').innerHTML = response["productList"];
document.getElementById('user_payments_history_area').innerHTML = response["payments"];
}
});
}
function searchUserInAdminPage(){
var value = document.getElementById("searchInAdminPage").value;
$(".column").each(function() {
if ($(this).text().toLowerCase().search(value.toLowerCase()) > -1) {
$(this).show();
}
else {
$(this).hide();
}
});
}
function checkInputForNumber(inputPayment,buttonId) {
var input = document.getElementById(inputPayment);
var payButton = document.getElementById(buttonId);
var x=input.value;
if (!isInputedAmoundValid(x) && x !="")
{
input.style.backgroundColor="#FF0000";
}else{
input.style.backgroundColor="#FFF";
}
}
function updateUserAmount(userId, inputFieldId){
var input = document.getElementById(inputFieldId);
var amound = input.value;
if(isInputedAmoundValid(amound)){
$.ajax({
url: 'php_scripts/dbutility.php?paymentRequested=1&id='+userId+'&amount='+amound,
success: function(html) {
var obj = JSON.parse(html);
var idOfBalanceToBeUpdated = "accountBalance"+userId;
document.getElementById(idOfBalanceToBeUpdated).innerHTML = obj["newBalance"]+" €";
input.value = "";
}
});
}
}
function updateProductNumber(productId, inputFieldId){
var input = document.getElementById(inputFieldId);
var productNumber = input.value;
if (isInteger(productNumber)){
$.ajax({
url: 'php_scripts/dbutility.php?productId='+productId+'&productNumber='+productNumber,
success: function(html) {
var obj = JSON.parse(html);
var idOfBalanceToBeUpdated = "numOfProduct"+productId;
var numberOfProduct = obj["newCount"];
document.getElementById(idOfBalanceToBeUpdated).innerHTML = numberOfProduct+" Stück";
input.value = "";
}
});
}
}
function confirmUserDeleting(personName, personId){
var r = confirm("Möchten Sie wirklich "+personName+" löschen?");
if (r == true) {
setUserInActive(personId);
}
}
function setUserInActive(personId){
$.ajax({
url: 'php_scripts/dbutility.php?personId='+personId+'&setUserInActive=1',
success: function(html) {
var obj = JSON.parse(html);
getUsersInAdminPage();
}
});
}
function confirmProductDeleting(productName, productId){
var r = confirm("Möchten Sie wirklich das Product "+productName+" löschen?");
if (r == true) {
deleteProduct(productId);
}
}
function deleteProduct(productId){
$.ajax({
url: 'php_scripts/dbutility.php?productId='+productId+'&deleteProductRequested=1',
success: function(html) {
var obj = JSON.parse(html);
getProducts();
}
});
}
function isInteger(x) {
return x % 1 === 0;
}
function isInputedAmoundValid(value){
var regex=/^\-?([1-9]\d*|0)(\.\d?[1-9])?$/;
if(value=="" || !value.match(regex)) {
return false;
}
else{
return true;
}
}
<file_sep><?php
echo'
<style>
/* Full-width input fields */
.login_input {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
/* Extra styles for the cancel button */
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
/* Center the image and position the close button */
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
position: relative;
}
img.avatar {
width: 40%;
border-radius: 50%;
}
.login_container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
/* The Modal (background) */
.login_modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
padding-top: 60px;
}
/* Modal Content/Box */
.login_modal-content {
background-color: #fefefe;
margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
border: 1px solid #888;
width: 30%; /* Could be more or less, depending on screen size */
}
/* The Close Button (x) */
.login_close {
position: absolute;
right: 25px;
top: 0;
color: #000;
font-size: 35px;
font-weight: bold;
background-color: red;
margin-top: -24px;
margin-right: -25px;
width: 35px;
}
.login_close:hover,
.login_close:focus {
color: red;
cursor: pointer;
}
/* Add Zoom Animation */
.login_animate {
-webkit-animation: animatezoom 0.6s;
animation: animatezoom 0.6s
}
@-webkit-keyframes animatezoom {
.login_from {-webkit-transform: scale(0)}
to {-webkit-transform: scale(1)}
}
@keyframes animatezoom {
.login_from {transform: scale(0)}
to {transform: scale(1)}
}
@media only screen and (max-device-width : 300px) {
.login_modal-content{width: 80%}
}
@media (max-width : 300px) {
.login_modal-content{width: 80%}
}
</style>
<div id="id01" class="login_modal">
<form class="login_modal-content login_animate login_form" action="php_scripts/login.php?login=1" method="POST">
<div class="imgcontainer">
<div onclick="document.getElementById(\'id01\').style.display=\'none\'" class="login_close" title="Close Modal">×</div>
<img style="width:200px"src="img/login_avatar.png" alt="Avatar" class="avatar">
</div>
<div class="login_container">
<label><b>EMail Address</b></label>
<input class="login_input" type="text" placeholder="Enter EMail" name="email" required>
<label><b>Password</b></label>
<input class="login_input" type="password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
</div>
<div></div>
</form>
</div>
<script>
// Get the modal
var login_modal = document.getElementById(\'id01\');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == login_modal) {
modal.style.display = "none";
}
}
</script>';
?><file_sep><?php
include "dbutility.php";
function getCurrentPageContent(){
require_once(__DIR__."/login.php");
$currentPageContent = getHomePageContent(); //= getLoginPage();
if(hasSession()){
if(isAdmin()){
$currentPageContent = getAdminPage();
}else{
$currentPageContent = getArticlePage();
}
}
return $currentPageContent;
}
function getUserAccountBalance(){
require_once("php_script.php");
$script = new FunctionScript();
$currentUserId = getSessionUserId();
$purchasedArticle = $script->getLastPurchasedArticle($currentUserId);
$articleName = $purchasedArticle['name'];
$date = $purchasedArticle['buy_date'];
$amound = $script->getAccountBalanceOfCurrentUser();
$color= "#616367";
if( floatval($amound) < 0){
$color= "#bf0000";
}
return '<div class="balance-container">
<span>Kontostand: </span><span style="color: '.$color.'">'.$amound.' €</span>
</div>
<div class="lastbuy-container">
<span>Letzter Kauf: </span><span>'.$articleName.' ('.$date.')</span>
</div>';
}
function getHomePageContent(){
require_once("./php_script.php");
$script = new FunctionScript();
return '<!DOCTYPE html>
<html>'.getPageScriptBinding().'<head>
</head>
<body>
<header>Mitarbeiter wählen</header>
<div class="content">
<form class="search_form">
<div>
<input type="text" class="search" id="search" placeholder="Search for names.." title="Type in a name">
</div>
</form>
<div class="users">'.$script->getUserLIs().'</div>'.getLoginPage().'
</div>
<footer>
<div style="float:right" id="adminLoginBtn"><img style="width:45px; float:right;" src="img/adminLogginImg.png" href="#" onclick="login()"></img></div>
</footer>
<!--'.getFooter().'-->';
}
function getAdminPage(){
return '
<!DOCTYPE html>
<html><link rel="stylesheet" href="./css/window_style.css">'.getPageScriptBinding().'<head>
<style>
.product_count {
width: 60px;
height: 40px;
padding: 1px;
border: none;
border: 1px solid #555;
font-weight: bold;
}
</style>
<script>
</script>
</head>
<body">
<header>Admin</header>
<div class="content" id="contentInAdminPage">
<form class="search_form">
<div style="float:right"> <input type="text" class="search" id="searchInAdminPage" onkeyup="searchUserInAdminPage()" placeholder="Search for names.." title="Type in a name"></div>
</form>
<menu id="admin_home_manu" style="padding-left:0px">'.getAdminPageContent().'</menu>'.getWindowToAddNewProduct().getWindowToAddNewPerson().'
<!--<div id="header_second_column_in_admin"><div>-->
</div>
<footer class="admin-footer" id="admin-footer">
<div class="header-btn-container" id="logout-from-admin"><img class="user_logout_img user_logout_in_admin_page" src="img/user_logout.png" href="#" onclick="closeAdminSite()"></img></div>
<div class="" id="toggle-button"></div>
<div class="header-btn-container" id="admin-home-button"><img class="home-btn" src="img/home.png" href="#" onclick="goToAdminHome()"></img></div>
</footer>
<!--'.getFooter().'-->';
}
function getArticlePage(){
require_once("login.php");
require_once("php_script.php");
$script = new FunctionScript();
return '
<!DOCTYPE html>
<html>'.getPageScriptBinding().'<head>
</head>
<body">
<header>
<div id="loggedUserName">'.getCurrentUserName().'</div></div>
</header>
<div class="content">
<div><form class="search_form"><input class="search" type="text" id="search" placeholder="Search for article.." title="Type in a name"></form></div>
<div class="articles">'.$script->getArticleLIs().'</div>
</div>
<footer class="articlepage-footer">
<div class="footer-container">
<div class="header-btn-container"><img class="user_logout_img user_logout_in_article_page" src="img/user_logout.png" href="#" onclick="closeAdminSite()"></img></div>
<div id="loggedUserImg" class="user_profil_icon" style="background-image:url(\''.$script->createUserImagePath(getCurrentUserImagePath()).'\')"></div>
<div class="user_info">'.getUserAccountBalance().'</div>
</div>
</footer>
<!--'.getFooter().'--><div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div>Du hast</div>
<div id="selectedProductName">Getränk</div>
<div>gewählt!</div>
<div class="confirm-container">
<button class="popupButton" id="productConfirmationBtn" style="background-image:url(\'img/ok_btn.png\')" onclick="sendSelectedProductForUser()">bestätigen</button>
<button class="popupButton" id="productCancelationBtn" style="background-image:url(\'img/x_btn.png\')">abbrechen</button>
</div>
</div>
</div>';
}
function getFooter(){
return '<div class="footer">
<footer id="footer">Copyright © e-oku.de</footer>
</div>
</div>
</body>
</html>';
}
function getPageScriptBinding(){
return '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script type="text/javascript" src="function.js"></script>
<script type="text/javascript" src="./js/administration.js"></script>
<link href="http://fonts.googleapis.com/css?family=Open+Sans|Baumans" rel="stylesheet" lazyload/>
<link rel="stylesheet" href="./css/style.css">';
}
function getLoginPage(){
return '
<div id="admin_login_Window" class="login_modal">
<form class="login_modal-content login_animate login_form" action="php_scripts/login.php?admin_login_requested=1" method="POST">
<div class="imgcontainer">
<div onclick="document.getElementById(\'admin_login_Window\').style.display=\'none\'" class="login_close" title="Close Modal">×</div>
<img style="width:110px"src="img/adminLogginImg.png" alt="Avatar" class="avatar">
</div>
<div class="login_container">
<label><b>EMail Address</b></label>
<input class="login_input" type="text" placeholder="Enter EMail" name="email" required>
<label><b>Password</b></label>
<input class="login_input" type="password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
</div>
<div><!--Error msg here--></div>
</form>
</div>
<script>
var login_modal = document.getElementById(\'admin_login_Window\');
window.onclick = function(event) {
if (event.target == login_modal) {
modal.style.display = "none";
}
}
</script>';
}
function getAdminPageContent(){
return '<li style="width:fil-content">
<div class="admin_menu_div">
<div class="admin_menu_img" style="background-image: url(\'img/users.png\');" href="#" onclick="getUsersInAdminPage()"></div>
<p>Employees</p>
</div>
</li>
<li style="width:fil-content">
<div class="admin_menu_div">
<div class="admin_menu_img" style="background-image: url(\'img/products.png\');" href="#" onclick="getProducts()"></div>
<p>Products</p>
</div>
</li>
<li style="width:fil-content">
<div class="admin_menu_div">
<div class="admin_menu_img" style="background-image: url(\'img/setting.png\');" href="#" onclick="showSetting()"></div>
<p>Setting</p>
</div>
</li>';
}
function getWindowToAddNewProduct(){
return'
<div id="add_product_form" class="login_modal">
<form class="login_modal-content login_animate login_form" action="php_scripts/dbArticle.php?" method="POST" enctype="multipart/form-data">
<div class="imgcontainer">
<h4>ADD NEW PRODUCT</h4>
<div onclick="document.getElementById(\'add_product_form\').style.display=\'none\'" class="login_close" title="Close Modal">×</div>
</div>
<div class="login_container">
<label><b style="float:left">Produkt Name</b></label>
<input class="login_input" type="text" placeholder="Enter Name" name="product_name" required>
<label><b style="float:left">Select Category</b></label>
<div><select name="product_category">
'.getCategoryOptionsElement().'
</select></div><br/>
<label><b style="float:left">Price</b></label>
<input class="login_input" type="text" placeholder="Enter price e.g. 1.0" name="product_price" required>
<label><b style="float:left">Select a picture</b></label>
<input type="file" name="product_img" id="article_photo" required>
</div>
<div style="text-align: center; margin-bottom:10px"><button class="button" type="submit">Save</button></div>
</form>
</div>';
}
function getWindowToAddNewPerson(){
return'
<div id="add_customer_form" class="login_modal">
<form class="login_modal-content login_animate login_form" action="php_scripts/dbutility.php?" method="POST" enctype="multipart/form-data">
<div class="imgcontainer">
<h4>ADD NEW CUSTOMER</h4>
<div onclick="document.getElementById(\'add_customer_form\').style.display=\'none\'" class="login_close" title="Close Modal">×</div>
</div>
<div class="login_container">
<label><b style="float:left">First Name</b></label>
<input class="login_input" type="text" placeholder="Enter firstname" name="first_name" required>
<label><b style="float:left">Last Name</b></label>
<input class="login_input" type="text" placeholder="Enter lastname" name="last_name" required>
<label><b style="float:left">Email</b></label>
<input class="login_input" type="email" placeholder="e.g. <EMAIL>" name="email" required>
<label><b style="float:left">Telefon</b></label>
<input class="login_input" type="tel" name="telefon" required>
<label><b style="float:left">Select picture</b></label>
<input class="upload-picture-btn" type="file" name="photo" id="user_photo" required>
<label for="user_photo"><span>Datei auswählen</span></label>
</div>
<div style="text-align: center; margin-bottom:16px"><button class="button" type="submit">Save</button></div>
</form>
</div>';
}
function getCategoryOptionsElement(){
require_once("php_script.php");
$script = new FunctionScript();
$categories = $script->getCategoriesFromDB();
$result = "";
foreach ($categories as $key => $value) {
$result = $result."<option value=".$key.">".$value."</option>";
}
return $result;
}
?>
<file_sep>CREATE DATABASE 'flex_kitchen';
use DATABASE 'flex_kitchen';
CREATE TABLE `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`price` float UNSIGNED NOT NULL,
`count` int(10) UNSIGNED NOT NULL,
`category` int(11) NOT NULL,
`img_path` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `article` (`name`, `price`, `count`, `category`, `img_path`) VALUES
('<NAME>', 1, 20, 1, 'clup_matte.jpg'),
('Caffee', 1.35, 20, 2, 'caffee.jpg'),
('Tee', 0.35, 18, 2, 'cay.jpg'),
('Wasser 1 lt', 1, 18, 1, 'wasser.jpg');
/*CREATE DATABASE USER */
CREATE USER 'flex_kitchen'@'localhost' IDENTIFIED BY 'root';
grant all privileges on flex_kitchen.* to flex_kitchen@'%' identified by 'root';
CREATE TABLE `category` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `category` (`id`, `name`) VALUES
(1, 'cold drinks'),
(2, 'warm drinks');
CREATE TABLE `person` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`firstname` varchar(30) NOT NULL,
`lastname` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`tel_no` int(10) UNSIGNED NOT NULL,
`img_path` varchar(100) DEFAULT NULL,
`account_balance` float DEFAULT NULL,
`is_admin` tinyint(1) DEFAULT NULL,
`user_pw` char(96) DEFAULT NULL,
`active` tinyint(1) DEFAULT 1,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `person` (`firstname`, `lastname`, `email`, `tel_no`, `img_path`, `account_balance`, `is_admin`, `user_pw`) VALUES
('Test', 'Person', '<EMAIL>', 1234, 'userImg1.png', -5.7, 0, 'cfcd208495d565ef66e7dff9f98764da'),
('Mike', 'Hans', '<EMAIL>', 72199, 'userImg2.png', -17.45, 0, 'cfcd208495d565ef66e7dff9f98764da'),
('Hatun', 'Hanim', '<EMAIL>', 8783, 'userImg3.png', 1, 0, 'cfcd208495d565ef66e7dff9f98764da'),
('admin', 'flex', '<EMAIL>', 111, 'admin.png', 0, 1, '897a779351421523cadbafccdce22efe');
CREATE TABLE `person_article_matrix` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`person_id` int(11) NOT NULL,
`article_id` int(11) NOT NULL,
`count` int(11) NOT NULL,
`buy_date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `person_article_matrix` (`person_id`, `article_id`, `count`, `buy_date`) VALUES
(1, 3, 1, '2017-12-30 13:50:15'),
(1, 1, 1, '2017-12-30 13:54:21'),
(1, 3, 1, '2018-01-07 00:00:00');
CREATE TABLE person_payment_matrix (id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY, person_id INT (10) NOT NULL, amount FLOAT default NULL, pay_date DATETIME NOT NULL);
DELIMITER $$
CREATE TRIGGER `update_person_balance` AFTER INSERT ON `person_article_matrix` FOR EACH ROW begin
DECLARE oldBalance FLOAT;
DECLARE articlePrice FLOAT;
DECLARE articleCount INT;
DECLARE newBalance FLOAT;
SET oldBalance = (SELECT account_balance FROM person WHERE id = NEW.person_id);
SET articlePrice = (SELECT price from article where id = NEW.article_id);
SET articleCount = (SELECT count from article where id = NEW.article_id);
SET newBalance = oldBalance - articlePrice;
UPDATE person
SET person.account_balance = newBalance
WHERE person.id = NEW.person_id;
UPDATE article
SET article.count = articleCount-1
WHERE article.id = NEW.article_id;
END
$$
DELIMITER ;
|
1ac2a1511c8e08daafedb124f57e63e7a8f0efa0
|
[
"SQL",
"JavaScript",
"Markdown",
"Python",
"PHP"
] | 21
|
JavaScript
|
kdogan/flex_kitchen
|
e913bcc655f08062d0efbb218f3ecf3c5abf572b
|
15fd34b3e306545db184e45b71a4450171660d17
|
refs/heads/master
|
<repo_name>by46/matrix<file_sep>/doc/matrix.rst
matrix.json Schema
====================
matrix.json为matrix提供元数据, 用于制作镜像。
Schemas
-----------------------------
matrix.json 内容为json格式, 包含多个字段:
- name
必填字段, string类型; 指定最终产生的镜像名称,建议此字段使用项目名
- image
必填字段, string类型; 指定基础镜像, 建议根据不同业务合理选择基础镜像
- tag
必填字段, string类型;指定最终产生镜像的tag, 建议使用MAJOR.MINOR.PATCH模式版本号管理镜像,例如:0.0.1
- port
可选字段, 数组类型, 数组中元素必须为整型;用于指定镜像内的使用端口, 目前只支持TCP端口
- volume
可选字段,数组类型, 数组中元素必须为字符串;用于指定镜像内使用的卷。
- nev
可选字段, 字典类型, 字典key为环境变量的名称, 字典value为环境变量的值;用于指定构建变量中使用的环境变量
- cmd
可选字段, 数组类型,数组中元素必须为字符串;用于指定镜像启动命令
下面给出一个完整的例子:
::
{
"name": "otter",
"image": "docker.neg/python:neg-biz",
"tag": "0.0.1",
"port": [80, 443],
"env": {"PATH": "/opt/matrix:$PATH", "DEBUG": true},
"volume": ["/opt/data", "/opt/home"],
"cmd": [ "python", "main.py", "-P", 8080]
}<file_sep>/matrix.sh
#!/usr/bin/env sh
MATRIX_HOME=$(cd `dirname $0`; pwd)
WORKDIR=/home/matrix
TMP=/tmp/images
DEP=/tmp/matrix
alias fab="fab --fabfile=${MATRIX_HOME}/fabfile.py"
# check volume directory exists
[ ! -d ${WORKDIR} ] && exit 80
# check matrix.json exists
[ ! -f "${WORKDIR}/matrix.json" ] && exit 84
# check matrix.json validate
fab valid_matrix_json:src=${WORKDIR},matrix=${MATRIX_HOME}
[ $? -gt 0 ] && exit 85
cd ${WORKDIR}
# virtualenv ${DEP}
source ${DEP}/bin/activate
if [ -f requirements.txt ]; then
pip install --trusted-host 10.16.78.86 -i http://10.16.78.86:3141/simple -r requirements.txt
# check install result
[ $? -gt 0 ] && exit 81
fi
if [ -f matrix_build.sh ]; then
chmod +x matrix_build.sh
./matrix_build.sh
# check run custom build.sh exit status
[ $? -gt 0 ] && exit 82
fi
mkdir ${TMP}
# collect source file
mkdir -p ${TMP}/opt/biz
fab copy:${WORKDIR},${TMP}/opt/biz
# collect dependency libs
mkdir -p ${TMP}/usr/lib/python2.7/
fab copy:${DEP}/lib/python2.7/site-packages,${TMP}/usr/lib/python2.7/
# package resource
tar zcf images.tgz -C ${TMP} .
# generate Dockerfile
fab gen_docker_file:matrix=${MATRIX_HOME}
# build images
docker build -t $(fab image_name | head -n 1) .
# check docker build result
[ $? -gt 0 ] && exit 83
exit 0
<file_sep>/setup.py
#! /usr/bin/env python
import os.path
from fabric.api import local
if __name__ == '__main__':
tmp = '/usr/local/bin'
local('cp -rvf Dockerfile.in {0}'.format(tmp))
local('cp -rvf matrix-schema.json {0}'.format(tmp))
local('cp -rvf fabfile.py {0}'.format(tmp))
local('cp -rvf matrix.sh {0}'.format(tmp))
local('cp -rvf MANIFEST.in {0}'.format(tmp))
local('chmod +x {0}'.format(os.path.join(tmp, 'matrix.sh')))
<file_sep>/doc/api.rst
API
====
commands
-----
.. automodule:: recipe.commands.basecommand
:members:
:undoc-members:
.. automodule:: recipe.commands.project
:members:
:undoc-members:
.. automodule:: recipe.commands.version
:members:
:undoc-members:
.. automodule:: recipe.commands.listcommand
:members:
:undoc-members:
<file_sep>/cookbook/cookbook.0.0.4.md
Matrix
=========================
Matrix是一个用于构建镜像的镜像。
那为什么需要这样一个镜像?
1. 因为像Python这样的语言,在安装很多第三方包的时候,需要从源码进行编译,需要一个完整的编译工具链, 这样的工具链无形的增加的镜像的大小,并且只会使用一次
Build
---------------------
Pre-installed
---------------------
- build-base
- git
- python
- python-dev
- py-pip
- freetds
- freetds-dev
- docker
- virtualenv
- fabric
- jsonschema
- gevent
```shell
sudo docker run --name onbuild --net=host -i docker.neg/alpine:3.3 /bin/sh
# in container
cat << EOF > /etc/apk/repositories
https://mirrors.tuna.tsinghua.edu.cn/alpine/v3.3/main
https://mirrors.tuna.tsinghua.edu.cn/alpine/v3.3/community
EOF
apk update
apk add build-base
apk add git
apk add python python-dev
apk add py-pip
apk add freetds freetds-dev
apk add docker
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple virtualenv
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple fabric
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jsonschema
virtualenv /tmp/matrix
pip --trusted-host scmesos06 install -i https://scmesos06/simple gevent
exit
# on host
# export container
sudo docker export onbuild > matrix.tar
# import container as a image
cat matrix.tar | sudo docker import - docker.neg/matrix:0.0.4
sudo docker push docker.neg/matrix:0.0.4
# start container
sudo docker pull docker.neg/matrix:0.0.4
sudo docker run --rm -v /home/benjamin/git/otter:/home/matrix -v $(which docker):$(which docker) -v /var/run/docker.sock:/var/run/docker.sock docker.neg/matrix:0.0.4 /usr/local/bin/matrix.sh
```<file_sep>/README.md
# Matrix
Matrix, 是一个制作镜像的工具,它可以让我们制作镜像变得简单。
Matrix,目前还只支持Python
更多详细信息请参见[Matrix 文档](http://scmesos06/docs/by46/matrix/)<file_sep>/TODO.md
# Matrix
1. matrix.json invalidate check - done
2. manifest.ini support
3. fabric script exception process
4. testing for completed
6. support for mapping hosts
7. use jinja2 templates<file_sep>/CHANGELOG.md
# Change log
## 0.0.4
## Added
- pre-install [gevent](http://www.gevent.org/)
- Copy files by MANIFEST.in
## 0.0.2
--------------------------
1. add [virtualenv](https://virtualenv.pypa.io/en/stable)
2. add [Fabric](http://www.fabfile.org)
3. add [jsonschema](https://github.com/Julian/jsonschema)
4. validate matrix.json
## 0.0.1
----------------------------
1. add [alpine build tools chain](http://pkgs.alpinelinux.org/package/v3.4/main/x86_64/build-base)
2. add git
3. add python 2.7.3, python-dev
4. add [freetds](http://www.freetds.org), freetds-dev
5. add docker
<file_sep>/cookbook.md
READ cookbook/cookbook.0.0.3.md<file_sep>/doc/index.rst
.. recipe documentation master file, created by
sphinx-quickstart on Tue Aug 02 13:31:32 2016.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Matrix's documentation!
==================================
Matrix, 是一个制作镜像的工具,它可以让我们制作镜像变得简单。
Matrix,目前还只支持Python
Matrix产生的原因
-----------------------------
- 类似 `Python <https://www.python.org>`_ 这样的开发语言, 在使用过程中,很可能使用到第三方扩展依赖库,有些依赖库需要一个C语言编译环境,但是编译工具往往比较庞大,
例如GCC的编译工具链就比较庞大,如果直接在Docker基础镜像中包含 `GCC <https://gcc.gnu.org/>`_ 编译工具链,就会构造的应用程序镜像的大小也会随之增加。
- Python提供了 `PIP <https://pip.pypa.io/en/stable/>`_ 这样包管理工具,也能很好解决递归依赖的问题,但是他需要一个 `PYPI <https://pypi.python.org/pypi>`_ 仓库。
如果依赖设置散落在众多应用程序的Dockerfile中,管理起来也是比较麻烦。
- 其实项目镜像的制作过程都是大体一致,只需要知道几个简单信息就能完成制作镜像,不用在去维护Dockerfile
Matrix能做什么
-----------------------------
- 安装Python依赖
- 制作发布镜像
如何使用
---------------------------
Matrix使用非常简单, Matrix本身也是一个镜像, 启动之后就可以在容器里面完成镜像的制作。
1. 项目根目录需要包含 ``matrix.json`` 文件,他的内容很简单, 下面给出一个简单的例子:
::
{
"name": "otter", // image name
"image": "docker.neg/python:neg-biz", // image base image name
"tag": "0.0.1", // image tag
"port": [80, 443],
"env": {"PATH": "/opt/matrix:$PATH", "DEBUG": true},
"volume": ["/opt/data", "/opt/home"],
"cmd": [ "python", "main1.py", "-P", 8080] // docker's command line
}
2. 使用也非常简单, 以matrix镜像启动一个容器, 把你的Python项目的路径映射容器中 ``/home/matrix`` 路径,并且 ``/var/run/docker.sock`` 也映射到容器的 ``/var/run/docker.sock`` ,
执行 ``/usr/local/bin/matrix.sh``, 执行命令如下:
::
sudo docker run --rm -v /home/benjamin/git/otter:/home/matrix -v $(which docker):$(which docker) -v /var/run/docker.sock:/var/run/docker.sock matrix:0.0.4 /usr/local/bin/matrix.sh
matrix 有时也会需要错误,你可以根据如下退出码来定位错误原因,错误码如下:
- 退出码80,/home/matrix is not exists
- 退出码81,install requirements.txt error
- 退出码82,run custom build.sh error
- 退出码83,build image error
- 退出码84,matrix.json is not exists
- 退出码85,matrix.json content invalid, read the matrix-schema.json for detail
.. attention::
构建成功之后,代码会部署到容器中/opt/biz目录,并且当前工作目录也会被设置成/opt/biz
Contents:
.. toctree::
:maxdepth: 2
matrix
<file_sep>/fabfile.py
#! /usr/bin/env python
import argparse
import errno
import fnmatch
import json
import locale
import logging
import os
import re
import shutil
import sys
from contextlib import contextmanager
from distutils.text_file import TextFile
import jsonschema
INCLUDE = []
INCLUDE_regexps = []
EXCLUDE = []
EXCLUDE_regexps = []
# -------------------------
# copy file
# --------------------------
@contextmanager
def cd(directory):
"""Change the current working directory, temporarily.
Use as a context manager: with cd(d): ...
"""
old_dir = os.getcwd()
try:
os.chdir(directory)
yield
finally:
os.chdir(old_dir)
def get_all_file_in(dirname):
prefix = len(dirname)
name_list = []
for root, dirs, files in os.walk(dirname):
# for dir in dirs:
# if isinstance(dir,bytes):
# name_list.append(dir.decode(locale.getpreferredencoding()))
# else:
# name_list.append(dir)
normal_root = root[prefix + 1:]
for name in files:
if isinstance(name, bytes):
name_list.append(
os.path.normpath(os.path.join(normal_root, name.decode(locale.getpreferredencoding()))))
else:
name_list.append(os.path.normpath(os.path.join(normal_root, name)))
return name_list
def _glob_to_regexp(pat):
pat = fnmatch.translate(pat)
sep = r'\\\\' if os.path.sep == '\\' else os.path.sep
return re.sub(r'((?<!\\)(\\\\)*)\.', r'\1[^%s]' % sep, pat)
def read_manifest(manifest='MANIFEST.in'):
include, include_regexps, exclude, exclude_regexps = _get_message_from_manifest(manifest)
INCLUDE.extend(include)
INCLUDE_regexps.extend(include_regexps)
EXCLUDE.extend(exclude)
EXCLUDE_regexps.extend(exclude_regexps)
def _get_message_from_list(list):
include, include_regexps, exclude, exclude_regexps = _get_message_from_manifest_lines(list)
INCLUDE.extend(include)
INCLUDE_regexps.extend(include_regexps)
EXCLUDE.extend(exclude)
EXCLUDE_regexps.extend(exclude_regexps)
def _get_message_from_manifest(filename):
template = TextFile(filename,
strip_comments=True,
skip_blanks=True,
join_lines=True,
lstrip_ws=True,
rstrip_ws=True,
collapse_join=True)
try:
lines = template.readlines()
finally:
template.close()
return _get_message_from_manifest_lines(lines)
def _get_message_from_manifest_lines(lines):
follow = []
follow_regexps = []
ignore = []
ignore_regexps = []
for line in lines:
try:
cmd, rest = line.split(None, 1)
except ValueError:
continue
if cmd == 'exclude':
for pat in rest.split():
if '*' in pat or '?' in pat or '[!' in pat:
ignore_regexps.append(_glob_to_regexp(pat))
else:
ignore.append(pat)
elif cmd == 'global-exclude':
ignore.extend(rest.split())
elif cmd == 'recursive-exclude':
try:
dirname, patterns = rest.split(None, 1)
except ValueError:
continue
dirname = dirname.rstrip(os.path.sep)
for pattern in patterns.split():
if pattern.startswith('*'):
ignore.append(dirname + os.path.sep + pattern)
else:
ignore.append(dirname + os.path.sep + pattern)
ignore.append(dirname + os.path.sep + '*' + os.path.sep +
pattern)
elif cmd == 'prune':
rest = rest.rstrip('/\\')
ignore.append(rest)
ignore.append(rest + os.path.sep + '*')
elif cmd == 'include':
for pat in rest.split():
if '*' in pat or '?' in pat or '[!' in pat:
follow_regexps.append(_glob_to_regexp(pat))
else:
follow.append(pat)
elif cmd == 'global-include':
follow.extend(rest.split())
elif cmd == 'recursive-include':
try:
dirname, patterns = rest.split(None, 1)
except ValueError:
continue
dirname = dirname.rstrip(os.path.sep)
for pattern in patterns.split():
if pattern.startswith('*'):
follow.append(dirname + os.path.sep + pattern)
else:
follow.append(dirname + os.path.sep + pattern)
follow.append(dirname + os.path.sep + '*' + os.path.sep +
pattern)
elif cmd == 'graft':
rest = rest.rstrip('/\\')
follow.append(rest)
follow.append(rest + os.path.sep + '*')
return follow, follow_regexps, ignore, ignore_regexps
def file_matches(filename, patterns):
"""Does this filename match any of the patterns?"""
return any(fnmatch.fnmatch(filename, pat) or
fnmatch.fnmatch(os.path.basename(filename), pat)
for pat in patterns)
def file_matches_regexps(filename, patterns):
"""Does this filename match any of the regular expressions?"""
return any(re.match(pat, filename) for pat in patterns)
def strip_sdist_extras(filelist):
"""Strip generated files that are only present in source distributions.
We also strip files that are ignored for other reasons, like
command line arguments, setup.cfg rules or MANIFEST.in rules.
"""
# file_names = os.path.
return [name for name in filelist
if (not file_matches(name, EXCLUDE)
and not file_matches_regexps(name, EXCLUDE_regexps))]
def copy(src, dst):
manifest = os.path.normpath(os.path.join(__file__, '..', 'MANIFEST.in'))
if os.path.exists(manifest):
read_manifest(manifest)
all_source_file = get_all_file_in(src)
source_file = strip_sdist_extras(all_source_file)
for item in source_file:
src_file = os.path.join(src, item)
dst_file = os.path.join(dst, item)
ensure_dir(os.path.dirname(dst_file))
print 'Copy', src_file, '->', dst_file
shutil.copy2(src_file, dst_file)
def load_settings(src):
full_path = os.path.join(src, 'matrix.json')
with open(full_path, 'rb') as f:
try:
return json.load(f)
except ValueError as e:
logging.error("%s is invalid json file: %s", full_path, e)
sys.exit(1)
def gen_docker_file(src='.', matrix='.'):
settings = load_settings(src)
cmd = settings.get('cmd', [])
settings['cmd'] = ','.join('"%s"' % x for x in cmd)
port = settings.get('port', [])
settings['expose'] = ''
if port:
settings['expose'] = 'EXPOSE ' + ' '.join(str(x) for x in port)
volume = settings.get('volume', [])
settings['volume'] = ''
if volume:
settings['volume'] = 'VOLUME [ ' + ', '.join('"%s"' % v for v in volume) + ' ]'
env = settings.get('env', {})
settings['env'] = '\r\n'.join(['ENV {0} {1}'.format(*item) for item in env.iteritems()])
docker_file_template = os.path.join(matrix, 'Dockerfile.in')
with open(docker_file_template, 'rb') as f:
template = f.read()
docker_file = os.path.join(src, 'Dockerfile')
with open(docker_file, 'wb') as out:
out.write(template.format(**settings))
def image_name(src='.'):
settings = load_settings(src)
print '{name}:{tag}'.format(name=settings.get('name'), tag=settings.get('tag', 'latest')),
def valid_matrix_json(src='.', matrix='.'):
with open(os.path.join(src, 'matrix.json'), 'rb') as meta:
meta_json = json.load(meta)
with open(os.path.join(matrix, 'matrix-schema.json'), 'rb') as schema:
schema_json = json.load(schema)
jsonschema.validate(meta_json, schema_json)
def ensure_dir(path):
"""os.makedirs without EEXIST."""
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Generate Dockerfile from source tree",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--src', dest='src', help='The source code path')
opts = parser.parse_args(sys.argv[1:])
gen_docker_file(opts.src)
<file_sep>/requirements.txt
Fabric
virtualenv
jsonschema<file_sep>/cookbook/cookbook.0.0.3.md
Matrix
=========================
Matrix是一个用于构建镜像的镜像。
那为什么需要这样一个镜像?
1. 因为像Python这样的语言,在安装很多第三方包的时候,需要从源码进行编译,需要一个完整的编译工具链, 这样的工具链无形的增加的镜像的大小,并且只会使用一次
Build
---------------------
Pre-installed
---------------------
1. build-base
2. git
3. python
4. python-dev
5. py-pip
6. freetds
7. freetds-dev
8. docker
9. virtualenv
10. fabric
11. jsonschema
```shell
sudo docker run --name onbuild --net=host -i docker.neg/alpine:3.3 /bin/sh
# in container
cat << EOF > /etc/apk/repositories
https://mirrors.tuna.tsinghua.edu.cn/alpine/v3.3/main
https://mirrors.tuna.tsinghua.edu.cn/alpine/v3.3/community
EOF
apk update
apk add build-base
apk add git
apk add python python-dev
apk add py-pip
apk add freetds freetds-dev
apk add docker
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple virtualenv
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple fabric
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jsonschema
virtualenv /tmp/matrix
exit
# on host
# export container
sudo docker export onbuild > matrix.tar
# import container as a image
cat matrix.tar | sudo docker import - matrix:0.0.3
# start container
sudo docker run --rm -v /home/benjamin/git/otter:/home/matrix -v /var/run/docker.sock:/var/run/docker.sock docker.neg/matrix:0.0.3 /usr/local/bin/matrix.sh
```
|
eb894435bebb86657f04e992870b37e7bec834aa
|
[
"reStructuredText",
"Markdown",
"Python",
"Text",
"Shell"
] | 13
|
reStructuredText
|
by46/matrix
|
30aa81d89b07272ec446cdba7d31f330049a14d7
|
e731d251ed235dd6d2e1095556c0c8a4ff0e2e0f
|
refs/heads/master
|
<repo_name>gomesvilasboas/StockMarketDataProvider<file_sep>/UnderlyingDataProvider.py
import yfinance as yf
import threading
from threading import Lock
import time
import logging
from UnderlyingData import UnderlyingData
class UnderlyingDataProvider:
logging.basicConfig(filename='./log/UnderlyingDataProvider.log', level=logging.INFO)
logger = logging.getLogger(__name__)
def __init__(self, period, interval, updateInterval, underlyingName, sign):
self.__period = period
self.__interval = interval
self.__updateInterval = updateInterval
self.__underlyingName = underlyingName
self.Sign = sign
# Properties
@property
def Sign(self):
return self.__sign
@Sign.setter
def Sign(self, sign):
self.__sign = sign
# End Properties
def DownloadUnderlyingHistory(self, underlyingName, lock):
while(True):
if self.Sign != 'off':
msg = '[{underlyingName}][{timestamp}] Downloading underlying history'.format(underlyingName=self.__underlyingName, timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
with lock:
logging.info(msg)
try:
startTime = time.time()
history = yf.download(underlyingName, period=self.__period, interval=self.__interval, progress=False)
endTime = time.time()
underlyingData = UnderlyingData(underlyingName, time.gmtime(), history)
#Save to MongoDB
msg = '[{underlyingName}][{timestamp}] Underlying history downloaded in {sec}s'.format(underlyingName=self.__underlyingName, timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()), sec=(endTime-startTime))
with lock:
logging.info(msg)
except Exception as ex:
msg = '[{underlyingName}][{timestamp}] Error downloading history: {error}'.format(underlyingName=self.__underlyingName, timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()), error=str(ex))
with lock:
logging.info(msg)
time.sleep(self.__updateInterval)
else:
time.sleep(1)
def StartUnderlyingDataCollection(self):
logger_lock = Lock()
thread = threading.Thread(target=self.DownloadUnderlyingHistory, args=(self.__underlyingName, logger_lock,))
thread.start()<file_sep>/main.py
from StockMarketData import StockMarketData
stockMarketData = StockMarketData()
stockMarketData.BuildStockMarketDataCollection()
stockMarketData.StartStockMarketDataCollection()<file_sep>/requirements.txt
numpy
scipy
matplotlib
fastnumbers
seaborn
pytidylib
beautifulsoup4
pandas
requests
pandas-datareader
yfinance<file_sep>/Database.py
import pymongo
import logging
from threading import Lock
import time
import json
import os
class MongoDB:
logging.basicConfig(filename='./log/MongoDB.log', level=logging.INFO)
logger = logging.getLogger(__name__)
logger_lock = Lock()
def __init__(self):
self.LoadConfig()
def LoadConfig(self):
with open('./config/MongoDB.config') as jsonfile:
config = json.load(jsonfile)
self.__databaseName = config['DatabaseName']
self.__URI = config['URI']
def Initalize(self):
user = os.getenv('MongoDBUSer')
passwd = os.getenv('MongoDBPasswd')
client = pymongo.MongoClient(self.__URI, user = user, password = <PASSWORD>)
self.__database = client[self.__databaseName]
def Insert(self, collection, data):
try:
self.__database[collection].insert(data)
msg = '[{timestamp}] Data inserted'.format(timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
logging.info(msg)
return True
except Exception as ex:
msg = '[{timestamp}] Error: {error}'.format(timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()), error=str(ex))
logging.error(msg)
return False
def Find(self, collection, query):
try:
return self.__database[collection].find(query)
except Exception as ex:
msg = '[{timestamp}] Error: {error}'.format(timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()), error=str(ex))
logging.info(msg)
return None
def FindOne(self, collection, query):
try:
return self.__database[collection].find_one(query)
except Exception as ex:
msg = '[{timestamp}] Error: {error}'.format(timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()), error=str(ex))
logging.error(msg)
return None
def Delete(self, collection, query):
try:
self.__database[collection].delete_one(query)
msg = '[{timestamp}] Data deleted'.format(timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
logging.info(msg)
return True
except Exception as ex:
msg = '[{timestamp}] Error: {error}'.format(timestamp=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()), error=str(ex))
logging.error(msg)
return False<file_sep>/UnderlyingData.py
class UnderlyingData:
def __init__(self, underlyingName, timestamp, history):
self.__underlyingName = underlyingName
self.__timestamp = timestamp
self.__history = history
@property
def UnderlyingName(self):
return self.__underlyingName
@property
def History(self):
return self.__history
@property
def Timestamp(self):
return self.__timestamp<file_sep>/StockMarketData.py
import json
import UnderlyingDataProvider as udp
class StockMarketData:
def __init__(self):
self.LoadConfig()
# Properties
@property
def UnderlyingNames(self):
return self.__UnderlyingNames
@UnderlyingNames.setter
def UnderlyingNames(self, underlyingNames):
self.__UnderlyingNames = underlyingNames
@property
def UnderlyingDataProviderList(self):
return self.__underlyingDataProviderList
@UnderlyingDataProviderList.setter
def UnderlyingDataProviderList(self, underlyingDataProviderList):
self.__underlyingDataProviderList = underlyingDataProviderList
# End properties
def LoadConfig(self):
with open('./config/Underlying.config') as jsonfile:
config = json.load(jsonfile)
self.UnderlyingNames = config['UnderlyginNames']
self.__period = config['Period']
self.__interval = config['Interval']
self.__updateInterval = config['UpdateInterval']
def BuildStockMarketDataCollection(self):
underlyingDataProviderList = []
for underlyingName in self.UnderlyingNames:
underlyingDataProviderList.append(udp.UnderlyingDataProvider(self.__period, self.__interval, self.__updateInterval, underlyingName, 'on'))
self.UnderlyingDataProviderList = underlyingDataProviderList
def StartStockMarketDataCollection(self):
for underlyingDataProvider in self.UnderlyingDataProviderList:
underlyingDataProvider.StartUnderlyingDataCollection()
|
19b5574812b04a02fe2952f5e8b25c83cb6208be
|
[
"Python",
"Text"
] | 6
|
Python
|
gomesvilasboas/StockMarketDataProvider
|
b5ff12ee3ff4439da3207dde740a9dd6cf231452
|
c9b08b5c98569ec4100d92b82499b86cebc04876
|
refs/heads/master
|
<file_sep>###########################################
# Automate web browsing
###########################################
# 1. import Selenium
from selenium import webdriver
# 2. call Chrome driver and pass the path location
driver = webdriver.Chrome(executable_path='C:\webdrivers\chromedriver.exe')
# 3. pass the URL to be opened
driver.get('https://www.seleniumeasy.com/test/basic-first-form-demo.html')
# get the message field xPath
messageField = driver.find_element_by_xpath('//*[@id="user-message"]')
# write text to the field
messageField.send_keys('Ciao Mundo')
# get the msg btn field xPath
showMessageButton = driver.find_element_by_xpath('//*[@id="get-input"]/button')
# submit the btn
showMessageButton.click()
# Get two input fields and the btn, add values to the input,
# click the btn
inputFieldOne = driver.find_element_by_xpath('//*[@id="sum1"]')
inputFieldOne.send_keys(10)
inputFieldTwo = driver.find_element_by_xpath('//*[@id="sum2"]')
inputFieldTwo.send_keys(3)
addTotalButton = driver.find_element_by_xpath('//*[@id="gettotal"]/button')
addTotalButton.click()
<file_sep>
###########################################
# Simple Browser Scrapping
###########################################
# # 1. import libraries
# import requests
# # 4A. Parse the HTML document
# from bs4 import BeautifulSoup
# # 2. Get website url assign it to a variable
# url = 'http://quotes.toscrape.com/'
# # 3. Connecting URL and getting the response
# response = requests.get(url)
# # 4B. Parse the HTML document
# soup = BeautifulSoup(response.text, 'lxml');
# # 5. Print it to verify if our parse worked correctly
# print(soup)
###########################################
# Isolating Data from browser
###########################################
# 1. import libraries
import requests
# 4A. Parse the HTML document
from bs4 import BeautifulSoup
# 2. Get website url assign it to a variable
url = 'http://quotes.toscrape.com/'
# 3. Connecting URL and getting the response
response = requests.get(url)
# 4B. Parse the HTML document
soup = BeautifulSoup(response.text, 'lxml');
# 5. Inspect the website and locate what html tags and class
# are holding the data you want to isolate
# get all quotes
quotes = soup.find_all('span', class_='text')
# get all authors
authors = soup.find_all('small', class_='author')
# get all tags
tags = soup.find_all('div', class_='tags')
# 6. loop through each quote
# for quote in quotes:
# print(quote.text);
# Altering the for loop since there is one author to a quote
for i in range(0, len(quotes)):
print("Quotes: " + quotes[i].text)
print("Author: " + authors[i].text)
quoteTags = tags[i].find_all('a', class_="tag")
for quoteTag in quoteTags:
print( "Tags: "+ quoteTag.text)
print("--------------------------------------------")
<file_sep>
# Read Files
# # find the file and store it in a variable
# inputFile = open('inputFile.txt', "r" );
# # print the entire file to the clg
# print(inputFile.read());
# # Always close the file once it is done
# inputFile.close();
# f = open("inputFile.txt", "r")
# count = 0;
# for line in f:
# print(str(count) + line)
# count = count + 1
# f.close()
f = open("inputFile.txt", "r")
count = 0
for line in f:
line_split = line.split()
if line_split[2] == "P":
print("You Passed => " + line)
elif line_split[2] == "F":
print("You failed => " + line)
f.close()<file_sep># 1. import libraries
import requests
# 4A. Parse the HTML document
from bs4 import BeautifulSoup
# 2. Get website url assign it to a variable
url = 'https://scrapingclub.com/exercise/list_basic/'
# 3. Connecting URL and getting the response
response = requests.get(url)
# 4B. Parse the HTML document
soup = BeautifulSoup(response.text, 'lxml');
# 5. Get the items from the page
items = soup.find_all('div', class_="col-lg-4 col-md-6 mb-4")
# 6. loop through and get the data
count = 1
for i in items:
itemName = i.find('h4', class_="card-title").text.strip("\n")
itemPrice = i.find("h5").text
print('%s ) Price: %s, Item Name: %s' % (count, itemPrice, itemName))
count = count + 1
###########################################
# Scrapping Pagination content
###########################################
# Get the pagination line and create a list
pages = soup.find('ul', class_='pagination')
urls = []
links = pages.find_all('a', class_="page-link")
for link in links:
pageNum = int(link.text) if link.text.isdigit() else None
if pageNum != None:
x = link.get('href')
urls.append(x)
print(urls)
count = 1
for i in urls:
newUrl = url + i
response = requests.get(newUrl)
soup = BeautifulSoup(response.text, 'lxml');
items = soup.find_all('div', class_="col-lg-4 col-md-6 mb-4")
for i in items:
itemName = i.find('h4', class_="card-title").text.strip("\n")
itemPrice = i.find("h5").text
print('%s ) Price: %s, Item Name: %s' % (count, itemPrice, itemName))
count = count + 1
<file_sep># python-automation-scripts
### About Project
Web scraping
Automate web browsing
Automate with APIS
|
c6de3a2cf145ebd81e53ba348a2f5d6d45ecc2c0
|
[
"Markdown",
"Python"
] | 5
|
Python
|
Brunno-DaSilva/python-automation-scripts
|
8ba34032c273c2cd3f945f4db766368acca4c826
|
71ad0083d2a8fd11a4973c3d04a24feb321f92fd
|
refs/heads/master
|
<repo_name>ChristoLuksatrio/tweeter<file_sep>/README.md
# Tweeter Project
Tweeter is a mini clone of Twitter. The app lets you post 140-character tweets to a server. I used the following to create this app:
- HTML
- CSS
- JS
- JQuery
- AJAX
- Node
- Express
## Screenshots


## Getting Started
1. Fork this repository, then clone your fork of this repository.
2. Install dependencies using the `npm install` command.
3. Start the web server using the `npm run local` command. The app will be served at <http://localhost:8080/>.
4. Go to <http://localhost:8080/> in your browser.
## Dependencies
- Express
- Node 5.10.x or above
<file_sep>/public/scripts/client.js
/*
* Client-side JS logic goes here
* jQuery is already loaded
* Reminder: Use (and do all your DOM work in) jQuery's document ready function
*/
// Test / driver code (temporary). Eventually will get this from the server.
$(document).ready(() => {
$( ".fancy-error" ).hide();
$( ".fancy-error2" ).hide();
$( ".fancy-footer" ).hide();
$('.tweetAnchor').click(function() {
$('.new-tweet').stop().slideToggle('slow', function() {
})
})
const loadTweets = () => {
$.ajax('/tweets', { method: 'GET'})
.then(function(array) {
$('.tweetBox').empty();
renderTweets(array);
})
}
const escape = function(str) {
let div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// loadTweets to loop over the database and append
const createTweetElement = tweetData => {
return `
<div class=tweets-container>
<header>
<img class='avatar' src='${tweetData.user.avatars}' />
<span class='name'>${tweetData.user.name}</span>
<span class='handle'>${tweetData.user.handle}</span>
</header>
<div class='tweet-message'>
<p>${escape(tweetData.content.text)}</p>
</div>
<footer>
<span class='tweet-date'>${moment(tweetData.created_at).fromNow()}</span>
<div class='tweet-buttons'>
<i class="fas fa-flag"></i>
<i class="fas fa-retweet"></i>
<i class="fas fa-heart"></i>
</div>
</footer>
</div>
`
}
const renderTweets = function(tweets) {
for (const tweet of tweets) {
const $tweet = createTweetElement(tweet);
$('.tweetBox').prepend($tweet);
}
}
const $tweetSend = $('.tweetFunction');
$tweetSend.on('submit', function(event) {
$( ".fancy-error" ).hide();
$( ".fancy-error2" ).hide();
event.preventDefault();
const textLength = $tweetSend.find('#tweet-placeholder').val().length;
if (textLength < 140 && textLength > 0) {
$.ajax('/tweets', { method: 'POST', data: $tweetSend.serialize()})
.then(() => {
loadTweets();
$tweetSend.trigger('reset');
$('.counter').text('140');
$('.counter').css('color', '#555149');
})
} else if (textLength > 140) {
$( ".fancy-error2" ).fadeIn( "slow", function() {
});
} else if (textLength <= 0) {
$( ".fancy-error" ).fadeIn( "slow", function() {
});
}
})
loadTweets();
$( ".fancy-footer" ).on('click', function(event) {
event.preventDefault();
window.scrollTo(0, 0);
})
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
$( ".fancy-footer" ).fadeIn();
} else {
$( ".fancy-footer" ).fadeOut();
}
});
});
|
7cecefc9eac21583eb3142ae7183d01f9c299139
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
ChristoLuksatrio/tweeter
|
7a57b41ff0931598951719c83b6087b14f06f614
|
a0f068d3d3053e10246c21e8f3dcb03751123d27
|
refs/heads/main
|
<repo_name>Peptidase/PythonFinacialTools<file_sep>/ImportingStock.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 18:24:23 2021
@author: ArifM
this uses the Intro and getting stock price data -
Python programming for finance tutorial series
"""
import datetime as dt
import pandas as pd
import pandas_datareader as web
#Lets you use various datasources from online
import matplotlib.pyplot as plt
from matplotlib import style
import mplfinance as mpf
style.use('ggplot')
start = dt.datetime(2019,1,1)
end = dt.datetime(2021, 1, 10)
df = web.DataReader('TSLA','yahoo',start,end)# Daily data,
df_ohlc = df['Adj Close'].resample('10D').ohlc() #open high low close
df_volume = df['Volume'].resample('10D').sum()
fig, ax = plt.subplots()
mpf.plot(df_ohlc, type='candle',mav = (10,50,100))
df['100ma'] = df['Adj Close'].rolling(window=100).mean()
df.dropna(inplace=True) # removes the rows that have nan
#TODO Create a subplot of volume below the candlestick graph that is coloured.
|
f78b2641f1739ddfa91a030ca971ef7a72a3cd8a
|
[
"Python"
] | 1
|
Python
|
Peptidase/PythonFinacialTools
|
7ca34767507a1553d9a0ea8a1ce7284f0ff022c6
|
6363c90b681ce2510b039de09fc60a09553a8915
|
refs/heads/master
|
<repo_name>JWXIAN/JWQrCode<file_sep>/JWQrCodeDemo/JWQrCode/JWHeader.h
//
// JWHeader.h
// JWQrCodeDemo
//
// Created by GJW on 16/8/3.
// Copyright © 2016年 JW. All rights reserved.
//
#ifndef JWHeader_h
#define JWHeader_h
//static NSString *bgImg_img = @"image.bundle/scanBackground";
//static NSString *Line_img = @"image.bundle/scanLine";
//
//static NSString *turn_on = @"image.bundle/turn_on";
//static NSString *turn_off = @"image.bundle/turn_off";
//设置自定义声音
static NSString *soundPath = @"image.bundle/ring";
static NSString *soundType = @"wav";
#endif /* JWHeader_h */
<file_sep>/README.md
# JWQrCode
封装AVFoundation实现扫描二维码/条形码、生成二维码。
|
6709bb5488929b3e5e4984cce690cac36b6a1eaa
|
[
"Markdown",
"C"
] | 2
|
C
|
JWXIAN/JWQrCode
|
03d741f8d0de6d15cc4600d4ab2d5fb76830bb15
|
0e805e5574280823e7d53686ad979d27a42e2914
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
import csv
import sys
import numpy as np
print "Use as follows: polynomial_regression.py <datafile> <degree>"
try:
with open(sys.argv[1], 'rb') as f:
reader = csv.DictReader(f)
x = []
y = []
for row in reader:
# print row
try:
x.append(float(row['reality']))
y.append(float(row['measurement']))
except ValueError:
print( "Could not convert '{}' to a float...skipping.".format(entry))
coeffs = np.polyfit(x,y,sys.argv[2])
print "The coeffs are ", coeffs
# p = np.poly1d(coeffs)
# for i in x:
# print p(i)
except:
print "Something went wrong. Check for correct file format."
<file_sep>#!python
import numpy as np
from numpy.random import *
import labyrinth
import matplotlib.pyplot as plt
import copy
class ParticleFilter(object):
maze = []
particles = list()
# weights = list()
mu_movement = 0.
mu_angle = 0.
mu_measurement = 0.
sigma_measrement = 3.8
sigma_movement_x = 2.
sigma_movement_y = 2.
sigma_angle = 5./180*np.pi
cumulated_weights = [0.]
resample_ready = False
def __init__(self, num_particles):
#init the maze with one square being 30cm, margin 10cm
self.maze = labyrinth.Labyrinth(30.,10.)
#determine how to spread the particles
stepsize = 1.0 #in cm
particles_per_cm2 = num_particles/16./self.maze.get_area()
if particles_per_cm2 > 1:
stepsize = 1./np.sqrt(particles_per_cm2)
print "Currently we get ", particles_per_cm2, " particles per cm2, making it one particle every", stepsize, "cm)"
#init the particles
current_pos = [0,0]
for field_x in range(3):
for field_y in range(3):
current_pos = [self.maze.margin,self.maze.margin]
#inside field
while current_pos[0]<=self.maze.size-self.maze.margin:
while current_pos[1]<=self.maze.size-self.maze.margin:
for i in range(16):
self.particles.append(Position([field_x*self.maze.size+current_pos[0],
field_y*self.maze.size+current_pos[1]], i*np.pi/8))
#self.weights.append(1.)
current_pos[1]+=stepsize
current_pos[0]+=stepsize
current_pos[1]=self.maze.margin
#connecting fields down/x dir
current_pos[0]=-self.maze.margin+stepsize
current_pos[1]=self.maze.margin
if self.maze.labyrinth_array[field_x*2+2,field_y*2+1] == 0:
print "connection down to", self.maze.labyrinth_array[field_x*2+3,field_y*2+1]
while current_pos[0]<self.maze.margin:
while current_pos[1]<=self.maze.size-self.maze.margin:
for i in range(16):
self.particles.append(Position([(field_x+1)*self.maze.size+current_pos[0],
field_y*self.maze.size+current_pos[1]], i*np.pi/8))
#self.weights.append(1)
current_pos[1]+=stepsize
current_pos[1]=self.maze.margin
current_pos[0]+=stepsize
#connecting exit down
current_pos[0]=-self.maze.margin+stepsize
current_pos[1]=self.maze.margin
if self.maze.labyrinth_array[field_x*2+2,field_y*2+1] == -2:
print "connection exit from", self.maze.labyrinth_array[field_x*2+1,field_y*2+1]
while current_pos[0]<=0:
while current_pos[1]<=self.maze.size-self.maze.margin:
for i in range(16):
self.particles.append(Position([(field_x+1)*self.maze.size+current_pos[0],
field_y*self.maze.size+current_pos[1]], i*np.pi/8))
#self.weights.append(1.)
current_pos[1]+=stepsize
current_pos[1]=self.maze.margin
current_pos[0]+=stepsize
#connecting fields right/y dir
current_pos[0]=self.maze.margin
current_pos[1]=-self.maze.margin+stepsize
if self.maze.labyrinth_array[field_x*2+1,field_y*2+2] == 0:
print "connection right to", self.maze.labyrinth_array[field_x*2+1,field_y*2+3]
while current_pos[0]<=self.maze.size-self.maze.margin:
while current_pos[1]<self.maze.margin:
for i in range(16):
self.particles.append(Position([(field_x)*self.maze.size+current_pos[0],
(field_y+1)*self.maze.size+current_pos[1]], i*np.pi/8))
#self.weights.append(1)
current_pos[1]+=stepsize
current_pos[1]=-self.maze.margin+stepsize
current_pos[0]+=stepsize
return
def plot(self):
# mx = 0self.
# for i in range(len(self.cumulated_weights)-2):
# if self.cumulated_weights[i+1]-self.cumulated_weights[i] > mx:
# mx = self.cumulated_weights[i+1]-self.cumulated_weights[i]
x=[]
y=[]
i=0
for pos in self.particles:
# if self.cumulated_weights[i+1]-self.cumulated_weights[i]>0.9*mx:
x.append(pos.position[0])
y.append(pos.position[1])
plt.scatter(x,y)
plt.show()
return
def movement_angle_deg(self, angle):
for pos in self.particles:
pos.turn_deg(angle+np.random.normal(self.mu_angle, self.sigma_angle, 1))
return
def movement_angle_rad(self, angle):
for pos in self.particles:
pos.turn_rad(angle+np.random.normal(self.mu_angle, self.sigma_angle/180*np.pi, 1))
return
def movement_position(self, translation):
i=0
for pos in self.particles:
pos.move(translation+np.array([np.random.normal(self.mu_movement, self.sigma_movement_x, 1),
np.random.normal(self.mu_movement, self.sigma_movement_y, 1)]))
i+=1
return
#angle, dist
def measurement(self, angle, dist):
if dist >20:
self.resample_ready = False
return False
angle = angle/180.*np.pi
for i in range(len(self.particles)):
error = self.maze.get_distance_wall_to_measurement(self.particles[i].position+
dist*np.array([np.cos(angle+self.particles[i].angle)-np.sin(angle+self.particles[i].angle),
np.sin(angle+self.particles[i].angle)+np.cos(angle+self.particles[i].angle)]))
if self.particles[i].position[0] < 0 or self.particles[i].position[1] < 0 or self.particles[i].position[0] > self.maze.size*3 or self.particles[i].position[1] > self.maze.size*3:
# self.weights[i] = 0
self.cumulated_weights.append(self.cumulated_weights[-1]+0)
else:
# self.weights[i] *= self.normpdf(error)
self.cumulated_weights.append(self.cumulated_weights[-1]+self.normpdf(error))
# if i%1004==0:
# print error, self.particles[i].position[0], self.cumulated_weights[-1]
self.resample_ready = True
return True
def normpdf(self, x):
var = float(self.sigma_measrement)**2
denom = (2*np.pi*var)**.5
num = np.exp(-(float(x)-float(self.mu_measurement))**2/(2*var))
return num/denom
def clear(self):
del self.particles[:]
return
def resample(self):
if not self.resample_ready:
return False
n = len(self.cumulated_weights)-1
step = self.cumulated_weights[-1]/n
print "Started resampling", n
particles_tmp = list()
# weights_tmp = list()
# max_weight = np.max(self.weights)
j = 0
for u in [(i*step) for i in range(n)]:
while u > self.cumulated_weights[j]:
j+=1
particles_tmp.append(copy.deepcopy(self.particles[j-1]))
# weights_tmp.append(self.weights[j-1]/max_weight)
del self.particles[:]
# del self.weights[:]
del self.cumulated_weights[:]
self.particles = particles_tmp
# self.weights = weights_tmp
self.cumulated_weights = [0.]
self.resample_ready = False
return True
class Position(object):
position = np.array([0.,0.])
angle = 0
def __init__(self, translation, angle):
self.position = np.array(translation, dtype=np.float64)
self.angle = angle
#first the movement then the rotation
def turn_deg(self, angle):
self.angle += float(angle)/180*np.pi
return
def turn_rad(self, angle):
self.angle += angle
return
def move(self, translation):
self.position += (translation[0]*np.array([np.cos(self.angle),np.sin(self.angle)])+translation[1]*np.array([-np.sin(self.angle),np.cos(self.angle)]))
return
<file_sep># Error Functions of robot movements and measurements
We will need functions describing the error we deal with in our measurements and movements for the particle filter. Therefore we use polynomial regression to fit a function in measured errors. This can be achieved by doing lots of tests, saving the data in csv-files and running a script on it.
## Csv file format
Save the measured data in an csv-file (**c**omma **s**eparated **v**alue). Is is called csv, because you will simply need to seperate each value with a comma. In the end, it should look like this:
|reality, | measurement |
|---- | ----------- |
|0, | 1 |
|2, | 3.3 |
|5.43, | 2342.34 |
|... | ... |
In every line one measurement is saved. There is an example in the *data/* folder :)
## Calculating the error funtions
Run the script *polynomial_regression.py* in the folder *scripts/* as follows:
~~~
python polynomial_regression.py <datafile> <degree>
e.g. from root folder: python scripts/polynomial_regression.py data/error_dist.csv 2
~~~
The degree parameter determines the largest degree of the polynomial. The printed values are the coefficients of the error polynomial.
<file_sep>#!python
import numpy as np
import graph
class Labyrinth(object):
labyrinth_array = []
labyrinth_graph = []
size = 0.
margin = 0.
def __init__(self, size, margin):
self.size = size #in cm of one tile
self.margin = margin
self.labyrinth_array = np.array(
[[-1, -1, -1, -1, -1, -1, -1],
[-1, 1, 0, 2, 0, 3, -1],
[-1, 0, -1, -1, -1, -1, -1],
[-1, 4, 0, 5, 0, 6, -1],
[-1, -1, -1, 0, -1, -1, -1],
[-1, 7, 0, 8, 0, 9, -1],
[-1, -1, -1, -1, -1, -2, -1]])
self.labyrinth_graph = graph.Graph({'1': ['2', '4'],
'2': ['1', '3'],
'3': ['2'],
'4': ['1', '5'],
'5': ['4', '6', '8'],
'6': ['5'],
'7': ['8'],
'8': ['5', '7', '9'],
'9': ['8', 'exit']})
def find_shortest_path(self, start, end):
return self.labyrinth_graph.find_shortest_path(start,end)
def numbers_connections(self):
return np.prod(self.labyrinth_array.shape) - np.count_nonzero(self.labyrinth_array)
def get_area(self):
return (self.size-2*self.margin)*(self.size-2*self.margin)*9+(self.numbers_connections()*2+1)*self.margin*(self.size-2*self.margin)
def get_distance_wall_to_measurement(self, position):
field = self.get_field_and_coords(position)
check = [-1,-1] #where to check for a wall
check_near = False
error = 0.
#checking if out of bound
if field[0]<0 or field[1]<0:
# print "negative", self.labyrinth_array[field[2]*2+1,field[3]*2+1], [field[2]*2+1+check[0],field[3]*2+1]
return -np.min(field[0:2])
elif field[2]>2:
# print "index", field
return field[0]
elif field[3]>2:
# print "index", field
return field[1]
#at what corner of the field is the robot
if field[0]>self.size/2:
field[0]=self.size-field[0]
check[0]+=2
if field[1]>self.size/2:
field[1] = self.size-field[1]
check[1]+=2
if field[0]>field[1]:
#is there a wall?
if self.labyrinth_array[field[2]*2+1,field[3]*2+1+check[1]] == -1:
# print "y taken", field, self.labyrinth_array[field[2]*2+1,field[3]*2+1], [field[2]*2+1,field[3]*2+1+check[1]]
error = field[1]
else:
#if not, check surrounding later
# print "checked", field, self.labyrinth_array[field[2]*2+1,field[3]*2+1]
check_near=True
elif self.labyrinth_array[field[2]*2+1+check[0],field[3]*2+1] == -1:
# print "x taken",field, self.labyrinth_array[field[2]*2+1,field[3]*2+1], [field[2]*2+1+check[0],field[3]*2+1]
error = field[0]
else:
# print "checked", field, self.labyrinth_array[field[2]*2+1,field[3]*2+1]
check_near = True
if check_near:
return np.linalg.norm(field[0:2],2)
return error
def get_field_and_coords(self, position):
#print position[0]
res = [position[0],position[1],0,0] #pos_x, pos_y, field_x,field_y
while res[0] > self.size:
res[0]-=self.size
res[2]+=1
while res[1] > self.size:
res[1]-=self.size
res[3]+=1
return res
<file_sep>#!python
def test(pf):
pf.plot()
print "Measuring"
pf.measurement(90,15)
pf.resample()
print "Measuring"
pf.measurement(-90,15)
pf.resample()
pf.measurement(0,35)
pf.resample()
pf.plot()
print "Moving"
pf.movement_position([20,0])
pf.plot()
print "Measuring"
pf.measurement(-90,15)
pf.resample()
pf.measurement(90,45)
pf.resample()
pf.measurement(0,15)
pf.resample()
pf.plot()
pf.movement_angle_deg(90)
pf.movement_position([30,0])
pf.measurement(0,15)
pf.resample()
#pf.movement_position([0,20])
print "Measuring"
pf.measurement(-90,15)
pf.resample()
pf.measurement(90,75)
pf.resample()
pf.plot()
return
if __name__ == "__main__":
import particlefilter
print("Staring the script...")
pf = particlefilter.ParticleFilter(2600*16)
test(pf)
else:
print("Just WHAT THE FUCK?")
<file_sep>class Graph:
graph = {'1': ['2', '4'],
'2': ['1', '3'],
'3': ['2'],
'4': ['1', '5'],
'5': ['4', '6', '8'],
'6': ['5'],
'7': ['8'],
'8': ['5', '7', '9'],
'9': ['8', 'exit']}
def __init__(self, graph_attr):
self.graph = graph_attr
def find_shortest_path(self, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not self.graph.has_key(start):
return None
shortest = None
for node in self.graph[start]:
if node not in path:
newpath = self.find_shortest_path(node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
|
e14c8b51388cb0c1a12451bc4158e93e220b7b98
|
[
"Markdown",
"Python"
] | 6
|
Python
|
Geccoloris/robot-assignment
|
40e919df107d201e45ba17e74b856c88d85b45f8
|
18553369aae3eca46dcd57c4b3579021d95eb445
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Models\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use App\Http\Requests\TagStoreRequest;
use App\Http\Requests\CategoryStoreRequest;
class TagController extends Controller
{
public function index()
{
$tags = Tag::orderBy('id', 'desc')->paginate(5);
return view('tag.index', compact('tags'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('tag.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(TagStoreRequest $request)
{
$file = $request->file('image');
$imgName = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/tag', $imgName);
$imgPath = 'tag/' . $imgName;
$tag = new Tag();
$tag->name = $request->tag;
$tag->image = $imgPath;
if ($tag->save()) {
return redirect()->route('tag.index')->with('success', 'tag create success!');
} else {
return redirect()->back()->with('error', 'Tag ထည့်သွင်းခြင်းမအောင်မြင်ပါ။');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$tag = Tag::findOrFail($id);
return view('tag.edit', compact('tag'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$tag = Tag::findOrFail($id);
$check = Tag::where('name', $request->tag)->where('id', '!=', $id)->first();
if (!$check) {
$tag->name = $request->tag;
## check image
if ($request->hasFile('image')) {
File::delete($tag->image);
$file = $request->file('image');
$imgName = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/tag', $imgName);
$imgPath = 'tag/' . $imgName;
$tag->image = $imgPath;
}
if ($tag->update()) {
return redirect()->route('tag.index')->with('success', 'tag update success!');
} else {
return redirect()->back()->with('error', 'tag update fail!');
}
} else {
return redirect()->back()->withErrors(['tag' => 'Tag အမျိုးအစားသည်ရှိပီးသားဖြစ်ပါသည်။']);
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$tag = Tag::findOrFail($id);
if ($tag->image) {
File::delete($tag->image);
}
$tag->delete();
return redirect()->back()->with('success', 'tag delete success!');
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CategoryStoreRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'category'=>'required|unique:categories,name',
'image'=>'required'
];
}
public function messages()
{
return [
'category.required'=>'Category ထည့်ရန်လိုအပ်ပါသည်။',
'category.unique'=>'Category အမျိုးအစားသည်ရှိပီးသားဖြစ်ပါသည်။',
'image.required'=>'category ဓာတ်ပုံထည့်ရန်လိုအပ်ပါသည်။',
];
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Models\Order;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\OrderItem;
class OrderController extends Controller
{
public function index()
{
$orders = Order::with('user')->latest()->paginate(5);
return view('order.order',compact('orders'));
}
public function delete($id){
OrderItem::where('order_id',$id)->delete();
Order::where('id',$id)->delete();
return redirect()->back()->with('success','Order delete success!');
}
public function changeOrderStatus($id){
$order = Order::findOrFail($id);
$order->status = !$order->status;
$order->update();
if($order->status)
return redirect()->back()->with('success','Order check success!');
else
return redirect()->back()->with('info','Order not check!');
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\OrderItem;
class OrderItemController extends Controller
{
public function orderItem($id){
$orderItem = OrderItem::where('order_id',$id)->latest()->get();
return view('order.order_item',compact('orderItem'));
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Http\Requests\LoginRequest;
use App\Models\Role;
use App\Models\RoleUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function test()
{
$user = Auth::user();
## get user from role
// $role = Role::all();
// return $role[0]->users;
// return $role[1];
## get role from user
// $user->roles()->attach(2);
// $user->roles()->attach(3);
// $user->roles()->detach(2);
return $user->roles;
## check has role
// if ($user->hasRole('super'))
// echo 'yes';
// else
// return 'no';
}
public function showLogin()
{
return view('login');
}
public function login(LoginRequest $request)
{
// dd( $request->get('rememberMe'));
$phone = $request->phone;
$password = $request->password;
$user = User::where('phone', $phone)->first();
if ($user) {
if (Hash::check($password, $user->password)) {
Auth::login($user);
return redirect()->route('home')->with(['login'=>'Welcome ' . $user->name,'rememberMe'=>$request->get('rememberMe') ?? 'off']);
} else {
return redirect()->back()->withErrors(['password' => '<PASSWORD>်။']);
}
} else {
return redirect()->back()->withErrors(['phone' => 'ယခု နံပါတ်ဖြင့်အကောင့်မရှိပါ']);
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Models\Category;
use App\Models\SubCategory;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use App\Http\Requests\CategoryStoreRequest;
use App\Http\Requests\CategoryUpdateRequest;
class SubCategoryController extends Controller
{
public function index($id)
{
$category = Category::with('subCat')->findOrFail($id);
return view('subcategory.index', compact('category'));
}
public function create($id)
{
$category = Category::findOrFail($id);
return view('subcategory.create', compact('category'));
}
public function store(CategoryStoreRequest $request, $id)
{
$file = $request->file('image');
$imgName = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/subCategory', $imgName);
$imgPath = 'subCategory/' . $imgName;
$subCat = new SubCategory();
$subCat->name = $request->category;
$subCat->category_id = $id;
$subCat->image = $imgPath;
if ($subCat->save()) {
return redirect()->route('category.sub.index', $id)->with('success', 'sub category create success!');
} else {
return redirect()->back()->with('error', 'Sub Category ထည့်သွင်းခြင်းမအောင်မြင်ပါ။');
}
}
public function show($id)
{
//
}
public function edit($id)
{
$subCat = SubCategory::with('cat')->findOrFail($id);
return view('subcategory.edit', compact('subCat'));
}
public function update(CategoryUpdateRequest $request, $id)
{
$category = SubCategory::findOrFail($id);
$check = SubCategory::where('name', $request->category)->where('id', '!=', $id)->first();
if (!$check) {
$category->name = $request->category;
## check image
if ($request->hasFile('image')) {
File::delete($category->image);
$file = $request->file('image');
$imgName = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/subCategory', $imgName);
$imgPath = 'subCategory/' . $imgName;
$category->image = $imgPath;
}
if ($category->update()) {
return redirect()->route('category.sub.index',$category->category_id)->with('success', 'sub category update success!');
} else {
return redirect()->back()->with('error', 'Sub Category update fail!');
}
} else {
return redirect()->back()->withErrors(['category' => 'Sub Category အမျိုးအစားသည်ရှိပီးသားဖြစ်ပါသည်။']);
}
}
public function destroy($id)
{
$category = SubCategory::findOrFail($id);
if ($category->image) {
File::delete($category->image);
}
$category->delete();
return redirect()->back()->with('success', 'category delete success!');
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Models\Category;
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;
use App\Http\Requests\CategoryStoreRequest;
use App\Http\Requests\CategoryUpdateRequest;
use Illuminate\Support\Facades\File;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::orderBy('id', 'desc')->paginate(5);
return view('category.index', compact('categories'));
}
public function create()
{
return view('category.create');
}
public function store(CategoryStoreRequest $request)
{
$file = $request->file('image');
$imgName = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/category', $imgName);
$imgPath = 'category/' . $imgName;
$category = new Category();
$category->name = $request->category;
$category->slug = time() . Str::slug($request->category);
$category->image = $imgPath;
if ($category->save()) {
return redirect()->route('category.index')->with('success', 'category create success!');
} else {
return redirect()->back()->with('error', 'Category ထည့်သွင်းခြင်းမအောင်မြင်ပါ။');
}
}
public function show($id)
{
//
}
public function edit($id)
{
$category = Category::findOrFail($id);
return view('category.edit', compact('category'));
}
public function update(CategoryUpdateRequest $request, $id)
{
$category = Category::findOrFail($id);
$check = Category::where('name', $request->category)->where('id', '!=', $id)->first();
if (!$check) {
$category->name = $request->category;
$category->slug = time() . Str::slug($request->category);
## check image
if ($request->hasFile('image')) {
File::delete($category->image);
$file = $request->file('image');
$imgName = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/category', $imgName);
$imgPath = 'category/' . $imgName;
$category->image = $imgPath;
}
if ($category->update()) {
return redirect()->route('category.index')->with('success', 'category update success!');
} else {
return redirect()->back()->with('error', 'Category update fail!');
}
} else {
return redirect()->back()->withErrors(['category' => 'Category အမျိုးအစားသည်ရှိပီးသားဖြစ်ပါသည်။']);
}
}
public function destroy($id)
{
$category = Category::with('subCat')->findOrFail($id);
if($category->subcat){
foreach($category->subcat as $cat){
File::delete($cat->image);
}
}
if ($category->image) {
File::delete($category->image);
}
$category->delete();
return redirect()->back()->with('success', 'category delete success!');
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'phone'=>'required|digits_between:7,11',
'password'=>'required|min:6'
];
}
public function messages()
{
return [
'phone.required'=>'ဖုန်းနံပါတ်ထည့်ရန်လိုအပ်ပါသည်။',
'phone.digits_between'=>'ဖုန်းနံပါတ်သည်အနည်းဆုံး ၇ လုံး အများဆုံး ၁၁ လုံးဖြစ်ရပါမည်။',
'password.required'=>'စကာား၀ှက်ထည့်ရန်လိုအပ်ပါသည်။',
'password.min'=>'စကာား၀ှက်သည်အနည်းဆုံး ၆ လုံးဖြစ်ရပါမည်။'
];
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
Route::get('/admin/login', 'AuthController@showLogin');
Route::post('/admin/login', 'AuthController@login')->name('login');
Route::get('/test', 'AuthController@test');
Route::group(['middleware' =>[ 'admin','auth'], 'prefix' => 'admin', 'namespace' => 'Admin'], function () {
Route::get('/', 'PageController@home')->name('home');
Route::resource('/category', 'CategoryController');
Route::resource('/category.sub', 'SubCategoryController')->shallow();
Route::resource('/tag', 'TagController');
Route::resource('/product', 'ProductController');
Route::get('/order', 'OrderController@index')->name('order');
Route::get('/order/delete/{id}', 'OrderController@delete')->name('order.delete');
Route::get('/orderItem/{id}', 'OrderItemController@orderItem')->name('order_item');
Route::patch('/changeOrderStatus/{id}', 'OrderController@changeOrderStatus')->name('change-status');
Route::get('/logout', 'PageController@logout')->name('logout');
});
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Models\Tag;
use App\Models\Product;
use App\Models\Category;
use App\Models\SubCategory;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use App\Http\Requests\ProductStoreRequest;
use App\Http\Requests\ProductUpdateRequest;
class ProductController extends Controller
{
public function index()
{
$products = Product::orderBy('id', 'desc')->paginate(5);
return view('product.index', compact('products'));
}
public function create()
{
$cats = Category::all();
$subcats = SubCategory::all();
$tags = Tag::all();
return view('product.create', compact('cats', 'subcats', 'tags'));
}
public function store(ProductStoreRequest $request)
{
if(!$request->hasFile('images')){
return redirect()->back()->withErrors(['images[]' => 'ဓာတ်ပုံထည့်ရန်လိုအပ်ပါသည်။']);
}
$files = $request->file('images');
$images = '';
foreach ($files as $file) {
$imgNames = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$images .= $imgNames . ',';
$file->move(public_path() . '/product/', $imgNames);
}
$images = rtrim($images, ',');
$product = new Product();
$product->category_id = $request->category_id;
$product->subcat_id = $request->subcat_id;
$product->tag_id = $request->tag_id;
$product->name = $request->name;
$product->price = $request->price;
$product->colors = $request->colors;
$product->sizes = $request->sizes;
$product->description = $request->description;
$product->images = $images;
$product->save();
return redirect()->route('product.index')->with('success', 'product create success!');
}
public function show($id)
{
//
}
public function edit($id)
{
$cats = Category::all();
$subcats = SubCategory::all();
$tags = Tag::all();
$product = Product::findOrFail($id);
return view('product.edit', compact('product', 'cats', 'subcats', 'tags'));
}
public function update(ProductUpdateRequest $request, $id)
{
$product = Product::findOrFail($id);
$check = Product::where('name', $request->name)->where('id', '!=', $id)->first();
if (!$check) {
$product->name = $request->name;
$product->category_id = $request->category_id;
$product->subcat_id = $request->subcat_id;
$product->tag_id = $request->tag_id;
$product->name = $request->name;
$product->price = $request->price;
$product->colors = $request->colors;
$product->sizes = $request->sizes;
$product->description = $request->description;
## check image
if ($request->hasFile('images')) {
if ($product->images) {
foreach (explode(',', $product->images) as $img) {
File::delete('product/'.$img);
}
}
$files = $request->file('images');
$images = '';
foreach ($files as $file) {
$imgNames = time() . uniqid() . '.' . $file->getClientOriginalExtension();
$images .= $imgNames . ',';
$file->move(public_path() . '/product/', $imgNames);
}
$images = rtrim($images, ',');
$product->images = $images;
}
if ($product->update()) {
return redirect()->route('product.index')->with('success', 'product update success!');
} else {
return redirect()->back()->with('error', 'product update fail!');
}
} else {
return redirect()->back()->withErrors(['name' => 'Product အမျိုးအစားသည်ရှိပီးသားဖြစ်ပါသည်။']);
}
}
public function destroy($id)
{
$product = Product::findOrFail($id);
if ($product->images) {
foreach (explode(',', $product->images) as $img) {
File::delete('product/' . $img);
}
}
$product->delete();
return redirect()->back()->with('success', 'product delete success!');
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use \Tymon\JWTAuth\Facades\JWTAuth;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\RoleUser;
use App\Models\SaveProduct;
use App\Models\SubCategory;
use App\Models\Tag;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class ApiController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'phone' => 'required|unique:users|digits_between:7,11',
'address' => 'required',
'password' => '<PASSWORD>',
'password_confrim' => 'required|same:password'
], [
'required' => ':attribute ထည့်ရန်လိုအပ်ပါသည်',
'digits_between' => ':attribute သည်အနည်းဆုံး 9လုံး အများဆုံး 11လုံး ထည့်ရန်လိုအပ်ပါသည်',
'unique' => ' :attribute သည်အသုံးပြုပီးဖြစ်ပါသည်',
'same' => ':attribute များတူညီရန်လိုအပ်ပါသည်။'
]);
if ($validator->fails()) {
return response()->json([
'status' => 500,
'success' => false,
'errors' => $validator->errors()
]);
}
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->phone = $request->phone;
$user->address = $request->address;
$user->password = <PASSWORD>($request->password);
$user->save();
## Define level
$role_user = new RoleUser();
$role_user->user_id = $user->id;
$role_user->role_id = 1;
$role_user->save();
return response()->json([
'status' => 200,
'success' => true,
'user' => $user
]);
}
public function login(Request $request)
{
$cre = $request->only('email', 'password');
$token = JWTAuth::attempt($cre);
$user = User::where('email', $request->email)->first();
if ($token) {
return response()->json([
'status' => 200,
'success' => true,
'token' => $token,
'user' => $user
]);
} else {
return response()->json([
'status' => 500,
'success' => false,
]);
}
}
public function me()
{
$user = Auth::user();
return response()->json([
'status' => 200,
'success' => true,
'user' => $user
]);
}
public function categories()
{
$categories = Category::withcount('product')->latest()->get();
return response()->json([
'status' => 200,
'success' => true,
'data' => $categories,
]);
}
public function subcats()
{
$subcats = SubCategory::withcount('product')->take(15)->get();
return response()->json([
'status' => 200,
'success' => true,
'data' => $subcats,
]);
}
public function subCategories($id)
{
$subCategories = SubCategory::where('category_id', $id)->get();
return response()->json([
'status' => 200,
'success' => true,
'data' => $subCategories,
]);
}
public function tags()
{
$tags = Tag::get();
return response()->json([
'status' => 200,
'success' => true,
'data' => $tags,
]);
}
public function products(Request $request)
{
$products = Product::with('cat', 'subcat', 'tag')->latest()->simplePaginate(12);
return response()->json([
'status' => 200,
'success' => true,
'data' => $products,
]);
}
public function productById($id)
{
$chkSave = SaveProduct::where('product_id', $id)->first();
if ($chkSave) {
$save = true;
} else {
$save = false;
}
$product = Product::with('cat', 'subcat', 'tag')->where('id', $id)->first();
$product['save'] = $save;
return response()->json([
'status' => 200,
'success' => true,
'data' => $product,
]);
}
public function productByCategory($id)
{
$products = Product::where('category_id', $id)->with('cat', 'subcat', 'tag')->simplePaginate(5);
return response()->json([
'status' => 200,
'success' => true,
'data' => $products
]);
}
public function productBysubCat($id)
{
$products = Product::where('subcat_id', $id)->simplePaginate(50);
return response()->json([
'status' => 200,
'success' => true,
'data' => $products
]);
}
public function productByTag($id)
{
$products = Product::where('tag_id', $id)->latest()->take(6)->get();
return response()->json([
'status' => 200,
'success' => true,
'data' => $products
]);
}
public function productByAllTag($id)
{
$products = Product::where('tag_id', $id)->latest()->paginate(50);
return response()->json([
'status' => 200,
'success' => true,
'data' => $products
]);
}
## set order
public function setOrder(Request $request)
{
$orders = $request->orders;
$orderId = $this->saveOrder($orders);
foreach ($orders as $od) {
$product = Product::find($od['id']);
$order_item = new OrderItem();
$order_item->order_id = $orderId;
$order_item->user_id = auth()->user()->id;
$order_item->category_id = $product->category_id;
$order_item->subcat_id = $product->subcat_id;
$order_item->tag_id = $product->tag_id;
$order_item->name = $product->name;
$order_item->price = $product->price;
$order_item->images = $product->images;
$order_item->color = $product->colors;
$order_item->size = $product->sizes;
$order_item->count = $od['count'];
$order_item->total = $product->price * $od['count'];
$order_item->save();
}
return response()->json([
'status' => 200,
'success' => true,
'message' => 'order success'
]);
}
public function saveOrder($orders)
{
## calculate total
$total = 0;
foreach ($orders as $od) {
$product = Product::find($od['id']);
$total += $product->price * $od['count'];
}
## save database
$order = new Order();
$order->user_id = auth()->user()->id;
$order->count = count($orders);
$order->status = false;
$order->total = $total;
$order->save();
return $order->id;
}
## get order
public function myOrder()
{
$orders = Order::where('user_id', auth()->user()->id)->get()->load('orderItem');
return response()->json([
'status' => 200,
'success' => true,
'data' => $orders
]);
}
public function orderItemByorderId($id)
{
$orders = OrderItem::where('order_id', $id)->get();
return response()->json([
'status' => 200,
'success' => true,
'orders' => $orders
]);
}
## save product
public function saveProduct(Request $request)
{
$user_id = auth()->user()->id;
$product_id = $request->product_id;
$save_product = new SaveProduct();
$save_product->user_id = $user_id;
$save_product->product_id = $product_id;
$save_product->save();
$product = Product::with('cat', 'subcat', 'tag')->where('id', $product_id)->first();
$product['save'] = true;
return response()->json([
'status' => 200,
'success' => true,
'data' => $product,
]);
}
## unsave product
public function unsaveProduct(Request $request)
{
$product_id = $request->product_id;
$product = Product::with('cat', 'subcat', 'tag')->where('id', $product_id)->first();
$product['save'] = false;
SaveProduct::where('product_id', $product_id)->delete();
return response()->json([
'status' => 200,
'success' => true,
'data' => $product,
]);
}
## get save product
public function getSaveProduct()
{
$user_id = auth()->user()->id;
// $product = SaveProduct::with('product.cat')->where('user_id', $user_id)->get();
$products = SaveProduct::where('user_id', $user_id)->get();
$product = [];
foreach ($products as $p) {
$data = Product::with('cat', 'tag', 'subcat')->where('id', $p->product_id)->first();
$data['save'] = true;
array_push($product, $data);
}
return response()->json([
'status' => 200,
'success' => true,
'data' => $product,
]);
}
## update profile
public function updateProfile(Request $request)
{
$user = auth()->user();
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users,email,' . $user->id . ',id',
'phone' => 'required|digits_between:7,11|unique:users,phone,' . $user->id . ',id',
'address' => 'required',
], [
'required' => ':attribute ထည့်ရန်လိုအပ်ပါသည်',
'digits_between' => ':attribute သည်အနည်းဆုံး 9လုံး အများဆုံး 11လုံး ထည့်ရန်လိုအပ်ပါသည်',
'unique' => ' :attribute သည်အသုံးပြုပီးဖြစ်ပါသည်',
'same' => ':attribute များတူညီရန်လိုအပ်ပါသည်။'
]);
if ($validator->fails()) {
return response()->json([
'status' => 500,
'success' => false,
'errors' => $validator->errors()
]);
}
$user = User::where('id', $user->id)->first();
$user->name = $request->name;
$user->email = $request->email;
$user->phone = $request->phone;
$user->address = $request->address;
$user->update();
return response()->json([
'status' => 200,
'success' => true,
'user' => $user
]);
}
## change password
public function changePassword(Request $request)
{
$user = auth()->user();
$validator = Validator::make($request->all(), [
'current_password' => '<PASSWORD>',
'new_password' => '<PASSWORD>|min:6',
'confirm_password' => '<PASSWORD>|same:new_password',
], [
'required' => ':attribute ထည့်ရန်လိုအပ်ပါသည်',
'same' => ':attribute သည် New Password နှင့် တူညီရန်လိုအပ်ပါသည်',
'min' => ':attribute သည် အနည်းဆုံး ၆ လုံးဖြစ်ရပါမည်',
]);
if ($validator->fails()) {
return response()->json([
'status' => 500,
'success' => false,
'errors' => $validator->errors()
]);
}
$user = User::where('id', $user->id)->first();
if (!Hash::check($request->current_password, $user->password)) {
return response()->json([
'status' => 500,
'success' => false,
'errors' => ["current_password" => [0 => "လက်ရှိစကားဝှက်မှားနေပါသည်။"]]
]);
} else {
$user->password = <PASSWORD>($request->new_password);
$user->update();
return response()->json([
'status' => 200,
'success' => true,
'user' => $user
]);
}
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ProductUpdateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'required',
'category_id'=>'required',
'subcat_id'=>'required',
'tag_id'=>'required',
'price'=>'required|numeric',
'colors'=>'required',
'sizes'=>'required',
'description'=>'required',
];
}
public function messages()
{
return [
'category_id.required'=>'Category ထည့်ရန်လိုအပ်ပါသည်။',
'subcat_id.required'=>'Sub Category ထည့်ရန်လိုအပ်ပါသည်။',
'tag_id.required'=>'Tag ထည့်ရန်လိုအပ်ပါသည်။',
'name.required'=>'Product ထည့်ရန်လိုအပ်ပါသည်။',
'colors.required'=>'အရောင်ထည့်ရန်လိုအပ်ပါသည်။',
'description.required'=>'အကြောင်းအရာထည့်ရန်လိုအပ်ပါသည်။',
'price.required'=>'စေ◌ျးနူန်း ထည့်ရန်လိုအပ်ပါသည်။',
'sizes.required'=>'အရွယ်အစား ထည့်ရန်လိုအပ်ပါသည်။',
'price.numeric'=>'စေ◌ျးနူန်း သည် Number ဖြစ်ရပါမည်။',
'name.unique'=>'Product အမျိုးအစားသည်ရှိပီးသားဖြစ်ပါသည်။',
];
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class PageController extends Controller
{
public function home(){
return view('home');
}
public function logout(){
Auth::logout();
return redirect()->route('login');
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
## For Not Auth
Route::group(['namespace'=>'Admin'],function(){
Route::post('/login','ApiController@login');
Route::post('/register','ApiController@register');
Route::get('/categories','ApiController@categories');
Route::get('/subcats','ApiController@subcats');
Route::get('/subcat/{id}','ApiController@subCategories');
Route::get('/tags','ApiController@tags');
Route::get('/products','ApiController@products');
Route::get('/product/{id}','ApiController@productById');
Route::get('/productByCat/{id}','ApiController@productByCategory');
Route::get('/productBySubCat/{id}','ApiController@productBysubCat');
Route::get('/productByTag/{id}','ApiController@productByTag');
Route::get('/productByAllTag/{id}','ApiController@productByAllTag');
});
## For If Auth
Route::group(['middleware'=>'jwt.auth',"namespace"=>"Admin"],function(){
Route::get('/me','ApiController@me');
Route::post('/order', 'ApiController@setOrder');
Route::get('/myOrder', 'ApiController@myOrder');
Route::get('/orderItemByOrderId/{id}', 'ApiController@orderItemByorderId');
Route::post('/save-product', 'ApiController@saveProduct');
Route::post('/unsave-product', 'ApiController@unsaveProduct');
Route::get('/getSaveProduct', 'ApiController@getSaveProduct');
Route::post('/profile-update', 'ApiController@updateProfile');
Route::post('/change-password', 'ApiController@changePassword');
});
<file_sep><?php
namespace App\Models;
use App\Models\Tag;
use App\Models\SubCategory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Product extends Model
{
use HasFactory;
public function cat(){
return $this->belongsTo(Category::class,'category_id');
}
public function subcat(){
return $this->belongsTo(SubCategory::class,'subcat_id');
}
public function tag(){
return $this->belongsTo(Tag::class,'tag_id');
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TagStoreRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'tag'=>'required|unique:categories,name',
'image'=>'required'
];
}
public function messages()
{
return [
'tag.required'=>'Tag ထည့်ရန်လိုအပ်ပါသည်။',
'tag.unique'=>'Tag အမျိုးအစားသည်ရှိပီးသားဖြစ်ပါသည်။',
'image.required'=>'Tag ဓာတ်ပုံထည့်ရန်လိုအပ်ပါသည်။',
];
}
}
|
8f0316da4b63e96873deac12695f90ff47e51cab
|
[
"PHP"
] | 16
|
PHP
|
iamtomc/Laravel-8-Ecommerce-API
|
2293476fae205280497666baa3e1a1f271f2b936
|
68c461d79657d377243893fcd0b9fc3e6e9dd8ff
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
"""
import helpers as helpers
import os
from collections import OrderedDict as od
import numpy as np
import matplotlib.pyplot as plt
import pyaerocom as pya
import logging
### GLOBAL SETTINGS
YEARS = [2010, 2008, 9999]
MODEL_LIST = ['ECMWF_CAMS_REAN',
'CAM6-Oslo_NF2kNucl_7jun2018AK',
'OsloCTM2_INSITU',
'TM5_AP3-CTRL2016',
'TM5_AP3-INSITU']
MODEL_LIST = MODEL_LIST[2:]
GRIDDED_OBS = {'MODIS6.terra' : ['od550aer'],
'MODIS6.aqua' : ['od550aer']}
# will be filled during the import
READ_PROBLEMATIC = {}
# Obs data and variables
UNGRIDDED_OBS = {'AeronetSunV2Lev2.daily' : ['od550aer', 'ang4487aer'],
'AeronetSunV3Lev2.daily' : ['od550aer', 'ang4487aer'],
'AeronetSDAV2Lev2.daily' : ['od550lt1aer',
'od550gt1aer'],
'AeronetSDAV3Lev2.daily' : ['od550lt1aer',
'od550gt1aer'],
pya.const.AERONET_INV_V2L2_DAILY_NAME : 'abs550aer',
pya.const.AERONET_INV_V3L2_DAILY_NAME : 'abs550aer'}
### Paths and directories
MODEL_INFO_FILE = ('/lustre/storeA/project/aerocom/'
'aerocom-users-database/AEROCOM-PHASE-III/reference-list')
OUT_DIR = './output/'
OUT_DIR_SCAT = os.path.join(OUT_DIR, 'scatter_plots')
OUT_DIR_RESULTS = os.path.join(OUT_DIR, 'results_csv')
OUT_STATS = os.path.join(OUT_DIR, 'statistics_results.csv')
VARS = []
for k, v in UNGRIDDED_OBS.items():
if isinstance(v, str):
VARS.append(v)
else:
VARS.extend(v)
for k, v in GRIDDED_OBS.items():
if isinstance(v, str):
VARS.append(v)
else:
VARS.extend(v)
VARS = list(dict.fromkeys(VARS))
def chk_make_dir(base, name):
d = os.path.join(base, name)
if not os.path.exists(d):
os.mkdir(d)
return d
def init_output_directories(model_reader, obs_data, out_base_dir):
if not os.path.exists(out_base_dir):
os.mkdir(out_base_dir)
dirs = {}
for name, data in model_reader.results.items():
model_base = chk_make_dir(out_base_dir, name)
dirs[name] = {}
for y in data.years:
year_sub = chk_make_dir(model_base, str(y))
dirs[name][y] = {}
for obs_network in obs_data:
obs_sub = chk_make_dir(year_sub, obs_network)
dirs[name][y][obs_network] = obs_sub
chk_make_dir(obs_sub, 'series_plots')
return dirs
def append_result(out_file, stats, model, obs, var, year, ts_type):
with open(out_file, 'a') as f:
f.write('Model: {}, Obs: {}, Var: {}, Year: {}, Freq: {}\n'.format(
model, obs, var, year, ts_type))
for k, v in stats.items():
f.write('{}:\t{:.3f}\n'.format(k, v))
f.write('\n')
if __name__=="__main__":
if os.path.exists(OUT_STATS):
os.remove(OUT_STATS)
plt.close('all')
helpers.print_file(MODEL_INFO_FILE)
### OPTIONS
RELOAD = 1
RUN_EVAL = 1
EVAL_UNGRIDDED = 1
EVAL_GRIDDED_OBS = 1
TEST = 0
PLOT_STATIONS = 0
pya.change_verbosity('critical')
### DATA IMPORT
if RELOAD:
print('Importing model and obs data, this could take some time')
### Read gridded model data
read_models = pya.io.ReadGriddedMulti(MODEL_LIST)
read_models.read_individual_years(VARS, YEARS)
print('Reading satellite data')
### Read gridded obs data
grid_obs = [k for k in GRIDDED_OBS.keys()]
read_gridded_obs = pya.io.ReadGriddedMulti(grid_obs)
read_gridded_obs.read_individual_years(VARS, YEARS)
read_ungridded_obs = pya.io.ReadUngridded()
read_ungridded_obs.logger.setLevel(logging.INFO)
print('Reading ungridded obs data')
# Load networks individually for now (easier for analysis below)
ungridded_obs_all = od()
if EVAL_UNGRIDDED:
for network, vars_to_retrieve in UNGRIDDED_OBS.items():
ungridded_obs_all[network] = read_ungridded_obs.read_dataset(
network, vars_to_retrieve=vars_to_retrieve)
dirs = init_output_directories(read_models, ungridded_obs_all, OUT_DIR)
if RUN_EVAL:
### ANALYSIS
PLOT_STATIONS = 0
# temporal resolution
TS_TYPES = ['daily', 'monthly', 'yearly']
filter_name = 'WORLD-noMOUNTAINS'
for ts_type in TS_TYPES:
plotname = 'mALLYEAR{}'.format(ts_type)
for model_id, model_reader in read_models.results.items():
for year in YEARS:
if not year in model_reader.years:
continue
for var in VARS:
if not var in model_reader.vars:
continue
if EVAL_GRIDDED_OBS:
for obs_id, obs_reader in read_gridded_obs.results.items():
if var in obs_reader.vars and year in obs_reader.years:
if year == 9999:
msg =('Ignoring climatology data (model: {}, '
'obs: {}). '
'Not yet implemented'.format(model_id,
obs_id))
print(msg)
with open(OUT_STATS, 'a') as f:
f.write('\n{}\n\n'.format(msg))
continue
print('Analysing variable: {}\n'
'Model {} vs. obs {}\n'
'Year: {} ({} resolution)\n'
.format(var, model_id, obs_id,
year, ts_type))
model = model_reader.data_yearly[var][year]
obs = obs_reader.data_yearly[var][year]
start_str = str(year)
stop_str = '{}-12-31 23:59:59'.format(year)
data = pya.collocation.collocate_gridded_gridded(
model, obs,
start=start_str,
stop=stop_str,
ts_type=ts_type,
filter_name=filter_name)
stats = data.calc_statistics()
append_result(OUT_STATS, stats,
model_id, obs_id, var, year, ts_type)
add_note=False
if np.isnan(stats['R']):
if sum(data.data.values[1].flatten()) != 0:
raise Exception('Check...')
add_note = True
save_name_fig = data.save_name_aerocom + '_SCAT.png'
data.plot_scatter(savefig=True,
save_dir=OUT_DIR_SCAT,
save_name=save_name_fig)
data.to_csv(OUT_DIR_RESULTS)
if TEST:
raise Exception
plt.close('all')
if EVAL_UNGRIDDED:
for obs_id, ungridded_obs in ungridded_obs_all.items():
if not var in ungridded_obs.contains_vars:
continue
if year == 9999:
msg =('Ignoring climatology data (model: {}, '
'obs: {}). '
'Not yet implemented'.format(model_id,
obs_id))
print(msg)
with open(OUT_STATS, 'a') as f:
f.write('\n{}\n\n'.format(msg))
continue
print('Analysing variable: {}\n'
'Model {} vs. obs {}\n'
'Year: {} ({} resolution)\n'
.format(var, model_id, obs_id,
year, ts_type))
model = model_reader.data_yearly[var][year]
start_str = str(year)
stop_str = '{}-12-31 23:59:00'.format(year)
data = pya.collocation.collocate_gridded_ungridded_2D(
model, ungridded_obs, ts_type=ts_type,
start=start_str, stop=stop_str,
filter_name=filter_name)
data.to_csv(OUT_DIR_RESULTS)
stats = data.calc_statistics()
append_result(OUT_STATS, stats,
model_id, obs_id, var, year, ts_type)
add_note=False
if np.isnan(stats['R']):
if sum(data.data.values[1].flatten()) != 0:
raise Exception('Check...')
add_note = True
save_name_fig = data.save_name_aerocom + '_SCAT.png'
data.plot_scatter(savefig=True,
save_dir=OUT_DIR_SCAT,
save_name=save_name_fig)
plt.close('all')
<file_sep># aerocom_obs_props
Repository for analysis scripts related to Aerocom optical properties comparison study.
See [results_overview.ipynb](https://github.com/jgliss/aerocom_obs_props/blob/master/results_overview.ipynb)
for an overview of the current analysis results.
The heavy parts of the analysis are performed in [EVAL_SCRIPT.py](https://github.com/jgliss/aerocom_obs_props/blob/master/EVAL_SCRIPT.py)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
"""
import helpers as helpers
import os
from collections import OrderedDict as od
from time import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pyaerocom as pya
from scipy.stats import pearsonr, spearmanr
import logging
from matplotlib.ticker import ScalarFormatter
### GLOBAL SETTINGS
YEARS = [2010, 2008, 9999]
MODEL_LIST = ['CAM6-Oslo_NF2kNucl_7jun2018AK',
'OsloCTM2_INSITU',
'TM5_AP3-CTRL2016',
'TM5_AP3-INSITU']
GRIDDED_OBS_NETWORKS = ['MODIS6.terra', #od550aer
'MODIS6.aqua',] #od550aer
#'CALIOP3'] #od550aer
# will be filled during the import
READ_PROBLEMATIC = {}
# Obs data and variables
UNGRIDDED_OBS_NETWORKS = {'AeronetSunV2Lev2.daily' : 'od550aer',
'AeronetSunV3Lev2.daily' : 'od550aer',
'AeronetSDAV2Lev2.daily' : ['od550lt1aer',
'od550gt1aer'],
'AeronetSDAV3Lev2.daily' : ['od550lt1aer',
'od550gt1aer'],
pya.const.AERONET_INV_V2L2_DAILY_NAME : 'abs550aer',
pya.const.AERONET_INV_V3L2_DAILY_NAME : 'abs550aer'
}
#'EBASMC'] # ec550aer, ...
### Paths and directories
MODEL_INFO_FILE = ('/lustre/storeA/project/aerocom/'
'aerocom-users-database/AEROCOM-PHASE-III/reference-list')
OUT_DIR = './output/'
OUT_DIR_SCAT = os.path.join(OUT_DIR, 'scatter_plots')
OUT_DIR_RESULTS = os.path.join(OUT_DIR, 'results_csv')
OUT_STATS = os.path.join(OUT_DIR, 'statistics_results.csv')
# some helper dictionaries for conversion of temporal resolution
TS_TYPE_TO_PANDAS_FREQ = {'hourly' : 'H',
'3hourly' : '3H',
'daily' : 'D',
'monthly' : 'M'}
VARS = []
for k, v in UNGRIDDED_OBS_NETWORKS.items():
if isinstance(v, str):
VARS.append(v)
else:
VARS.extend(v)
VARS = list(dict.fromkeys(VARS))
def chk_make_dir(base, name):
d = os.path.join(base, name)
if not os.path.exists(d):
os.mkdir(d)
return d
def init_output_directories(model_reader, obs_data, out_base_dir):
dirs = {}
for name, data in model_reader.results.items():
model_base = chk_make_dir(out_base_dir, name)
dirs[name] = {}
for y in data.years:
year_sub = chk_make_dir(model_base, str(y))
dirs[name][y] = {}
for obs_network in obs_data:
obs_sub = chk_make_dir(year_sub, obs_network)
dirs[name][y][obs_network] = obs_sub
chk_make_dir(obs_sub, 'series_plots')
return dirs
def calc_statistics(model_vals, obs_vals):
result = {}
difference = model_vals - obs_vals
num_points = len(model_vals)
result['obs_mean'] = obs_vals.mean()
result['model_mean'] = model_vals.mean()
result['rms'] = np.sqrt(np.nansum(np.power(difference, 2)) / num_points)
result['nmb'] = np.sum(difference) / np.sum(obs_vals)*100.
tmp = difference / (model_vals + obs_vals)
result['mnmb'] = 2. / num_points * np.sum(tmp) * 100.
result['fge'] = 2. / np.sum(np.abs(tmp)) * 100.
result['R_pearson'] = pearsonr(model_vals, obs_vals)[0]
result['R_spearman'] = spearmanr(model_vals, obs_vals)[0]
return result
def plot_scatter(model_vals, obs_vals, model_id, var, obs_id, year, stations_ok,
plotname, filter_name, statistics=None, savefig=True,
save_dir=None, save_name=None, add_data_missing_note=False):
if statistics is None:
statistics = calc_statistics(model_vals, obs_vals)
VAR_PARAM = pya.const.VAR_PARAM[var]
fig, ax = plt.subplots(figsize=(8,6))
ax.loglog(obs_vals, model_vals, ' k+')
ax.set_xlim(VAR_PARAM['scat_xlim'])
ax.set_ylim(VAR_PARAM['scat_ylim'])
ax.set_xlabel('Obs: {} ({})'.format(obs_id, year), fontsize=14)
ax.set_ylabel('{} ({})'.format(model_id, year), fontsize=14)
ax.xaxis.set_major_formatter(ScalarFormatter())
ax.yaxis.set_major_formatter(ScalarFormatter())
plt.plot(VAR_PARAM['scat_xlim'], VAR_PARAM['scat_ylim'], '-',
color='grey')
# text positions for the scatter plot annotations
xypos=[]
xypos.append((.01, 0.95))
xypos.append((0.01, 0.90))
xypos.append((0.3, 0.90))
xypos.append((0.01, 0.86))
xypos.append((0.3, 0.86))
xypos.append((0.01, 0.82))
xypos.append((0.3, 0.82))
xypos.append((0.01, 0.78))
xypos.append((0.3, 0.78))
xypos.append((0.8, 0.1))
xypos.append((0.8, 0.06))
xypos_index = 0
var_str = var + VAR_PARAM.unit_str
ax.annotate("{} #: {} # st: {}".format(var_str,
len(obs_vals), stations_ok),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=14, color='red')
xypos_index += 1
ax.annotate('Obs: {:.3f}'.format(statistics['obs_mean']),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=10, color='red')
xypos_index += 1
ax.annotate('Mod: {:.3f}'.format(statistics['model_mean']),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=10, color='red')
xypos_index += 1
ax.annotate('NMB: {:.1f}%'.format(statistics['nmb']),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=10, color='red')
xypos_index += 1
ax.annotate('MNMB: {:.1f}%'.format(statistics['mnmb']),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=10, color='red')
xypos_index += 1
ax.annotate('R: {:.3f}'.format(statistics['R_pearson']),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=10, color='red')
xypos_index += 1
ax.annotate('RMS: {:.3f}'.format(statistics['rms']),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=10, color='red')
xypos_index += 1
ax.annotate('FGE: {:.3f}'.format(statistics['fge']),
xy=xypos[xypos_index], xycoords='axes fraction',
fontsize=10, color='red')
# right lower part
ax.annotate('{}'.format(plotname),
xy=xypos[-2], xycoords='axes fraction',
ha='center',
fontsize=10, color='black')
ax.annotate('{}'.format(filter_name),
xy=xypos[-1], xycoords='axes fraction', ha='center',
fontsize=10, color='black')
if add_data_missing_note:
ax.annotate('NO MODEL DATA',
xy=(0.4, 0.3), xycoords='axes fraction', ha='center',
fontsize=20, color='red')
ax.set_aspect('equal')
if savefig:
if any([x is None for x in (save_dir, save_name)]):
raise IOError
fig.savefig(os.path.join(save_dir, save_name))
return ax
def append_result(out_file, stats, model, obs, var, year, ts_type):
with open(out_file, 'a') as f:
f.write('Model: {}, Obs: {}, Var: {}, Year: {}, Freq: {}\n'.format(
model, obs, var, year, ts_type))
for k, v in stats.items():
f.write('{}:\t{:.3f}\n'.format(k, v))
f.write('\n')
if __name__=="__main__":
if os.path.exists(OUT_STATS):
os.remove(OUT_STATS)
plt.close('all')
helpers.print_file(MODEL_INFO_FILE)
### OPTIONS
RUN_EVAL = 1
RELOAD = 1
TEST_FIRST = 0
PLOT_STATIONS = 0
pya.change_verbosity('critical')
if RUN_EVAL:
### DATA IMPORT
if RELOAD:
print('Importing model and obs data, this could take some time')
### Read gridded model data
read_models = pya.io.ReadGriddedMulti(MODEL_LIST)
read_models.read_individual_years(VARS, YEARS)
### Read gridded obs data
read_gridded_obs = pya.io.ReadGriddedMulti(GRIDDED_OBS_NETWORKS)
read_gridded_obs.read_individual_years(VARS, YEARS)
read_ungridded_obs = pya.io.ReadUngridded()
read_ungridded_obs.logger.setLevel(logging.INFO)
# Load networks individually for now (easier for analysis below)
ungridded_obs_all = od()
for network, vars_to_retrieve in UNGRIDDED_OBS_NETWORKS.items():
ungridded_obs_all[network] = read_ungridded_obs.read_dataset(
network, vars_to_retrieve=vars_to_retrieve)
dirs = init_output_directories(read_models, ungridded_obs_all, OUT_DIR)
if TEST_FIRST:
### TEST SCRIPT
# Ungridded data for Aeronet v2 level 2 daily
ungridded_obs = ungridded_obs_all['AeronetSunV2Lev2.daily']
# get coordinates of stations
station_lons = ungridded_obs.longitude
station_lats = ungridded_obs.latitude
var = 'od550aer'
# 2010
year = YEARS[0]
# temporal resolution
ts_type = 'monthly'
start_str = str(year)
stop_str = '{}-12-31 23:59:00'.format(year)
model_id = 'TM5_AP3-CTRL2016'
obs_id = ungridded_obs.metadata[0]['dataset_name']
filter_name = 'WORLD-wMOUNTAINS'
plotname = 'mALLYEAR{}'.format(ts_type)
# TM5_AP3-CTRL2016
model = read_models[model_id].data_yearly[var][year]
# extract year (it should be actually already the year, since
# we used the method read_individual_years above)
data_cropped = model.crop(time_range=(start_str,
stop_str))
# converted to daily resolution (Aeronet is daily)
model_data = data_cropped.downscale_time(to_ts_type='monthly')
RELOAD_SERIES = 1
if RELOAD_SERIES:
t10 = time()
model_stat_data = model_data.to_time_series(longitude=station_lons,
latitude=station_lats)
t11 = time()
freq = TS_TYPE_TO_PANDAS_FREQ[model_data.ts_type]
t20 = time()
obs_stat_data = ungridded_obs.to_station_data_all(vars_to_convert=var,
start=start_str,
stop=stop_str,
freq=freq,
interp_nans=False,
min_coverage_interp=0.68)
t21 = time()
ax = pya.plot.plot_series_year(obs_stat_data[3],
model_stat_data[3],
var, save_dir=OUT_DIR)
obs_vals = []
model_vals = []
num_valid_obs = 0
stations_ok = 0
t30 = time()
for i, obs_data in enumerate(obs_stat_data):
if obs_data is not None:
if PLOT_STATIONS:
plt.close('all')
print('Plotting station {}'.format(i))
save_dir = os.path.join(dirs[model_id][year][obs_id], 'series_plots')
ax = pya.plot.plot_series_year(obs_data,
model_stat_data[i],
var,
save_dir=save_dir)
# get model data corresponding to station
model_values = model_stat_data[i][var]
if sum(model_values.isnull()) > 0:
raise Exception
model_values.index = model_values.index.values.astype('<M8[{}]'.format(freq))
# get all days that are not nan
obs = obs_data[var]
obs_ok = ~obs.isnull()
obs_dates_ok = obs.index[obs_ok].values.astype('<M8[{}]'.format(freq))
obs_vals.extend(obs.values[obs_ok])
mv = model_values[obs_dates_ok].values
if sum(np.isnan(mv)) > 0:
raise Exception
model_vals.extend(mv)
num_valid_obs += sum(obs_ok)
stations_ok += 1
model_vals = np.asarray(model_vals)
obs_vals = np.asarray(obs_vals)
if np.sum(np.isnan(model_vals)) > 0:
raise Exception('Model stuff wrong...')
elif np.sum(np.isnan(obs_vals)) > 0:
raise Exception('Obs stuff wrong...')
stats = calc_statistics(model_vals, obs_vals)
save_name = ('{}_SCATTER_{}_{}_{}_{}_WORLD.png'.format(var, model_id, obs_id,
year, ts_type))
plot_scatter(model_vals, obs_vals, model_id, var, obs_id, year,
stations_ok, plotname, filter_name,stats, save_dir=OUT_DIR,
save_name=save_name)
t31 = time()
print('Elapsed time computing model time series at stations: {:.2f} s'.format(t11-t10))
print('Elapsed time computing model time series at stations: {:.2f} s'.format(t21-t20))
print('Elapsed time merging all: {:.2f} s'.format(t31-t30))
else:
### ANALYSIS
PLOT_STATIONS = 0
# temporal resolution
ts_type = 'monthly'
plotname = 'mALLYEAR{}'.format(ts_type)
filter_name = 'WORLD-wMOUNTAINS'
# init results dictionary
REEVAL = True
for model_id, model_reader in read_models.results.items():
for year in YEARS:
if not year in model_reader.years:
continue
for var in VARS:
if not var in model_reader.vars:
continue
for obs_id, ungridded_obs in ungridded_obs_all.items():
if not var in ungridded_obs.contains_vars:
continue
if year == 9999:
msg =('Ignoring climatology data (model: {}, '
'obs: {}). '
'Not yet implemented'.format(model_id,
obs_id))
print(msg)
with open(OUT_STATS, 'a') as f:
f.write('\n{}\n\n'.format(msg))
continue
print('Analysing variable: {}\n'
'Model {} vs. obs {}\n'
'Year: {} ({} resolution)\n'
.format(var, model_id, obs_id,
year, ts_type))
save_name_csv = ('{}_{}_{}_{}_{}_WORLD.csv'
.format(var, model_id, obs_id,
year, ts_type))
loc_csv = os.path.join(OUT_DIR_RESULTS,
save_name_csv)
if os.path.exists(loc_csv) and not REEVAL:
print('Result file {} already exists'
.format(loc_csv))
else:
### TODO: Here is where filters should be applied (e.g. altitude, region)
station_lons = ungridded_obs.longitude
station_lats = ungridded_obs.latitude
start_str = str(year)
stop_str = '{}-12-31 23:59:00'.format(year)
model = model_reader.data_yearly[var][year]
# extract year (it should be actually already the year, since
# we used the method read_individual_years above)
model = model.crop(time_range=(start_str, stop_str))
# converted to daily resolution (Aeronet is daily)
model_data = model.downscale_time(to_ts_type='monthly')
model_stat_data = model_data.to_time_series(longitude=station_lons,
latitude=station_lats)
freq = TS_TYPE_TO_PANDAS_FREQ[model_data.ts_type]
obs_stat_data = ungridded_obs.to_station_data_all(vars_to_convert=var,
start=start_str,
stop=stop_str,
freq=freq,
interp_nans=False,
min_coverage_interp=0.68)
obs_vals = []
model_vals = []
num_valid_obs = 0
stations_ok = 0
for i, obs_data in enumerate(obs_stat_data):
if obs_data is not None:
if PLOT_STATIONS:
plt.close('all')
print('Plotting station {}'.format(i))
save_dir = os.path.join(dirs[model_id][year][obs_id], 'series_plots')
ax = pya.plot.plot_series_year(obs_data,
model_stat_data[i],
var,
save_dir=save_dir)
# get model data corresponding to station
model_values = model_stat_data[i][var]
if sum(model_values.isnull()) > 0:
raise Exception
model_values.index = model_values.index.values.astype('<M8[{}]'.format(freq))
# get all days that are not nan
obs = obs_data[var]
obs_ok = ~obs.isnull()
obs_dates_ok = obs.index[obs_ok].values.astype('<M8[{}]'.format(freq))
obs_vals.extend(obs.values[obs_ok])
mv = model_values[obs_dates_ok].values
if sum(np.isnan(mv)) > 0:
raise Exception
model_vals.extend(mv)
num_valid_obs += sum(obs_ok)
stations_ok += 1
model_vals = np.asarray(model_vals)
obs_vals = np.asarray(obs_vals)
if np.sum(np.isnan(model_vals)) > 0:
raise Exception('Model stuff wrong...')
elif np.sum(np.isnan(obs_vals)) > 0:
raise Exception('Obs stuff wrong...')
stats = calc_statistics(model_vals, obs_vals)
print(stats)
append_result(OUT_STATS, stats, model_id, obs_id,
var, year, ts_type)
save_name = ('{}_{}_{}_{}_{}_WORLD_SCATTER.png'
.format(var, model_id, obs_id,
year, ts_type))
df = pd.DataFrame({'obs':obs_vals,
'model': model_vals})
df.to_csv(os.path.join(OUT_DIR_RESULTS, save_name_csv))
add_note=False
if np.isnan(stats['R_pearson']):
if sum(model_vals) != 0:
raise Exception('Check...')
add_note = True
plot_scatter(model_vals, obs_vals,
model_id, var, obs_id, year,
stations_ok,
plotname, filter_name,
stats, save_dir=OUT_DIR_SCAT,
save_name=save_name,
add_data_missing_note=add_note)
plt.close('all')
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 14:48:03 2018
@author: jonasg
"""
import pyaerocom as pya
from warnings import filterwarnings
MODEL_ID = 'TM5_AP3-INSITU'
OBS_ID = 'AeronetSunV3Lev2.daily'
YEAR = 2010
if __name__=='__main__':
filterwarnings('ignore')
model_reader = pya.io.ReadGridded(MODEL_ID)
obs_reader = pya.io.ReadUngridded()
#obs_data = obs_reader.read(OBS_ID, VAR)
VARS_FAILED = []
RESULTS = {}
for i, VAR in enumerate(model_reader.vars):
try:
h_avail = True
model_h = model_reader.read_var(VAR, ts_type='hourly',
flex_ts_type=False)
except IOError:
h_avail = False
try:
var_ok = True
model_d = model_reader.read_var(VAR, ts_type='daily',
flex_ts_type=False)
model_m = model_reader.read_var(VAR, ts_type='monthly',
flex_ts_type=False)
except IOError:
var_ok = False
VARS_FAILED.append(VAR)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
Note
----
Bug was fixed
"""
import pyaerocom as pya
### GLOBAL SETTINGS
YEARS = [2010, 2008]
GRIDDED_OBS = 'MODIS6.terra'
VAR = 'od550aer'
if __name__=="__main__":
read_gridded_obs = pya.io.ReadGridded(GRIDDED_OBS)
read_gridded_obs.read_individual_years(VAR, YEARS)
d2008 = read_gridded_obs.data_yearly['od550aer'][2008]
d2010 = read_gridded_obs.data_yearly['od550aer'][2010]
print(d2008.suppl_info)
print(d2010.suppl_info)<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 14:48:03 2018
@author: jonasg
"""
import pyaerocom as pya
OBS_DIR = '/lustre/storeA/project/aerocom/aerocom-users-database/SATELLITE-DATA/CALIOP3/renamed/'
if __name__=='__main__':
### Model data
import os, iris
files = os.listdir(OBS_DIR)
data4D = []
data4D_filename_wrong = []
lacks_dim = []
lacks_time_dim = []
lacks_longitude_dim = []
lacks_latitude_dim = []
time_wrong = []
var_not_found = []
filename_invalid = []
all_dim_varnames = []
more_than_one = []
fconv = pya.io.FileConventionRead('aerocom2')
for f in files:
fp = OBS_DIR + f
if not fp.endswith('.nc'):
continue
cubes = iris.load(fp)
data = None
try:
info = fconv.get_info_from_file(f)
var = info['var_name']
except pya.exceptions.FileConventionError:
filename_invalid.append(f)
else:
if len(cubes) > 1:
more_than_one.append(f)
var_found = False
for cube in cubes:
if cube.var_name == var:
data = cube
var_found = True
if not var_found:
var_not_found.append(f)
else:
is4d = False
if data.ndim == 4:
data4D.append(f)
is4d = True
if not '3d' in var.lower():
data4D_filename_wrong.append(f)
dim_names = [x.name() for x in data.dim_coords]
print(dim_names)
if not len(dim_names) == data.ndim:
lacks_dim.append(f)
if not 'time' in dim_names:
lacks_time_dim.append(f)
elif not 'longitude' in dim_names:
lacks_longitude_dim.append(f)
elif not 'latitude' in dim_names:
lacks_latitude_dim.append(f)
if 'time' in dim_names:
if not pya.io.iris_io.check_time_coord(data,
info['ts_type'],
info['year']):
time_wrong.append(f)
for name in dim_names:
if not name in all_dim_varnames:
all_dim_varnames.append(name)
totnum = len(files)
with open('CALIOP3_read_test.csv', 'w+') as f:
f.write('# Files that contain 4D data but not conclusive from filename ({} of {})\n'.format(len(data4D_filename_wrong), totnum))
for file in data4D_filename_wrong:
f.write(file + '\n')
f.write('\n')
f.write('# Files that miss time dimension ({} of {})\n'.format(len(lacks_time_dim), totnum))
for file in lacks_time_dim:
f.write(file + '\n')
f.write('\n')
f.write('# Files that include time dimension but time in data does not match filename info ({} of {})\n'.format(len(time_wrong), totnum))
for file in time_wrong:
f.write(file + '\n')
f.write('\n')
f.write('# Files that miss longitude dimension ({} of {})\n'.format(len(lacks_longitude_dim), totnum))
for file in lacks_longitude_dim:
f.write(file + '\n')
f.write('\n')
f.write('# Files that miss latitude dimension ({} of {})\n'.format(len(lacks_latitude_dim), totnum))
for file in lacks_latitude_dim:
f.write(file + '\n')
f.write('\n')
f.write('# Files that do not match aerocom file naming convention({} of {})\n'.format(len(filename_invalid), totnum))
for file in filename_invalid:
f.write(file + '\n')
f.write('\n')
f.write('# Files that miss at least one dimension definition ({} of {})\n'.format(len(lacks_dim), totnum))
for file in lacks_dim:
f.write(file + '\n')
f.write('\n')
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 14:48:03 2018
@author: jonasg
"""
import pyaerocom as pya
import iris
import numpy as np
MODEL = 'INCA-BCext_CTRL2016-PD'
START =2010
VAR = 'ang4487aer'
def calc_ang4487aer_from_ods_cubes(cube_od1, cube_od2):
wvl1 = pya.variable.VarNameInfo(cube_od1.var_name).wavelength_nm
wvl2 = pya.variable.VarNameInfo(cube_od2.var_name).wavelength_nm
wvlr = np.log(wvl1 / wvl2)
logr = iris.analysis.maths.log(cube_od1 / cube_od2)
return iris.analysis.maths.divide(logr, wvlr)*-1
if __name__=='__main__':
### Model data
reader = pya.io.ReadGridded(MODEL)
ang4487aer = reader.read_var('ang4487aer')
od550aer = reader.read_var('od550aer').grid
od443aer = reader.read_var('od443aer').grid
od865aer = reader.read_var('od865aer').grid
r = od443aer / od865aer
logr = iris.analysis.maths.log(r)
wvl_r = np.log(443/865)
ang4487aer = iris.analysis.maths.divide(logr, wvl_r)*-1
ang4487aer_ = float(ang4487aer[0,0,0].data)
od443aer_ = float(od443aer[0,0,0].data)
od865aer_ = float(od865aer[0,0,0].data)
od550aer_calc = od443aer_ * (443 / 550)**ang4487aer_
od550aer_ = float(od550aer[0,0,0].data)
diff = od550aer_ - od550aer_calc
#model = reader.read_var(VAR, start_time=START)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 14:48:03 2018
@author: jonasg
"""
import pyaerocom as pya
MODEL = 'TM5_AP3-CTRL2016'
OBS = 'CALIOP_V3.00_Cloudfree_day'
VAR = 'od550aer'
START=2007
STOP=2009
if __name__=='__main__':
### Model data
read_model = pya.io.ReadGridded(MODEL)
read_obs = pya.io.ReadGridded(OBS)
model = read_model.read_var(VAR,
start_time=START,
stop_time=STOP)
### CALIOP_V3.00_Cloudfree_day'
obs = read_obs.read_var(VAR,
start_time=START,
stop_time=STOP)
print(obs)
print(model.downscale_time('monthly'))
#od_regrid = od_obs.regrid(model)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
"""
import helpers
# alternative ts_types in case one of the provided in setup is not in dataset
TS_TYPE_READ_ALT = {'daily' : ['hourly', '3hourly'],
'monthly' : ['daily', 'hourly', '3hourly']}
# Todo: put this into class
TS_TYPE_SETUP = dict(monthly=['monthly', 'yearly'],
daily = ['monthly', 'yearly'],
read_alt=TS_TYPE_READ_ALT)
# Years to be analysed
YEARS = sorted([2008, 2010])
MODEL_ID = 'INCA-BCext_CTRL2016-PD'
OBS_ID = 'AeronetSunV3Lev2.daily'
VARS = ['ang4487aer']
FILTER = 'WORLD-noMOUNTAINS'
### output directories
OUT_DIR = './output_TEMP/'
if __name__ == '__main__':
from time import time
import os
t0 = time()
stp = helpers.AnalysisSetup(vars_to_analyse=VARS,
obs_id=OBS_ID,
years=YEARS,
filter_name=FILTER,
ts_type_setup=TS_TYPE_SETUP,
out_basedir=OUT_DIR)
with open(os.path.join(OUT_DIR, 'result_log_{}.csv'.format(OBS_ID)), 'w+') as log:
log.write('Analysis configuration\n')
for k, v in stp.items():
if k == 'model_id':
continue
elif k == 'ts_type_setup':
log.write('TS_TYPES (<read>: <analyse>)\n')
for key, val in v.items():
if key == 'read_alt':
continue
log.write(' {}:{}\n'.format(key, val))
if v['read_alt']:
log.write(' Alternative TS_TYPES (read)\n')
for key, val in v['read_alt'].items():
log.write(' {}:{}\n'.format(key, val))
else:
log.write('{}: {}\n'.format(k, v))
print(stp)
log.write('\n\nModel: {}\n'.format(MODEL_ID))
stp.model_id = MODEL_ID
helpers.perform_analysis(logfile=log,
reanalyse_existing=True,
**stp)
dt = (time()-t0)/60
print('Analysis finished. Total time: {} min'.format(dt))<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
"""
from models import all_model_ids
import pyaerocom as pya
import helpers
# alternative ts_types in case one of the provided in setup is not in dataset
TS_TYPE_READ_ALT = {'daily' : ['hourly', '3hourly'],
'monthly' : ['daily', 'hourly', '3hourly']}
# Todo: put this into class
TS_TYPE_SETUP = dict(monthly=['monthly', 'yearly'],
daily = ['monthly', 'yearly'],
read_alt=TS_TYPE_READ_ALT)
# Years to be analysed
YEARS = sorted([2008, 2010])
ALL_MODELS = all_model_ids()
OBS_INFO = {'MODIS6.terra' : ['od550aer'],
'MODIS6.aqua' : ['od550aer'],
'AeronetSunV2Lev2.daily' : ['od550aer', 'ang4487aer'],
'AeronetSunV3Lev2.daily' : ['od550aer', 'ang4487aer'],
'AeronetSDAV2Lev2.daily' : ['od550lt1aer',
'od550gt1aer'],
'AeronetSDAV3Lev2.daily' : ['od550lt1aer',
'od550gt1aer'],
pya.const.AERONET_INV_V2L2_DAILY_NAME : ['abs550aer'],
pya.const.AERONET_INV_V3L2_DAILY_NAME : ['abs550aer']}
OBS_INFO = {'EBASMC' : ['absc550aer',
'scatc550aer']}
OBS_IDS = list(OBS_INFO.keys())
FILTER = 'WORLD-noMOUNTAINS'
### output directories
OUT_DIR = './output/'
if __name__ == '__main__':
from time import time
import traceback
t0 = time()
REANALYSE_EXISTING = False
RUN_ANALYSIS = True
ONLY_FIRST = False
RAISE_EXCEPTIONS = False
if ONLY_FIRST:
OBS_IDS = [OBS_IDS[0]]
for OBS_ID in OBS_IDS:
VARS = OBS_INFO[OBS_ID]
stp = helpers.AnalysisSetup(vars_to_analyse=VARS,
obs_id=OBS_ID,
years=YEARS,
filter_name=FILTER,
ts_type_setup=TS_TYPE_SETUP,
out_basedir=OUT_DIR)
with open('output/result_log_{}.csv'.format(OBS_ID), 'w+') as log:
log.write('Analysis configuration\n')
for k, v in stp.items():
if k == 'model_id':
continue
elif k == 'ts_type_setup':
log.write('TS_TYPES (<read>: <analyse>)\n')
for key, val in v.items():
if key == 'read_alt':
continue
log.write(' {}:{}\n'.format(key, val))
if v['read_alt']:
log.write(' Alternative TS_TYPES (read)\n')
for key, val in v['read_alt'].items():
log.write(' {}:{}\n'.format(key, val))
else:
log.write('{}: {}\n'.format(k, v))
print(stp)
if RUN_ANALYSIS:
models = all_model_ids()
if ONLY_FIRST:
models = [models[0]]
for model_id in models:
log.write('\n\nModel: {}\n'.format(model_id))
stp.model_id = model_id
try:
helpers.perform_analysis(logfile=log,
reanalyse_existing=REANALYSE_EXISTING,
**stp)
except:
log.write('Failed to perform analysis: {}\n'.format(traceback.format_exc()))
if RAISE_EXCEPTIONS:
raise Exception(traceback.format_exc())
dt = (time()-t0)/60
print('Analysis finished. Total time: {} min'.format(dt))<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
"""
import pandas as pd
import numpy as np
import pyaerocom as pya
import os
import EVAL_SCRIPT as EVAL
### GLOBAL SETTINGS
def get_info_filename(fpath):
return pya.collocateddata.CollocatedData().get_meta_from_filename(fpath)
def load_result_files(out_dir=EVAL.OUT_DIR_RESULTS):
files = os.listdir(out_dir)
results = []
for file in files:
info = get_info_filename(file)
info['model_id'] = info['data_source_idx'][1]
info['obs_id'] = info['data_source_idx'][0]
info['year'] = info['start'].year
info['data'] = pd.DataFrame.from_csv(os.path.join(out_dir, file))
results.append(info)
return results
def calc_stats(results):
for result in results:
obs = result['data']['ref'].values
model = result['data']['data'].values
stats = pya.mathutils.calc_statistics(model, obs)
result.update(stats)
return results
def to_multiindex_dataframe(results):
header = ['Model', 'Year', 'Freq', 'Variable', 'Obs', 'Bias', 'RMS', 'R', 'FGE']
data = []
for r in results:
file_data = [r['model_id'], r['year'], r['ts_type'], r['var_name'], r['obs_id'],
r['nmb'], r['rms'], r['R'], r['fge']]
data.append(file_data)
df = pd.DataFrame(data, columns=header)
df.set_index(['Model', 'Year', 'Freq', 'Variable', 'Obs'], inplace=True)
return df
if __name__=="__main__":
results = load_result_files()
results = calc_stats(results)
result= to_multiindex_dataframe(results)
print(result)
bias = result['Bias']
print(bias)
# =============================================================================
# s = pd.Series(bias)
# s2 = pd.Series(rms)
#
# =============================================================================
#pd.Dat
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
"""
import os
import numpy as np
from functools import reduce
import pyaerocom as pya
from models import all_model_ids
### GLOBAL SETTINGS
class AnalysisSetup(pya.utils.BrowseDict):
def __init__(self, **kwargs):
self.vars = None
self.model_id = None
self.obs_id = None
self.filer_name = None
self.ts_types_read = None
self.ts_types_ana = None
self.years = None
# all temporal resolutions that are supposed to be read
TS_TYPES_READ = ['monthly', 'daily']
# all temporal resolutions for which analysis is performed
TS_TYPES_ANA = ['yearly', 'monthly', 'daily']
# Years to be analysed
YEARS = sorted([2008, 2010])
ALL_MODELS = all_model_ids()
MODEL_ID = ALL_MODELS[0]
OBS_ID = 'AeronetSunV3Lev2.daily'
VARS = ['od550aer', 'ang4487aer']
FILTER = 'WORLD-noMOUNTAINS'
### output directories
OUT_DIR = './output/'
OUT_DIR_SCAT = os.path.join(OUT_DIR, 'scatter_plots')
OUT_DIR_RESULTS = os.path.join(OUT_DIR, 'results_csv')
_PLOTNAME_BASESTR = 'mALLYEAR{}'
TS_TYPES = pya.const.GRID_IO.TS_TYPES
def start_stop_from_year(year):
start = pya.helpers.to_pandas_timestamp(year)
stop = pya.helpers.to_pandas_timestamp('{}-12-31 23:59:59'.format(year))
return (start, stop)
if __name__=="__main__":
exceptions = []
pya.change_verbosity('warning')
obs_reader = pya.io.ReadUngridded()
obs_data = obs_reader.read(OBS_ID, VARS)
model_reader = pya.io.ReadGridded(MODEL_ID)
var_matches = list(reduce(np.intersect1d, (VARS,
model_reader.vars,
obs_data.contains_vars)))
if len(var_matches) == 0:
raise pya.exceptions.DataCoverageError('No variable matches between '
'{} and {} for input vars: {}'
.format(MODEL_ID, OBS_ID,
VARS))
year_matches = list(np.intersect1d(YEARS, model_reader.years))
ts_type_matches = list(np.intersect1d(TS_TYPES_READ, model_reader.ts_types))
for year in year_matches:
start, stop = start_stop_from_year(year)
for ts_type in ts_type_matches:
model_reader.read(var_matches, start_time=year,
ts_type = ts_type,
flex_ts_type=False)
plotname = _PLOTNAME_BASESTR.format(ts_type)
if len(model_reader.data) == 0:
exceptions.append('{}_{}: No data available'.format(year, ts_type))
else:
for var, model_data in model_reader.data.items():
for ts_type_ana in TS_TYPES_ANA:
if TS_TYPES.index(ts_type_ana) >= TS_TYPES.index(ts_type):
data_coll = pya.collocation.collocate_gridded_ungridded_2D(
model_data, obs_data,
ts_type=ts_type_ana,
start=start, stop=stop,
filter_name=FILTER)
data_coll.to_csv(OUT_DIR_RESULTS)
save_name_fig = data_coll.save_name_aerocom + '_SCAT.png'
data_coll.plot_scatter(savefig=True,
save_dir=OUT_DIR_SCAT,
save_name=save_name_fig)
# =============================================================================
# for year in YEARS:
#
# for var in VARS:
# if not var in model_reader.vars:
# continue
#
#
#
# for obs_id, ungridded_obs in ungridded_obs_all.items():
# if not var in ungridded_obs.contains_vars:
# continue
# if year == 9999:
# msg =('Ignoring climatology data (model: {}, '
# 'obs: {}). '
# 'Not yet implemented'.format(model_id,
# obs_id))
# print(msg)
# with open(OUT_STATS, 'a') as f:
# f.write('\n{}\n\n'.format(msg))
#
# continue
# print('Analysing variable: {}\n'
# 'Model {} vs. obs {}\n'
# 'Year: {} ({} resolution)\n'
# .format(var, model_id, obs_id,
# year, ts_type))
#
# model = model_reader.data_yearly[var][year]
#
# start_str = str(year)
# stop_str = '{}-12-31 23:59:00'.format(year)
#
# data = pya.collocation.collocate_gridded_ungridded_2D(
# model, ungridded_obs, ts_type=ts_type,
# start=start_str, stop=stop_str,
# filter_name=filter_name)
#
# data.to_csv(OUT_DIR_RESULTS)
#
# stats = data.calc_statistics()
# append_result(OUT_STATS, stats,
# model_id, obs_id, var, year, ts_type)
#
# add_note=False
# if np.isnan(stats['R']):
# if sum(data.data.values[1].flatten()) != 0:
# raise Exception('Check...')
# add_note = True
#
# save_name_fig = data.save_name_aerocom + '_SCAT.png'
# data.plot_scatter(savefig=True,
# save_dir=OUT_DIR_SCAT,
# save_name=save_name_fig)
#
# plt.close('all')
#
#
#
#
#
#
# =============================================================================
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for intercomparison of optical properties between models and
"""
import os
import numpy as np
from functools import reduce
import pyaerocom as pya
import matplotlib.pyplot as plt
from models import all_model_ids
TS_TYPES_SETUP = {'monthly' : ['monthly', 'yearly'],
'daily' : ['monthly', 'yearly', 'daily']}
# all temporal resolutions that are supposed to be read
TS_TYPES_READ = list(TS_TYPES_SETUP.keys())
# alternative ts_types in case one of the provided in setup is not in dataset
TS_TYPES_READ_ALT = {'daily' : ['hourly', '3hourly']}
# Years to be analysed
YEARS = sorted([2008, 2010])
ALL_MODELS = all_model_ids()
MODEL_ID = ALL_MODELS[0]
OBS_ID = 'MODIS6.terra'
VARS = ['od550aer']
FILTER = 'WORLD-noMOUNTAINS'
### output directories
OUT_DIR = './output/'
OUT_DIR_SCAT = os.path.join(OUT_DIR, 'scatter_plots')
OUT_DIR_RESULTS = os.path.join(OUT_DIR, 'collocated_data')
_PLOTNAME_BASESTR = 'mALLYEAR{}'
TS_TYPES = pya.const.GRID_IO.TS_TYPES
def start_stop_from_year(year):
start = pya.helpers.to_pandas_timestamp(year)
stop = pya.helpers.to_pandas_timestamp('{}-12-31 23:59:59'.format(year))
return (start, stop)
if __name__=="__main__":
exceptions = []
pya.change_verbosity('warning')
model_reader = pya.io.ReadGridded(MODEL_ID)
obs_reader = pya.io.ReadGridded(OBS_ID)
var_matches = list(reduce(np.intersect1d, (VARS,
model_reader.vars,
obs_reader.vars)))
if len(var_matches) == 0:
raise pya.exceptions.DataCoverageError('No variable matches between '
'{} and {} for input vars: {}'
.format(MODEL_ID, OBS_ID,
VARS))
year_matches = list(reduce(np.intersect1d, (YEARS,
model_reader.years,
obs_reader.years)))
if len(year_matches) == 0:
raise pya.exceptions.DataCoverageError('No year matches between '
'{} and {} for input vars: {}'
.format(MODEL_ID, OBS_ID,
VARS))
ts_type_matches = list(np.intersect1d(TS_TYPES_READ, model_reader.ts_types))
for ts_type, ts_types_alt in TS_TYPES_READ_ALT.items():
if not ts_type in ts_type_matches:
for ts_type_alt in ts_types_alt:
if ts_type_alt in model_reader.ts_types:
ts_type_matches.append(ts_type_alt)
TS_TYPES_SETUP[ts_type_alt] = TS_TYPES_SETUP[ts_type]
break
if len(ts_type_matches) == 0:
raise pya.exceptions.DataCoverageError('No ts_type matches between '
'{} and {} for input vars: {}'
.format(MODEL_ID, OBS_ID,
VARS))
for year in year_matches:
start, stop = start_stop_from_year(year)
for ts_type in ts_type_matches:
ts_types_ana = TS_TYPES_SETUP[ts_type]
model_reader.read(var_matches, start_time=year,
ts_type = ts_type,
flex_ts_type=False)
obs_reader.read(var_matches, start_time=year,
ts_type = ts_type,
flex_ts_type=True)
plotname = _PLOTNAME_BASESTR.format(ts_type)
if len(model_reader.data) == 0:
exceptions.append('{}_{}: No data available'.format(year, ts_type))
else:
for var, model_data in model_reader.data.items():
for ts_type_ana in ts_types_ana:
if TS_TYPES.index(ts_type_ana) >= TS_TYPES.index(ts_type):
if var in obs_reader.data:
obs_data = obs_reader.data[var]
data_coll = pya.collocation.collocate_gridded_gridded(
model_data, obs_data,
ts_type=ts_type_ana,
start=start, stop=stop,
filter_name=FILTER)
data_coll.to_netcdf(OUT_DIR_RESULTS)
save_name_fig = data_coll.save_name_aerocom + '_SCAT.png'
data_coll.plot_scatter(savefig=True,
save_dir=OUT_DIR_SCAT,
save_name=save_name_fig)
plt.close('all')
# =============================================================================
# for year in YEARS:
#
# for var in VARS:
# if not var in model_reader.vars:
# continue
#
#
#
# for obs_id, ungridded_obs in ungridded_obs_all.items():
# if not var in ungridded_obs.contains_vars:
# continue
# if year == 9999:
# msg =('Ignoring climatology data (model: {}, '
# 'obs: {}). '
# 'Not yet implemented'.format(model_id,
# obs_id))
# print(msg)
# with open(OUT_STATS, 'a') as f:
# f.write('\n{}\n\n'.format(msg))
#
# continue
# print('Analysing variable: {}\n'
# 'Model {} vs. obs {}\n'
# 'Year: {} ({} resolution)\n'
# .format(var, model_id, obs_id,
# year, ts_type))
#
# model = model_reader.data_yearly[var][year]
#
# start_str = str(year)
# stop_str = '{}-12-31 23:59:00'.format(year)
#
# data = pya.collocation.collocate_gridded_ungridded_2D(
# model, ungridded_obs, ts_type=ts_type,
# start=start_str, stop=stop_str,
# filter_name=filter_name)
#
# data.to_csv(OUT_DIR_RESULTS)
#
# stats = data.calc_statistics()
# append_result(OUT_STATS, stats,
# model_id, obs_id, var, year, ts_type)
#
# add_note=False
# if np.isnan(stats['R']):
# if sum(data.data.values[1].flatten()) != 0:
# raise Exception('Check...')
# add_note = True
#
# save_name_fig = data.save_name_aerocom + '_SCAT.png'
# data.plot_scatter(savefig=True,
# save_dir=OUT_DIR_SCAT,
# save_name=save_name_fig)
#
# plt.close('all')
#
#
#
#
#
#
# =============================================================================
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 14:48:03 2018
@author: jonasg
"""
import pyaerocom as pya
from warnings import filterwarnings
import iris
import xarray
if __name__=='__main__':
filterwarnings('ignore')
### AEROCOM 2
d1 = '/lustre/storeA/project/aerocom/aerocom-users-database/AEROCOM-PHASE-II/OsloCTM2.A2.CTRL/renamed/'
f11 = 'aerocom.OsloCTM2.A2.CTRL.monthly.abs5503Daer.2006.nc'
f12 = 'aerocom.OsloCTM2.A2.CTRL.daily.od550oa.2006.nc'
d11 = iris.load(d1 + f11)
d12 = iris.load(d1 + f12)
### AEROCOM 3
d2 = '/lustre/storeA/project/aerocom/aerocom-users-database/AEROCOM-PHASE-III/TM5_AP3-INSITU/renamed/'
f21 = 'aerocom3_TM5_AP3-INSITU_vmrch4_ModelLevel_2010_monthly.nc'
f22 = 'aerocom3_TM5_AP3-INSITU_ec870dryaer_Surface_2010_hourly.nc'
f23 = 'aerocom3_TM5_AP3-INSITU_loadbc_Column_2010_monthly.nc'
d21 = iris.load(d2 + f21)
d22 = iris.load(d2 + f22)
d23 = iris.load(d2 + f23)
data = [d11, d12, d21, d22, d23]
#reader = pya.io.ReadGridded('TM5_AP3-INSITU')
#dat = reader.read_var('vmrch4')
for i, cubes in enumerate(data):
print('At iter {}'.format(i))
for d in cubes:
print('\n')
print(d.var_name)
print(d.shape)
print(d.ndim)
print([c.standard_name for c in d.dim_coords])
print([c.var_name for c in d.dim_coords])
print('\n\n')
print(d11)
ds11 = xarray.open_dataset(d1 + f11)
ds21 = xarray.open_dataset(d2 + f21)
data11 = pya.GriddedData(d1+f11, var_name='abs5503Daer')
data21 = pya.GriddedData(d2+f21, var_name='vmrch4')
print(ds21)<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 7 08:19:06 2018
@author: jonasg
"""
import os
import numpy as np
import pyaerocom as pya
from functools import reduce
import pandas as pd
import matplotlib.pyplot as plt
class AnalysisSetup(pya._lowlevel_helpers.BrowseDict):
"""Setup class for model / obs intercomparison
An instance of this setup class can be used to run a collocation analysis
between a model and an observation network and will create a number of
:class:`pya.CollocatedData` instances and save them as netCDF file.
Note
----
This is a very first draft and may change
Attributes
----------
vars_to_analyse : list
variables to be analysed (should be available in model and obs data)
"""
def __init__(self, vars_to_analyse=None, model_id=None, obs_id=None,
years=None, filter_name='WORLD-noMOUNTAINS',
ts_type_setup=None, out_basedir=None, **kwargs):
self.vars_to_analyse = vars_to_analyse
self.model_id = model_id
self.obs_id = obs_id
self.filter_name = filter_name
if not isinstance(ts_type_setup, _TS_TYPESetup):
ts_type_setup = _TS_TYPESetup(**ts_type_setup)
self.ts_type_setup = ts_type_setup
self.years = years
self.out_basedir = out_basedir
self.update(**kwargs)
def get_all_vars(OBS_INFO_DICT):
all_vars = []
for obs_id, variables in OBS_INFO_DICT.items():
for variable in list(variables):
if not variable in all_vars:
all_vars.append(variable)
return all_vars
class _TS_TYPESetup(pya._lowlevel_helpers.BrowseDict):
def __init__(self, *args, **kwargs):
self.read_alt = {}
super(_TS_TYPESetup, self).__init__(*args, **kwargs)
def __str__(self):
s ='ts_type settings (<read>: <analyse>)\n'
for key, val in self.items():
if key == 'read_alt':
continue
s+=' {}:{}\n'.format(key, val)
if self['read_alt']:
s+=' Alternative ts_types (read)\n'
for key, val in self['read_alt'].items():
s+=' {}:{}\n'.format(key, val)
def check_prepare_dirs(basedir, model_id):
def chk_make_dir(base, name):
d = os.path.join(base, name)
if not os.path.exists(d):
os.mkdir(d)
return d
dirs = {}
if not os.path.exists(basedir):
basedir = pya.const.OUT_BASEDIR
out_dir = chk_make_dir(basedir, model_id)
dirs['data'] = chk_make_dir(out_dir, 'data')
dirs['scatter_plots'] = chk_make_dir(out_dir, 'scatter_plots')
return dirs
def prepare_ts_types(model_reader, ts_type_setup):
ts_type_read = list(ts_type_setup.keys())
ts_type_matches = list(np.intersect1d(ts_type_read, model_reader.ts_types))
if 'read_alt' in ts_type_setup:
ts_type_read_alt = ts_type_setup.read_alt
for ts_type, ts_types_alt in ts_type_read_alt.items():
if not ts_type in ts_type_matches:
for ts_type_alt in ts_types_alt:
if ts_type_alt in model_reader.ts_types:
ts_type_matches.append(ts_type_alt)
ts_type_setup[ts_type_alt] = ts_type_setup[ts_type]
break
return (ts_type_matches, ts_type_setup)
def start_stop_from_year(year):
start = pya.helpers.to_pandas_timestamp(year)
stop = pya.helpers.to_pandas_timestamp('{}-12-31 23:59:59'.format(year))
return (start, stop)
def colldata_save_name(model_data, model_id, obs_id, ts_type_ana, filter_name,
start=None, stop=None):
if start is None:
start = model_data.start_time
else:
start = pya.helpers.to_pandas_timestamp(start)
if stop is None:
stop = model_data.stop_time
else:
stop = pya.helpers.to_pandas_timestamp(stop)
start_str = pya.helpers.to_datestring_YYYYMMDD(start)
stop_str = pya.helpers.to_datestring_YYYYMMDD(stop)
ts_type_src = model_data.ts_type
coll_data_name = pya.CollocatedData._aerocom_savename(model_data.var_name,
obs_id,
model_id,
ts_type_src,
start_str,
stop_str,
ts_type_ana,
filter_name)
return coll_data_name + '.nc'
def check_colldata_exists(data_dir, colldata_save_name):
files = os.listdir(data_dir)
if colldata_save_name in files:
return True
return False
def get_file_list(result_dir, models, verbose=True):
all_files = []
for item in os.listdir(result_dir):
if item in models:
data_dir = os.path.join(result_dir, item, 'data/')
files = os.listdir(data_dir)
if len(files) > 0:
if verbose:
print('Importing {} result files from model {}'
.format(len(files), item))
for f in files:
if f.endswith('COLL.nc'):
all_files.append(os.path.join(data_dir, f))
return all_files
def load_result_files(file_list, verbose=True):
results = []
data = pya.CollocatedData()
try:
from ipywidgets import FloatProgress
from IPython.display import display
max_count = len(file_list)
f = FloatProgress(min=0, max=max_count) # instantiate the bar
display(f) # display the bar
except Exception as e:
print('Failed to instantiate progress bar: {}'.format(repr(e)))
for file in file_list:
info = data.get_meta_from_filename(file)
info['model_id'] = info['data_source'][1]
info['obs_id'] = info['data_source'][0]
info['year'] = info['start'].year
info['data'] = data.read_netcdf(file).to_dataframe()
obs = info['data']['ref'].values
model = info['data']['data'].values
stats = pya.mathutils.calc_statistics(model, obs)
info.update(stats)
results.append(info)
if f is not None:
f.value += 1
return results
def results_to_dataframe(results):
"""Based on output of :func:`get_result_info`"""
header = ['Model', 'Year', 'Variable', 'Obs', 'Freq', 'FreqSRC',
'Bias', 'RMS', 'R', 'FGE']
data = []
for info in results:
file_data = [info['model_id'],
info['year'],
info['var_name'],
info['obs_id'],
info['ts_type'],
info['ts_type_src'],
info['nmb'],
info['rms'],
info['R'],
info['fge']]
data.append(file_data)
df = pd.DataFrame(data, columns=header)
df.set_index(['Model', 'Year', 'Variable', 'Obs'], inplace=True)
df.sort_index(inplace=True)
return df
def slice_dataframe(df, values, levels):
"""Crop a selection from a MultiIndex Dataframe
Parameters
----------
df : DataFrame
"""
names = df.index.names
num_indices = len(names)
if num_indices == 1:
# no Multiindex
return df.loc[values, :]
else:
# Multiindex
if levels is None:
print("Input levels not defined for MultiIndex, assuming 0")
levels = [0]
elif isinstance(levels, str): #not a list
levels, values = [levels], [values]
else: #not a string and not None, so either a list or a number (can be checked using iter())
try:
iter(levels)
except:
#input is single level / value pair
levels, values = [levels], [values]
if isinstance(levels[0], str):
level_nums = [names.index(x) for x in levels]
else:
level_nums = levels
indexer = []
for idx in range(len(names)):
if idx in level_nums:
pos = level_nums.index(idx)
indexer.append(values[pos])
else:
indexer.append(slice(None))
df = df.loc[tuple(indexer), :]
for i, level in enumerate(levels):
if len(values[i]) == 1:
df.index = df.index.droplevel(level)
df.sort_index(inplace=True)
return df
def perform_analysis(vars_to_analyse, model_id, obs_id, years, filter_name,
ts_type_setup, out_basedir=None, logfile=None,
reanalyse_existing=False):
plt.ioff()
try:
pya.io.ReadUngridded(obs_id)
_run_gridded_ungridded(vars_to_analyse, model_id, obs_id, years, filter_name,
ts_type_setup, out_basedir, logfile,
reanalyse_existing)
except pya.exceptions.NetworkNotSupported:
_run_gridded_gridded(vars_to_analyse, model_id, obs_id, years,
filter_name, ts_type_setup, out_basedir, logfile,
reanalyse_existing)
plt.ion()
def _run_gridded_ungridded(vars_to_analyse, model_id, obs_id, years, filter_name,
ts_type_setup, out_basedir=None, logfile=None,
reanalyse_existing=False):
# all temporal resolutions that are supposed to be read
dirs = check_prepare_dirs(out_basedir, model_id)
obs_reader = pya.io.ReadUngridded()
obs_data = obs_reader.read(obs_id, vars_to_analyse)
ts_types = pya.const.GRID_IO.TS_TYPES
model_reader = pya.io.ReadGridded(model_id)
var_matches = list(reduce(np.intersect1d, (vars_to_analyse,
model_reader.vars_provided,
obs_data.contains_vars)))
if len(var_matches) == 0:
raise pya.exceptions.DataCoverageError('No variable matches between '
'{} and {} for input vars: {}'
.format(model_id, obs_id,
vars_to_analyse))
year_matches = list(np.intersect1d(years, model_reader.years))
if len(year_matches) == 0:
raise pya.exceptions.DataCoverageError('No year matches between '
'{} and {} for input vars: {}'
.format(model_id, obs_id,
vars_to_analyse))
ts_type_matches, ts_type_setup = prepare_ts_types(model_reader,
ts_type_setup)
if len(ts_type_matches) == 0:
raise pya.exceptions.DataCoverageError('No ts_type matches between '
'{} and {} for input vars: {}'
.format(model_id, obs_id,
vars_to_analyse))
for year in year_matches:
start, stop = start_stop_from_year(year)
for ts_type in ts_type_matches:
ts_types_ana = ts_type_setup[ts_type]
model_reader.read(var_matches,
start_time=year,
ts_type=ts_type,
flex_ts_type=False)
if len(model_reader.data) == 0:
if logfile:
logfile.write('No model data available ({}, {})\n'.format(year,
ts_type))
continue
for var, model_data in model_reader.data.items():
if not var in obs_reader.data:
if logfile:
logfile.write('No obs data available ({}, {})\n'.format(year,
ts_type))
continue
for ts_type_ana in ts_types_ana:
if ts_types.index(ts_type_ana) >= ts_types.index(ts_type):
out_dir = dirs['data']
savename = colldata_save_name(model_data,
model_id,
obs_id,
ts_type_ana,
filter_name,
start,
stop)
file_exists = check_colldata_exists(out_dir,
savename)
if file_exists:
if not reanalyse_existing:
if logfile:
logfile.write('SKIP: {}\n'.format(savename))
continue
else:
os.remove(os.path.join(out_dir, savename))
data_coll = pya.collocation.collocate_gridded_ungridded_2D(
model_data, obs_data,
ts_type=ts_type_ana,
start=start, stop=stop,
filter_name=filter_name)
data_coll.to_netcdf(out_dir)
save_name_fig = data_coll.save_name_aerocom + '_SCAT.png'
if logfile:
logfile.write('WRITE: {}\n'.format(savename))
data_coll.plot_scatter(savefig=True,
save_dir=dirs['scatter_plots'],
save_name=save_name_fig)
plt.close('all')
def _run_gridded_gridded(vars_to_analyse, model_id, obs_id, years, filter_name,
ts_type_setup, out_basedir=None, logfile=None,
reanalyse_existing=False):
# all temporal resolutions that are supposed to be read
dirs = check_prepare_dirs(out_basedir, model_id)
ts_types = pya.const.GRID_IO.TS_TYPES
model_reader = pya.io.ReadGridded(model_id)
obs_reader = pya.io.ReadGridded(obs_id)
var_matches = list(reduce(np.intersect1d, (vars_to_analyse,
model_reader.vars_provided,
obs_reader.vars)))
if len(var_matches) == 0:
raise pya.exceptions.DataCoverageError('No variable matches between '
'{} and {} for input vars: {}'
.format(model_id, obs_id,
vars_to_analyse))
year_matches = list(reduce(np.intersect1d, (years,
model_reader.years,
obs_reader.years)))
if len(year_matches) == 0:
raise pya.exceptions.DataCoverageError('No year matches between '
'{} and {} for input vars: {}'
.format(model_id, obs_id,
vars_to_analyse))
ts_type_matches, ts_type_setup = prepare_ts_types(model_reader,
ts_type_setup)
if len(ts_type_matches) == 0:
raise pya.exceptions.DataCoverageError('No ts_type matches between '
'{} and {} for input vars: {}'
.format(model_id, obs_id,
vars_to_analyse))
for year in year_matches:
start, stop = start_stop_from_year(year)
for ts_type in ts_type_matches:
ts_types_ana = ts_type_setup[ts_type]
# reads only year if starttime is provided but not stop time
model_reader.read(var_matches,
start_time=year,
ts_type=ts_type,
flex_ts_type=False)
obs_reader.read(var_matches, start_time=year,
ts_type = ts_type,
flex_ts_type=True)
if len(model_reader.data) == 0:
if logfile:
logfile.write('No model data available ({}, {})\n'.format(year,
ts_type))
continue
for var, model_data in model_reader.data.items():
if not var in obs_reader.data:
if logfile:
logfile.write('No obs data available ({}, {})\n'.format(year,
ts_type))
continue
for ts_type_ana in ts_types_ana:
if ts_types.index(ts_type_ana) >= ts_types.index(ts_type):
obs_data = obs_reader.data[var]
out_dir = dirs['data']
savename = colldata_save_name(model_data,
model_id,
obs_id,
ts_type_ana,
filter_name,
start,
stop)
file_exists = check_colldata_exists(out_dir,
savename)
if file_exists:
if not reanalyse_existing:
if logfile:
logfile.write('SKIP: {}\n'.format(savename))
continue
else:
os.remove(os.path.join(out_dir, savename))
data_coll = pya.collocation.collocate_gridded_gridded(
model_data, obs_data,
ts_type=ts_type_ana,
start=start, stop=stop,
filter_name=filter_name)
if data_coll.save_name_aerocom + '.nc' != savename:
raise Exception
data_coll.to_netcdf(out_dir)
save_name_fig = data_coll.save_name_aerocom + '_SCAT.png'
if logfile:
logfile.write('WRITE: {}\n'.format(savename))
data_coll.plot_scatter(savefig=True,
save_dir=dirs['scatter_plots'],
save_name=save_name_fig)
plt.close('all')
def print_file(file_path):
if not os.path.exists(file_path):
raise IOError('File not found...')
with open(file_path) as f:
for line in f:
if line.strip():
print(line)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 14:48:03 2018
@author: jonasg
"""
import pyaerocom as pya
MODEL = 'ECHAM6-HAM2_AP3-CTRL2016-PD'
OBS = 'AeronetSunV3Lev2.daily'
VAR = 'od550aer'
START=2010
if __name__=='__main__':
pya.change_verbosity('critical')
reader = pya.io.ReadGridded(MODEL)
obsr = pya.io.ReadUngridded(OBS)
model = reader.read_var(VAR, start_time=START)
obs = obsr.read(vars_to_retrieve=VAR)
for i, f in enumerate(reader.files):
data = pya.io.iris_io.load_cube_custom(f, grid_io=pya.const.GRID_IO)
print(i)
print(data.coord('longitude').points.min())
print(data.coord('longitude').points.max())
coll = pya.collocation.collocate_gridded_ungridded_2D(model,
obs,
ts_type='monthly')
ax = coll.plot_scatter()
|
9b313b1a4d36bdc3883479f58f7f38d681b009b0
|
[
"Markdown",
"Python"
] | 16
|
Python
|
jgliss/aerocom_obs_props
|
8c2824b2cdf558a74edc0f180a653e86faf9a442
|
6fd0de913bff3da97c32977ed341d7061e461658
|
refs/heads/master
|
<file_sep>var button = document.getElementById('buttoni');
var input = document.getElementById('input');
var msg = document.getElementById('answer');
button.addEventListener("click",callback);
function callback(){
msg.innerHTML = ""
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState === 4 && request.status < 400){
var userInput = JSON.parse(request.responseText)
var enter = userInput.Search
console.log("enter: ", enter);
for (var i = 0; i < enter.length; i++) {
var title = enter[i].Title
var poster = enter[i].Poster
if(poster === "N/A"){
var add = document.createElement("h3");
add.className = "movie_poster"
add.innerHTML = title+"<img class= movie_poster src="+"./mockups/images/no_image.png"+">"
msg.appendChild(add)
}else{
var add = document.createElement("h3");
add.className = "movie_poster"
add.innerHTML = title+"<img class= movie_poster src="+poster+">"
msg.appendChild(add)
}
}
}
}
request.open("GET","http://www.omdbapi.com/?s="+input.value)
request.send()
}
|
bca39e1def282db271dbbb4366a0ec5ad8affa78
|
[
"JavaScript"
] | 1
|
JavaScript
|
vanrick/api_traversal
|
276bbc8eac27a2e7aa835a15aae8310e96c6019b
|
511b919ad0951edf40d9e2e9cbad2a6e45696b16
|
refs/heads/master
|
<repo_name>DangerCloud/template-cli-master<file_sep>/index.js
#!/usr/bin/env node
import inquirer from 'inquirer';
import * as fs from 'fs';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import createDirectoryContents from './createDirectoryContents.js';
const CURR_DIR = process.cwd();
const __dirname = dirname(fileURLToPath(import.meta.url));
const CHOICES = fs.readdirSync(`${__dirname}/templates`);
const QUESTIONS = [
{
name: 'project-choice',
type: 'list',
message: 'What project template would you like to generate?',
choices: CHOICES,
},
{
name: 'project-name',
type: 'input',
message: 'Project name:',
validate: function (input) {
if (/^([A-Za-z\-\\_\d])+$/.test(input)) return true;
else return 'Project name may only include letters, numbers, underscores and hashes.';
},
},
];
inquirer.prompt(QUESTIONS).then(answers => {
const projectChoice = answers['project-choice'];
const projectName = answers['project-name'];
const templatePath = `${__dirname}/templates/${projectChoice}`;
fs.mkdirSync(`${CURR_DIR}/${projectName}`);
createDirectoryContents(templatePath, projectName);
});
|
717d75451909cc828edc99d4d702b079a0620b96
|
[
"JavaScript"
] | 1
|
JavaScript
|
DangerCloud/template-cli-master
|
583cbb5b9e250fc755cf29a361631b1c5ad08ae0
|
de9c9335d627a095e1d79df3e6cef666e0644c30
|
refs/heads/master
|
<file_sep>import React, {Component} from "react";
import PropTypes from "prop-types";
import { withStyles } from "material-ui/styles";
import styles from "./LeftNavMenuStyles";
import List from "material-ui/List";
import Divider from "material-ui/Divider";
import mixin from "../../common/mixinCore";
import StoreLoaderMixin from "../../common/StoreLoaderMixin";
import initStore from "../../stores/initStore";
import {menuConfig} from "../../common/leftMenuConfig";
import { ListItem, ListItemIcon, ListItemText } from "material-ui/List";
import * as materialUiIcons from "material-ui-icons";
import {NavLink} from "react-router-dom";
function renderNavLink(pageKey, i){
let mConfig = menuConfig[pageKey];
return <NavLink
key={i}
to={mConfig.url}>
<ListItem button>
<ListItemIcon>
{
React.createElement(materialUiIcons[mConfig.icon])
}
</ListItemIcon>
<ListItemText primary={mConfig.label} />
</ListItem>
</NavLink>;
}
class LeftNavMenu extends Component {
constructor(props, context) {
super(props, context);
this.store = initStore;
}
render(){
const {classes} = this.props;
return (
<div>
{
this.state.userActionPages.length > 0 ?
<div>
<Divider />
<List className={classes.list}> {
this.state.userActionPages.map(renderNavLink)
}
</List>
</div> : ""
}
{
this.state.userManagePages.length > 0 ?
<div>
<Divider />
<List className={classes.list}> {
this.state.userManagePages.map(renderNavLink)
}
</List>
</div> : ""
}
</div>
);
}
}
LeftNavMenu.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
mixin(LeftNavMenu, [StoreLoaderMixin]);
export default withStyles(styles)(LeftNavMenu);
<file_sep>import React from "react";
import { ListItem, ListItemIcon, ListItemText } from "material-ui/List";
import CreateIcon from "material-ui-icons/AddCircle";
import ViewModuleIcon from "material-ui-icons/ViewModule";
import VerifiedUserIcon from "material-ui-icons/VerifiedUser";
import {NavLink} from "react-router-dom";
export const mailFolderListItems = (
<div>
<NavLink
to="/createTicket">
<ListItem button>
<ListItemIcon>
<CreateIcon />
</ListItemIcon>
<ListItemText primary="Create Ticket" />
</ListItem>
</NavLink>
<NavLink
to="/viewTickets">
<ListItem button>
<ListItemIcon>
<ViewModuleIcon />
</ListItemIcon>
<ListItemText primary="View Tickets" />
</ListItem>
</NavLink>
</div>
);
export const otherMailFolderListItems = (
<div>
<NavLink
to="/manageUsers">
<ListItem button>
<ListItemIcon>
<VerifiedUserIcon />
</ListItemIcon>
<ListItemText primary="Manage Users" />
</ListItem>
</NavLink>
</div>
);
<file_sep>const styles = theme => ({
root: {
marginTop: theme.spacing.unit * 3,
width: "100%",
},
column1: {
flexBasis: "80%",
},
column2: {
flexBasis: "20%",
},
heading: {
fontSize: theme.typography.pxToRem(15),
fontWeight: theme.typography.fontWeightRegular,
},
secondaryHeading: {
fontSize: theme.typography.pxToRem(15),
color: theme.palette.text.secondary,
},
expansionPane: {
flexDirection: "column"
}
});
export default styles;
<file_sep>import React, {Component} from "react";
import PropTypes from "prop-types";
import { withStyles } from "material-ui/styles";
import styles from "./CreateTicketStyles";
import {TextField, Paper, Button} from "material-ui";
import {MenuItem} from "material-ui/Menu";
import mixin from "../../common/mixinCore";
import StoreLoaderMixin from "../../common/StoreLoaderMixin";
import initStore from "../../stores/initStore";
import {dispatcher} from "visd-redux-adapter";
import Actions from "../../common/Actions.js";
import {MAX_PRIORITY} from "../../common/enum";
import {Validation, fieldValidatorCore} from "react-validation-framework";
import validator from "validator";
class CreateTicket extends Component {
constructor(props, context){
super(props, context);
this.store = initStore;
this.handleCreateTickectButtonClick = this.handleCreateTickectButtonClick.bind(this);
}
handleCreateTickectButtonClick(){
if (fieldValidatorCore.checkGroup("createTicket").isValid === true){
dispatcher.publish(Actions.CREATE_NEW_TICKET);
} else {
dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, "Please correct marked errors");
}
}
render(){
const {classes} = this.props;
let {createTicketFormData} = this.state;
if (this.state.stateSetFromDb === true) {
return <div>
<h1>Create Ticket</h1>
<Paper className={classes.paperRoot} elevation={10}>
<div className={classes.positionRelative}>
{
Object.keys(createTicketFormData).map((k, j)=>{
let v = createTicketFormData[k];
if (v.type === "select"){
return <TextField
select
fullWidth={true}
label={v.label}
className={classes.textField}
value={v.value ? v.value : (k === "assignTo" ? this.state.allUsers[0] : 1)}
onChange={e => dispatcher.publish(Actions.CREATE_TICKET_FORM_MODIFY, k, e.target.value)}
SelectProps={{
MenuProps: {
className: classes.menu,
},
}}
margin="normal">
{
k === "assignTo" ?
this.state.allUsers.map((v1, i)=>{
return <MenuItem key={i} value={v1}>{v1}</MenuItem>;
}) : [...Array(MAX_PRIORITY).fill("")].map((v1, i)=>{
return <MenuItem key={i} value={i+1}>{i+1}</MenuItem>;
})
}
</TextField>;
} else {
return <Validation
key={j}
group={"createTicket"}
onChangeCallback="onChange"
validators={[
{
validator: (val) => !(!val || v.isRequired && validator.isEmpty(val)),
errorPropValue: true,
errorMessage: "Please enter a value"
},
{
validator: (val) => {
if (v.testRegex) {
if (typeof v.testRegex.regex === "function") {
return v.testRegex.regex(val);
} else {
return new RegExp(v.testRegex.regex).test(val);
}
} else {
return true;
}
},
errorPropValue: true,
errorMessage: v.testRegex ? v.testRegex.errorMessage : ""
}]}>
<TextField
type={v.type === "date" ? "date" : null}
value={v.value}
className={classes.textField}
helperText={v.label}
fullWidth={true}
onChange={(e, t, value) => dispatcher.publish(Actions.CREATE_TICKET_FORM_MODIFY, k, value)}
margin="normal">
</TextField>
</Validation>;
}
})
}
<Button
raised
dense
className={classes.Loginbutton}
onClick={this.handleCreateTickectButtonClick}>
Create New Ticket
</Button>
</div>
</Paper>
</div>;
} else {
return <div></div>;
}
}
}
CreateTicket.propTypes = {
classes: PropTypes.object.isRequired
};
mixin(CreateTicket, [StoreLoaderMixin]);
export default withStyles(styles)(CreateTicket);
<file_sep>export const DB_DATE_FORMAT = "YYYY-MM-DD";
export const MAX_PRIORITY = 5;
export const DATA_BASE_ROOT = "db";
export const AVAILABLE_STATUS = {
OPEN: "Open",
CLOSE: "Close",
MOREINFO: "More Info",
READYFORTESTING: "Ready For Testing",
DONE: "Done"
};
export const ROLES = {
ADMIN: "admin",
SUPPORT_ENGINEER: "se",
PRODUCT_ENGINEER: "pe"
};
<file_sep>const styles = theme => ({
positionRelative: {
position: "relative"
},
textField: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit,
},
paperRoot: theme.mixins.gutters({
paddingTop: 16,
paddingBottom: 16,
margin: "0 auto 50px",
marginTop: theme.spacing.unit * 3,
width: "90%"
}),
Loginbutton: {
margin: theme.spacing.unit,
},
formControl: {
margin: theme.spacing.unit,
minWidth: 120,
},
});
export default styles;
<file_sep>import React, {Component} from "react";
class ErrorBoundry extends Component {
constructor(props, context){
super(props, context);
this.state = {
error: null,
info: null,
hasError: false
};
}
componentDidCatch(error, info){
this.setState(state => ({...state, error, errorInfo: info, hasError: true}));
}
componentWillReceiveProps(){
this.setState(state=>({...state, hasError: false}));
}
render(){
if (this.state.hasError) {
return <div>Something went wrong here! {`${this.state.error}`}</div>;
} else {
return this.props.children;
}
}
}
export default ErrorBoundry;
<file_sep>import {createStore, dispatcher} from "visd-redux-adapter";
import Actions from "../common/Actions.js";
import {menuConfig} from "../common/leftMenuConfig";
import moment from "moment";
import {DB_DATE_FORMAT, DATA_BASE_ROOT, AVAILABLE_STATUS, ROLES} from "../common/enum";
const DEFAULT_ROLE = ROLES.SUPPORT_ENGINEER;
console.log("menuconfig", menuConfig);
const USER_ACTION_PAGES = Object.values(menuConfig).filter(v=>v.area === "actions").map(v=>v.key);
const USER_MANAGE_PAGES = Object.values(menuConfig).filter(v=>v.area === "manage").map(v=>v.key);
const firebaseAuth = firebase.auth();
const firebaseDatabase = firebase.database();
const ERROR_MESSAGE_TIMEOUT = 4000;
function processStateFromDb(state, db) {
state.tickets = db.tickets;
state.roles = db.roles;
state.userRoles = Object.entries(db.roles).filter(([, value]) => value.includes(state.userInfo.email)).map((r)=>r[0]);
state.settings = db.settings;
state.userActionPages = state.userRoles.reduce((pageSettings, role)=>{
pageSettings.merge(state.settings[role]);
return pageSettings;
}, []).filter((pageKey)=>{
return USER_ACTION_PAGES.includes(pageKey);
});
state.userManagePages = state.userRoles.reduce((pageSettings, role)=>{
pageSettings.merge(state.settings[role]);
return pageSettings;
}, []).filter((pageKey)=>{
return USER_MANAGE_PAGES.includes(pageKey);
});
state.allUsers = Object.values(db.roles).reduce((uniqueUsers, v)=>{
uniqueUsers.merge(v);
return uniqueUsers;
}, []);
state.stateSetFromDb = true;
setTimeout(()=>dispatcher.publish(Actions.ROUTE_CHANGED, window.location.href));
}
function getTicketId(allTickets) {
let largestNum = 0;
Object.keys(allTickets).forEach((k)=>{
if (!isNaN(Number(k.substring(2)))){
largestNum = Number(k.substring(2)) > largestNum ? Number(k.substring(2)) : largestNum;
}
});
return `AR${largestNum+1}`;
}
function clearFormData(obj) {
Object.keys(obj).forEach((k)=>{
obj[k].value = "";
});
}
var InitStore = createStore({
INIT(state) {
state.loggedIn = null;
state.userInfo = null;
state.userRoles = [];
state.userActionPages = [];
state.userManagePages = [];
state.createTicketFormData = {
title: {
label: "Title",
type: "text",
value: null,
isRequired: true
},
description: {
label: "Description",
type: "text",
value: null,
isRequired: true
},
assignTo: {
label: "Assign To",
type: "select",
value: null,
isRequired: true
},
dueDate: {
label: "Due Date",
type: "date",
value: null,
isRequired: false
},
priority: {
label: "Priority",
type: "select",
value: null,
isRequired: true
}
};
state.errorConfig = {
error: false,
errorMessage: ""
};
state.allUsers = [];
state.stateSetFromDb = false;
},
LOGIN_APP_LOAD(state){
console.log(state);
state.stateSetFromDb = false;
firebaseAuth.onAuthStateChanged(user => {
if (user){
dispatcher.publish(Actions.LOGIN_USER_LOGGES_IN, user);
} else {
dispatcher.publish(Actions.LOGIN_USER_LOGGES_OUT);
}
});
firebaseDatabase.ref().child(DATA_BASE_ROOT).on("value", (cdb)=>{
setTimeout(()=>dispatcher.publish(Actions.DB_VALUE_UPDATE, cdb.val()));
});
},
DB_VALUE_UPDATE(state, db){
processStateFromDb(state, db);
},
LOGIN_USER_LOGGES_IN(state, user){
state.loggedIn = true;
state.userInfo = user;
firebaseDatabase.ref(DATA_BASE_ROOT).once("value").then((cdb)=>{
dispatcher.publish(Actions.DB_VALUE_UPDATE, cdb.val());
});
},
SETUP_USER(state, user, rolesData, allTickets){
state.userRoles = Object.entries(rolesData).filter(([, value]) => value.includes(user.email)).map((r)=>r[0]);
state.allTickets = allTickets;
state.loggedIn = true;
state.userInfo = user;
},
LOGIN_USER_LOGGES_OUT(state){
state.loggedIn = false;
state.userInfo = null;
},
LOGIN_SUBMIT(state, email, password){
firebaseAuth.signInWithEmailAndPassword(email, password).then((user)=>{
dispatcher.publish(Actions.LOGIN_USER_LOGGES_IN, user);
}).catch((e)=>dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, e.message));
},
CREATE_TICKET_FORM_MODIFY(state, field, value){
state.createTicketFormData[field].value = value;
},
CREATE_NEW_TICKET(state){
let allTickets = state.tickets;
allTickets[getTicketId(allTickets)] = {
title: state.createTicketFormData.title.value,
description: state.createTicketFormData.description.value,
assignTo: state.createTicketFormData.assignTo.value,
dueDate: state.createTicketFormData.dueDate.value,
priority: state.createTicketFormData.priority.value,
status: AVAILABLE_STATUS.OPEN,
creator: state.userInfo.email,
creationdt: moment().format(DB_DATE_FORMAT),
};
firebaseDatabase.ref().child(DATA_BASE_ROOT).child("tickets").set(allTickets).then(()=>{
clearFormData(state.createTicketFormData);
dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, "New Ticket Created!");
}).catch((e)=>{
dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, e.message);
});
},
SHOW_EDIT_TICKET_POPUP(state, ticketId){
if (ticketId) {
state.editingTicketData = {
id: ticketId,
...state.tickets[ticketId]
};
state.showEditTicketsPopup = true;
}
},
EDIT_TICKET_FORM_MODIFY(state, field, value){
state.editingTicketData[field] = value;
},
EDIT_TICKET_FORM_SUBMIT(state){
let ticketId = state.editingTicketData.id;
delete state.editingTicketData.id;
firebaseDatabase.ref().child(DATA_BASE_ROOT).child("tickets").child(ticketId).set(state.editingTicketData).then(()=>{
dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, "Changes Saved");
dispatcher.publish(Actions.HIDE_EDIT_TICKET_POPUP);
});
},
HIDE_EDIT_TICKET_POPUP(state){
state.editingTicketData = {};
state.showEditTicketsPopup = false;
},
SHOW_SNACK_MESSAGE(state, errorMessage = "An error occured", actualError){
console.log(actualError);
state.errorConfig = {
error: true,
errorMessage: errorMessage
};
setTimeout(function () {
dispatcher.publish(Actions.HIDE_SNACK_MESSAGE);
}, ERROR_MESSAGE_TIMEOUT);
},
HIDE_SNACK_MESSAGE(state){
state.errorConfig = {
error: false,
errorMessage: ""
};
},
ADD_NEW_USER(state, email, password, role){
firebaseAuth.createUserWithEmailAndPassword(email, password).then(()=>{
let allUserForRole = state.roles[role];
allUserForRole.push(email);
firebaseDatabase.ref().child(DATA_BASE_ROOT).child("roles").child(role).set(allUserForRole).then(()=>{
dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, "User Creation Successful");
}).catch((e)=>dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, e.message));
}).catch((e)=>dispatcher.publish(Actions.SHOW_SNACK_MESSAGE, e.message));
},
ROUTE_CHANGED(state, route){
let userManageRoles = JSON.parse(JSON.stringify(state.userManagePages));
let userActionRoles = JSON.parse(JSON.stringify(state.userActionPages));
let routeAllowed = userManageRoles.merge(userActionRoles).filter((pageid)=>{
return route.indexOf(pageid) !== -1;
}).length > 0;
if (routeAllowed === false){
//todo to0 much bad
if (route !== "http://localhost:8010/"){
window.location.href = "http://localhost:8010/";
}
}
}
});
export default InitStore;
<file_sep>import React, {Component} from "react";
import PropTypes from "prop-types";
import { withStyles } from "material-ui/styles";
import styles from "./MainAppStyles";
import classNames from "classnames";
import Drawer from "material-ui/Drawer";
import AppBar from "material-ui/AppBar";
import Toolbar from "material-ui/Toolbar";
import IconButton from "material-ui/IconButton";
import MenuIcon from "material-ui-icons/Menu";
import ChevronLeftIcon from "material-ui-icons/ChevronLeft";
import ChevronRightIcon from "material-ui-icons/ChevronRight";
import AccountCircle from "material-ui-icons/AccountCircle";
import Menu, { MenuItem } from "material-ui/Menu";
import SearchBox from "../SearchBox/SearchBox";
import {Router} from "react-router-dom";
import createBrowserHistory from "history/createBrowserHistory";
import ContentArea from "../ContentArea/ContentArea";
import LeftNavMenu from "../LeftNavMenu/LeftNavMenu";
import {dispatcher} from "visd-redux-adapter";
import Actions from "../../common/Actions.js";
const history = createBrowserHistory();
history.listen( location => {
dispatcher.publish(Actions.ROUTE_CHANGED, location.pathname);
});
class MainApp extends Component {
constructor(props, context){
super(props, context);
this.state = {
open: true,
anchorEl: null
};
this.handleDrawerOpen = this.handleDrawerOpen.bind(this);
this.handleDrawerClose = this.handleDrawerClose.bind(this);
this.handleMenu = this.handleMenu.bind(this);
this.handleShowUserProfile = this.handleShowUserProfile.bind(this);
this.handleRequestClose = this.handleRequestClose.bind(this);
this.handleSignout = this.handleSignout.bind(this);
}
handleMenu(event) {
this.setState({ anchorEl: event.currentTarget });
}
handleRequestClose() {
this.setState({ anchorEl: null });
}
handleDrawerOpen(){
this.setState({ open: true });
}
handleDrawerClose(){
this.setState({ open: true });
}
handleShowUserProfile(){
console.log("todo");
}
handleSignout(){
firebase.auth().signOut();
}
render() {
const { classes, theme } = this.props;
const { anchorEl } = this.state;
const open = Boolean(anchorEl);
return (
<div className={classes.root}>
<div className={classes.appFrame}>
<AppBar className={classNames(classes.appBar, this.state.open && classes.appBarShift)}>
<Toolbar disableGutters={!this.state.open}>
<IconButton
color="contrast"
aria-label="open drawer"
onClick={this.handleDrawerOpen}
className={classNames(classes.menuButton, this.state.open && classes.hide)}
>
<MenuIcon />
</IconButton>
<div className={classes.flex}>
<SearchBox />
</div>
<div>
<IconButton
aria-owns={open ? "menu-appbar" : null}
aria-haspopup="true"
onClick={this.handleMenu}
color="contrast"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={open}
onRequestClose={this.handleRequestClose}
>
<MenuItem onClick={this.handleShowUserProfile}>Profile</MenuItem>
<MenuItem onClick={this.handleSignout}>Sign Out</MenuItem>
</Menu>
</div>
</Toolbar>
</AppBar>
<Router history={history}>
<div>
<Drawer
type="permanent"
classes={{
paper: classNames(classes.drawerPaper, !this.state.open && classes.drawerPaperClose),
}}
open={this.state.open}
>
<div className={classes.drawerInner}>
<div className={classes.drawerHeader}>
<IconButton onClick={this.handleDrawerClose}>
{theme.direction === "rtl" ? <ChevronRightIcon /> : <ChevronLeftIcon />}
</IconButton>
</div>
<LeftNavMenu />
</div>
</Drawer>
<main className={classes.content}>
<ContentArea />
</main>
</div>
</Router>
</div>
</div>
);
}
}
MainApp.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
export default withStyles(styles, { withTheme: true })(MainApp);
<file_sep>var ExtractTextPlugin = require("extract-text-webpack-plugin");
var LiveReloadPlugin = require("webpack-livereload-plugin");
var CopyWebpackPlugin = require("copy-webpack-plugin");
var webpack = require("webpack");
var appExtractTextPlugin = new ExtractTextPlugin({
filename: "app.css",
disable: false,
allChunks: true
});
//new UglifyJsPlugin({ sourceMap: false })
var baseConfig = {
entry: {
bundle: ["./src/index"]
},
output: {
filename: "[name].js"
},
devServer: {
headers: { "Access-Control-Allow-Origin": "*" },
disableHostCheck: true
},
plugins: [
appExtractTextPlugin,
new webpack.LoaderOptionsPlugin({
options: {
"if-loader": process.env.NODE_ENV === "production" ? "production" : "dev",
debug: process.env.NODE_ENV !== "production"
}
}),
new CopyWebpackPlugin([
{from: "./index.html"}])
],
module: {
rules: [
{
test: /.jsx?$/,
exclude: /node_modules/,
use: [{
loader: "babel-loader",
options: {
presets: [
["flow"],
["es2015", { loose: true, modules: false }],
["react"],
["stage-0"]
],
plugins: [
["transform-object-rest-spread", "transform-class-properties"]
]
}
}, {
loader: "if-loader"
}]
},
{
test: /\.css$/,
include: [/node_modules/],
use: appExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.(woff|woff2|ttf|eot|svg|ico|gif|png)(\?v=[a-z0-9]\.[a-z0-9]\.[a-z0-9])?$/,
use: "url-loader?limit=100000"
}
]
}
};
if (process.env.NODE_ENV === "production") {
baseConfig.cache = false;
// baseConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
// compress: false,
// sourceMap: false
// }));
} else {
baseConfig.plugins.push(new LiveReloadPlugin({
port: 36010
}));
baseConfig.cache = true;
baseConfig.devtool = "inline-source-map";
}
module.exports = baseConfig;
<file_sep>export const uipallete = {
50: "#e6f7fd",
100: "#c2ecf9",
200: "#99dff5",
300: "#70d2f1",
400: "#51c8ee",
500: "#32beeb",
600: "#2db8e9",
700: "#26afe5",
800: "#1fa7e2",
900: "#1399dd",
A100: "#ffffff",
A200: "#d9f1ff",
A400: "#a6dfff",
A700: "#8cd5ff",
contrastDefaultColor: "dark",
};
export const uipalleteSecondary = {
50: "#eff4f7",
100: "#d7e3ec",
200: "#bdd1df",
300: "#a2bed2",
400: "#8eb0c8",
500: "#7aa2be",
600: "#729ab8",
700: "#6790af",
800: "#5d86a7",
900: "#4a7599",
A100: "#f6fbff",
A200: "#c3e3ff",
A400: "#90cbff",
A700: "#76bfff",
contrastDefaultColor: "dark",
};
<file_sep>import React, {Component} from "react";
import PropTypes from "prop-types";
import { withStyles } from "material-ui/styles";
import styles from "./ViewTicketsStyles";
import ExpansionPanel, {
ExpansionPanelSummary,
ExpansionPanelDetails,
} from "material-ui/ExpansionPanel";
import Typography from "material-ui/Typography";
import ExpandMoreIcon from "material-ui-icons/ExpandMore";
import mixin from "../../common/mixinCore";
import StoreLoaderMixin from "../../common/StoreLoaderMixin";
import initStore from "../../stores/initStore";
import {dispatcher} from "visd-redux-adapter";
import Actions from "../../common/Actions.js";
import {Button} from "material-ui";
import ViewTicketsFieldsRenderer from "./ViewTicketsFieldsRenderer";
import Dialog, {
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
} from "material-ui/Dialog";
import Slide from "material-ui/transitions/Slide";
import ErrorBoundry from "../ErrorBoundry/ErrorBoundry";
function Transition(props) {
let p = Object.assign({}, props, {timeout: 300});
return <Slide direction="up" {...p} />;
}
class ViewTickets extends Component {
constructor(props, context){
super(props, context);
this.store = initStore;
}
render(){
const { classes } = this.props;
return (
<div className={classes.root}>
<h1>View Tickets</h1>
{
this.state.tickets && Object.entries(this.state.tickets).map(([key, value], i)=>{
return <ErrorBoundry key={i}><ExpansionPanel>
<ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
<div className={classes.column1}>
<Typography className={classes.heading}>{key}</Typography>
</div>
<div className={classes.column2}>
<div className={classes.secondaryHeading}>
<Button
raised
dense
className={classes.Loginbutton}
onClick={()=>dispatcher.publish(Actions.SHOW_EDIT_TICKET_POPUP, key)}>
Edit
</Button>
</div>
</div>
</ExpansionPanelSummary>
<ExpansionPanelDetails className={classes.expansionPane}>
<ViewTicketsFieldsRenderer disabledAll={true} allUsers={this.state.allUsers} data={value}/>
</ExpansionPanelDetails>
</ExpansionPanel></ErrorBoundry>;
})
}
{
this.state.showEditTicketsPopup ?
<Dialog
open={this.state.showEditTicketsPopup}
transition={Transition}
keepMounted>
<DialogTitle>{`Edit ${this.state.editingTicketData.id}`}</DialogTitle>
<DialogContent>
<DialogContentText>
<ViewTicketsFieldsRenderer disabledAll={false} allUsers={this.state.allUsers} data={this.state.editingTicketData}/>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={()=>dispatcher.publish(Actions.HIDE_EDIT_TICKET_POPUP)} color="secondary">
Back
</Button>
<Button onClick={()=>dispatcher.publish(Actions.EDIT_TICKET_FORM_SUBMIT)} color="primary">
Save
</Button>
</DialogActions>
</Dialog> : ""
}
</div>
);
}
}
ViewTickets.propTypes = {
classes: PropTypes.object.isRequired,
};
mixin(ViewTickets, [StoreLoaderMixin]);
export default withStyles(styles)(ViewTickets);
<file_sep>import React, {Component} from "react";
import PropTypes from "prop-types";
import { withStyles } from "material-ui/styles";
import styles from "./DashboardStyles";
class Dashboard extends Component {
constructor(props, context){
super(props, context);
}
render(){
return <div>The Dashboard</div>;
}
}
Dashboard.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(Dashboard);
<file_sep>import React from "react";
import PropTypes from "prop-types";
import {withStyles} from "material-ui/styles";
import styles from "./SearchBoxStyles";
import TextField from "material-ui/TextField";
import Search from "material-ui-icons/Search";
import IconButton from "material-ui/IconButton";
const SearchBox = (props) => {
const {classes} = props;
return (
<div>
<IconButton
color="contrast"
>
<Search className={classes.svgIcon}/>
</IconButton>
<TextField
label="Search Ticket"
type="search"
className={classes.textField}
margin="normal"
/>
</div>
);
};
SearchBox.propTypes = {
classes: PropTypes.object
};
export default withStyles(styles)(SearchBox);
<file_sep>let mixin = function (comp, toMix) {
let allPropertyNames = toMix.map((v) => {
return Object.getOwnPropertyNames(v.prototype);
});
let m = allPropertyNames.reduce(function (a, b) {
return a.concat(b);
}, []).filter(function (item, pos, arr) {
return arr.indexOf(item) === pos && item !== "constructor";
});
m.forEach((method) => {
var old = comp.prototype[method];
comp.prototype[method] = function () {
toMix.forEach((v) => {
if (typeof v.prototype[method] === "function") {
v.prototype[method].apply(this, arguments);
}
});
if (typeof old === "function") {
old.apply(this, arguments);
}
};
});
};
module.exports = mixin;
<file_sep>const headEle = document.getElementsByTagName("head")[0];
const addToHead = function (path, type) {
debugger;
let url;
if (path.includes("http://") || path.includes("https://")) {
url = path;
} else {
url = `${window.STATIC_SERVER_URL}/${path}`;
}
if (type === "link"){
let link = document.createElement("link");
link.setAttribute("type", "text/css");
link.setAttribute("href", url);
link.setAttribute("rel", "stylesheet");
headEle.appendChild(link);
} else if (type === "script") {
let script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", url);
headEle.appendChild(script);
}
};
const loadVersionJSON = function (callback) {
debugger;
window.fetch(`${window.STATIC_SERVER_URL}/version.json?hash=${Date.now()}`)
.then((data)=>data.json())
.then(callback);
};
loadVersionJSON(function ({gitVersion}) {
debugger;
addToHead(`bundle.js?hash=${gitVersion}`, "script");
});
addToHead("http://localhost:36010/livereload.js", "script");
<file_sep>import React, {Component} from "react";
import styles from "./HeaderStyles";
import PropTypes from "prop-types";
import {withStyles} from "material-ui/styles";
import AppBar from "material-ui/AppBar";
import Toolbar from "material-ui/Toolbar";
import IconButton from "material-ui/IconButton";
import MenuIcon from "material-ui-icons/Menu";
import AccountCircle from "material-ui-icons/AccountCircle";
import Menu, {MenuItem} from "material-ui/Menu";
import SearchBox from "../SearchBox/SearchBox";
class Header extends Component {
constructor(props, context) {
super(props, context);
this.state = {
anchorEl: null
};
this.handleMenu = this.handleMenu.bind(this);
this.handleRequestClose = this.handleRequestClose.bind(this);
}
handleMenu(event){
this.setState({ anchorEl: event.currentTarget });
}
handleRequestClose(){
this.setState({ anchorEl: null });
}
render() {
const {anchorEl} = this.state;
const {classes, handleChangeRequestNavDrawer} = this.props;
return (
<div>
<AppBar position="static">
<Toolbar>
<IconButton onClick={handleChangeRequestNavDrawer} className={classes.menuButton} color="contrast" aria-label="Menu">
<MenuIcon />
</IconButton>
<SearchBox />
<div>
<IconButton
aria-owns={open ? "menu-appbar" : null}
aria-haspopup="true"
onClick={this.handleMenu}
color="contrast"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={open}
onRequestClose={this.handleRequestClose}
>
<MenuItem onClick={this.handleRequestClose}>Profile</MenuItem>
<MenuItem onClick={this.handleRequestClose}>My account</MenuItem>
</Menu>
</div>
</Toolbar>
</AppBar>
</div>
);
}
}
Header.propTypes = {
classes: PropTypes.object,
children: PropTypes.element,
width: PropTypes.number,
handleChangeRequestNavDrawer: PropTypes.func
};
export default withStyles(styles)(Header);
<file_sep>- npm i
- npm start
- open http://localhost:8010
Used -
- React, material-ui (next/beta), firebase, JSS, webpack, eslint, react-validation-framework, visd-redux-adapter (Redux),
Wish List -
- Flow, eslint/flow git hooks, testing
|
2a80a8b1564afb5f177ab316005113b13ddd7187
|
[
"JavaScript",
"Markdown"
] | 18
|
JavaScript
|
vishalvisd/visd-artoo-web
|
0ba5522528f52047ab220854580bfc3b47f47bf7
|
d5e78b8947f60c549d5d399a0815c27523e279ab
|
refs/heads/master
|
<repo_name>TylerYao0407/MyBatis_One_To_Many<file_sep>/src/main/java/com/tyler/mapper/SonMapper.java
package com.tyler.mapper;
import com.tyler.pojo.Son;
import java.util.List;
/**
* Created by tyler on 2016/12/12.
*/
public interface SonMapper {
public Son selectSon(int id);
public int addSon(List<Son> sons);
public int deleteSon(int id);
public int updateSon(Son son);
}
<file_sep>/src/main/java/com/tyler/pojo/Son.java
package com.tyler.pojo;
/**
* Created by tyler on 2016/12/12.
*/
public class Son {
private int sid;
private int fid;
private String sname;
public Son(){}
public Son(int fid, String sname) {
this.fid = fid;
this.sname = sname;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public int getFid() {
return fid;
}
public void setFid(int fid) {
this.fid = fid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}
<file_sep>/src/main/java/com/tyler/pojo/Father.java
package com.tyler.pojo;
import java.util.List;
/**
* Created by tyler on 2016/12/12.
*/
public class Father {
private int fid;
private String fname;
private List<Son> sons;
public Father(){}
public Father(String fname){
this.fname = fname;
}
public Father(String fname, List<Son> sons) {
this.fname = fname;
this.sons = sons;
}
public int getFid() {
return fid;
}
public void setFid(int fid) {
this.fid = fid;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public List<Son> getSons() {
return sons;
}
public void setSons(List<Son> sons) {
this.sons = sons;
}
}
|
9a0c41d3226fec911513018c0d7a28177b99a938
|
[
"Java"
] | 3
|
Java
|
TylerYao0407/MyBatis_One_To_Many
|
687e74b665b5a8ce2600ce3c6e97103a21be2ad7
|
5518d40385f8a821e45fba17d11d50cfed846c82
|
refs/heads/master
|
<file_sep>Plugin Scaffold
===============
Create a basic Wordpress plugin from the command line.
Usage:
```
$ cd /wordpress/wp-content/plugins
$ python /path/to/plugin.py "Plugin Name" [options]
```
# options: #
- `--force` Override existing plugin
- `admin_css` Enqueue css globally in admin
- `admin_js` Enqueue js globally in admin
- `frontend_css` Enqueue css in frontend
- `frontend_js` Enqueue js in frontend
- `settings_css` Enqueue css on settings page (only if settings is present)
- `settings_js` Enqueue js on settings page (only if settings is present)
- `admin` Create an admin class
- `admin_page` Add Admin page
- `settings` | `settings_section` Create Settings section
- `settings_page` Create Settings page
- `shortcodes:a_shortcode[:another_shortcode[:..]]` Add shortcode handler(s)
- `post_type:"Post Type name"` Register post type.
- `post_type_with_caps:"Post Type name"` Will register a post type having its own capability type.
- `widget` Register a Widget
# Make plugin.py available from everywhere #
```
$ mkdir ~/.scripts
$ cd ~/.scripts
$ git clone <EMAIL>:mcguffin/wp-plugin-scaffold.git
$ ln -s ./wp-plugin-scaffold/plugin.py ./wp-plugin
```
Finally add `~/.scripts/` to the PATH variable in your `~/.bash_profile`
Todo:
- add Autoload
- add admin page
<file_sep>#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import sys, os, pystache, re, pwd, pprint, shutil,codecs,subprocess
from datetime import date
from pprint import pprint
class wp_plugin:
defaults = {
'plugin_name' : '',
'plugin_slug' : '',
'wp_plugin_slug' : '',
'plugin_class_name' : '',
'plugin_author' : '',
'plugin_author_uri' : '',
'frontend_css' : False,
'frontend_js' : False,
'admin_css' : False,
'admin_js' : False,
'admin_page' : False,
'admin_page_css' : False,
'admin_page_js' : False,
'admin_page_hook' : False,
'settings_css' : False,
'settings_js' : False,
'admin' : False,
'settings' : False,
'settings_section' : False,
'settings_page' : False,
'backend' : False,
'shortcodes':False,
'widget':False,
'post_type':False,
'post_type_slug':False,
'post_type_with_caps':False,
'post_type_with_caps_slug':False,
'github_user':False,
'git':False
}
_private_defaults = {
'settings_assets' : False,
'admin_assets' : False,
'admin_pages' : False,
'shell_command' : False
}
allowed_admin_pages = [
'dashboard',
'posts',
'media',
'links',
'pages',
'comments',
'theme',
'plugins',
'users',
'management'
]
def __init__(self,config):
self.config = self.process_config(config)
self.plugin_dir = os.getcwd()+'/'+slugify(self.config['plugin_name'],'-')
pass
def process_config(self,config):
# set names
config['plugin_slug'] = plugin_slug(config['plugin_name'])
config['wp_plugin_slug'] = slugify(config['plugin_name'],'-')
config['plugin_class_name'] = plugin_classname(config['plugin_name'])
author = pwd.getpwuid( os.getuid() ).pw_gecos
try:
github_user = subprocess.check_output(["git","config","user.name"]).strip()
print "github user is",github_user
except:
github_user = ''
pass
config['github_user'] = github_user.decode('utf-8')#.encode('utf-8')
config['plugin_author'] = author.decode('utf-8')#.encode('utf-8')
config['plugin_author_uri'] = ''
config['this_year'] = date.today().year
# default is settings section
if config['settings'] and not config['settings_page'] and not config['settings_section']:
config['settings_section'] = True
config['settings'] = config['settings_page'] or config['settings_section']
config['settings_section'] = not config['settings_page']
config['settings_assets'] = config['settings_css'] or config['settings_js']
config['admin_assets'] = config['admin_css'] or config['admin_js']
config['admin_page'] = config['admin_page'] or config['admin_page_css'] or config['admin_page_js']
if isinstance(config['admin_page'],list) :
admin_pages = config['admin_page']
if 'all' in admin_pages:
config['admin_pages'] = self.allowed_admin_pages
else:
# replace tools alias
admin_pages = [x if (x != 'tools') else 'management' for x in admin_pages]
# unique list, containing only alloewd items
config['admin_pages'] = []
[config['admin_pages'].append(x) for x in admin_pages if x in self.allowed_admin_pages and x not in config['admin_pages'] ]
config['admin_page'] = True
config['admin_page_hook'] = config['admin_page'] or config['admin_pages']
config['admin'] = config['admin'] or config['admin_page']
config['backend'] = config['settings'] or config['admin']
if config['shortcodes'] and config['shortcodes'] == True:
config['shortcodes'] == False
print 'Could not generate shortcode.'
print 'shortcode usage is: shortcode:my_shortcode'
if config['post_type'] and config['post_type'] == True:
config['post_type'] == False
print 'Could not generate post_type.'
print 'post_type usage is: post_type:"Post Type Name"'
if config['post_type_with_caps'] and config['post_type_with_caps'] == True:
config['post_type_with_caps'] == False
print 'Could not generate post_type_with_caps.'
print 'post_type_with_caps usage is: post_type_with_caps:"Post Type Name"'
if config['frontend_js'] or config['frontend_css']:
config['frontend_assets'] = true
if config['post_type']:
config['post_type'] = map(lambda post_type: {'post_type_slug':slugify(post_type),'post_type_name':post_type}, config['post_type'])
if config['post_type_with_caps']:
config['post_type_with_caps'] = map(lambda post_type: {'post_type_slug':slugify(post_type),'post_type_name':post_type,'capabilities':True}, config['post_type_with_caps'])
config['has_post_type_caps'] = True
if config['post_type']:
config['post_type'] = config['post_type'] + config['post_type_with_caps']
else :
config['post_type'] = config['post_type_with_caps']
config['has_post_types'] = bool(config['post_type'])
return config
def make(self):
# make plugin dir
try:
os.mkdir(self.plugin_dir)
except OSError as e:
return e
templates = ['index.php','readme.txt'] # ,'languages/__wp_plugin_slug__.pot'
if self.config['frontend_css']:
templates.append('css/__slug__.css')
if self.config['frontend_js']:
templates.append('js/__slug__.js')
if self.config['settings_css']:
templates.append('css/__slug__-settings.css')
if self.config['settings_js']:
templates.append('js/__slug__-settings.js')
if self.config['admin_css']:
templates.append('css/__slug__-admin.css')
if self.config['admin_js']:
templates.append('js/__slug__-admin.js')
if self.config['admin_page_css']:
templates.append('css/__slug__-admin-page.css')
if self.config['admin_page_js']:
templates.append('js/__slug__-admin-page.js')
if self.config['admin']:
templates.append('include/class-__class__Admin.php')
if self.config['widget']:
templates.append('include/class-__class___Widget.php')
if self.config['settings']:
templates.append('include/class-__class__Settings.php')
if self.config['git']:
templates.append('README.md')
templates.append('.gitignore')
self.process_templates(templates);
if self.config['git'] and self.config['github_user']:
if self.config['github_user']:
repo_name = '<EMAIL>:%s/%s.git' % ( self.config['github_user'] , self.config['wp_plugin_slug'] )
print "Creating git repository %s" % repo_name
else:
print "Creating git repository"
print self.plugin_dir
os.chdir(self.plugin_dir);
subprocess.call(["git","init"])
subprocess.call(["git","add" , '.'])
subprocess.call(["git","commit" , '-m "Initial commit"'])
if self.config['github_user']:
subprocess.call(['git','remote' , 'add' , 'origin' , repo_name ])
print 'Git repository created. Now go to github.com and create a repository named `%s`' % ( self.config['wp_plugin_slug'] )
print 'Finally come back and type `git push -u origin master` here.'
return ''
def process_templates(self,templates):
for template in templates:
content = pystache.render( self._read_template(template),self.config)
self._write_plugin_file(template,content)
def _read_template(self,template):
template_path = os.path.dirname(os.path.realpath(__file__))+'/templates/'+template
return self._read_file_contents( template_path )
def _write_plugin_file( self , template , contents ):
template_filename = template.replace('__slug__',self.config['plugin_slug']).replace('__class__',self.config['plugin_class_name']).replace('__wp_plugin_slug__',self.config['wp_plugin_slug']);
plugin_path = self.plugin_dir + '/'+template_filename
return self._write_file_contents( plugin_path , contents )
def _read_file_contents( self , file_path ):
if not os.path.exists(file_path):
return ''
f = codecs.open(file_path,'rb',encoding='utf-8')
contents = f.read()
f.close()
return contents
def _write_file_contents( self , file_path , contents ):
dir = os.path.dirname(file_path)
if not os.path.exists(dir):
os.makedirs(dir)
f = codecs.open(file_path,'wb',encoding='utf-8')
f.write(contents)
f.close()
def rm_wp(str):
return re.sub(r'(?i)^(WP|WordPress\s?)','',str).strip()
def slugify(plugin_name,separator='_'):
return re.sub(r'\s',separator,plugin_name.strip()).lower()
def plugin_slug(plugin_name):
return slugify(rm_wp(plugin_name))
def plugin_classname(plugin_name):
return ''.join(x for x in rm_wp(plugin_name).title() if not x.isspace())
usage = '''
usage ./plugin.py 'Plugin Name' options
options can be any of:
--force Override existing plugin
admin_css Enqueue css globally in admin
admin_js Enqueue js globally in admin
frontend_css Enqueue css in frontend
frontend_js Enqueue js in frontend
settings_css Enqueue css on settings page (only if settings is present)
settings_js Enqueue js on settings page (only if settings is present)
admin Create an admin class
admin_page Add an admin page (will create admin also)
admin_page:a_page[:a_page]
Add submenu page to admin. a_page can be any of
Page can be any of
dashboard
posts
media
links
pages
comments
theme
plugins
users
management
tools (Alias of management)
admin_page_js Add js to admin page (adds admin_page also)
admin_page_css Add css to admin page (adds admin_page also)
settings | settings_section
Create Settings section
settings_page
Create Settings page
shortcodes:a_shortcode[:another_shortcode[:..]]
Add shortcode handler(s)
post_type:'Post Type name'
register post type
post_type_with_caps:'Post Type name'
register post type having its own capabilities
widget Register a Widget
git Inits a git repository
'''
defaults = config = wp_plugin.defaults
try:
config['plugin_name'] = sys.argv[1]
except IndexError as e:
print usage
sys.exit(0)
config['shell_args'] = "\"%s\" %s" % ( sys.argv[1] , ' '.join(sys.argv[2:]) )
for arg in sys.argv[2:]:
conf = arg.split(':')
param = True
if len(conf) > 1:
param = conf[1:]
conf = conf[0]
elif len(conf) == 1:
conf = conf[0]
if conf in defaults.keys():
config[conf] = param
if "all" in sys.argv[2:]:
for arg in config.keys():
if config[arg] == False:
config[arg] = True
print "Generating Plugin:", config['plugin_name']
maker = wp_plugin(config)
if '--force' in sys.argv and os.path.exists(maker.plugin_dir):
shutil.rmtree( maker.plugin_dir )
result = maker.make()
if isinstance(result, Exception):
print 'Plugin exists:',result
print 'use --force to override existing plugin'
|
cd6cd8235156a8818daf2d2d2ea9a166a3654010
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
MantisWare/wp-plugin-scaffold
|
486de5e7c24376cbfea0f10a09fd9edeb3a59d53
|
fdab962402ff7a6cd309219abf8fda07451ceae4
|
refs/heads/master
|
<repo_name>RFA-ENR/MyProShop<file_sep>/backend/routes/productRoute.js
import express from "express";
import { getProductById, getProducts } from "../controllers/productControllers.js";
const router = express.Router();
// @desc Fetch all products
// @route Get/api/product
// @access public
router.route("/").get(getProducts);
// @desc Fetch single product
// @route Get/api/product/:id
// @access Public
router.route("/:id").get(getProductById);
export default router;
|
b29332ed3b7a40a205a6cdb93408ddb543a9aee3
|
[
"JavaScript"
] | 1
|
JavaScript
|
RFA-ENR/MyProShop
|
60cc324dced5114216c090d895be3edba2e53118
|
843664da38df658bb849bfc0585ed8b166138bc4
|
refs/heads/main
|
<repo_name>SauravL3010/GameDev<file_sep>/temp.py
import pygame
from pygame.locals import *
pygame.init()
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Breakout')
#define colours
bg = (234, 218, 184)
#block colours
block_red = (242, 85, 96)
block_green = (86, 174, 87)
block_blue = (69, 177, 232)
#define game variables
cols = 6
rows = 6
#brick will class
class wall():
def __init__(self):
self.width = screen_width // cols
self.height = 50
def create_wall(self):
# list containing all blocks in rows
self.blocks = []
block_individual = [] # individual block
for row in range(rows):
#initialize row
block_row = []
for col in range(cols):
# x and y coordinates
block_x = col * self.width
block_y = row * self.height
rect = pygame.Rect(block_x, block_y, self.width, self.height)
#block strenght
if row < 2:
strength = 3
elif row < 4:
strength = 2
elif row < 6:
strength = 1
block_individual = [rect, strength]
block_row.append(block_individual)
self.blocks.append(block_row)
def draw_wall(self):
for row in self.blocks:
for block in row:
if block[1] == 1:
block_col = block_red
elif block[1] == 2:
block_col = block_green
elif block[1] == 3:
block_col = block_blue
pygame.draw.rect(screen, block_col, block[0])
pygame.draw.rect(screen, bg, block[0], 2)
wall = wall()
wall.create_wall()
run = True
while run:
screen.fill(bg)
wall.draw_wall()
for event in pygame.event.get():
if event.type == 256: # 256 = pygame.QUIT
run = False
pygame.display.update()
pygame.quit()
|
95a9de5d8bdce7ba9e2027e18cf3f5ec144cfc2f
|
[
"Python"
] | 1
|
Python
|
SauravL3010/GameDev
|
b98ff4f46a71c2a6692d24fc783f2026e6feeb8e
|
eca6be0b2d634f6cd4795ff9e67bf8c3d66e7508
|
refs/heads/master
|
<repo_name>crpineda1/ruby-enumerables-hash-practice-emoticon-translator-lab-nyc-web-102819<file_sep>/lib/translator.rb
# require modules here
require 'yaml'
require 'pry'
def load_library(file_path)
# code goes here
doc = YAML.load_file(file_path)
#binding.pry
doc
hash = {"get_meaning" => {},"get_emoticon" => {}}
doc.each do |key, value|
hash["get_meaning"][value[1]] = key
hash["get_emoticon"][value[0]] = doc[key][1]
end
hash
end
def get_japanese_emoticon(file_path, english_emoticon)
# code goes here
x = load_library(file_path)
hash = x["get_emoticon"][english_emoticon]
if hash == nil
return "Sorry, that emoticon was not found"
end
hash
end
def get_english_meaning(file_path, japanese_emoticon)
# code goes here
x = load_library(file_path)
hash = x["get_meaning"][japanese_emoticon]
if hash == nil
return "Sorry, that emoticon was not found"
end
hash
end
|
00fe1d63f02d7fcfc5e0c1934bbf17333ba9ac1e
|
[
"Ruby"
] | 1
|
Ruby
|
crpineda1/ruby-enumerables-hash-practice-emoticon-translator-lab-nyc-web-102819
|
84b5b04c7e9419f008dd997d38b4162104ab1f0d
|
2f2a34b906a2e42bda06253abd7411873a26ec84
|
refs/heads/master
|
<repo_name>cod-e-ash/hisaab-front<file_sep>/src/app/components/reports/tax/tax.component.ts
import { InfoService } from './../../../services/info.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-tax',
templateUrl: './tax.component.html',
styleUrls: ['./tax.component.css']
})
export class TaxComponent implements OnInit {
fyear: number;
fmonth: number;
tyear: number;
tmonth: number;
fromDate: Date;
toDate: Date;
curYear = new Date().getFullYear();
curMonth = new Date().getMonth()+1;
taxReport: any;
totalTax = 0;
constructor(private router: Router, private route: ActivatedRoute, private infoService: InfoService) { }
ngOnInit() {
this.fyear = +this.route.snapshot.queryParamMap.get('fyear');
this.fmonth = +this.route.snapshot.queryParamMap.get('fmonth');
this.tyear = +this.route.snapshot.queryParamMap.get('tyear');
this.tmonth = +this.route.snapshot.queryParamMap.get('tmonth');
if ((!this.fyear || !this.fmonth || !this.tyear || !this.tmonth) ||
(this.fyear+this.fmonth/100 > this.tyear+this.tmonth/100) ||
((this.tyear-this.fyear)*12 + (this.tmonth - this.fmonth) > 11) ||
(this.tyear > this.curYear || (this.tyear === this.curYear && this.tmonth > this.curMonth))
) {
this.router.navigate(['/reports']);
}
this.fromDate = new Date(this.fyear.toString()+'-'+this.fmonth.toString()+'-'+'01');
this.toDate = new Date(this.tyear.toString()+'-'+this.tmonth.toString()+'-'+'01');
this.infoService.getTaxReport(this.fyear, this.fmonth, this.tyear, this.tmonth)
.subscribe( data => {
this.taxReport = data;
this.taxReport.forEach(taxdata => {
this.totalTax += taxdata.taxamount;
});
});
}
}
<file_sep>/src/app/models/company.model.ts
export interface Company {
_id?: string;
name?: string;
phone?: string;
email?: string;
address?: string;
city?: string;
state?: string;
country?: string;
zipcode?: string;
gstn?: string;
pan?: string;
currency?: string;
}
<file_sep>/src/app/services/customer.service.ts
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Customer } from './../models/customer.model';
import { tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class CustomerService {
private customers: Customer[];
private url = environment.apiUrl + '/customers';
// HTTP Options
private httpOptions = {
headers: new HttpHeaders({
'x-auth-token':
'xxxy<PASSWORD>'
})
};
// Constructor
constructor(private http: HttpClient) {}
// HTTP GET
getData(inParams: { page?: number; name?: string }, type: string) {
const params = new HttpParams()
.set('page', (inParams && inParams.page ? inParams.page : 1).toString())
.set('name', inParams && inParams.name ? inParams.name : '')
.set('type', type ? type : 'Customer');
return this.http
.get<{
error: string;
totalRecs: number;
totalPages: number;
curPage: number;
customers: Customer[];
}>(this.url, { params: params })
.pipe(
tap(data => {
this.customers = data.customers;
})
);
}
createData(data: Customer) {
return this.http.post<Customer>(this.url, data, this.httpOptions);
}
patchData(id: string, status: boolean) {
const data = { _id: id, status: status };
return this.http.patch(this.url + '/' + id, data, this.httpOptions);
}
updateData(data: Customer) {
return this.http.put(this.url + '/' + data._id, data, this.httpOptions);
}
deleteData(id: string) {
return this.http.delete<{ error?: string; customer?: Customer }>(
this.url + '/' + id,
this.httpOptions
);
}
getSingle(id: string) {
if (this.customers) {
return this.customers.filter(customer => {
return customer._id === id;
})[0];
}
}
}
<file_sep>/src/app/components/customers/customers.component.ts
import { Customer } from '../../models/customer.model';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CustomerService } from '../../services/customer.service';
import { combineLatest, Observable, Subscription } from 'rxjs';
import { map, debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'app-customers',
templateUrl: './customers.component.html',
styleUrls: ['./customers.component.css']
})
export class CustomersComponent implements OnInit, OnDestroy {
customers: Customer[];
curPage = 0;
totalPages: number;
totalRecs: number;
navPages: number[];
startPage = 0;
endPage = 0;
qParams: any = {
page: null,
name: null
};
delCustomerId: string;
delCustomerName: string;
alertMsgSuccess: string;
alertMsgFail: string;
type: string;
latestParams: Observable<any>;
combSub: Subscription;
isLoading = true;
constructor(
private router: Router,
private route: ActivatedRoute,
private dataservice: CustomerService
) {}
ngOnInit() {
this.isLoading = true;
// Combine route and query params
// Distinct will check for distinct parameter
// debounce will wait untill stack request are cleared
this.latestParams = combineLatest([this.route.queryParamMap, this.route.paramMap]).pipe(
debounceTime(0),
distinctUntilChanged(),
map(data => ({
qParams: data[0],
params: data[1]
}))
);
// Subscribe to navigation or query parameter changes
this.combSub = this.latestParams.subscribe(allParams => {
let wChange = false;
const newQParams = {};
// Copy query parameters to new object
if (allParams.qParams.keys.length > 0) {
allParams.qParams.keys.forEach(key => {
newQParams[key] = allParams.qParams.get(key);
});
}
// If already on customer page and customer type changed (customer/supplier)
// (clear query parameter in this case)
if (this.type && this.type.toLowerCase() + 's' !== allParams.params.get('type')) {
this.qParams = null;
wChange = true;
} else if (
!this.type ||
!this.qParams ||
JSON.stringify(newQParams) !== JSON.stringify(this.qParams)
) {
// If new query params are different from old query params
this.qParams = newQParams;
wChange = true;
}
// Update customer type
this.type = allParams.params.get('type') === 'customers' ? 'Customer' : 'Supplier';
// Get data
if (wChange) {
this.dataservice.getData(this.qParams, this.type).subscribe(
data => {
// If change in data
if (this.totalRecs !== data.totalRecs || this.totalPages !== data.totalPages) {
this.endPage = 0;
}
this.customers = data.customers;
this.curPage = data.curPage;
this.totalPages = data.totalPages;
this.totalRecs = data.totalRecs;
this.pageLogic();
this.isLoading = false;
},
error => {
this.customers = [];
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
this.pageLogic();
this.isLoading = false;
}
);
}
});
}
searchParamChange(newParam) {
if (!newParam.name) {
newParam.name = null;
}
this.router.navigate(['/clients', this.type.toLowerCase() + 's'], {
queryParams: { ...newParam },
queryParamsHandling: 'merge'
});
}
pageLogic() {
// If previous page requested is less than first page link and not zero
if (this.curPage < this.startPage && this.curPage >= 0) {
// Clear page array and fill with only 5 pages or total pages in case less that 5 pages
this.navPages = [];
this.startPage = this.curPage - 4 > 0 ? this.curPage - 4 : 1;
this.endPage = this.startPage + 4 > this.totalPages ? this.totalPages : this.startPage + 4;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
// If next page requested is greater than last page link and not the last page
if (this.curPage > this.endPage && this.curPage <= this.totalPages) {
this.navPages = [];
this.endPage = this.curPage + 4 > this.totalPages ? this.totalPages : this.curPage + 4;
this.startPage = this.endPage - 4 > 0 ? this.endPage - 4 : 1;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
}
deleteCustomer() {
this.isLoading = true;
this.alertMsgSuccess = null;
this.alertMsgFail = null;
if (this.delCustomerId) {
this.dataservice.deleteData(this.delCustomerId).subscribe(
data => {
if (!data.error) {
const index = this.getCustomerIndex(this.delCustomerId);
if (index >= 0) {
this.customers.splice(index, 1);
this.totalRecs -= this.totalRecs > 1 ? 1 : 0;
this.alertMsgSuccess = 'Customer deleted successfully';
this.delCustomerId = null;
this.delCustomerName = null;
}
} else {
this.alertMsgFail = 'Customer not deleted.' + data.error;
}
this.isLoading = false;
},
error => {
this.alertMsgFail = 'Customer not deleted. Server Error!';
this.isLoading = false;
}
);
}
}
getCustomerIndex(id: string) {
return this.customers.findIndex(customer => {
return customer['_id'] === id;
});
}
ngOnDestroy() {
this.combSub.unsubscribe();
}
}
<file_sep>/src/app/components/navbar/navbar.component.ts
import { TaxRateService } from './../../services/taxrate.service';
import { Subscription } from 'rxjs';
import { CompanyService } from './../../services/company.service';
import { Company } from './../../models/company.model';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit, OnDestroy {
curView: string;
company: Company = {};
companyListner: Subscription;
constructor(
private router: Router,
private companyService: CompanyService,
private taxRateService: TaxRateService
) {}
ngOnInit() {
this.taxRateService.getTaxes();
this.companyService.getCompanyFromServer();
this.companyListner = this.companyService.getCompanyListner()
.subscribe(data => {
if (data) {
this.company = data;
}
});
this.router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
if (this.router.parseUrl(val.url).root.children.primary) {
const segments = this.router.parseUrl(val.url).root.children.primary.segments;
if (segments && segments.length > 0) {
if (segments[0].path && segments[0].path === 'products') {
this.curView = segments[0].path;
} else if (segments.length > 2) {
this.curView = segments[segments.length - 2].path;
} else {
this.curView = segments[segments.length - 1].path;
}
}
}
}
});
}
ngOnDestroy() {
// try {
// this.companyListner.unsubscribe();
// } catch {}
}
}
<file_sep>/src/app/components/product-details/product-details.component.ts
import { ProductService } from './../../services/product.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {
product: any = {};
mode: string;
messageSuccess: string;
messageFail: string;
prvParams = {};
constructor(
private route: ActivatedRoute,
private dataService: ProductService,
private router: Router
) {}
ngOnInit() {
// Store mode new/edit/display
this.mode = this.route.snapshot.paramMap.get('mode');
this.route.queryParamMap.subscribe(params => {
this.prvParams = {
id: params.get('id')
};
this.prvParams['id'] = null;
if (this.mode === 'edit' || this.mode === 'display') {
this.product = this.dataService.getSingle(params.get('id'));
if (!this.product) {
this.router.navigate(['/products'], {
queryParams: this.prvParams
});
}
} else {
this.product.stock = 0;
}
});
}
saveProduct(product: NgForm) {
this.messageFail = null;
this.messageSuccess = null;
if (!product.valid) {
this.messageFail = 'Invalid Entries in Form';
} else {
if (this.mode === 'new') {
this.dataService.createData(product.value).subscribe(data => {
product.reset();
this.messageSuccess = 'Record Added Successfully';
});
} else {
this.dataService.updateData(this.product).subscribe(data => {
this.messageSuccess = 'Record Updated Successfully';
});
}
}
}
changeStockQty(opr, pqty) {
if (pqty && pqty > 0) {
if (opr === 'add') {
this.product.stock += pqty;
} else {
this.product.stock -= pqty;
}
}
}
}
<file_sep>/src/app/services/neworder.service.ts
import { Customer } from './../models/customer.model';
import { TaxRateService } from './taxrate.service';
import { Injectable } from '@angular/core';
import { Product } from './../models/product.model';
import { Order, OrderDetails } from '../models/order.model';
@Injectable({
providedIn: 'root'
})
export class NewOrderService {
curOrder: Order;
alltaxrates = [];
alltaxamounts = {};
constructor(private taxRateService: TaxRateService) {}
createOrder(customer?: Customer) {
if (customer) {
this.curOrder = {
customername: customer.name,
customer: customer,
status: 'Pending',
details: [],
date: new Date
};
} else {
this.curOrder = {
details: [],
status: 'Pending',
date: new Date
};
}
}
addCustomer(customer: Customer) {
if (!this.curOrder) {
this.createOrder(customer);
} else {
this.curOrder.customername = customer.name;
this.curOrder.customer = customer;
}
}
async addOrderItem(product: Product, discountRate?: number, quantity?: number) {
let isNew = true;
let foundIndex = -1;
let prvQuantity = 0;
let prvDiscountRate = 0;
// Create new Order Item if currently not added to array
if (!this.curOrder) {
this.createOrder();
} else {
this.curOrder.details.forEach((detail, index) => {
if (detail.product.name === product.name) {
isNew = false;
foundIndex = index;
prvQuantity = detail.quantity;
prvDiscountRate = detail.discountrate;
}
});
}
discountRate = discountRate ? discountRate : prvDiscountRate;
quantity = quantity ? quantity : prvQuantity + 1;
let total = product.price + (product.mrp * product.margin) / 100;
const discount = discountRate ? total * (discountRate / 100) : 0;
total = total - discount;
const taxrates = this.taxRateService.getTaxRate(product.taxrate);
const taxrate = taxrates.rate ?? 0;
const tax = (taxrate / 100) * total;
if (isNew) {
const newItem: OrderDetails = {
itemno: this.curOrder.details ? this.curOrder.details.length + 1 : 1,
product: product,
price: product.price,
quantity: quantity ? quantity : 1,
discountrate: discountRate,
discount: discount,
taxrate: product.taxrate,
tax: Math.round((tax + 0.00001) * 100) / 100,
total: Math.round((total + 0.00001) * 100) / 100
};
this.curOrder.details.push(newItem);
} else {
// If Product already Exist, change the quantity
// QUANTITY
this.curOrder.details[foundIndex].quantity = quantity;
// DISCOUNT
this.curOrder.details[foundIndex].discountrate = discountRate;
this.curOrder.details[foundIndex].discount =
discount * this.curOrder.details[foundIndex].quantity;
// TAX
this.curOrder.details[foundIndex].tax = tax * this.curOrder.details[foundIndex].quantity;
// TOTAL AMOUNT
this.curOrder.details[foundIndex].total = total * this.curOrder.details[foundIndex].quantity;
}
this.calculateSummary();
}
deleteOrderItem(index) {
this.curOrder.details.splice(index, 1);
this.calculateSummary();
}
addDiscount(discountrate) {
if (!this.curOrder) {
this.createOrder();
}
this.curOrder.discountrate = discountrate;
this.calculateSummary();
}
calculateSummary() {
let total = 0;
let totaltax = 0;
let discount = 0;
this.alltaxrates = [];
this.alltaxamounts = {};
if (this.curOrder.details && this.curOrder.details.length > 0) {
this.curOrder.details.forEach((item,index) => {
this.curOrder.details[index].itemno = index + 1;
total += item.total;
totaltax += item.tax;
if (item.product.taxrate !== 'Exempted') {
if (this.alltaxrates.indexOf(item.product.taxrate) < 0) {
this.alltaxrates.push(item.product.taxrate);
this.alltaxamounts[item.product.taxrate] = 0;
}
this.alltaxamounts[item.product.taxrate] += item.tax;
}
});
}
if (this.curOrder.discountrate && this.curOrder.discountrate > 0) {
discount = total * (this.curOrder.discountrate / 100);
totaltax = totaltax - totaltax * (this.curOrder.discountrate / 100);
}
this.curOrder.total = total;
this.curOrder.discount = discount;
this.curOrder.totaltax = totaltax;
this.curOrder.finalamount = Math.round(total - discount);
}
setOrder(order: Order) {
if (!order) {
return;
}
this.curOrder = order;
this.calculateSummary();
}
changeOrderStatus(status) {
this.curOrder.status = status;
}
changeOrderDate(orderDate) {
this.curOrder.date = orderDate;
}
}
<file_sep>/src/app/components/reports/reports.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-reports',
templateUrl: './reports.component.html',
styleUrls: ['./reports.component.css']
})
export class ReportsComponent implements OnInit {
monthArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
yearArr = [];
curYear = new Date().getFullYear();
curMonth = new Date().toLocaleString('en-us', {month: 'short'});
alertMsgFail: string;
constructor(private router: Router) {}
ngOnInit() {
for(let i=this.curYear; i>1950; i--) {
this.yearArr.push(i);
}
}
getTaxReport(fmonth, fyear, tmonth, tyear) {
this.alertMsgFail = null;
if (fyear+fmonth/100 > tyear+tmonth/100) {
this.alertMsgFail = "Start date cannot be greater than end date";
} else if ((tyear-fyear)*12 + (tmonth - fmonth) > 11) {
this.alertMsgFail = "Report cannot be generated for more than 12 months";
} else {
this.router.navigate(['/reports','tax'], {queryParams: {fyear: fyear, fmonth: fmonth, tyear: tyear, tmonth: tmonth}});
}
}
}
<file_sep>/src/app/components/customer-details/customer-details.component.ts
import { CustomerService } from './../../services/customer.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-customer-details',
templateUrl: './customer-details.component.html',
styleUrls: ['./customer-details.component.css']
})
export class CustomerDetailsComponent implements OnInit {
customer: any = {};
paramtype: string;
ctype: string;
mode: string;
messageSuccess: string;
messageFail: string;
prvParams = {};
constructor(
private route: ActivatedRoute,
private dataService: CustomerService,
private router: Router
) {}
ngOnInit() {
// Get customer type
this.paramtype = this.route.snapshot.paramMap.get('type');
this.ctype = this.paramtype === 'customers' ? 'Customer' : 'Supplier';
// Get Mode (New/Edit/Display)
this.mode = this.route.snapshot.paramMap.get('mode');
this.route.queryParamMap.subscribe(params => {
params.keys.forEach(key => {
this.prvParams[key] = params.get(key);
});
this.prvParams['id'] = null;
if (this.mode === 'edit' || this.mode === 'display') {
this.customer = this.dataService.getSingle(params.get('id'));
if (!this.customer) {
this.router.navigate(['/clients', this.paramtype], {
queryParams: this.prvParams
});
}
}
});
}
saveCustomer(customer: NgForm) {
this.messageFail = null;
this.messageSuccess = null;
if (!customer.valid) {
this.messageFail = 'Invalid Entries in Form';
} else {
if (this.mode === 'new') {
customer.value['type'] = this.ctype;
this.dataService.createData(customer.value).subscribe(data => {
customer.reset();
this.messageSuccess = 'Record Added Successfully';
});
} else {
this.dataService.updateData(this.customer).subscribe(data => {
this.messageSuccess = 'Record Updated Successfully';
});
}
}
}
}
<file_sep>/src/app/services/utility.service.ts
import { Injectable } from '@angular/core';
export enum CountryCodes {
IND = "IND",
USA = "USA",
GBR = "GBR"
}
@Injectable({
providedIn: 'root'
})
export class UtilityService {
private first = [
"",
"One ",
"Two ",
"Three ",
"Four ",
"Five ",
"Six ",
"Seven ",
"Eight ",
"Nine ",
"Ten ",
"Eleven ",
"Twelve ",
"Thirteen ",
"Fourteen ",
"Fifteen ",
"Sixteen ",
"Seventeen ",
"Eighteen ",
"Nineteen ",
];
private tens = [
"",
"",
"Twenty ",
"Thirty ",
"Forty ",
"Fifty ",
"Sixty ",
"Seventy ",
"Eighty ",
"Ninety ",
];
private numSys: { [currencyCode: string]: string[] } = {
usNumSys: [
"",
"Hundred ",
"Thousand ",
"Million ",
"Billion ",
"Trillion ",
],
inNumSys: ["", "Hundred ", "Thousand ", "Lakh ", "Crore "],
};
private curCodes: { [countryCode: string]: string[] } = {
IND: ["Rupee", "Paisa", "Paise", "₹", "inNumSys"],
USA: ["Dollar", "Cent", "Cents", "$", "usNumSys"],
GBR: ["Pound", "Pence", "Pence", "£", "usNumSys"],
};
public toWords = (amount: string | number, countryCode: string = "IND") => {
// console.log(num);
const numSys = this.numSys[this.getNumSys(countryCode)];
const nStr = amount.toString().split(".");
// Remove any other characters than numbers
const wholeStr = Number(nStr[0].replace(/[^a-z\d\s]+/gi, ""));
const decimalStr = nStr.length > 1 ? Number(nStr[1]) : 0;
const wholeStrPart =
this.getNumSys(countryCode) === "inNumSys"
? this.convert(wholeStr, numSys).trim()
: this.convertInUS(wholeStr, numSys).trim();
const decimalPart = this.convert(decimalStr, numSys).trim();
let valueInStr =
wholeStrPart.length > 0
? `${wholeStrPart} ${this.getCurrencyWhole(countryCode, wholeStr)}`
: `Zero ${this.getCurrencyWhole(countryCode, wholeStr)}`;
valueInStr =
decimalPart.length > 0
? `${valueInStr} And ${decimalPart} ${this.getCurrencyChange(
countryCode,
decimalStr
)}`
: valueInStr;
// console.log(valueInStr);
return valueInStr;
};
private getCurrencyWhole = (
countryCode: string = "IND",
amount: number = 0
) => {
const cur = this.curCodes[countryCode]
? this.curCodes[countryCode][0]
: this.curCodes["IND"][0];
if (amount > 1) return cur + "s";
else return cur;
};
private getCurrencyChange = (countryCode: string, amount: number = 0) => {
if (amount > 1)
return this.curCodes[countryCode]
? this.curCodes[countryCode][2]
: this.curCodes["IND"][2];
else
return this.curCodes[countryCode]
? this.curCodes[countryCode][1]
: this.curCodes["IND"][1];
};
private getCurrencySymbol = (countryCode: string) => {
return this.curCodes[countryCode]
? this.curCodes[countryCode][2]
: this.curCodes["IND"][2];
};
private getNumSys = (countryCode: string) => {
return this.curCodes[countryCode]
? this.curCodes[countryCode][4]
: this.curCodes["IND"][4];
};
private convert = (num: number | string, numSys: string[]) => {
const numStr = num.toString().split("");
const finalStr = [];
while (numStr.length > 0) {
for (let i = 0; i < numSys.length - 1; ++i) {
if (i === 1)
finalStr.unshift(this.getUnits(numStr.splice(-1), numSys, i));
else finalStr.unshift(this.getUnits(numStr.splice(-2), numSys, i));
}
if (numStr.length > 0) finalStr.unshift(...numSys.slice(-1));
}
return finalStr.join("");
};
private convertInUS = (num: number | string, numSys: string[]) => {
const numStr = num.toString().split("");
const finalStr = [];
while (numStr.length > 0) {
// console.log(numSys.length);
for (let i = 0, l = numSys.length * 2 - 1; i < l; ++i) {
// console.log(numStr, i, (i/2)+1);
if (i === 0)
finalStr.unshift(this.getUnits(numStr.splice(-2), numSys, 0));
else if (i % 2 === 1)
finalStr.unshift(this.getUnits(numStr.splice(-1), numSys, 1));
else {
finalStr.unshift(this.getUnits(numStr.splice(-2), numSys, i / 2 + 1));
}
}
if (numStr.length > 0) finalStr.unshift(...numSys.slice(-1));
else break;
}
return finalStr.join("");
};
private getUnits = (
lastTwo: string[],
numSys: string[],
place?: number
): string => {
if (!lastTwo || lastTwo.length === 0) return "";
let numInStr = "";
if (this.first[Number(lastTwo.join(""))])
numInStr = this.first[Number(lastTwo.join(""))];
else
numInStr = `${this.tens[Number(lastTwo.shift())]}${this.getUnits(
lastTwo.slice(-1),
numSys
)}`;
if (numInStr && place) numInStr = `${numInStr}${numSys[place] ?? ""}`;
return numInStr;
};
}
<file_sep>/src/app/models/customer.model.ts
export interface Customer {
_id: string;
name: string;
phone1: string;
phone2: string;
email1: string;
email2: string;
address: string;
city: string;
state: string;
country: string;
zipcode: string;
gstn: string;
pan: string;
type: string;
}
<file_sep>/src/app/services/company.service.ts
import { tap } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { Company } from './../models/company.model';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class CompanyService {
company: Company;
private companyUpdSubject = new Subject<Company>();
private url = environment.apiUrl + '/company'
constructor(private http: HttpClient) {}
getCompanyFromServer() {
this.http.get<{error: string, company: Company}>(this.url).subscribe(data => {
this.company = data.company;
this.emitCompanyEvent();
});
}
emitCompanyEvent() {
this.companyUpdSubject.next(this.company);
}
getCompanyListner() {
return this.companyUpdSubject.asObservable();
}
setCompany(company) {
if (!this.company || !this.company.name) {
return this.http.post<{error: string, company: Company}>(this.url, company)
.pipe(
tap(data => {
this.company = data.company;
this.emitCompanyEvent();
})
);
} else {
return this.http.put<{error: string, company: Company}>(this.url, company)
.pipe(
tap(data => {
this.company = data.company;
this.emitCompanyEvent();
})
);
}
}
}<file_sep>/src/app/components/receipt/receipt.component.ts
import { UtilityService } from './../../services/utility.service';
import { CompanyService } from './../../services/company.service';
import { Order } from './../../models/order.model';
import { Company } from './../../models/company.model';
import { TaxRateService } from './../../services/taxrate.service';
import { NewOrderService } from './../../services/neworder.service';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-receipt',
templateUrl: './receipt.component.html',
styleUrls: ['./receipt.component.css']
})
export class ReceiptComponent implements OnInit {
curOrder: Order;
allTaxRates = [];
allTaxAmounts = {};
company: Company;
recsPerPage = 12;
pages = [];
pageStart= [];
recsDone = 0;
constructor(
private newOrderService: NewOrderService,
private route: ActivatedRoute,
private router: Router,
private taxRateService: TaxRateService,
private companyService: CompanyService,
private utilityService: UtilityService
) { }
ngOnInit() {
// Store mode new/edit/display
if (!this.companyService.company || !this.companyService.company.name) {
this.router.navigate(['/settings']);
} else {
this.company = this.companyService.company;
}
this.route.queryParamMap.subscribe(params => {
this.curOrder = this.newOrderService.curOrder;
if (!this.curOrder || this.curOrder.details.length === 0) {
this.router.navigate(['/orders']);
}
this.allTaxRates = this.newOrderService.alltaxrates.sort();
this.allTaxAmounts = this.newOrderService.alltaxamounts;
if (this.curOrder) {
this.pageLogic(this.curOrder.details.length);
}
});
}
getTaxRate(rate: string): number {
return this.taxRateService.getTaxRate(rate).rate ?? 0;
}
pageLogic(noOfRecs) {
let prvsDone = 0;
this.pages = [];
this.pageStart = [];
while(noOfRecs > 12){
if(noOfRecs > 20) {
this.pages.push(20);
this.pageStart.push(prvsDone);
noOfRecs -= 20;
prvsDone += 20;
} else if (noOfRecs > 12){
this.pageStart.push(prvsDone);
prvsDone += noOfRecs-1;
this.pages.push(noOfRecs-1);
noOfRecs = 1;
}
}
this.pageStart.push(prvsDone);
this.pages.push(noOfRecs);
}
public getAmountInWords = () =>
{
return this.utilityService.toWords(this.curOrder.finalamount);
}
}
<file_sep>/src/app/models/auth.model.ts
export interface UserDetails {
username?: string;
firstName?: string;
lastName?: string;
authority?: number;
}
export interface AuthDetails {
username?: string;
password?: string;
}<file_sep>/src/app/components/taxrate-details/taxrate-details.component.ts
import { TaxRate } from './../../models/taxrate.model';
import { TaxRateService } from 'src/app/services/taxrate.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-taxrate-details',
templateUrl: './taxrate-details.component.html',
styleUrls: ['./taxrate-details.component.css']
})
export class TaxRateDetailsComponent implements OnInit {
taxRate: TaxRate;
mode: string;
messageSuccess: string;
messageFail: string;
prvParams = {};
constructor(
private route: ActivatedRoute,
private dataService: TaxRateService,
private router: Router
) {}
ngOnInit() {
// Store mode new/edit/display
this.mode = this.route.snapshot.paramMap.get('mode');
this.route.queryParamMap.subscribe(params => {
this.prvParams = {
name: params.get('name')
};
this.prvParams['name'] = null;
if (this.mode === 'edit' || this.mode === 'display') {
this.taxRate = this.dataService.getTaxRate(params.get('name'));
if (!this.taxRate) {
this.router.navigate(['/taxrates'], {
queryParams: this.prvParams
});
}
} else {
this.taxRate = null;
}
});
}
savetaxRate(taxRate: NgForm) {
this.messageFail = null;
this.messageSuccess = null;
if (!taxRate.valid) {
this.messageFail = 'Invalid Entries in Form';
} else {
if (this.mode === 'new') {
this.dataService.createData(taxRate.value).subscribe(data => {
taxRate.reset();
this.messageSuccess = 'Record Added Successfully';
});
} else {
this.dataService.updateData(this.taxRate).subscribe(data => {
this.messageSuccess = 'Record Updated Successfully';
});
}
}
}
}
<file_sep>/src/app/components/order-details/order-details.component.ts
import { OrderDetails } from './../../models/order.model';
import { TaxRateService } from './../../services/taxrate.service';
import { OrderService } from './../../services/order.service';
import { ProductService } from './../../services/product.service';
import { NewOrderService } from './../../services/neworder.service';
import { CustomerService } from './../../services/customer.service';
import { Product } from './../../models/product.model';
import { Customer } from './../../models/customer.model';
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-order-details',
templateUrl: './order-details.component.html',
styleUrls: ['./order-details.component.css']
})
export class OrderDetailsComponent implements OnInit, OnDestroy {
@ViewChild('productSBtn') productSBtn: ElementRef;
@ViewChild('customerSBtn') customerSBtn: ElementRef;
products: Product[];
customers: Customer[];
curPage = 0;
totalPages: number;
totalRecs: number;
navPages: number[];
startPage = 0;
endPage = 0;
prodOpts: {};
stockOpt: boolean;
dataSubs: Subscription;
productS: string;
codeS: string;
companyS: string;
customerS: string;
alltaxrates: string[];
tempProdArr: Product[] = [];
curOrder;
editType: string;
curProd;
curProdDiscount: number;
custOpts: {};
curSearch = '';
tempCust: Customer;
mode: string;
prvParams: {};
alertMsgSuccess: string;
alertMsgFail: string;
fragment: string;
isModalDataLoading = true;
curOrderNo: string;
constructor(
private router: Router,
private route: ActivatedRoute,
private productService: ProductService,
private customerService: CustomerService,
private newOrderService: NewOrderService,
private orderService: OrderService,
private taxRateService: TaxRateService
) {}
ngOnInit() {
// Store mode new/edit/display
this.fragment = 'customer';
this.mode = this.route.snapshot.paramMap.get('mode');
this.route.queryParamMap.subscribe(params => {
// this.prvParams = {
// id: params.get('id')
// };
// this.prvParams['id'] = null;
if (this.mode === 'edit' || this.mode === 'display') {
this.curOrder = this.orderService.getSingle(params.get('id'));
this.newOrderService.setOrder(this.curOrder);
this.retrieveOrder();
if (!this.curOrder) {
this.router.navigate(['/orders'], {
queryParams: this.prvParams
});
}
} else{
this.newOrderService.createOrder();
this.retrieveOrder();
}
});
}
onNext() {
if (this.fragment === 'customer') {
this.fragment = 'details';
} else if (this.fragment === 'details') {
this.fragment = 'summary';
} else if (this.fragment === 'summary') {
if (this.mode === 'display') {
this.router.navigate(['orders']);
} else {
this.saveOrder();
}
}
}
onPrevious() {
if (this.fragment === 'summary') {
this.fragment = 'details';
} else if (this.fragment === 'details') {
this.fragment = 'customer';
}
}
saveOrder() {
this.alertMsgFail = null;
this.alertMsgSuccess = null;
this.curOrderNo = null;
if (
!this.curOrder ||
this.curOrder.details.length === 0 ||
!this.curOrder.customername ||
this.curOrder.customername === ''
) {
this.alertMsgFail = 'Incomplete order details';
} else {
if (this.mode === 'new') {
this.orderService.createData({...this.curOrder}).subscribe(data => {
if (data.orderno) {
this.newOrderService.createOrder();
this.retrieveOrder();
this.fragment = 'customer';
this.curOrderNo = data.orderno;
this.alertMsgSuccess = 'created successfully';
} else {
this.alertMsgFail = 'Error creating order';
}
});
} else {
this.orderService.updateData({ ...this.curOrder }).subscribe(data => {
this.newOrderService.setOrder(data[0]);
this.retrieveOrder();
this.curOrderNo = this.curOrder.orderno;
this.alertMsgSuccess = 'updated successfully';
});
}
}
}
deleteOrderItem() {
this.newOrderService.deleteOrderItem(this.curOrder.details.indexOf(this.curProd));
this.retrieveOrder();
}
changeOrderStatus() {
if (this.curOrder.status !== 'Pending') {
this.curOrder.status = 'Pending';
} else {
this.curOrder.status = 'Completed';
}
this.newOrderService.changeOrderStatus(this.curOrder.status);
}
changeOrderDate(billDate) {
this.curOrder.date = billDate;
this.newOrderService.changeOrderDate(billDate);
}
onProductSearch(prodOpts: { code?: string; name?: string; company?: string; page?: number }) {
this.isModalDataLoading = true
if (this.curSearch !== 'product') {
this.curSearch = 'product';
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
}
// Show only in stok product by default
this.stockOpt = true;
this.taxRateService.getTaxes();
// Compare old and new params, so that page is not reloaded if no changes
this.prodOpts = prodOpts;
// Get data from data service by passing the params
this.dataSubs = this.productService.getData(this.prodOpts).subscribe(
data => {
// Copy new values if records or number of pages change
if (this.totalRecs !== data.totalRecs || this.totalPages !== data.totalPages) {
this.endPage = 0;
}
this.products = data.products;
this.curPage = data.curPage;
this.totalPages = data.totalPages;
this.totalRecs = data.totalRecs;
// Execute pagination logic
this.pageLogic();
this.isModalDataLoading = false;
},
error => {
// Set all fields to default if no records found or server error
this.products = [];
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
this.pageLogic();
this.isModalDataLoading = false;
}
);
}
showProducts() {
this.productSBtn.nativeElement.click();
}
retrieveOrder() {
this.curOrder = this.newOrderService.curOrder;
this.alltaxrates = this.newOrderService.alltaxrates;
}
addProductToArr(product, addProduct) {
if (addProduct) {
this.tempProdArr.push(product);
} else {
this.tempProdArr.splice(this.tempProdArr.indexOf(product), 1);
}
}
addProductsToOrder() {
this.tempProdArr.forEach(product => {
this.newOrderService.addOrderItem({ ...product });
});
this.tempProdArr = [];
this.retrieveOrder();
}
editProduct(value) {
if (this.editType === 'Discount') {
this.newOrderService.addOrderItem(this.curProd.product, value, this.curProd.quantity);
} else if (this.editType === 'Quantity') {
this.newOrderService.addOrderItem(this.curProd.product, this.curProd.discountRate, value);
} else if (this.editType === 'Overall Discount') {
this.newOrderService.addDiscount(value);
}
this.retrieveOrder();
}
showCustomers() {
this.customerSBtn.nativeElement.click();
}
addCustomerToOrder() {
this.newOrderService.addCustomer(this.tempCust);
this.retrieveOrder();
}
onCustomerSearch(custOpts: { name?: string; page?: number }) {
this.customers = [];
this.isModalDataLoading = true
if (this.curSearch !== 'customer') {
this.curSearch = 'customer';
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
}
// Compare old and new params, so that page is not reloaded if no changes
this.custOpts = custOpts;
// Get data from data service by passing the params
this.dataSubs = this.customerService.getData(this.custOpts, 'Customer').subscribe(
data => {
// Copy new values if records or number of pages change
if (this.totalRecs !== data.totalRecs || this.totalPages !== data.totalPages) {
this.endPage = 0;
}
this.customers = data.customers;
this.curPage = data.curPage;
this.totalPages = data.totalPages;
this.totalRecs = data.totalRecs;
// Execute pagination logic
this.pageLogic();
this.isModalDataLoading = false;
},
error => {
// Set all fields to default if no records found or server error
this.customers = [];
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
this.pageLogic();
this.isModalDataLoading = false;
}
);
}
pageLogic() {
// If previous page requested is less than first page link and not zero
if (this.curPage < this.startPage && this.curPage >= 0) {
// Clear page array and fill with only 5 pages or total pages in case less that 5 pages
this.navPages = [];
this.startPage = this.curPage - 2 > 0 ? this.curPage - 2 : 1;
this.endPage = this.startPage + 2 > this.totalPages ? this.totalPages : this.startPage + 2;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
// If next page requested is greater than last page link and not the last page
if (this.curPage > this.endPage && this.curPage <= this.totalPages) {
this.navPages = [];
this.endPage = this.curPage + 2 > this.totalPages ? this.totalPages : this.curPage + 2;
this.startPage = this.endPage - 2 > 0 ? this.endPage - 2 : 1;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
}
getProductIndex(id: string) {
return this.products.findIndex(product => {
return product['_id'] === id;
});
}
ngOnDestroy() {
if (this.dataSubs) {
this.dataSubs.unsubscribe();
}
}
}
<file_sep>/src/app/app-routing.module.ts
import { Company } from './models/company.model';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { OrdersComponent } from './components/orders/orders.component';
import { ReportsComponent } from './components/reports/reports.component';
import { SettingsComponent } from './components/settings/settings.component';
import { CustomersComponent } from './components/customers/customers.component';
import { ProductsComponent } from './components/products/products.component';
import { OrderDetailsComponent } from './components/order-details/order-details.component';
import { ProductDetailsComponent } from './components/product-details/product-details.component';
import { CustomerDetailsComponent } from './components/customer-details/customer-details.component';
import { TaxComponent } from './components/reports/tax/tax.component';
import { ReceiptComponent } from './components/receipt/receipt.component';
import { CompanyComponent } from './components/company/company.component';
import { TaxRatesComponent } from './components/taxrates/taxrates.component';
import { TaxRateDetailsComponent } from './components/taxrate-details/taxrate-details.component';
import { AuthComponent } from './components/auth/auth.component';
const routes: Routes = [
{path: 'dashboard', component: DashboardComponent},
{path: 'orders', component: OrdersComponent},
{path: 'orders/:mode', component: OrderDetailsComponent},
{path: 'clients/:type', component: CustomersComponent, pathMatch: 'full'},
{path: 'clients/:type/:mode', component: CustomerDetailsComponent, pathMatch: 'full'},
{path: 'clients/:type/edit', component: CustomerDetailsComponent, pathMatch: 'full'},
{path: 'products', component: ProductsComponent},
{path: 'products/:mode', component: ProductDetailsComponent},
{path: 'taxrates', component: TaxRatesComponent},
{path: 'taxrates/:mode', component: TaxRateDetailsComponent},
{path: 'reports', component: ReportsComponent},
{path: 'reports/tax', component: TaxComponent},
{path: 'receipt', component: ReceiptComponent},
{path: 'settings', component: CompanyComponent},
{path: 'login', component: AuthComponent},
{path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/models/product.model.ts
export interface Product {
_id: string;
code: string;
name: string;
company: string;
hsn: string;
size: string;
variant: string;
unit: string;
price: number;
mrp: number;
margin: number;
stock: number;
taxrate: string;
}
<file_sep>/src/app/components/taxrates/taxrates.component.ts
import { TaxRate } from './../../models/taxrate.model';
import { TaxRateService } from 'src/app/services/taxrate.service';
import { Subscription } from 'rxjs';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-taxrates',
templateUrl: './taxrates.component.html',
styleUrls: ['./taxrates.component.css']
})
export class TaxRatesComponent implements OnInit, OnDestroy {
taxRates: TaxRate[];
curPage = 0;
totalPages: number;
totalRecs: number;
navPages: number[];
startPage = 0;
endPage = 0;
params: any;
curTaxRate: TaxRate;
alertMsgSuccess: string;
alertMsgFail: string;
stockOpt: boolean;
dataSubs: Subscription;
isLoading = true;
constructor(
private router: Router,
private route: ActivatedRoute,
private dataservice: TaxRateService
) {}
ngOnInit() {
this.isLoading = true;
// Show only in stok product by default
this.stockOpt = true;
// Subscribe to query param changes
this.route.queryParamMap.subscribe(params => {
const newparams = {};
params.keys.forEach(key => {
newparams[key] = params.get(key);
});
// Compare old and new params, so that page is not reloaded if no changes
if (JSON.stringify(newparams) !== JSON.stringify(this.params)) {
this.params = newparams;
// Set stock option to false if all passed
// Get data from data service by passing the params
this.dataSubs = this.dataservice.getData(this.params).subscribe(
data => {
// Copy new values if records or number of pages change
if (this.totalRecs !== data.totalRecs || this.totalPages !== data.totalPages) {
this.endPage = 0;
}
this.taxRates = data.taxRates;
this.curPage = data.curPage;
this.totalPages = data.totalPages;
this.totalRecs = data.totalRecs;
// Execute pagination logic
this.pageLogic();
this.isLoading = false;
},
error => {
// Set all fields to default if no records found or server error
this.taxRates = [];
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
this.pageLogic();
this.isLoading = false;
}
);
}
});
}
pageLogic() {
// If previous page requested is less than first page link and not zero
if (this.curPage < this.startPage && this.curPage >= 0) {
// Clear page array and fill with only 5 pages or total pages in case less that 5 pages
this.navPages = [];
this.startPage = this.curPage - 4 > 0 ? this.curPage - 4 : 1;
this.endPage = this.startPage + 4 > this.totalPages ? this.totalPages : this.startPage + 4;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
// If next page requested is greater than last page link and not the last page
if (this.curPage > this.endPage && this.curPage <= this.totalPages) {
this.navPages = [];
this.endPage = this.curPage + 4 > this.totalPages ? this.totalPages : this.curPage + 4;
this.startPage = this.endPage - 4 > 0 ? this.endPage - 4 : 1;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
}
searchParamChange(newParam) {
// Stock option changed
if (newParam.stockOpt === false && (!newParam.company || !newParam.name)) {
newParam.stockOpt = 'all';
} else if (newParam.stockOpt === true && (!newParam.company || !newParam.name)) {
newParam.stockOpt = null;
}
this.router.navigate(['/taxrates'], {
queryParams: { ...newParam },
queryParamsHandling: 'merge'
});
}
deleteProduct() {
this.alertMsgSuccess = null;
this.alertMsgFail = null;
if (this.curTaxRate.name) {
this.dataservice.deleteData(this.curTaxRate.name).subscribe(
data => {
if (!data.error) {
const index = this.getProductIndex(this.curTaxRate.name);
if (index >= 0) {
this.taxRates.splice(index, 1);
this.totalRecs -= this.totalRecs > 1 ? 1 : 0;
this.alertMsgSuccess = 'Product deleted successfully';
this.curTaxRate = null;
}
} else {
this.alertMsgFail = 'Product not deleted.' + data.error;
}
},
error => {
this.alertMsgFail = 'Product not deleted. Server Error!';
}
);
}
}
getProductIndex(name: string) {
return this.taxRates.findIndex(product => {
return product['name'] === name;
});
}
ngOnDestroy() {
this.dataSubs.unsubscribe();
}
}
<file_sep>/src/app/models/order.model.ts
import { Product } from './product.model';
import { Customer } from './customer.model';
export interface Order {
_id?: string;
orderno?: string;
date?: Date;
customername?: string;
customer?: Customer;
total?: number;
discountrate?: number;
discount?: number;
totaltax?: number;
finalamount?: number;
details?: OrderDetails[];
status?: string;
}
export interface OrderDetails {
itemno: number;
product: Product;
quantity: number;
discountrate: number;
discount: number;
price: number;
taxrate: string;
tax: number;
total: number;
}
<file_sep>/src/app/components/company/company.component.ts
import { Subscription } from 'rxjs';
import { CompanyService } from './../../services/company.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
import { Company } from '../../models/company.model';
@Component({
selector: 'app-company',
templateUrl: './company.component.html',
styleUrls: ['./company.component.css']
})
export class CompanyComponent implements OnInit, OnDestroy {
company: any = {};
mode: string;
messageSuccess: string;
messageFail: string;
companyListner: Subscription;
constructor(
private route: ActivatedRoute,
private dataService: CompanyService,
private router: Router
) {}
ngOnInit() {
// Get company type
// Get Mode (New/Edit/Display)
this.messageFail = null;
this.mode = this.route.snapshot.paramMap.get('mode');
this.route.paramMap.subscribe(params => {
this.mode = params.get('mode');
if (!this.dataService.company || !this.dataService.company.name) {
this.dataService.getCompanyFromServer();
} else {
Object.assign(this.company, this.dataService.company);
}
this.companyListner = this.dataService.getCompanyListner().subscribe(data => {
if (data) {
this.company = data;
}
});
if (!this.company) {
if (this.mode === 'display') {
this.router.navigate(['/settings', 'edit']);
} else {
this.messageFail = 'Please add company details!';
}
}
});
}
saveCompany(company: NgForm) {
this.messageFail = null;
this.messageSuccess = null;
if (!company.valid) {
this.messageFail = 'Invalid Entries in Form';
} else {
this.dataService.setCompany(company.value).subscribe(data => {
this.messageSuccess = 'Record Updated Successfully';
});
}
}
ngOnDestroy() {
this.companyListner.unsubscribe();
}
}
<file_sep>/src/app/components/dashboard/dashboard.component.ts
import { CompanyService } from './../../services/company.service';
import { Component, OnInit } from '@angular/core';
import { InfoService } from '../../services/info.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
pendingData: any = {count:0, revenue: 0};
completedData: any = {count:0, revenue: 0};
supplierData : any = {count: 0};
customerData : any = {count: 0};
productCount = 0;
constructor(private infoService: InfoService, private companyService: CompanyService) { }
ngOnInit() {
const curYear = new Date().getFullYear();
const curMonth = new Date().getMonth()+1;
this.infoService.getOrderInfo(curYear, curMonth)
.subscribe( data => {
this.pendingData = data[0] && data[0]._id === 'Pending' ? data[0] : data[1] ? data[1] : {count: 0};
this.completedData = data[0] && data[0]._id === 'Completed' ? data[0] : data[1] ? data[1] : {count: 0};
});
this.infoService.getClientInfo()
.subscribe( data => {
this.supplierData = data[0] && data[0]._id === 'Supplier' ? data[0] : data[1] ? data[1] : 0;
this.customerData = data[0] && data[0]._id === 'Customer' ? data[0] : data[1] ? data[1] : 0;
});
this.infoService.getProductInfo()
.subscribe( data => {
this.productCount = data['count'] ? data['count'] : 0;
});
}
}
<file_sep>/src/app/services/taxrate.service.ts
import {
HttpClient,
HttpHeaders,
HttpParams
} from '@angular/common/http';
import {
TaxRate
} from './../models/taxrate.model';
import {
Injectable
} from '@angular/core';
import {
environment
} from '../../environments/environment';
import {
tap
} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TaxRateService {
taxRate: TaxRate;
taxRates: TaxRate[];
private url = environment.apiUrl + '/taxrates';
constructor(private http: HttpClient) {}
private httpOptions = {
headers: new HttpHeaders({
'x-auth-token': '<PASSWORD>'
})
};
getTaxes() {
if (!this.taxRates) {
this.taxRates = [];
this.http.get < {
error: string;
totalRecs: number;
totalPages: number;
curPage: number;
taxRates: TaxRate[];
} > (this.url).subscribe(data => {
// tslint:disable-next-line: curly
this.taxRates = data.taxRates;
});
}
}
// HTTP GET
getData(inParams: {
page ? : number;name ? : string
}) {
const params = new HttpParams()
.set('page', (inParams && inParams.page ? inParams.page : 1).toString())
.set('name', inParams && inParams.name ? inParams.name : '')
return this.http
.get < {
error: string;
totalRecs: number;
totalPages: number;
curPage: number;
taxRates: TaxRate[];
} > (this.url, {
params: params
})
.pipe(
tap(data => {
this.taxRates = data.taxRates;
})
);
}
createData(data: TaxRate) {
return this.http.post < TaxRate > (this.url, data, this.httpOptions);
}
// patchData(id: string, status: boolean) {
// const data = { _id: id, status: status };
// return this.http.patch(this.url + '/' + id, data, this.httpOptions);
// }
updateData(data: TaxRate) {
return this.http.put(this.url + '/' + data.name, data, this.httpOptions);
}
deleteData(id: string) {
return this.http.delete < {
error ? : string;taxRate ? : TaxRate
} > (
this.url + '/' + id,
this.httpOptions
);
}
getTaxRate(taxName: string): TaxRate {
if (this.taxRates) {
return this.taxRates.find(taxRate => {
return taxRate.name === taxName;
});
}
}
getSingle(name: string): TaxRate {
if (this.taxRates) {
return this.taxRates.filter(taxRate => {
return taxRate.name === name;
})[0];
}
}
}
<file_sep>/src/app/services/info.service.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
@Injectable({
'providedIn':'root'
})
export class InfoService {
private url = environment.apiUrl + '/info';
constructor(private http: HttpClient) {}
getOrderInfo(year: number, month:number) {
const params = new HttpParams()
.set('year', (year ? year : 0).toString())
.set('month', (month ? month : 0).toString());
return this.http.get(this.url + '/orders', {params: params});
}
getClientInfo() {
return this.http.get(this.url + '/clients');
}
getProductInfo() {
return this.http.get(this.url + '/products');
}
getTaxReport(fyear, fmonth, tyear, tmonth) {
const params = new HttpParams()
.set('startyear', (fyear ? fyear : 0).toString())
.set('startmonth', (fmonth ? fmonth : 0).toString())
.set('endyear', (tyear ? tyear : 0).toString())
.set('endmonth', (tmonth ? tmonth : 0).toString());
return this.http.get(this.url + '/tax', {params: params});
}
}<file_sep>/src/app/components/products/products.component.ts
import { NewOrderService } from './../../services/neworder.service';
import { Subscription } from 'rxjs';
import { Product } from './../../models/product.model';
import { ProductService } from './../../services/product.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit, OnDestroy {
products: Product[];
curPage = 0;
totalPages: number;
totalRecs: number;
navPages: number[];
startPage = 0;
endPage = 0;
params: any;
curProduct: Product;
alertMsgSuccess: string;
alertMsgFail: string;
stockOpt: boolean;
dataSubs: Subscription;
isLoading = true;
constructor(
private router: Router,
private route: ActivatedRoute,
private dataservice: ProductService,
private newOrderService: NewOrderService
) {}
ngOnInit() {
this.isLoading = true;
// Show only in stok product by default
this.stockOpt = true;
// Subscribe to query param changes
this.route.queryParamMap.subscribe(params => {
const newparams = {};
params.keys.forEach(key => {
newparams[key] = params.get(key);
});
// Compare old and new params, so that page is not reloaded if no changes
if (JSON.stringify(newparams) !== JSON.stringify(this.params)) {
this.params = newparams;
// Set stock option to false if all passed
if (this.params['stockOpt'] === 'all') {
this.stockOpt = false;
}
// Get data from data service by passing the params
this.dataSubs = this.dataservice.getData(this.params).subscribe(
data => {
// Copy new values if records or number of pages change
if (this.totalRecs !== data.totalRecs || this.totalPages !== data.totalPages) {
this.endPage = 0;
}
this.products = data.products;
this.curPage = data.curPage;
this.totalPages = data.totalPages;
this.totalRecs = data.totalRecs;
// Execute pagination logic
this.pageLogic();
this.isLoading = false;
},
error => {
// Set all fields to default if no records found or server error
this.products = [];
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
this.pageLogic();
this.isLoading = false;
}
);
}
});
}
pageLogic() {
// If previous page requested is less than first page link and not zero
if (this.curPage < this.startPage && this.curPage >= 0) {
// Clear page array and fill with only 5 pages or total pages in case less that 5 pages
this.navPages = [];
this.startPage = this.curPage - 4 > 0 ? this.curPage - 4 : 1;
this.endPage = this.startPage + 4 > this.totalPages ? this.totalPages : this.startPage + 4;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
// If next page requested is greater than last page link and not the last page
if (this.curPage > this.endPage && this.curPage <= this.totalPages) {
this.navPages = [];
this.endPage = this.curPage + 4 > this.totalPages ? this.totalPages : this.curPage + 4;
this.startPage = this.endPage - 4 > 0 ? this.endPage - 4 : 1;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
}
searchParamChange(newParam) {
// Stock option changed
if (newParam.stockOpt === false && (!newParam.company || !newParam.name)) {
newParam.stockOpt = 'all';
} else if (newParam.stockOpt === true && (!newParam.company || !newParam.name)) {
newParam.stockOpt = null;
}
this.router.navigate(['/products'], {
queryParams: { ...newParam },
queryParamsHandling: 'merge'
});
}
deleteProduct() {
this.alertMsgSuccess = null;
this.alertMsgFail = null;
if (this.curProduct._id) {
this.dataservice.deleteData(this.curProduct._id).subscribe(
data => {
if (!data.error) {
const index = this.getProductIndex(this.curProduct._id);
if (index >= 0) {
this.products.splice(index, 1);
this.totalRecs -= this.totalRecs > 1 ? 1 : 0;
this.alertMsgSuccess = 'Product deleted successfully';
this.curProduct = null;
}
} else {
this.alertMsgFail = 'Product not deleted.' + data.error;
}
},
error => {
this.alertMsgFail = 'Product not deleted. Server Error!';
}
);
}
}
addProductsToOrder() {
this.newOrderService.addOrderItem(this.curProduct);
this.curProduct = null;
}
getProductIndex(id: string) {
return this.products.findIndex(product => {
return product['_id'] === id;
});
}
ngOnDestroy() {
this.dataSubs.unsubscribe();
}
}
<file_sep>/src/app/services/order.service.ts
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Order } from './../models/order.model';
import { tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class OrderService {
private orders: Order[];
private url = environment.apiUrl + '/orders';
// HTTP Options
private httpOptions = {
headers: new HttpHeaders({
'x-auth-token':
'<PASSWORD>'
})
};
// Constructor
constructor(private http: HttpClient) {}
// HTTP GET
getData(inParams: {
page?: number;
orderno?: string;
client?: string;
statusOpt?: string;
fromDate?: string;
toDate?: string;
}) {
const params = new HttpParams()
.set('page', (inParams && inParams.page ? inParams.page : 1).toString())
.set('client', inParams && inParams.client ? inParams.client : '')
.set('orderno', inParams && inParams.orderno ? inParams.orderno : '')
.set('statusOpt', inParams && inParams.statusOpt ? inParams.statusOpt : '')
.set('fromDate', inParams && inParams.fromDate ? inParams.fromDate : '')
.set('toDate', inParams && inParams.toDate ? inParams.toDate : '');
return this.http
.get<{
error: string;
totalRecs: number;
totalPages: number;
curPage: number;
orders: Order[];
}>(this.url, { params: params })
.pipe(
tap(data => {
this.orders = data.orders;
})
);
}
createData(newdata: any) {
// Set Customer ID
const data = JSON.parse(JSON.stringify(newdata));
data['customername'] = data.customer.name;
data['customer'] = data.customer._id;
data.details.forEach((detail, index) => {
data.details[index]['product'] = detail.product._id;
});
return this.http.post<Order>(this.url, data, this.httpOptions);
}
patchData(id: string, status: boolean) {
const data = { _id: id, status: status };
return this.http.patch(this.url + '/' + id, data, this.httpOptions);
}
updateData(newdata: any) {
const data = JSON.parse(JSON.stringify(newdata));
data['customername'] = data.customer.name;
data['customer'] = data.customer._id;
data.details.forEach((detail, index) => {
data.details[index]['product'] = detail.product._id;
});
return this.http.put(this.url + '/' + data._id, data, this.httpOptions);
}
deleteData(id: string) {
return this.http.delete<{ error?: string; order?: Order }>(
this.url + '/' + id,
this.httpOptions
);
}
getSingle(id: string) {
if (this.orders) {
return this.orders.filter(order => {
return order._id === id;
})[0];
}
}
}
<file_sep>/src/app/components/orders/orders.component.ts
import { TaxRateService } from './../../services/taxrate.service';
import { Subscription } from 'rxjs';
import { Order } from './../../models/order.model';
import { OrderService } from './../../services/order.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-orders',
templateUrl: './orders.component.html',
styleUrls: ['./orders.component.css']
})
export class OrdersComponent implements OnInit, OnDestroy {
orders: Order[];
curPage = 0;
totalPages: number;
totalRecs: number;
navPages: number[];
startPage = 0;
endPage = 0;
params: any;
curOrder: Order;
alertMsgSuccess: string;
alertMsgFail: string;
statusOpt: boolean;
dataSubs: Subscription;
isLoading = true;
constructor(
private router: Router,
private route: ActivatedRoute,
private dataservice: OrderService,
private taxRateService: TaxRateService
) {}
ngOnInit() {
this.isLoading = true;
// Show only in stok product by default
this.statusOpt = true;
this.taxRateService.getTaxes();
// Subscribe to query param changes
this.route.queryParamMap.subscribe(params => {
const newparams = {};
params.keys.forEach(key => {
newparams[key] = params.get(key);
});
// Compare old and new params, so that page is not reloaded if no changes
if (JSON.stringify(newparams) !== JSON.stringify(this.params)) {
this.params = newparams;
// Set stock option to false if all passed
if (this.params['statusOpt'] === 'all') {
this.statusOpt = false;
}
// Get data from data service by passing the params
this.dataSubs = this.dataservice.getData(this.params).subscribe(
data => {
// Copy new values if records or number of pages change
if (this.totalRecs !== data.totalRecs || this.totalPages !== data.totalPages) {
this.endPage = 0;
}
this.orders = data.orders;
this.curPage = data.curPage;
this.totalPages = data.totalPages;
this.totalRecs = data.totalRecs;
// Execute pagination logic
this.pageLogic();
this.isLoading = false;
},
error => {
// Set all fields to default if no records found or server error
this.orders = [];
this.curPage = 1;
this.totalPages = 1;
this.totalRecs = 0;
this.pageLogic();
this.isLoading = false;
}
);
}
});
}
searchParamChange(newParam) {
if (newParam.fromDate || newParam.toDate) {
if (newParam.fromDate.value !== '') {
newParam.fromDate = newParam.fromDate.value;
} else {
newParam.fromDate = null;
}
if (newParam.toDate.value !== '') {
newParam.toDate = newParam.toDate.value;
} else {
newParam.toDate = null;
}
}
if (newParam.statusOpt === false && (!newParam.client || !newParam.orderno)) {
newParam.statusOpt = 'all';
} else if (newParam.statusOpt === true && (!newParam.client || !newParam.orderno)) {
newParam.statusOpt = null;
}
this.router.navigate(['/orders'], {
queryParams: { ...newParam },
queryParamsHandling: 'merge'
});
}
pageLogic() {
// If previous page requested is less than first page link and not zero
if (this.curPage < this.startPage && this.curPage >= 0) {
// Clear page array and fill with only 5 pages or total pages in case less that 5 pages
this.navPages = [];
this.startPage = this.curPage - 4 > 0 ? this.curPage - 4 : 1;
this.endPage = this.startPage + 4 > this.totalPages ? this.totalPages : this.startPage + 4;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
// If next page requested is greater than last page link and not the last page
if (this.curPage > this.endPage && this.curPage <= this.totalPages) {
this.navPages = [];
this.endPage = this.curPage + 4 > this.totalPages ? this.totalPages : this.curPage + 4;
this.startPage = this.endPage - 4 > 0 ? this.endPage - 4 : 1;
for (let i = this.startPage; i <= this.endPage; i++) {
this.navPages.push(i);
}
}
}
deleteOrder() {
this.alertMsgSuccess = null;
this.alertMsgFail = null;
if (this.curOrder) {
this.dataservice.deleteData(this.curOrder._id).subscribe(
data => {
if (!data.error) {
const index = this.getOrderIndex(this.curOrder._id);
if (index >= 0) {
this.orders.splice(index, 1);
this.totalRecs -= this.totalRecs > 1 ? 1 : 0;
this.alertMsgSuccess = 'Order deleted successfully';
this.curOrder = null;
}
} else {
this.alertMsgFail = 'Order not deleted.' + data.error;
}
},
error => {
this.alertMsgFail = 'Order not deleted. Server Error!';
}
);
}
}
changeOrderStatus() {
this.alertMsgSuccess = null;
this.alertMsgFail = null;
if (this.curOrder) {
this.curOrder.status = 'Completed';
this.dataservice.updateData(this.curOrder).subscribe(
data => {
if (data) {
const index = this.getOrderIndex(this.curOrder._id);
if (index >= 0) {
if (this.statusOpt) {
this.orders.splice(index, 1);
} else {
this.orders[index].status = 'Completed';
}
this.alertMsgSuccess = 'Order updated successfully';
this.curOrder = null;
} else {
this.orders[index].status = 'Pending';
this.alertMsgFail = 'Order not updated.';
}
} else {
this.alertMsgFail = 'Order not updated.';
}
},
error => {
this.alertMsgFail = 'Order not updated. Server Error!';
}
);
}
}
getOrderIndex(id: string) {
return this.orders.findIndex(order => {
return order['_id'] === id;
});
}
ngOnDestroy() {
this.dataSubs.unsubscribe();
}
}
<file_sep>/src/app/services/product.service.ts
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Product } from './../models/product.model';
import { tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private products: Product[];
private url = environment.apiUrl + '/products';
// HTTP Options
private httpOptions = {
headers: new HttpHeaders({
'x-auth-token':
'xxxy<PASSWORD>'
})
};
// Constructor
constructor(private http: HttpClient) {}
// HTTP GET
getData(inParams: {
code?: string;
page?: number;
name?: string;
company?: string;
stockOpt?: string;
}) {
const params = new HttpParams()
.set('code', (inParams && inParams.code ? inParams.code : ''))
.set('page', (inParams && inParams.page ? inParams.page : 1).toString())
.set('name', inParams && inParams.name ? inParams.name : '')
.set('company', inParams && inParams.company ? inParams.company : '')
.set('stockOpt', inParams && inParams.stockOpt ? inParams.stockOpt : '');
return this.http
.get<{
error: string;
totalRecs: number;
totalPages: number;
curPage: number;
products: Product[];
}>(this.url, {
params: params
})
.pipe(
tap(data => {
this.products = data.products;
})
);
}
createData(data: Product) {
return this.http.post<Product>(this.url, data, this.httpOptions);
}
patchData(id: string, status: boolean) {
const data = {
_id: id,
status: status
};
return this.http.patch(this.url + '/' + id, data, this.httpOptions);
}
updateData(data: Product) {
return this.http.put(this.url + '/' + data._id, data, this.httpOptions);
}
deleteData(id: string) {
return this.http.delete<{
error?: string;
product?: Product;
}>(this.url + '/' + id, this.httpOptions);
}
getSingle(id: string) {
if (this.products) {
return this.products.filter(product => {
return product._id === id;
})[0];
}
}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SidebarComponent } from './components/sidebar/sidebar.component';
import { BodyComponent } from './components/body/body.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { OrdersComponent } from './components/orders/orders.component';
import { ProductsComponent } from './components/products/products.component';
import { CustomersComponent } from './components/customers/customers.component';
import { SettingsComponent } from './components/settings/settings.component';
import { ReportsComponent } from './components/reports/reports.component';
import { OrderDetailsComponent } from './components/order-details/order-details.component';
import { CustomerDetailsComponent } from './components/customer-details/customer-details.component';
import { ProductDetailsComponent } from './components/product-details/product-details.component';
import { CompanyComponent } from './components/company/company.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ReceiptComponent } from './components/receipt/receipt.component';
import { TaxComponent } from './components/reports/tax/tax.component';
import { TaxRatesComponent } from './components/taxrates/taxrates.component';
import { TaxRateDetailsComponent } from './components/taxrate-details/taxrate-details.component';
import { ConfigComponent } from './components/config/config.component';
import { AuthComponent } from './components/auth/auth.component';
import { AuthInterceptor } from './services/auth-interpreter-service';
@NgModule({
declarations: [
AppComponent,
SidebarComponent,
BodyComponent,
NavbarComponent,
DashboardComponent,
OrdersComponent,
ProductsComponent,
CustomersComponent,
SettingsComponent,
ReportsComponent,
OrderDetailsComponent,
CustomerDetailsComponent,
ProductDetailsComponent,
CompanyComponent,
ReceiptComponent,
TaxComponent,
TaxRatesComponent,
TaxRateDetailsComponent,
AuthComponent,
ConfigComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule
],
providers: [{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}],
bootstrap: [AppComponent]
})
export class AppModule { }
|
8a7ea5dbe004ca2152966a4e9297ed9d415e4009
|
[
"TypeScript"
] | 29
|
TypeScript
|
cod-e-ash/hisaab-front
|
bd16d20e4848b63de675c5e6eeb42d49fa119b43
|
ff77ab66f872aff449748c8a466eec75b49afcc5
|
refs/heads/master
|
<file_sep>import { connect } from 'react-redux'
import * as authActions from '../../actions/authActions'
import wxLogin from "../components/wxLogin";
const mapDispatchToProps = (dispatch) => {
return {
socialLogin: function (type,token,onSuccess) {
dispatch(authActions.socialLogin(type,token,onSuccess))
}
}
}
export default connect(mapDispatchToProps)(wxLogin);<file_sep>import { API_ROOT, parseResponse } from './api'
import {showSpinner,hideSpinner} from './uiActions'
import {get_cookie, set_cookie, get_intl} from '../utils'
/*****************************************
* Social login Action
*****************************************/
export function socialLogin(type,token,onSuccess) {
return dispatch => {
dispatch(showSpinner())
const fullUrl = API_ROOT + 'oauth/' + type + '/';
return fetch(fullUrl, {
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
'X-CSRFToken': get_cookie('csrftoken')
},
method: "post",
credentials: 'include',
body: JSON.stringify(token)
})
.then(console.log(JSON.stringify(token)))
.then(parseResponse)
.then((user) => {
dispatch(gotAuthedUser(user.user))
dispatch(hideSpinner())
if(onSuccess) {
onSuccess()
}
})
.catch((errors) => {
dispatch(hideSpinner())
throw errors
});
};
}
/*****************************************
* Utility functions
*****************************************/
export const GOT_AUTHED_USER = 'GOT_AUTHED_USER';
export function gotAuthedUser(user=null, errors=null) {
if(user){
let date = new Date()
date.setDate(date.getDate()+14)
set_cookie(SESSION_NAME, true, {path: '/', expires: date})
return {
type: GOT_AUTHED_USER,
user,
};
}
if(errors){
set_cookie(SESSION_NAME, false, {path: '/'})
// return null
}
}
<file_sep>import React, { Component, PropTypes } from 'react'
import './signUp.css'
class SignUp extends Component{
renderSocialLoginSection(){
const re_uri = encodeURIComponent(redirect_uri);
const app_id = app_id;
const weChat_url = `https://open.weixin.qq.com/connect/qrconnect?appid=${app_id}&redirect_uri=${re_uri}&response_type=code&scope=snsapi_login#wechat_redirect`
return (
<div className="socialSignUpContainer">
<a className="weChatLoginButton" href={weChat_url}>
<i className="fa fa-weixin" aria-hidden='true' style={{'fontSize':'42px', 'padding':'2px'}}/>
</a>
</div>
)
}
render() {
return (
<div className="signUpContainer">
{this.renderSocialLoginSection()}
</div>
)
}
}
export default SignUp<file_sep># wechat-login-react
Just part of the complete code.
And I wrote a blog about the wechat login.
<a href="https://jerryzhao0423.github.io/others/2018/01/29/wechat-login.html">Blog</a>
|
6f649e88865b6798c6a37b41db875bf795223dbf
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
jerryzhao0423/wechat-login-react
|
a4b65a1df0b2118bbb47a4d53a4ee85de05ce2d7
|
f5aadb1a08ebe7fe7c4bad69c5d3cab03a650449
|
refs/heads/master
|
<file_sep>
# __RAW NOTES__ -- DO NOT USE
# References
Create Local Repo
https://wiki.centos.org/HowTos/CreateLocalRepos
https://www.digitalocean.com/community/tutorials/how-to-set-up-and-use-yum-repositories-on-a-centos-6-vps
https://www.ostechnix.com/download-rpm-package-dependencies-centos/
Kubernetes Offline Installs
## Setup RHEL repo
```
yum-config-manager --enable rhui-REGION-rhel-server-extras
```
## Set kubernetes repository
Create a reposoitory file for the Kubernetes repo.
```
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
exclude=kube*
EOF
setenforce 0
```
## Create a root directory - that will make it easier to tar everything up
## RPM Downloads ------------------------------------------------------------------
## These are broken up into directories, so we can install only what we need on the internet connected host
```
# This is the local directory where the rpms we need will live
mkdir -p /lib/LocalRepos/MyRPMs
#Download base and docker rpms
yum install -y --downloadonly --downloaddir=/lib/LocalRepos/MyRPMs/ wget zip unzip createrepo yum-utils device-mapper-persistent-data docker
#Download kube rpms
yum install -y --disableexcludes=kubernetes --downloadonly --downloaddir=/lib/LocalRepos/MyRPMs/ kubelet kubeadm kubectl
cd ..
```
```
# Before you can create the repository you need the tool to do so.
# Install the rpms in the order below. The versions of your install may/will likely
# be different
yum install -y deltarpm-3.6-3.el7.x86_64.rpm
yum install -y python-deltarpm-3.6-3.el7.x86_64.rpm
yum install -y createrepo-0.9.9-28.el7.noarch.rpm
# Now configure the new local repository the place where the repo's will live
# This is the directory we created earlier and downloaded the RPMs to
createrepo /lib/LocalRepos/MyRPMs
# Create the repository config file
cat <<EOF > /etc/yum.repos.d/LocalInstall.repo
[MyRPMs]
name=LocalRepo
baseurl=file:///lib/LocalRepos/MyRPMs
enabled=1
gpgcheck=0
EOF
```
sudo yum install --disablerepo=* --enablerepo=MyRPMs /lib/LocalRepos/MyRPMs/*.rpm -y
systemctl enable docker && systemctl start docker
## download the calico network configuration files
mkdir cni
cd cni
wget https://docs.projectcalico.org/v3.1/getting-started/kubernetes/installation/hosted/rbac-kdd.yaml
wget https://docs.projectcalico.org/v3.1/getting-started/kubernetes/installation/hosted/kubernetes-datastore/calico-networking/1.7/calico.yaml
cd ..
## Install Base, Docker and Kubernetes. On the interent connected machine we don't need kubernetes, but hey... I'm lazy
sudo yum install --disablerepo=* --enablerepo=MyRPMs /lib/LocalRepos/MyRPMs/*.rpm -y
systemctl enable docker && systemctl start docker
cd ..
## Download the docker images ----------------------------------------------------------------
docker image pull k8s.gcr.io/kube-proxy-amd64:v1.11.3
docker image pull k8s.gcr.io/kube-scheduler-amd64:v1.11.3
docker image pull k8s.gcr.io/kube-apiserver-amd64:v1.11.3
docker image pull k8s.gcr.io/kube-controller-manager-amd64:v1.11.3
docker image pull quay.io/calico/node:v3.1.3
docker image pull quay.io/calico/cni:v3.1.3
docker image pull k8s.gcr.io/coredns:1.1.3
docker image pull k8s.gcr.io/etcd-amd64:3.2.18
docker image pull k8s.gcr.io/pause:3.1
docker pull registry
docker pull busybox
## Export docker images ------------------------------------------------------------------------
kubeadm config images pull --kubernetes-version
mkdir container_images
cd container_images
docker image save k8s.gcr.io/kube-proxy-amd64:v1.11.3 > kube-proxy-amd64_v1.11.3.tar
docker image save k8s.gcr.io/kube-scheduler-amd64:v1.11.3 > kube-scheduler-amd64_v1.11.3.tar
docker image save k8s.gcr.io/kube-apiserver-amd64:v1.11.3 > kube-apiserver-amd64_v1.11.3.tar
docker image save k8s.gcr.io/kube-controller-manager-amd64:v1.11.3 > kube-controller-manager-amd64_v1.11.3.tar
docker image save quay.io/calico/node:v3.1.3 > calico_node_v3.1.3.tar
docker image save quay.io/calico/cni:v3.1.3 > calico_cni_v3.1.3.tar
docker image save k8s.gcr.io/coredns:1.1.3 > coredns_1.1.3.tar
docker image save k8s.gcr.io/etcd-amd64:3.2.18 > etc_amd64_3.2.18.tar
docker image save k8s.gcr.io/pause:3.1 > paus_3.2.tar
docker image save registry > registry.tar
docker image save busybox > busybox.tar
cd ..
## Tar it all up
cd ..
tar -c
#----------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------
## Install RPMS for base and docker
cd rpms/base
yum install -y *.rpm
cd ../docker
yum install -y *.rpm
systemctl enable docker && systemctl start docker
cd ../../container_images
## Load docker images
docker load < apiserver.tar
37 docker load < busybox.tar
38 ls -al *.tar
39 docker load < calico_cni.tar
40 docker load < calico_node.tar
41 docker load < controller-manager.tar
42 docker load < coredns.tar
43 docker load < etc.tar
44 docker load < kube-proxy_v1.11.3.tar
45 docker load < kube-proxy_v1.11.3.tar pause.tar
46 docker load < pause.tar
47 docker load < registry_latest.tar
48 docker load < scheduler.tar
docker images ls
# Install kubernetes
cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system
cd ../rpms/kubes
yum install -y *.rpm
systemctl enable kubelet && systemctl start kubelet
sudo kubeadm init --pod-network-cidr=10.244.0.0/16
kubectl apply -f https://docs.projectcalico.org/v3.1/getting-started/kubernetes/installation/hosted/rbac-kdd.yaml
kubectl apply -f https://docs.projectcalico.org/v3.1/getting-started/kubernetes/installation/hosted/kubernetes-datastore/calico-networking/1.7/calico.yaml
kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system calico-node-g6fqt 2/2 Running 0 1m
kube-system coredns-78fcdf6894-5zttp 1/1 Running 0 35m
kube-system coredns-78fcdf6894-xqt29 1/1 Running 0 35m
kube-system etcd-ip-10-0-3-215.ec2.internal 1/1 Running 0 34m
kube-system kube-apiserver-ip-10-0-3-215.ec2.internal 1/1 Running 0 35m
kube-system kube-controller-manager-ip-10-0-3-215.ec2.internal 1/1 Running 0 34m
kube-system kube-proxy-6nc9l 1/1 Running 0 35m
kube-system kube-scheduler-ip-10-0-3-215.ec2.internal 1/1 Running 0 34m
# Disable SE Linux
setenforce 0
and
vi /etc/sysconfig/selinux
Change SELINUX=enforcing to SELINUX=disabled
<file_sep>
Sometimes you just want to use a specific namespace
```
# First get your context name
$ kubectl config get-context
your-awesome-cluster
# Now set your namespace
$ kubectl config set-context your-awesome-cluster --namespace=stellar
Context "your-awesome-cluster" modified.
```
Sometimes you just need a shell in cluster
```
kubectl run myshell --rm -i --tty --image ubuntu -- bash
```
Sometimes you just to get a shell on one of the PODS in the cluster
```
kubectl exec -it <target pod> -- /bin/bash
```
kubeadm token create --print-join-command<file_sep>### Setup OMG Admin Kubectl on another computer
* Copy /etc/kubernetes/admin.conf to the target computer
* run `kubectl --kubeconfig ./admin.conf get nodes`
### Network Options
[Calico](https://docs.projectcalico.org/v3.2/introduction/)
* I like this one because it is simple, secure and easy to use. It creates and manages a flat layer 3 network, assigning each workload a fully routable IP address. Workloads can communicate without IP encapsulation or network address translation for bare metal performance, easier troubleshooting, and better interoperability. Calico leverages the routing and iptables firewall capabilities native to the Linux kernel. All traffic to and from individual containers, virtual machines, and hosts traverses these in-kernel rules before being routed to its destination.
* Reference Links
* [cluster Setup](https://docs.projectcalico.org/v3.2/getting-started/kubernetes/)
* [simple policy](https://docs.projectcalico.org/v3.2/getting-started/kubernetes/tutorials/simple-policy)
* <file_sep>yum-config-manager --enable rhui-REGION-rhel-server-extras
yum install -y docker
systemctl enable docker && systemctl start docker
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
exclude=kube*
EOF
setenforce 0
yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes
systemctl enable kubelet && systemctl start kubelet
cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system
|
ddbe01551f4861252dc1a7f7297d0e13997d8e48
|
[
"Markdown",
"Shell"
] | 4
|
Markdown
|
Currax/KubernetesExamples
|
034dc2394964ed18a55a93dd5032000e0c4adea5
|
dc01c3beb5701229ba2fcb8a27ffdc97d061b487
|
refs/heads/master
|
<file_sep>class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
Docker.url = 'tcp://172.16.42.43:4243'
end
<file_sep>class InstanceController < ApplicationController
def create
Instance.create!
end
end
<file_sep>class Instance < ActiveRecord::Base
belongs_to :app
after_create :start
before_destroy :stop
def start
Docker.url = Settings.docker_url
container = Docker::Container.create('Cmd' => ['/sbin/my_init'], 'Image' => 'phusion/baseimage')
self.container_id = container.id
self.save
container.start
end
def stop
Docker.url = Settings.docker_url
container = Docker::Container.get(self.container_id)
container.stop
end
end<file_sep>class AddContainerIdToInstance < ActiveRecord::Migration
def change
add_column :instances, :container_id, :string
end
end
<file_sep>Rails.application.routes.draw do
get 'instance/create'
devise_for :users
end
<file_sep>== README
Install Rails
brew install mysql
mysqld
mysql -uroot
create database linux_box_db
use linux_box_db
|
b2bb4247c6b4a63a1cb7e116040b5b9ad6553b83
|
[
"RDoc",
"Ruby"
] | 6
|
Ruby
|
davidgbe/LinuxBox
|
4aa3b216abd4133d3b3be6bf4b8d00cddc41d59b
|
5d457fdadee84efed3718300df82a4ad433d0408
|
refs/heads/master
|
<file_sep>
This repository contains a basic reverse shell written in golang.
The project is a slightly modified version of the initial [hershell golang reverse shell](https://sysdream.com/news/lab/2018-01-15-en-golang-for-pentests-hershell/), needs additional work to bypass other AV vendors.
### Build
```
make GOOS=windows GOARCH=amd64 LHOST=127.0.0.1 LPORT=9999
```
### Todo
* Add in hershell functionality while keeping it AV clean
* Check what windows syscall occurs upon command execution (and see if we can substitute it with a different one to avoid AV)
<file_sep># Makefile
SOURCE=shelly_shell.go
BUILD=go build
OUTPUT=shelly_shell
LDFLAGS=--ldflags "-s -w -X main.ip=${LHOST}:${LPORT}"
all:
${BUILD} ${LDFLAGS} -o ${OUTPUT} ${SOURCE}
clean:
rm -f ${OUTPUT}
<file_sep>#[cfg(windows)] extern crate winapi;
use std::mem;
use std::ptr;
use std::ffi::CString;
use winapi::um::winsock2::{
WSADATA,WSAStartup,WSAPROTOCOL_INFOW,WSASocketW,connect,
};
use winapi::shared::minwindef::{MAKEWORD,DWORD,TRUE};
use winapi::shared::ntdef::{HANDLE};
use winapi::shared::ws2def::{AF_INET,ADDRINFOA,SOCK_STREAM};
use winapi::um::ws2tcpip::getaddrinfo;
use winapi::um::processthreadsapi::{STARTUPINFOW,CreateProcessW,PROCESS_INFORMATION};
use winapi::um::winbase::{STARTF_USESTDHANDLES,CREATE_UNICODE_ENVIRONMENT,DETACHED_PROCESS,CREATE_NEW_PROCESS_GROUP};
use widestring::WideCString;
#[cfg(windows)]
fn shelly(){
//todo move strings to args, directly assigned as cstrings
let addr = String::from("127.0.0.1");
let port = String::from("9999");
let cmd = String::from("C:\\Windows\\System32\\cmd.exe");
let addr_cs = CString::new(addr.as_bytes()).unwrap();
let port_cs = CString::new(port.as_bytes()).unwrap();
let cmd_cs = WideCString::from_str(&cmd).unwrap();
//setup
let mut wsa_data: WSADATA = unsafe{mem::zeroed()};
unsafe{
WSAStartup(MAKEWORD(2,2),&mut wsa_data)
};
//init sockaddr_in
let mut hints: ADDRINFOA = unsafe { mem::zeroed() };
let mut servinfo: *mut ADDRINFOA = 0 as *mut ADDRINFOA;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 1;
unsafe{
getaddrinfo(addr_cs.as_ptr(),port_cs.as_ptr(), &hints, &mut servinfo);
};
//init socket
let socket = unsafe {
WSASocketW((*servinfo).ai_family,(*servinfo).ai_socktype,(*servinfo).ai_protocol,
mem::transmute::<usize, *mut WSAPROTOCOL_INFOW>(0),0,0)
};
//call socket
unsafe{
connect(socket,(*servinfo).ai_addr, (*servinfo).ai_addrlen as i32);
}
//init process
let mut si: STARTUPINFOW = unsafe {mem::zeroed()};
si.cb = mem::size_of::<STARTUPINFOW>() as DWORD;
si.hStdInput = socket as HANDLE;
si.hStdOutput = socket as HANDLE;
si.hStdError = socket as HANDLE;
si.dwFlags = STARTF_USESTDHANDLES;
let mut pi =PROCESS_INFORMATION {
hProcess: ptr::null_mut(),
hThread: ptr::null_mut(),
dwProcessId: 0,
dwThreadId: 0,
};
//exec Proc
//todo: check security_attributes and see if detached is needed
unsafe{
CreateProcessW(cmd_cs.as_ptr(),ptr::null_mut(),ptr::null_mut(),ptr::null_mut(),TRUE,CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,ptr::null_mut(),ptr::null(),&mut si,&mut pi);
}
}
fn main() {
shelly()
}
<file_sep>
This repository contains a basic reverse shell written in rust using the [winapi](https://github.com/retep998/winapi-rs) library.
Rust provides a standard lib for windows allowing access to ffi, so an alternate reverse shell could be created using [std::os::windows](https://doc.rust-lang.org/std/os/windows/index.html)
### Build:
x86/x64 for windows using [Cross](https://github.com/rust-embedded/cross)
```
cross build --release --target x86_64-pc-windows-gnu
```
### Todo:
* Add support for powershell
* Dynamic ip/port at compile/runtime
* Secure Bind shell
<file_sep>[package]
name = "shelly_shell"
version = "0.1.0"
authors = ["randomactsofsecurity"]
edition = "2018"
[dependencies]
winapi = { version = "0.3.4", features = ["winsock2","ws2tcpip","winbase"]}
widestring = "0.3"
[profile.release]
lto = true
<file_sep>package main
import (
"net"
"os"
"os/exec"
"runtime"
"syscall"
)
var ip string
func main() {
if len(ip) == 0{
os.Exit(1)
}
cnn, err := net.Dial("tcp", ip)
if err != nil {
cnn.Close()
os.Exit(1)
}
var ccc *exec.Cmd
switch runtime.GOOS{
case "windows":
ccc = exec.Command("C:\\Windows\\system32\\cmd.exe")
ccc.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
default:
ccc = exec.Command("/bin/sh")
}
ccc.Stdin = cnn
ccc.Stdout = cnn
ccc.Stderr = cnn
ccc.Run()
}
|
db4c269050ed547be155b8f721a19fdf2c8d590e
|
[
"Markdown",
"TOML",
"Makefile",
"Rust",
"Go"
] | 6
|
Markdown
|
rainlow/Awsome-shells
|
09a9fa84039937f126957f15436c14f473a7f21d
|
95d53c3d671164aad2ba3308cb863efd4db35bd6
|
refs/heads/master
|
<file_sep>class MentionslegalesController < ApplicationController
before_action :set_mentionslegale, only: [:show, :edit, :update, :destroy]
# GET /mentionslegales
# GET /mentionslegales.json
def index
end
# GET /mentionslegales/1
# GET /mentionslegales/1.json
def show
end
# GET /mentionslegales/new
def new
@mentionslegale = Mentionslegale.new
end
# GET /mentionslegales/1/edit
def edit
end
# POST /mentionslegales
# POST /mentionslegales.json
def create
@mentionslegale = Mentionslegale.new(mentionslegale_params)
respond_to do |format|
if @mentionslegale.save
format.html { redirect_to @mentionslegale, notice: 'Mentionslegale was successfully created.' }
format.json { render :show, status: :created, location: @mentionslegale }
else
format.html { render :new }
format.json { render json: @mentionslegale.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /mentionslegales/1
# PATCH/PUT /mentionslegales/1.json
def update
respond_to do |format|
if @mentionslegale.update(mentionslegale_params)
format.html { redirect_to @mentionslegale, notice: 'Mentionslegale was successfully updated.' }
format.json { render :show, status: :ok, location: @mentionslegale }
else
format.html { render :edit }
format.json { render json: @mentionslegale.errors, status: :unprocessable_entity }
end
end
end
# DELETE /mentionslegales/1
# DELETE /mentionslegales/1.json
def destroy
@mentionslegale.destroy
respond_to do |format|
format.html { redirect_to mentionslegales_url, notice: 'Mentionslegale was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_mentionslegale
@mentionslegale = Mentionslegale.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def mentionslegale_params
params.fetch(:mentionslegale, {})
end
end
<file_sep>json.array! @cgus, partial: 'cgus/cgu', as: :cgu
<file_sep>json.partial! "mentionslegales/mentionslegale", mentionslegale: @mentionslegale
<file_sep>json.extract! mentionslegale, :id, :created_at, :updated_at
json.url mentionslegale_url(mentionslegale, format: :json)
<file_sep>json.extract! cgu, :id, :created_at, :updated_at
json.url cgu_url(cgu, format: :json)
<file_sep>require "application_system_test_case"
class CgusTest < ApplicationSystemTestCase
setup do
@cgu = cgus(:one)
end
test "visiting the index" do
visit cgus_url
assert_selector "h1", text: "Cgus"
end
test "creating a Cgu" do
visit cgus_url
click_on "New Cgu"
click_on "Create Cgu"
assert_text "Cgu was successfully created"
click_on "Back"
end
test "updating a Cgu" do
visit cgus_url
click_on "Edit", match: :first
click_on "Update Cgu"
assert_text "Cgu was successfully updated"
click_on "Back"
end
test "destroying a Cgu" do
visit cgus_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Cgu was successfully destroyed"
end
end
<file_sep>require 'test_helper'
class CategorieCompetencesControllerTest < ActionDispatch::IntegrationTest
setup do
@categorie_competence = categorie_competences(:one)
end
test "should get index" do
get categorie_competences_url
assert_response :success
end
test "should get new" do
get new_categorie_competence_url
assert_response :success
end
test "should create categorie_competence" do
assert_difference('CategorieCompetence.count') do
post categorie_competences_url, params: { categorie_competence: { nom: @categorie_competence.nom } }
end
assert_redirected_to categorie_competence_url(CategorieCompetence.last)
end
test "should show categorie_competence" do
get categorie_competence_url(@categorie_competence)
assert_response :success
end
test "should get edit" do
get edit_categorie_competence_url(@categorie_competence)
assert_response :success
end
test "should update categorie_competence" do
patch categorie_competence_url(@categorie_competence), params: { categorie_competence: { nom: @categorie_competence.nom } }
assert_redirected_to categorie_competence_url(@categorie_competence)
end
test "should destroy categorie_competence" do
assert_difference('CategorieCompetence.count', -1) do
delete categorie_competence_url(@categorie_competence)
end
assert_redirected_to categorie_competences_url
end
end
<file_sep>class CgusController < ApplicationController
before_action :set_cgu, only: [:show, :edit, :update, :destroy]
# GET /cgus
# GET /cgus.json
def index
@cgus = Cgu.all
end
# GET /cgus/1
# GET /cgus/1.json
def show
end
# GET /cgus/new
def new
@cgu = Cgu.new
end
# GET /cgus/1/edit
def edit
end
# POST /cgus
# POST /cgus.json
def create
@cgu = Cgu.new(cgu_params)
respond_to do |format|
if @cgu.save
format.html { redirect_to @cgu, notice: 'Cgu was successfully created.' }
format.json { render :show, status: :created, location: @cgu }
else
format.html { render :new }
format.json { render json: @cgu.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cgus/1
# PATCH/PUT /cgus/1.json
def update
respond_to do |format|
if @cgu.update(cgu_params)
format.html { redirect_to @cgu, notice: 'Cgu was successfully updated.' }
format.json { render :show, status: :ok, location: @cgu }
else
format.html { render :edit }
format.json { render json: @cgu.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cgus/1
# DELETE /cgus/1.json
def destroy
@cgu.destroy
respond_to do |format|
format.html { redirect_to cgus_url, notice: 'Cgu was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cgu
@cgu = Cgu.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cgu_params
params.fetch(:cgu, {})
end
end
<file_sep>json.array! @mentionslegales, partial: 'mentionslegales/mentionslegale', as: :mentionslegale
<file_sep>class AddCategorieCompetenceToCompetence < ActiveRecord::Migration[5.2]
def change
add_reference :competences, :categorie_competence, foreign_key: true
end
end
<file_sep>class CategorieCompetencesController < ApplicationController
before_action :set_categorie_competence, only: [:show, :edit, :update, :destroy]
# GET /categorie_competences
# GET /categorie_competences.json
def index
@categorie_competences = CategorieCompetence.all
end
# GET /categorie_competences/1
# GET /categorie_competences/1.json
def show
end
# GET /categorie_competences/new
def new
@categorie_competence = CategorieCompetence.new
end
# GET /categorie_competences/1/edit
def edit
end
# POST /categorie_competences
# POST /categorie_competences.json
def create
@categorie_competence = CategorieCompetence.new(categorie_competence_params)
respond_to do |format|
if @categorie_competence.save
format.html { redirect_to @categorie_competence, notice: 'Categorie competence was successfully created.' }
format.json { render :show, status: :created, location: @categorie_competence }
else
format.html { render :new }
format.json { render json: @categorie_competence.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categorie_competences/1
# PATCH/PUT /categorie_competences/1.json
def update
respond_to do |format|
if @categorie_competence.update(categorie_competence_params)
format.html { redirect_to @categorie_competence, notice: 'Categorie competence was successfully updated.' }
format.json { render :show, status: :ok, location: @categorie_competence }
else
format.html { render :edit }
format.json { render json: @categorie_competence.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categorie_competences/1
# DELETE /categorie_competences/1.json
def destroy
@categorie_competence.destroy
respond_to do |format|
format.html { redirect_to categorie_competences_url, notice: 'Categorie competence was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_categorie_competence
@categorie_competence = CategorieCompetence.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def categorie_competence_params
params.require(:categorie_competence).permit(:nom)
end
end
<file_sep>require "application_system_test_case"
class CategorieCompetencesTest < ApplicationSystemTestCase
setup do
@categorie_competence = categorie_competences(:one)
end
test "visiting the index" do
visit categorie_competences_url
assert_selector "h1", text: "Categorie Competences"
end
test "creating a Categorie competence" do
visit categorie_competences_url
click_on "New Categorie Competence"
fill_in "Nom", with: @categorie_competence.nom
click_on "Create Categorie competence"
assert_text "Categorie competence was successfully created"
click_on "Back"
end
test "updating a Categorie competence" do
visit categorie_competences_url
click_on "Edit", match: :first
fill_in "Nom", with: @categorie_competence.nom
click_on "Update Categorie competence"
assert_text "Categorie competence was successfully updated"
click_on "Back"
end
test "destroying a Categorie competence" do
visit categorie_competences_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Categorie competence was successfully destroyed"
end
end
<file_sep>require 'test_helper'
class CgusControllerTest < ActionDispatch::IntegrationTest
setup do
@cgu = cgus(:one)
end
test "should get index" do
get cgus_url
assert_response :success
end
test "should get new" do
get new_cgu_url
assert_response :success
end
test "should create cgu" do
assert_difference('Cgu.count') do
post cgus_url, params: { cgu: { } }
end
assert_redirected_to cgu_url(Cgu.last)
end
test "should show cgu" do
get cgu_url(@cgu)
assert_response :success
end
test "should get edit" do
get edit_cgu_url(@cgu)
assert_response :success
end
test "should update cgu" do
patch cgu_url(@cgu), params: { cgu: { } }
assert_redirected_to cgu_url(@cgu)
end
test "should destroy cgu" do
assert_difference('Cgu.count', -1) do
delete cgu_url(@cgu)
end
assert_redirected_to cgus_url
end
end
<file_sep>json.partial! "cgus/cgu", cgu: @cgu
<file_sep>class CategorieCompetence < ApplicationRecord
has_many :competence
end
<file_sep>Rails.application.routes.draw do
resources :categorie_competences
resources :competences
resources :services
resources :cgus
resources :mentionslegales
resources :faqs
resources :contacts
resources :freelances
resources :portfolios
resources :resumes
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'home#index'
end
<file_sep>json.extract! freelance, :id, :created_at, :updated_at
json.url freelance_url(freelance, format: :json)
<file_sep>json.extract! service, :id, :nom, :contenu, :image, :competences, :created_at, :updated_at
json.url service_url(service, format: :json)
<file_sep>json.extract! categorie_competence, :id, :nom, :created_at, :updated_at
json.url categorie_competence_url(categorie_competence, format: :json)
<file_sep>require 'test_helper'
class MentionslegalesControllerTest < ActionDispatch::IntegrationTest
setup do
@mentionslegale = mentionslegales(:one)
end
test "should get index" do
get mentionslegales_url
assert_response :success
end
test "should get new" do
get new_mentionslegale_url
assert_response :success
end
test "should create mentionslegale" do
assert_difference('Mentionslegale.count') do
post mentionslegales_url, params: { mentionslegale: { } }
end
assert_redirected_to mentionslegale_url(Mentionslegale.last)
end
test "should show mentionslegale" do
get mentionslegale_url(@mentionslegale)
assert_response :success
end
test "should get edit" do
get edit_mentionslegale_url(@mentionslegale)
assert_response :success
end
test "should update mentionslegale" do
patch mentionslegale_url(@mentionslegale), params: { mentionslegale: { } }
assert_redirected_to mentionslegale_url(@mentionslegale)
end
test "should destroy mentionslegale" do
assert_difference('Mentionslegale.count', -1) do
delete mentionslegale_url(@mentionslegale)
end
assert_redirected_to mentionslegales_url
end
end
<file_sep>require "application_system_test_case"
class MentionslegalesTest < ApplicationSystemTestCase
setup do
@mentionslegale = mentionslegales(:one)
end
test "visiting the index" do
visit mentionslegales_url
assert_selector "h1", text: "Mentionslegales"
end
test "creating a Mentionslegale" do
visit mentionslegales_url
click_on "New Mentionslegale"
click_on "Create Mentionslegale"
assert_text "Mentionslegale was successfully created"
click_on "Back"
end
test "updating a Mentionslegale" do
visit mentionslegales_url
click_on "Edit", match: :first
click_on "Update Mentionslegale"
assert_text "Mentionslegale was successfully updated"
click_on "Back"
end
test "destroying a Mentionslegale" do
visit mentionslegales_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Mentionslegale was successfully destroyed"
end
end
<file_sep>class ContactMailer < ApplicationMailer
def contact
mail(to: '<EMAIL>', subject: 'Sujet du mail')
end
end
<file_sep>class Competence < ApplicationRecord
belongs_to :categorie_competence
end
|
1920a8cbc602b3132398eb03e8c1f3718efddc71
|
[
"Ruby"
] | 23
|
Ruby
|
BrianNKY/deploydigital
|
33c2310ea8227f359e79c595550d4b4bc454888f
|
bc600d3804d175d054deea4be7bc7a43c9a826d7
|
refs/heads/master
|
<repo_name>RobertoQuazzyAmato/playMath<file_sep>/README.md
# playMath
<file_sep>/app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var fs = require('fs');
server.listen(3000);
// usa express per gestire il routing
//
// quando il client richiede (con metodo GET) il
// percorso '/', invia il file index.html
app.get('/', function(req, res) {
res.sendFile(__dirname+'/index.html');
});
// usa socket.io per registrare le azioni da compiere
// quando si verificano certi eventi.
//
// Gestisce l'evento 'connection'
io.on('connection', function(socket) {
// all'avvio di una connessione viene creato un socket!
console.log('user connected');
// a connessione avvenuta,
// usa il modulo fs per monitorare il file image.jpg
fs.watch(__dirname+'/pictures/image.jpg', function(evt, filename) {
console.log('rilevata variazione immagine');
// in caso di variazione del file image.jpg lo reinvia
// al client tramite il socket precedentemente creato
fs.readFile(__dirname+'/pictures/image.jpg', function(err, buf) {
socket.emit('update_image', {image: true, buffer: buf.toString('base64')});
});
});
});
console.log('server listening on port 3000');
|
191fbb2567efdb293ce7dd5f1465120641ca22e3
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
RobertoQuazzyAmato/playMath
|
dd74c5642a6a799171f50ef9b9df9b0e3c95da79
|
6c35775a19a800a7dec1998c4a844c0f5510283a
|
refs/heads/master
|
<file_sep>import os
import json
import base64
from flask import request, Flask
from flask_restful import Api, Resource
class SendFile(Resource):
def post(self):
pass
def get(self):
pass
class CheckConfig(Resource):
def post(self):
pass
def get(self):
pass
class PurchaseKey(Resource):
def post(self):
pass
def get(self):
pass
class Initialize(Resource):
@staticmethod
def successfully_initialized():
return {"success": "initialized"}
@staticmethod
def already_initialized():
return {"error": "already initialized"}
def post(self):
data = request.json
results = init(api_key=data["apikey"], url=data["url"])
if results[1]:
return self.already_initialized()
else:
return self.successfully_initialized()
def get(self):
return {"error": "nothing here"}
class ListNewestDownloads(Resource):
def post(self):
pass
def get(self):
pass
class LocalFlask(Flask):
def process_response(self, response):
response.headers['Server'] = "Malbug API handler"
response.headers['Contact'] = "For more information email us at <EMAIL>"
response.headers['Hey-There'] = str(base64.b64decode(
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"29t"
))
response.headers['Made-With-Love'] = "Penetrum; Audits, security, and research. Made Simple"
super(LocalFlask, self).process_response(response)
return response
def get_downloads_folder():
if os.name == "nt":
import winreg
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
location = winreg.QueryValueEx(key, downloads_guid)[0]
else:
location = os.path.join(os.path.expanduser("~"), 'Downloads')
return location
def init(**kwargs):
api_key = kwargs.get("api_key", None)
url = kwargs.get("url", None)
home = kwargs.get("home", "{}/.malbug".format(os.path.expanduser("~")))
config = "{}/malbug.json".format(home)
if not os.path.exists(home):
os.makedirs(home)
with open(config, "a+") as f:
data = {
"api_key": str(base64.b64encode(api_key.encode())) if api_key is not None else "API-KEY-FILLER",
"url": str(base64.b64encode(url.encode())) if url is not None else "https://api.penetrum.com/score",
"downloads_folder": get_downloads_folder()
}
json.dump(data, f)
is_done = False
else:
with open(config) as f:
data = json.load(f)
is_done = True
return data, is_done
def main():
app = LocalFlask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 35000000
api = Api(app)
api.add_resource(SendFile, "/malbugapi/send")
api.add_resource(CheckConfig, "/malbugapi/config")
api.add_resource(PurchaseKey, "/malbugapi/purchase")
api.add_resource(Initialize, "/malbugapi/init")
app.run(host="127.0.0.1", port=9801)
if __name__ == "__main__":
main()
<file_sep># Malbug extension helper
This repository contains the source code to the Malbug browser extension helper. Basically the job of this program is to create a local API that is responsible for sending the data back and forth to the Malbug browser extension. The reason for this extra step is that the browser is incapable of reading files over 10kb which leaves us with a lot of files that we are unable to analyze, so with that in mind we had the idea to create an extra helper script to open an API that the extension can talk to. The Malbug browser extension is closed source as of now but we are fully opensourcing the helper file.
|
c592166ccde0622875264395540139d3c85992c0
|
[
"Markdown",
"Python"
] | 2
|
Python
|
Penetrum-Security/Malbug-extension-helper
|
c55dfcf58c807ec6abf76695f5f81ec5f09a8dc8
|
a3ffd07634212c6fd8b0cd0c7d4de2bc4d5e5310
|
refs/heads/main
|
<file_sep>import { baseUrl } from "@/api/common";
export default {
/** 获取歌手详情 */
artistDetail: baseUrl + "/artist/detail",
/** 获取歌手专辑 */
artistAlbum: baseUrl + "/artist/album",
};
<file_sep>import { reactive, Ref } from "vue";
import { ElMessage } from "element-plus";
import {
IListState,
IPlayerState,
ISongState,
IUsePlayerState,
PlayBackType,
} from "../interface";
import { IUseAudioReturn } from "./interface";
export const useAudio = (
audioRef: Ref<HTMLAudioElement>,
songState: ISongState,
playNext: () => void
): IUseAudioReturn => {
/** 初始化音乐播放器 */
const initAudio = () => {
const ele = audioRef.value;
// 音频缓冲事件
ele.onprogress = () => {
try {
if (ele.buffered.length > 0) {
songState.songDuration = ele.duration;
}
} catch (error) {
console.log("error", error);
}
};
// 开始播放音乐
ele.onplay = () => {
songState.isPause = false;
};
// 获取当前播放时间
ele.ontimeupdate = () => {
songState.playedSongDuration = ele.currentTime;
songState.playRate = ele.currentTime / ele.duration;
};
// 当前音乐播放完毕
ele.onended = () => {
// if (that.mode === playMode.loop) {
// that.loop();
// } else {
// that.next();
// }
playNext();
};
// 音乐播放出错
ele.onerror = () => {
if (!songState.isPause) {
ElMessage({
showClose: true,
message: "当前音乐不可播放,已自动播放下一曲",
type: "error",
duration: 2000,
});
const timer = setTimeout(() => {
clearTimeout(timer);
playNext();
}, 1000);
}
// if (retry === 0) {
// let toastText = "当前音乐不可播放,已自动播放下一曲";
// if (that.playlist.length === 1) {
// toastText = "没有可播放的音乐哦~";
// }
// that.$mmToast(toastText);
// that.next(true);
// } else {
// // eslint-disable-next-line no-console
// console.log("重试一次");
// retry -= 1;
// ele.url = that.currentMusic.url;
// ele.load();
// }
// console.log('播放出错啦!')
};
// 音乐进度拖动大于加载时重载音乐
ele.onstalled = () => {
// ele.load();
// that.setPlaying(false);
// let timer;
// clearTimeout(timer);
// timer = setTimeout(() => {
// that.setPlaying(true);
// }, 10);
};
// 将能播放的音乐加入播放历史
ele.oncanplay = () => {
// retry = 1;
// if (
// that.historyList.length === 0 ||
// that.currentMusic.id !== that.historyList[0].id
// ) {
// that.setHistory(that.currentMusic);
// }
};
// 音频数据不可用时
ele.onstalled = () => {
console.log("音频数据不可用时");
// ele.load();
// that.setPlaying(false);
// let timer;
// clearTimeout(timer);
// timer = setTimeout(() => {
// that.setPlaying(true);
// }, 10);
};
// 当音频已暂停时
ele.onpause = () => {
// that.setPlaying(false);
};
};
return {
initAudio,
};
};
/** 播放器状态hooks */
export const usePlayerState = (): IUsePlayerState => {
const playerState = reactive<IPlayerState>({
listState: "in-order",
listStateDesc: "顺序播放",
listStateIcon: "in-order",
volume: 0.6,
showLyrics: false,
expandSong: false,
});
/** 列表播放状态数组 */
const listStateArray: IListState[] = [
{
listState: "in-order",
listStateDesc: "顺序播放",
listStateIcon: "in-order",
},
{
listState: "list-loop",
listStateDesc: "列表循环",
listStateIcon: "list-loop",
},
{
listState: "single-cycle",
listStateDesc: "单曲循环",
listStateIcon: "single-cycle",
},
{
listState: "shuffle",
listStateDesc: "随机播放",
listStateIcon: "shuffle",
},
];
/**
* 切换播放器列表状态到列表中的下一个状态
* @param state 播放器播放列表状态
*/
const changeListState = (state: PlayBackType) => {
const result = listStateArray.findIndex(
(listState) => listState.listState === state
);
if (result !== -1) {
const currentIndex =
result === listStateArray.length - 1 ? 0 : result + 1;
const currentListState = listStateArray[currentIndex];
playerState.listState = currentListState.listState;
playerState.listStateDesc = currentListState.listStateDesc;
playerState.listStateIcon = currentListState.listStateIcon;
}
};
/** 展开|关闭 播放列表 */
const toggleExpandSong = (state: boolean | undefined = undefined) => {
if (state !== undefined) {
playerState.expandSong = state;
} else {
playerState.expandSong = !playerState.expandSong;
}
};
/**
* 调整音量
* @param volume 音量,0-1之间的数字
*/
const adjustVolume = (volume: number) => {
let volumeNum = 0;
if (volume < 0) {
volumeNum = 0;
} else if (volume > 1) {
volumeNum = 1;
}
playerState.volume = volumeNum;
};
return {
playerState,
changeListState,
toggleExpandSong,
adjustVolume,
};
};
<file_sep>import { ITab } from "./index";
export interface ITabsState {
currentTab: string | number /** 当前歌曲类型 */;
tabs: ITab[] /** 类型tabs */;
currentSongId: undefined | number /** 当前歌曲id */;
}
export interface ICurrentSongsState {
limit: 10 /** 分页参数 */;
offset: 0 /** 分页参数 */;
}
<file_sep>export interface IPageState {
limit: number /** 每页条数 */;
offset: number /** 分页偏移量 */;
}
<file_sep>import { ILog } from "@/store/modules/interface/bulletin";
export const logs: ILog[] = [
{
date: "2021-08-19",
title: "web-music-player更新公告(2021-08-19)",
briefContent: `<p>1. 优化了所有请求的图片资源的大小,避免持续下载图片造成卡顿</p><p>2. 修复了歌单中没有歌曲、没有收藏者时没有提示的问题</p>`,
content: `<p>1. 优化了所有请求的图片资源的大小,避免持续下载图片造成卡顿</p><p>2. 修复了歌单中没有歌曲、没有收藏者时没有提示的问题</p>`,
},
{
date: "2021-08-17",
title: "web-music-player更新公告(2021-08-16)",
briefContent: `<p>1. 新增页面最新音乐-新碟上架;</p><p>2. 移除了部分重复定义的接口;</p><p>3. 最新音乐-新碟上架,添加自定义分页;</p>`,
content: `<p>1. 新增页面最新音乐-新碟上架;</p><p>2. 移除了部分重复定义的接口;</p><p>3. 最新音乐-新碟上架,添加自定义分页;</p>`,
},
{
date: "2021-08-16",
title: "web-music-player更新公告(2021-08-16)",
briefContent: `<p>1. 新增页面最新音乐-新歌速递;</p>`,
content: `<p>1. 新增页面最新音乐-新歌速递;</p>`,
},
{
date: "2021-08-13",
title: "web-music-player更新公告(2021-08-13)",
briefContent: `<p>1. 新增全局的更新公告弹窗组件,显示简略公告信息;</p>
<p>2. 新增全局公告导航,显示公告列表和更详细信息;</p>`,
content: `<p>1. 新增全局的更新公告弹窗组件,显示简略公告信息;</p>
<p>2. 新增全局公告导航,显示公告列表和更详细信息;</p>`,
},
];
|
67542961478b568c6cc78b26c326c2e4dc1e10d2
|
[
"TypeScript"
] | 5
|
TypeScript
|
liulipeng721/web-music-player
|
a06a3a279d603494b5b7f32e66bf14def935f73e
|
c2569bb8feca7678837dc469abc0341923d12ddb
|
refs/heads/master
|
<file_sep>import matplotlib.pyplot as plt
import sklearn.datasets as skdata
import numpy as np
%matplotlib inline
numeros = skdata.load_digits()
target = numeros['target']
imagenes = numeros['images']
n_imagenes = len(target)
print(np.shape(imagenes), n_imagenes) # Hay 1797 digitos representados en imagenes 8x8
data = imagenes.reshape((n_imagenes, -1)) # para volver a tener los datos como imagen basta hacer data.reshape((n_imagenes, 8, 8))
print(np.shape(data))
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
scaler = StandardScaler()
x_train, x_test, y_train, y_test = train_test_split(data, target, train_size=0.5)
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
numero = 1
dd = y_train==numero
cov = np.cov(x_train[dd].T)
valores, vectores = np.linalg.eig(cov)
valores = np.real(valores)
vectores = np.real(vectores)
ii = np.argsort(-valores)
valores = valores[ii]
vectores = vectores[:,ii]
print(vectores)
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.metrics import f1_score
scores_train=[]
scores_test=[]
scores_train_ceros=[]
scores_test_ceros=[]
#proyecciones
proyecciones=x_train@vectores
proyecciones_test=x_test@vectores
y_train_transf=np.where(y_train!=1,0,y_train)
y_test_transf=np.where(y_test!=1,0,y_test)
for i in range(3,40):
proyecciones_f=proyecciones[:,:i]
clf = LinearDiscriminantAnalysis()
clf.fit(proyecciones_f, y_train_transf)
proyecciones_test_f=proyecciones_test[:,:i]
y_predict_test=clf.predict(proyecciones_test_f)
y_predict_train=clf.predict(proyecciones_f)
scores_test.append(f1_score(y_test_transf, y_predict_test, ))
scores_train.append(f1_score(y_train_transf,y_predict_train))
scores_test_ceros.append(f1_score(y_test_transf, y_predict_test,pos_label=0))
scores_train_ceros.append(f1_score(y_train_transf,y_predict_train,pos_label=0))
plt.figure(figsize=(15,5))
plt.subplot(1,2,1)
plt.title("F1 scoresde los UNOS")
componentes=np.arange(3, 40, 1)
plt.scatter(componentes,scores_train,label='train')
plt.scatter(componentes,scores_test,label='test')
plt.legend()
plt.subplot(1,2,2)
plt.title("F1 scores de los NO UNOS")
componentes1=np.arange(3, 40, 1)
plt.scatter(componentes1,scores_train_ceros,label='train')
plt.scatter(componentes1,scores_test_ceros,label='test')
plt.legend()
|
74db25f1848ff001eb8f56bfd8e777332bdd295a
|
[
"Python"
] | 1
|
Python
|
CristinaNavarrete/NavarreteCristina_Ejercicio11
|
7bcd842f56230745a6de09486fbb833706b252e4
|
8ee00ba9220404f3149c232be5060d423bf116f0
|
refs/heads/master
|
<file_sep>require 'test_helper'
class TestApp < Rigle::Application; end
class TestRigle < Minitest::Test
def app
TestApp.new
end
def test_that_it_has_a_version_number
refute_nil ::Rigle::VERSION
end
def test_request
get '/'
assert_equal true, last_response.ok?
# assert last_response.body['Hello']
assert_match /Hello/, last_response.body
assert_equal 'text/html', last_response.content_type
end
def test_that_it_is_not_successful_for_non_existing_files
skip('for now')
get '/404'
assert_equal true, last_response.not_found?
end
def test_that_it_is_not_short_and_stout
head '/'
refute last_response.i_m_a_teapot?, "\n\t» Tip me over and pour me out."
end
end
<file_sep>require 'rack/test'
require 'minitest/autorun'
require 'pry'
# Prefix the load path with our lib folder so we use the local, currently
# under development version of our gem.
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'rigle'
require 'rigle/array'
class Minitest::Test
include Rack::Test::Methods
end
<file_sep>require 'test_helper'
class ArrayTest < Minitest::Test
def test_sum_adds_up_the_elements_of_the_array
fourty_two = [12, 14, 16].sum
assert_equal 42, fourty_two
end
end
<file_sep>source 'https://rubygems.org'
ruby '2.2.1'
# Specify your gem's dependencies in rigle.gemspec
gemspec
<file_sep># Rigle
[](http://badge.fury.io/rb/rigle) [](https://travis-ci.org/mariusbutuc/rigle)
This repo with follow along building a Rails-like framework from an empty directory, using the same Ruby features and structures that make Rails so interesting.
> Knowing the deepest levels of any piece of software lets you master it. It’s a special kind of competence you can’t fake. You have to know it so well you could build it. What if you did build it? Wouldn’t that be worth it?
It's just me going through the moves of with @noahgibbs' [Rebuilding Rails](https://rebuilding-rails.com/).
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'rigle'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install rigle
## Usage
Usage instructions here will eventually find their home here.
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
1. Fork it ( https://github.com/mariusbutuc/rigle/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
<file_sep>require 'rigle/version'
require 'rigle/routing'
module Rigle
class Application
def call(env)
case env['PATH_INFO']
when '/favicon.ico'
return render_html(status: 404, content: [])
when '/'
return redirect_to(path: '/quotes/quote')
end
klass, act = get_controller_and_action(env)
controller = klass.new(env)
begin
text = controller.send(act)
render_html(status: 200, content: [text])
rescue
render_html(status: 500, content: [
'<p>Huston, we have a problem!</p>',
%q(<p>Told you, there's no place like <a href="http://localhost:3001/">home</a>...</p>)
])
end
end
private
def render_html(status:, content:)
[status, {'Content-Type' => 'text/html'}, content]
end
def redirect_to(path:)
headers = {
'Content-Type' => 'text/html',
'Location' => path
}
[302, headers, ['302 you are being redirected']]
end
end
class Controller
def initialize(env)
@env = env
end
def env
@env
end
end
end
|
98fa5f204cf88e11e063e963c4d13bd7fe5fc1ee
|
[
"Markdown",
"Ruby"
] | 6
|
Ruby
|
mariusbutuc/rigle
|
17494252485e834b486f87e489805d86bb4d3e14
|
e317a1bc857f5783592e2e1186082be85dc5a97c
|
refs/heads/master
|
<repo_name>mavisfrancia/maxinami_games<file_sep>/check_if_username_available.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['username'])) {
require_once 'userDAO.php';
require_once 'databaseConnector.php';
$userDAO = new userDAO();
$db = new databaseConnector();
$con = $db->getConnection();
$result = $userDAO->selectByUsername($_POST['username'],$con);
if (mysqli_num_rows($result) == 0)
exit("true");
else
exit("false");
} else {
exit("false");
}
} else {
exit("false");
}
?><file_sep>/scripts/create_account.js
//This script stops new users from creating an account if either
//all required fields are not entered or password and confirm password is mismatched
$(document).ready(function(){
//Create boolean variables
var usernameFilled = false;
var nameFilled = false;
var addressFilled = false;
var passwordFilled = false;
//This text contains the error of passwords mismatch
var text = "";
//For number relation teet
var isNumber = /^[0-9]+$/;
//For the username(email) field
$("#username").keyup(function(){
//Store email error message
var emailText = "";
//If the field is empty
if($(this).val() === '')
{
//Empty text
emailText = "";
$("#usernameerror").css({"color": "green"});
document.getElementById("usernameerror").innerHTML = emailText;
usernameFilled = false;
}
else
{
//Check to see if email is valid
var email = document.getElementById("username").value;
var isEmail = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var isCorrect = isEmail.test(email);
//If email is invalid, stop user from entering data
if(!isCorrect)
{
emailText = "Username must be an email";
$("#usernameerror").css({"color": "red"});
document.getElementById("usernameerror").innerHTML = emailText;
usernameFilled = false;
}
else//If email is valid, pass the usernameFilled check
{
//Empty text
emailText = "";
$("#usernameerror").css({"color": "green"});
document.getElementById("usernameerror").innerHTML = emailText;
//Check if username already exists
$.ajax({
url: "check_if_username_available.php",
type: "post",
data: encodeURI("username=" + $("#username").val()),
success: function(data) {
if(data === "false") //If username exists prevent the user from entering the data and inform them
{
emailText = "Email already exists";
$("#usernameerror").css({"color": "red"});
document.getElementById("usernameerror").innerHTML = emailText;
usernameFilled = false;
}
else //If username is new, give the user an ok message
{
emailText = "Username is OK";
$("#usernameerror").css({"color": "green"});
document.getElementById("usernameerror").innerHTML = emailText;
usernameFilled = true;
}
},
error: function(data) {
alert("error! " + data);
}
});
}
}
//Check it all required fields are filled and enable/disable button if they
//are or are not respectively
if(usernameFilled && nameFilled && addressFilled && passwordFilled)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
//For the name field
$("#name").keyup(function(){
if($(this).val() === '')
{
nameFilled = false;
}
else
{
nameFilled = true;
}
//Check it all required fields are filled and enable/disable button if they
//are or are not respectively
if(usernameFilled && nameFilled && addressFilled && passwordFilled)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
//For the address field
$("#address").keyup(function(){
if($(this).val() === '')
{
addressFilled = false;
}
else
{
addressFilled = true;
}
//Check it all required fields are filled and enable/disable button if they
//are or are not respectively
if(usernameFilled && nameFilled && addressFilled && passwordFilled)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
//For phone field
$("#phone").keyup(function(){
var phoneText = "";
var phone = document.getElementById("phone").value;
//If phone field is empty check to see if all other required fields are filled
if($(this).val() === '')
{
//Empty text
phoneText = "";
$("#phoneerror").css({"color": "green"});
document.getElementById("phoneerror").innerHTML = phoneText;
//Check it all required fields are filled and enable/disable button if they
//are or are not respectively
if(usernameFilled && nameFilled && addressFilled && passwordFilled)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
}
else//If phone is filled, check to see if the entry is valid
{
var isCorrect = isNumber.test(phone);
//If phone number is invalid stop user from entering data
if(!isCorrect)
{
phoneText = "Phone number can only consist of numbers";
$("#phoneerror").css({"color": "red"});
document.getElementById("phoneerror").innerHTML = phoneText;
$("#userSubmit").prop("disabled", true);
}
else//Check to see if all required fields are filled
{
//Empty text
phoneText = "";
$("#phoneerror").css({"color": "green"});
document.getElementById("phoneerror").innerHTML = phoneText;
//Check it all required fields are filled and enable/disable button if they
//are or are not respectively
if(usernameFilled && nameFilled && addressFilled && passwordFilled)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
}
}
});
//For the password field
$("#password").keyup(function(){
//Get strings for both confirm and password
var pass = document.getElementById("password").value;
var confirm = document.getElementById("confirm").value;
//Contains the text for password strength
var passverify = "";
//Determines the strength of the password by checking for special character or number
var numberTest = /\d+/;
var specialTest = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;
//Test password for either a number or special character
var hasNumber = numberTest.test(pass);
var hasSpecial = specialTest.test(pass);
var hasLength = false;
//Check for password length
if (pass.length >= 8)//Check for length
{
hasLength = true;
}
else
{
hasLength = false;
}
//Show password strength
//If password is long and contains either a special character or number
if((hasSpecial || hasNumber) && hasLength)
{
passverify = "Password <PASSWORD>";
$("#passverification").css({"color": "green"});
document.getElementById("passverification").innerHTML = passverify;
}
else if(hasLength)//If password is long
{
passverify = "<PASSWORD>";
$("#passverification").css({"color": "orange"});
document.getElementById("passverification").innerHTML = passverify;
}
else//If neither
{
passverify = "<PASSWORD>";
$("#passverification").css({"color": "red"});
document.getElementById("passverification").innerHTML = passverify;
}
//If password is empty, clear text
if (pass === "")
{
//Empty Text
passverify = "";
$("#passverification").css({"color": "red"});
document.getElementById("passverification").innerHTML = passverify;
}
//If both password and confirm are filled check for match and
//change password filled to true if so or show error text if not
if(pass === "" || confirm === "")
{
passwordFilled = false;
}
else
{
//Test if confirm password is the same as password
if(pass === confirm)
{
text = "";
document.getElementById("test").innerHTML = text;
passwordFilled = true;
}
else
{
text = "Password and Confirm Password are different!";
$("#test").css({"color": "red"});
document.getElementById("test").innerHTML = text;
}
}
//Check it all required fields are filled and enable/disable button if they
//are or are not respectively
if(usernameFilled && nameFilled && addressFilled && passwordFilled)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
//For confirm
$("#confirm").keyup(function(){
var pass = document.getElementById("password").value;
var confirm = document.getElementById("confirm").value;
//If both password and confirm are filled check for match and
//change password filled to true if so or show error text if not
if($(this).val() === '' || pass === "")
{
passwordFilled = false;
}
else
{
//Test if confirm password is the same as password
if(pass === confirm)
{
text = "";
document.getElementById("test").innerHTML = text;
passwordFilled = true;
}
else
{
text = "Password and Confirm Password are different!";
$("#test").css({"color": "red"});
document.getElementById("test").innerHTML = text;
passwordFilled = false;
}
}
//Check it all required fields are filled and enable/disable button if they
//are or are not respectively
if(usernameFilled && nameFilled && addressFilled && passwordFilled)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
});<file_sep>/confirmation.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Icon set -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4 text-center text-white border-success">
<div class="card-body text-success">
<h1>Order placed!</h1>
</div>
</div>
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © Maxinami Games 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<file_sep>/purchaseHistoryDAO.php
<?php
/*
* 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.
*/
/**
* Description of purchaseHistoryDAO
*
* @author Nathan
*/
class purchaseHistoryDAO {
private $createSQL="INSERT INTO purchase_history (user_id,product_id,quantity,time_of_purchase) VALUES (?,?,?,?)";
private $selectByUserSQL="SELECT * FROM purchase_history WHERE user_id=? ORDER_BY (time_of_purchase) DESC";
private $selectByUserItemSQL="SELECT * FROM purchase_history WHERE product_id=? AND user_id=?";
private $selectByItemSQL="SELECT * FROM purchase_history WHERE product_id=?";
private $updateSQL="UPDATE purchase_history SET user_id=?,product_id=?,quantity=?,time_of_purchase=? WHERE user_id=? AND product_id=?";
private $deleteSQL="DELETE FROM purchase_history WHERE user_id=? AND product_id=? AND time_of_purchase=?";
function createPurchase($userID,$itemID,$quantity,$con) {
$statement=mysqli_prepare($con, $this->createSQL);
$time = time();
$mysqltime = date("Y-m-d H:i:s", $time);
$statement->bind_param("iiis",$userID,$itemID,$quantity, $mysqltime);
$statement->execute();
$statement->close();
}
function selectByUser($userId,$con){
$statement= mysqli_prepare($con, $this->selectByUserSQL);
$statement->bind_param("i", $userId);
$statement->bind_result($result);
$statement->execute();
$statement->close();
return $result;
}
function selectByItem($itemId,$con){
$statement= mysqli_prepare($con, $this->selectByItemSQL);
$statement->bind_param("i", $itemId);
$statement->bind_result($result);
$statement->execute();
$statement->close();
return $result;
}
function selectUserItem($userId,$itemId,$con){
$statement= mysqli_prepare($con, $this->selectByUserItemSQL);
$statement->bind_param("ii", $itemId,$userId);
// $statement->bind_result($result);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function deletePurchase($userId,$productId,$con){
$statement= mysqli_prepare($con, $this->deleteSQL);
$statement->bind_param("ii", $userId,$productId);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
function updatePurchase($userID,$itemID,$oldTimestamp,$newUserId,$newItemId,$quantity,$timestamp,$con) {
$statement=mysqli_prepare($con, $this->updateSQL);
$statement->bind_param("iiisiis",$newUserId,$newItemId,$quantity,$timestamp,$userID,$itemID,$oldTimestamp);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
}
<file_sep>/review.php
<?php session_start();
if ($_SERVER['REQUEST_METHOD'] != 'POST' ||
!isset($_POST['action']) ||
!isset($_POST['item-id']) ||
!isset($_SESSION['user_id']) ) {
header('Location: account.php');
}
require_once 'itemDAO.php';
require_once 'databaseConnector.php';
$db = new databaseConnector();
$con = $db->getConnection();
$itemDAO = new itemDAO();
$items = $itemDAO->selectByID($_POST['item-id'], $con);
if (count($items) == 1) {
$name = $items[0]->name;
$pictureLink=$items[0]->imageLink;
} else {
header('Location: account.php'); // ERROR: duplicate item found
}
require_once 'ratingService.php';
$ratingService = new ratingService();
$hasReviewed = $ratingService->hasReviewed($_SESSION['user_id'], $_POST['item-id'], $con);
if ($hasReviewed) {
$ratings = $ratingService->getRatings($_SESSION['user_id']);
while($row = mysqli_fetch_array($ratings, MYSQLI_ASSOC)) {
$id = $row['product_id'];
if ($id == $_POST['item-id']) {
$item_rating = $row['rating'];
$item_description = $row['description'];
break;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<link href="css/review.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4">
<img class="card-img-top img-fluid col-sm-6" src="imgs/<?php echo $pictureLink; ?>" alt="">
<div class="card-body">
<h1><?php echo ($hasReviewed ? "Update " : "Write a "); ?> Review</h1>
<h3 class="card-title"><?php echo $name; ?></h3>
<hr>
<form action="#">
<span id="item-id" hidden><?php echo $_POST['item-id']; ?></span>
<div class="form-group">
<h4>Rating:</h4>
<!--div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Rate from 1-5:</span>
</div>
<input type="text" class="form-control" aria-label="Rating (whole number out of 5)">
<div class="input-group-append">
<span class="input-group-text">/5</span>
</div>
</div-->
<div class="input-group mb-3">
<select class="custom-select" name="rating" id="rating">
<option <?php echo ($hasReviewed ? "" : "selected"); ?> disabled hidden>Select a rating...</option>
<option <?php echo ($hasReviewed && $item_rating == 1? "selected" : ""); ?> value="1">★ ☆ ☆ ☆ ☆ (1 star)</option>
<option <?php echo ($hasReviewed && $item_rating == 2? "selected" : ""); ?> value="2">★ ★ ☆ ☆ ☆ (2 stars)</option>
<option <?php echo ($hasReviewed && $item_rating == 3? "selected" : ""); ?> value="3">★ ★ ★ ☆ ☆ (3 stars)</option>
<option <?php echo ($hasReviewed && $item_rating == 4? "selected" : ""); ?> value="4">★ ★ ★ ★ ☆ (4 stars)</option>
<option <?php echo ($hasReviewed && $item_rating == 5? "selected" : ""); ?> value="5">★ ★ ★ ★ ★ (5 stars)</option>
</select>
</div>
<h4>Review:</h4>
<div class="input-group">
<textarea id="review-description" class="form-control" rows="6"><?php echo ($hasReviewed ? $item_description : ""); ?></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit-btn"><?php echo ($hasReviewed ? "Update" : "Submit"); ?></button>
</div>
</form>
</div>
</div>
<!-- /.card -->
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © <NAME> 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="scripts/review.js"></script>
</body>
</html>
<file_sep>/README.md
# maxinami_games
Final project for Web Programming Languages project
<file_sep>/search.php
<?php session_start();
function getRatingStarString($rating) {
/*
1 star: 0 - 1.49999
2 star: 1.5 - 2.499999
3 star: 2.5. - 3.499999
4 star: 3.5 - 4.499999
5 star: 4.5 - 5
*/
if($rating==0)
return "☆ ☆ ☆ ☆ ☆";
else if ($rating < 1.5)
return "★ ☆ ☆ ☆ ☆";
else if ($rating < 2.5)
return "★ ★ ☆ ☆ ☆";
else if ($rating < 3.5)
return "★ ★ ★ ☆ ☆";
else if ($rating < 4.5)
return "★ ★ ★ ★ ☆";
else
return "★ ★ ★ ★ ★";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<link href="css/search.css" rel="stylesheet">
<script type="text/javascript">
function itemsPerPage(val){
document.getElementById(val).selected = "true";
}
</script>
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li><li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<br>
<br>
<?php
$search=$_GET['search_item'];
include_once 'itemService.php';
$service=new itemService();
$result = $service->searchItem($search);
if(mysqli_num_rows($result)== 0){
echo "no results found";
}
else{
$rows=array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[]=$row;
}
if(isset($_POST['price'])){
if($_POST['price']=='0to10'){
$min=0;
$max=9.99;
}
elseif($_POST['price']=='10to20'){
$min=10;
$max=19.99;
}
elseif($_POST['price']=='20to40'){
$min=20;
$max=39.99;
}
elseif($_POST['price']=='40to70'){
$min=40;
$max=69.99;
}
elseif($_POST['price']=='70up'){
$min=70;
$max=PHP_FLOAT_MAX;
}
include_once 'sort_item.php';
$rows= sortByPrice($min, $max, $rows);
}
if(isset($_POST['rating'])){
if($_POST['rating']=='1'){
$min=0;
$max=1;
}
elseif($_POST['rating']=='2'){
$min=1;
$max=2;
}
elseif($_POST['rating']=='3'){
$min=2;
$max=3;
}
elseif($_POST['rating']=='4'){
$min=4;
$max=5;
}
elseif($_POST['rating']=='5'){
$min=70;
$max=PHP_FLOAT_MAX;
}
include_once 'sort_item.php';
$rows= sortByRating($_POST['rating'], $rows);
}
?>
<form id='priceSort' action = '' method = 'post'>Price Ranges    
<button name='price' id='price' value='0to10'> $0-$9.99  </button>
<button name='price' id='price' value='10to20'> $10-$19.99  </button>
<button name='price' id='price' value='20to40'> $20-$39.99  </button>
<button name='price' id='price' value='40to70'> $40-$69.99  </button>
<button name='price' id='price' value='70up'> above $70</button>
</form>
<br/>
<form id='ratingSort' action = '' method = 'post'>Minimum Rating  
<button name='rating' id='rating' value='1'> ★☆☆☆☆   </button>
<button name='rating' id='rating' value='2'> ★★☆☆☆   </button>
<button name='rating' id='rating' value='3'> ★★★☆☆   </button>
<button name='rating' id='rating' value='4'> ★★★★☆   </button>
<button name='rating' id='rating' value='5'> ★★★★★</button>
</form>
<br/>
<?php
$arraySize=sizeof($rows);
include 'pages.php';
$page = new pages();
$page->setArraySize($arraySize);
$currentPage=$page->getCurrentPage();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['perPage']))
{
if ($_POST['perPage']=='all')
$total=$arraySize;
else
$total=$_POST['perPage'];
$page->setItemsPerPage($total);
}
if(isset($_POST['pageNum'])){
$page->setCurrentPage((int)($_POST['pageNum']));
}
}
$currentPage=$page->getCurrentPage();
$pages=$page->setPages();
$itemsPerPage = $page->getItemsPerPage();
?>
<div id='page-buttons'>
<?php
if(sizeof($rows)==0)
echo "no results found";
else{
echo "<form id='pageform' action = '' method = 'post'>";
if($currentPage==1)
echo "<button id='pageNum' disabled>previous</button>";
else{
echo "<button name='pageNum' id='pageNum' value='".($currentPage-1)."'>previous</button>";
}
echo "</form>";
for($i=1;$i<=$pages;$i++){
echo "<form id='pageform' action = '' method = 'post'>";
if($i==$currentPage)
echo " <button id='pageNum' disabled>".$i."</button>";
else{
echo " <button id='pageNum' name='pageNum' value='".$i."'>".$i."</button>";
}
echo "</form>";
}
echo "<form id='pageform' action = '' method = 'post'>";
if($currentPage==$pages)
echo "<button id='pageNum' disabled>next</button>";
else{
echo "<button id='pageNum' name='pageNum' value='".($currentPage+1)."'>next</button>";
}
echo "</form>";
?>
<form action="" id='formid' method="POST">
<label>items per page: </label>
<select name='perPage' id='perPage' onchange="$('#formid').submit();" >
<option id='6' value='6'>6</option>
<option id='12' value='12'>12</option>
<option id='18' value='18'>18</option>
<option id='all' value='all'>all</option>
</select>
</form>
<script>itemsPerPage(<?php if($_POST['perPage']=='all') echo "'all'"; else echo $itemsPerPage;?>)</script>
</div>
<br/>
<div class="row">
<?php
for($i=($currentPage-1)*$itemsPerPage;$i<$currentPage*$itemsPerPage&&$i<$arraySize;$i++){
?>
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<a href=<?php echo "product.php?action=get_product&id=" . $rows[$i]["itemid"] ?>><img class="card-img-top" src=<?php echo 'imgs/'.$rows[$i]['pictureLink']?> alt=""></a>
<div class="card-body">
<h4 class="card-title">
<a href=<?php echo "product.php?action=get_product&id=" . $rows[$i]["itemid"] ?>><?php echo $rows[$i]['name']?></a>
</h4>
<h5>$<?php echo number_format($rows[$i]['price'], 2, '.', '');?></h5>
<p class="card-text" id="description"><?php echo $rows[$i]['description']?></p>
</div>
<div class="card-footer">
<small class="<?php echo ($rows[$i]['rating'] > 0 ? 'text-warning' : 'text-muted'); ?>">
<?php echo getRatingStarString($rows[$i]['rating']); ?>
</small>
</div>
</div>
</div>
<?php
}
?>
</div>
<!-- /.row -->
<?php
echo "<form id='pageform' action = '' method = 'post'>";
if($currentPage==1)
echo "<button id='pageNum' disabled>previous</button>";
else{
echo "<button name='pageNum' id='pageNum' value='".($currentPage-1)."'>previous</button>";
}
echo "</form>";
for($i=1;$i<=$pages;$i++){
echo "<form id='pageform' action = '' method = 'post'>";
if($i==$currentPage)
echo " <button id='pageNum' disabled>".$i."</button>";
else{
echo " <button id='pageNum' name='pageNum' value='".$i."'>".$i."</button>";
}
echo "</form>";
}
echo "<form id='pageform' action = '' method = 'post'>";
if($currentPage==$pages)
echo "<button id='pageNum' disabled>next</button>";
else{
echo "<button id='pageNum' name='pageNum' value='".($currentPage+1)."'>next</button>";
}
echo "</form>";
}
}
?>
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © Maxinami Games 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- <script src="scripts/pages.js"></script> -->
</body>
</html>
<file_sep>/scripts/adminaccount.js
$(document).ready(function() {
// Toggle content when respective tab is clicked
$("#order-history-tab").click(function(event) {
event.preventDefault();
$("#order-history-tab").addClass("active");
$("#account-info-tab").removeClass("active");
$("#modify-items-tab").removeClass("active");
$("#modify-items-card").addClass("hidden");
$("#account-info-card").addClass("hidden");
$("#order-history-card").removeClass("hidden");
});
$("#account-info-tab").click(function(event) {
event.preventDefault();
$("#account-info-tab").addClass("active");
$("#order-history-tab").removeClass("active");
$("#modify-items-tab").removeClass("active");
$("#modify-items-card").addClass("hidden");
$("#order-history-card").addClass("hidden");
$("#account-info-card").removeClass("hidden");
});
$("#modify-items-tab").click(function(event) {
event.preventDefault();
$("#modify-items-tab").addClass("active");
$("#order-history-tab").removeClass("active");
$("#account-info-tab").removeClass("active");
$("#order-history-card").addClass("hidden");
$("#account-info-card").addClass("hidden");
$("#modify-items-card").removeClass("hidden");
});
$('.inventory').change(function() {
var inventory = $(this).val();
if (validateIntegerInventory(inventory)) {
$.ajax({
url: "admin_update_itemlist.php",
type: "post",
data: encodeURI("action=update_inventory&id=" + $(this).parent().siblings(".item-id").html() + "&inventory=" + inventory),
success: function(data) {
},
error: function() {
alert("error!");
}
});
} else {
alert("ERROR: Quantities must be nonnegative integer values.");
//location.reload();
}
});
// returns true if qty is a postive integer (or string equivalent)
function validateIntegerInventory(inventory) {
if (Number.isInteger(inventory) && inventory >= 0)
return true;
if(typeof(inventory) === 'string') {
var onlyDigits = inventory.match(new RegExp(/^[0-9]+$/, 'g'));
if (onlyDigits)
return true;
else
return false;
}
return false;
};
$('.delete-btn').click(function() {
$.ajax({
url: "admin_update_itemlist.php",
type: "post",
data: encodeURI("action=disable_item" + "&id=" + $(this).parent().siblings(".item-id").html()),
success: function(data) {
//alert(data);
location.reload();
},
error: function(data) {
alert("error! " + data);
}
});
});
$('.update-btn').click(function() {
location.href = "product_info_form.php?" + encodeURI("action=update_product" + "&id=" + $(this).parent().siblings(".item-id").html());
});
});<file_sep>/checkoutitems.php
<?php
session_start();
require_once 'userService.php';
if($_SERVER["REQUEST_METHOD"] == "POST"){
require_once 'purchaseService.php';
$purchaseService = new purchaseService();
// Check out as user
if (isset($_SESSION['user_name'])) {
$result = $purchaseService->userPurchase($_SESSION['user_id']);
if (is_array($result)) {
foreach ($result as $item) {
if (!$item['outcome']) {
$_SESSION['cart'][$item['id']] = $item['inventory'];
}
}
?>
<form id="failForm" action="fail.php" method="post">
<input type="text" name="result_arr" value="<?php echo urlencode(json_encode($result)); ?>" />
</form>
<script>
document.getElementById('failForm').submit();
</script>
<?php
}
else if ($result != FALSE) {
// Purchase successful
unset($_SESSION['cart']);
session_write_close();
header('Location: confirmation.php');
} else {
// Tried to purchase nothing
die("Something went wrong");
}
}
// Create new account, then check out as guest
else if(isset($_POST['create-check'])) {
$ERR="";
$servername = 'localhost';
$serverusername = 'root';
$serverpassword = '';
if(empty($_POST["username"])){
$ERR = "Username is Required";
}
else{
$username = test_input($_POST["username"]);
}
if(empty($_POST["name"])){
$ERR = "Name is Required";
}
else{
$fullname = test_input($_POST["name"]);
}
if(empty($_POST["address"])){
$ERR = "Address is Required";
}
else{
$address = test_input($_POST["address"]);
}
if(empty($_POST["password"])){
$ERR = "Password is Required";
}
else{
$password = test_input($_POST["password"]);
}
if(empty($_POST["confirm"])){
$ERR = "Confirm password is Required";
}
else{
$confirm = test_input($_POST["confirm"]);
}
//Test if confirm password is the same as password
if(strcmp($password, $confirm))
{
$ERR = "Password and Confirm Password are different!";
}
//If required fields are empty or passwords are different, return to account create
if(!empty($ERR)){
header('Location: account_create.php');
exit();
}
else{
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$fullname = $_POST['name'];
$address= $_POST['address'];
$phone = '';
if (isset($_POST['phone']))
$phone = $_POST['phone'];
//Encrypt password
$userpass = password_hash($_POST['password'], PASSWORD_BCRYPT);
$add = new userService();
$id = $add->addUser($username,$fullname,$address,$userpass,$phone,1);
if($id != -1)
{
session_regenerate_id();
$_SESSION['user_name'] = $username;
$_SESSION['fullname'] = $fullname;
$_SESSION['phone'] = $phone;
$_SESSION['user_status'] = 1;
$_SESSION['address'] = $address;
$_SESSION['user_id'] = $id;
load_cart();
$result = $purchaseService->userPurchase($_SESSION['user_id']);
if ($result) {
unset($_SESSION['cart']);
header('Location: confirmation.php');
} else {
die("Something went wrong");
}
session_write_close();
}
else
{
header('Location: account_create.php');
exit();
}
}
}
// Checkout as guest
else {
$result = $purchaseService->anonymousPurchase($_SESSION['cart']);
if (is_array($result)) {
// Tried to purchase too much
foreach ($result as $item) {
if (!$item['outcome']) {
$_SESSION['cart'][$item['id']] = $item['inventory'];
}
}
?>
<form id="failForm" action="fail.php" method="post">
<input type="text" name="result_arr" value="<?php echo urlencode(json_encode($result)); ?>" />
</form>
<script>
document.getElementById('failForm').submit();
</script>
<?php
}
else if ($result != FALSE) {
// Purchase successful
unset($_SESSION['cart']);
session_write_close();
header('Location: confirmation.php');
} else {
// Tried to purchase nothing
die("Something went wrong");
}
}
} else {
header('Location: index.php');
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function load_cart() {
// Load cart from database
require_once 'cartService.php';
$cartService = new cartService();
if (!isset($_SESSION['cart'])) { // create cart if not created yet
$_SESSION['cart'] = [];
}
$cartService->moveCartToUser($_SESSION['user_id'],$_SESSION['cart']);
$result = $cartService->getCart($_SESSION['user_id']);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$itemid = $row['product_id'];
$quantity = $row['quantity'];
$_SESSION['cart'][$itemid] = $quantity;
}
}
?><file_sep>/Item.php
<?php
/*
* 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.
*/
/**
* Description of Item
*
* @author Nathan
*/
class Item {
var $name;
var $id;
var $description;
var $price;
var $rating;
var $imageLink;
var $number;
var $type;
function __construct($id=null,$productName=null,$description=null,$price=0.0,$type=0,$rating=5.0,$inventory=0,$imageLink=null) {
$this->name=$productName;
$this->id=$id;
$this->description=$description;
$this->imageLink=$imageLink;
$this->number=$inventory;
$this->price=$price;
$this->type=$type;
$this->rating=$rating;
}
}
<file_sep>/itemService.php
<?php
require_once 'databaseConnector.php';
require_once 'itemDAO.php';
require_once 'ItemQuery.php';
/**
* Description of itemService
*TODO queryItem
* @author Nathan
*/
class itemService {
var $connector;
var $itemAccess;
public function __construct() {
$this->connector=new databaseConnector();
$this->itemAccess=new itemDAO();
}
function addItem($name,$description,$price,$inventory,$pictureLink,$type,$rating){
try{
$con= $this->connector->getConnection();
return $this->itemAccess->createItem($name,$description,$price,$inventory,$pictureLink,$type,$rating, $con);
}
finally {
$con->close();
}
}
function searchItem($queryString){
try{
$con=$this->connector->getConnection();
$itemQuery= new ItemQuery(mysqli_real_escape_string($con,$queryString));
return $this->itemAccess->selectByQuery($itemQuery, $con);
}
finally{
$con->close();
}
}
function makeInactive($id){
try{
$con= $this->connector->getConnection();
$con->begin_transaction();
$result=$this->itemAccess->selectByID($id, $con);
if(count($result)==1){
$item=$result[0];
$item->type=0;
$number= $this->itemAccess->updateUsingItem($item, $con);
$this->determineAction($number, $con);
}
return false;
}
finally {
// mysqli_free_result($result);
$con->close();
}
}
function adjustInventory($id,$quantity){
try{
$con= $this->connector->getConnection();
$con->begin_transaction();
$result=$this->itemAccess->selectByID($id, $con);
if(count($result)==1){
$item=$result[0];
$item->number=$quantity;
$number= $this->itemAccess->updateUsingItem($item, $con);
return $this->determineAction($number, $con);
}
return false;
}
finally {
// mysqli_free_result($result);
$con->close();
}
}
function modifyItem($id,$name,$description,$price,$inventory,$pictureLink,$type,$rating){
try{
$con= $this->connector->getConnection();
$item=new Item($id,$name,$description,$price,$type,$rating,$inventory,$pictureLink);
$con->begin_transaction();
$number= $this->itemAccess->updateUsingItem($item, $con);
return $this->determineAction($number, $con);
}
finally {
$con->close();
}
}
function deleteItem($id){
try{
$con= $this->connector->getConnection();
$con->begin();
$number= $this->itemAccess->deleteItem($id, $con);
return $this->determineAction($number, $con);
}
finally {
$con->close();
}
}
private function determineAction($number,$con){
if(!is_int($number)||$number!=1){
$con->rollback();
return false;
}
else{
$con->commit();
return true;
}
}
}
<file_sep>/addtocart.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'])) {
$itemid = $_POST['id'];
// User is logged in, store in session and database
if (isset($_SESSION['user_name'])) {
// If user is logged in, store cart items in database
require_once 'cartService.php';
$cartService = new cartService();
if (!isset($_SESSION['cart'])) { // create cart if not created yet
$_SESSION['cart'] = [];
}
if (!isset($_SESSION['cart'][$itemid]) || $_SESSION['cart'][$itemid] == 0) { // create entry for item in cart if not created yet
$_SESSION['cart'][$itemid] = 1;
// also create entry in database
$cartService->addItem($_SESSION['user_id'], $itemid, 1);
}
else {
// update quantity of item in cart and database
$_SESSION['cart'][$itemid] += 1;
$cartService->updateItem($_SESSION['user_id'], $itemid, $_SESSION['cart'][$itemid]);
}
session_write_close();
//var_dump($_SESSION['cart']);
//header('Location: product.php?id=' . $itemid);
}
// User is not logged in, just store in session
else {
if (!isset($_SESSION['cart'])) { // create cart if not created yet
$_SESSION['cart'] = [];
}
if (!isset($_SESSION['cart'][$itemid])) { // create entry for item in cart if not created yet
$_SESSION['cart'][$itemid] = 0;
}
$_SESSION['cart'][$itemid] += 1;
session_write_close();
//var_dump($_SESSION['cart']);
header('Location: product.php?id=' . $itemid);
}
} else {
header('Location: cart.php');
}
?><file_sep>/itemDAO.php
<?php
require_once 'Item.php';
require_once 'ItemQuery.php';
/*
* 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.
*/
/**
* Description of itemDAO
* TODO Select by QueryItem
* @author Nathan
*/
class itemDAO {
private $createSQL="INSERT INTO items (name,description,price,inventory,pictureLink,type,rating) VALUES (?,?,?,?,?,?,?)";
private $selectByIdSQL="SELECT * FROM items WHERE itemid=?";
private $updateSQL="UPDATE items SET name=?,description=?,price=?,inventory=?,pictureLink=?,type=?,rating=? WHERE itemid=?";
private $deleteSQL="DELETE FROM items WHERE itemid=?";
private $searchSQL='SELECT * FROM items WHERE type > "0"';
private $reduceQuantitySQL="UPDATE items SET inventory=inventory-? WHERE itemid=? AND inventory>=?";
function createItem($name,$description,$price,$inventory,$pictureLink,$type,$rating,$con) {
$statement=mysqli_prepare($con, $this->createSQL);
$statement->bind_param("ssdisid",$name,$description,$price,$inventory,$pictureLink,$type,$rating );
$statement->execute();
$id=$statement->insert_id;
$statement->close();
return $id;
}
function selectByID($id,$con){
$statement= mysqli_prepare($con, $this->selectByIdSQL);
$statement->bind_param("i", $id);
$statement->execute();
$result=$statement->get_result();
$items=[];
if(mysqli_num_rows($result)>0){
while($row= mysqli_fetch_array($result,MYSQLI_ASSOC)){
$name=$row["name"];
$price=$row["price"];
$description=$row["description"];
$inventory=$row["inventory"];
$type=$row["type"];
$pictureLink=$row["pictureLink"];
$rating=$row["rating"];
array_push($items,new Item($id,$name,$description,$price,$type,$rating,$inventory,$pictureLink));
}
}
$statement->close();
return $items;
}
function selectByQuery($itemQuery,$con){
if($itemQuery instanceof ItemQuery){
$query= $this->searchSQL.$itemQuery->createSQL();
$result=mysqli_query($con, $query);
return $result;
}
}
function deleteItem($id,$con){
$statement= mysqli_prepare($con, $this->deleteSQL);
$statement->bind_param("i", $id);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
function updateItem($id,$name,$description,$price,$inventory,$pictureLink,$type,$rating,$con) {
$statement=mysqli_prepare($con, $this->updateSQL);
$statement->bind_param("ssdisidi",$name,$description,$price,$inventory,$pictureLink,$type,$rating,$id);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
function updateUsingItem($item,$con){
if(is_a($item, "Item")){
return $this->updateItem($item->id, $item->name, $item->description, $item->price, $item->number, $item->imageLink, $item->type, $item->rating, $con);
}
return 0;
}
function reduceQuantity($id,$quantity,$con){
$statement= mysqli_prepare($con, $this->reduceQuantitySQL);
$statement->bind_param("iii", $quantity,$id,$quantity);
$statement->execute();
$result=$statement->affected_rows;
return $result;
}
}
<file_sep>/ItemQuery.php
<?php
/*
* 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.
*/
/**
* Description of ItemQuery
*
* @author Nathan
*/
class ItemQuery {
var $types;
var $price;
var $strings;
var $order;
var $minQuantity;
var $ratingMin;
const boardgame=1;
const videogame=2;
const cardgame=3;
const giftcard=4;
const price="price";
const quantity="inventory";
const rating="rating";
const asc="ASC";
const desc="DESC";
const all="%all%";
function __construct($queryString) {
$this->types=[];
$this->price=["max"=>0,"min"=>INF];
$this->strings=[];
$this->order=["orderValue"=>ItemQuery::quantity,"direction"=> ItemQuery::desc];
$this->minQuantity=1;
$this->ratingMin=0;
if(is_string($queryString)){
$parts= preg_split("/[\s,]+/", $queryString);
for($i=0;$i<count($parts);$i++){
$i+= $this->process($parts,$i);
}
}
}
function createSQL(){
$s="";
$s.=$this->typeSQL();
$s.=" AND inventory >= \"".$this->minQuantity."\"";
$s.=" AND rating >= \"". $this->ratingMin."\"";
$s.= $this->priceSQL();
foreach ($this->strings as $value){
$s.=" AND (name LIKE \"%".$value."%\" OR description LIKE \"%".$value."%\")";
}
$s.=" ORDER BY ".$this->order["orderValue"]." ".$this->order["direction"];
return $s;
}
private function typeSQL(){
$s="";
for($i=0;$i<count($this->types);$i++){
if($i==0){
$s.=" AND (";
}
else{
$s.=" OR";
}
$s.=" type = '".$this->types[$i]."'";
}
if(count($this->types)>0){
$s.=")";
}
return $s;
}
private function priceSQL(){
if(!$this->price["max"]<$this->price["min"]){
$s=" AND price BETWEEN ";
if($this->price["max"]== $this->price["min"]){
$s.="".($this->price["max"]-5)." AND ".($this->price["max"]+5);
}else {
$s.="".$this->price["min"]." AND ".$this->price["max"];
}
return $s;
}
return "";
}
function process($queryParts,$index){
if(strstr($queryParts[$index],"$")!==FALSE&&empty(strstr($queryParts[$index], "$", TRUE))){
$this->addPrice($queryParts, $index);
}elseif (strcmp($queryParts[$index],"%rtd")==0) {
return $this->changeRating($queryParts, $index);
}elseif (strcmp($queryParts[$index],"%ordr")==0) {
return $this->changeOrder($queryParts, $index);
}elseif (strcmp($queryParts[$index],"%cardgame")==0|| strcmp($queryParts[$index], "%boardgame") == 0||strcmp($queryParts[$index],"%videogame")==0||strcmp($queryParts[$index],"%giftcard")==0) {
$this->addType($queryParts[$index]);
//$index==0&&
}elseif (strcmp($queryParts[$index], ItemQuery::all)==0) {
return $this->allSearch($queryParts,$index);
}
else{
$this->addString($queryParts[$index]);
}
return 0;
}
private function allSearch($queryParts,$index){
$this->minQuantity=0;
for($i=$index+1;$i<count($queryParts);$i++){
if(strcmp($queryParts[$index],"ordr")==0) {
$this->changeOrder($queryParts, $index);
$i= count($queryParts);
}
}
return $i;
}
private function changeOrder($queryParts,$index){
if(count($queryParts)>$index+1){
$goodOrder= $this->changeOrderCategory($queryParts[$index+1]);
if($goodOrder>0&& count($queryParts)>$index+2){
$goodOrder+= $this->changeOrderDirection($queryParts[$index+2]);
}
return $goodOrder;
}
return 0;
}
private function changeOrderCategory($category){
if(strcmp($category, ItemQuery::price)==0){
$this->order["orderValue"]= ItemQuery::price;
return 1;
}
if(strcmp($category, ItemQuery::quantity)==0){
$this->order["orderValue"]= ItemQuery::quantity;
return 1;
}
if(strcmp($category, ItemQuery::rating)==0){
$this->order["orderValue"]= ItemQuery::rating;
return 1;
}
return 0;
}
private function changeOrderDirection($direction){
if(strcmp($direction, "asc")==0){
$this->order["direction"]= ItemQuery::asc;
return 1;
}
if(strcmp($direction, "desc")==0){
$this->order["direction"]= ItemQuery::desc;
return 1;
}
return 0;
}
private function addString($searchItem){
array_push($this->strings,$searchItem);
}
private function addType($type) {
$typeval= ItemQuery::boardgame;
switch ($type){
case "%videogame":{
$typeval= ItemQuery::videogame;
break;
}
case "%cardgame":{
$typeval= ItemQuery::cardgame;
break;
}
case "%giftcard" :
$typeval= ItemQuery::giftcard;
}
array_push($this->types,$typeval);
}
private function addPrice($queryParts,$index) {
preg_match("/[\d]+(\.[\d]+)?/", $queryParts[$index], $matches);
foreach ($matches as $value){
$this->price["min"]= min($value, $this->price["min"]);
$this->price["max"]= max($value, $this->price["max"]);
}
}
private function changeRating($queryParts,$index){
if(count($queryParts)>$index+1){
preg_match("/[\d]+(\.[\d]+)?/", $queryParts[$index+1], $matches);
foreach ($matches as $value){
$this->ratingMin= max($value, $this->ratingMin);
}
return 1;
}
return 0;
}
}
<file_sep>/shoppingCartDAO.php
<?php
/*
* 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.
*/
/**
* Description of shoppingCartDAO
*
* @author Nathan
*/
class shoppingCartDAO {
private $createSQL="INSERT INTO shopping_cart (user_id,product_id,quantity) VALUES (?,?,?)";
private $selectByUserSQL="SELECT * FROM shopping_cart WHERE user_id=?";
private $selectByUserItemSQL="SELECT * FROM shopping_cart WHERE user_id=? AND product_id=?";
private $updateSQL="UPDATE shopping_cart SET quantity=? WHERE user_id=? AND product_id=?";
private $deleteSQL="DELETE FROM shopping_cart WHERE user_id=? AND product_id=?";
function createCartItem($userID,$itemID,$quantity,$con) {
$statement=mysqli_prepare($con, $this->createSQL);
$statement->bind_param("iii",$userID,$itemID,$quantity);
$statement->execute();
$num=$statement->affected_rows;
$statement->close();
return $num;
}
function selectByUserAndItem($userId,$itemID,$con){
$statement= mysqli_prepare($con, $this->selectByUserItemSQL);
$statement->bind_param("ii", $userId,$itemID);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function selectByUser($userId,$con){
$statement= mysqli_prepare($con, $this->selectByUserSQL);
$statement->bind_param("i", $userId);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function deleteCartItem($userId,$productId,$con){
$statement= mysqli_prepare($con, $this->deleteSQL);
$statement->bind_param("ii", $userId,$productId);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
function updatePurchase($userID,$itemID,$quantity,$con) {
$statement=mysqli_prepare($con, $this->updateSQL);
$statement->bind_param("iii",$quantity,$userID,$itemID);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
}
<file_sep>/userDAO.php
<?php
/**
* Description of userDAO
*
* @author Nathan
*/
class userDAO {
private $createSQL="INSERT INTO users (username,fullname,address,hashedpass,phonenumber,status) VALUES (?,?,?,?,?,?)";
private $selectByIdSQL="SELECT * FROM users WHERE user_id=?";
private $selectByUsernameSQL="SELECT user_id, username, hashedpass FROM users WHERE username=?";
private $updateSQL="UPDATE users SET username=?, fullname=?, address=?, hashedpass=?, phonenumber=?, status=? WHERE user_id=?";
private $deleteSQL="DELETE FROM users WHERE user_id=?";
function createUser($email,$name,$address,$password,$phoneNum,$status,$con) {
$statement=mysqli_prepare($con, $this->createSQL);
$statement->bind_param("sssssi", $email,$name,$address,$password,$phoneNum,$status);
$statement->execute();
$id=$statement->insert_id;
$statement->close();
return $id;
}
function selectByUsername($username,$con){
$statement= mysqli_prepare($con, $this->selectByUsernameSQL);
$statement->bind_param("s", $username);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function selectByID($id,$con){
$statement= mysqli_prepare($con, $this->selectByIdSQL);
$statement->bind_param("i", $id);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function deleteUser($id,$con){
$statement= mysqli_prepare($con, $this->deleteSQL);
$statement->bind_param("i", $id);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
function updateUser($id,$email,$name,$address,$password,$phoneNum,$status,$con) {
$statement=mysqli_prepare($con, $this->updateSQL);
$statement->bind_param("sssssii", $email,$name,$address,$password,$phoneNum,$status,$id);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
}
<file_sep>/product.php
<?php
session_start();
function getRatingStarString($rating) {
/*
1 star: 0 - 1.49999
2 star: 1.5 - 2.499999
3 star: 2.5. - 3.499999
4 star: 3.5 - 4.499999
5 star: 4.5 - 5
*/
if($rating==0)
return "☆ ☆ ☆ ☆ ☆";
else if ($rating < 1.5)
return "★ ☆ ☆ ☆ ☆";
else if ($rating < 2.5)
return "★ ★ ☆ ☆ ☆";
else if ($rating < 3.5)
return "★ ★ ★ ☆ ☆";
else if ($rating < 4.5)
return "★ ★ ★ ★ ☆";
else
return "★ ★ ★ ★ ★";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<link href="css/product.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4">
<?php
if(isset($_GET['id'])) {
$product_name = 'A Product';
$product_description = 'A description of the product';
$product_price = "$50.00";
$product_avg_rating = 2.33;
$product_rating_string = getRatingStarString($product_avg_rating);
$product_id = (int)$_GET['id'];
require_once 'ratingService.php';
$ratingService = new ratingService();
$ratingService->refreshItemRating($product_id);
require_once 'databaseConnector.php';
require_once 'itemDAO.php';
$db = new databaseConnector();
$con = $db->getConnection();
$item_dao = new itemDAO();
$items = $item_dao->selectByID($product_id, $con);
if (count($items) == 1) {
$product_name = $items[0]->name;
$product_description = $items[0]->description;;
$product_price = $items[0]->price;
$product_avg_rating = $items[0]->rating;
$product_rating_string = getRatingStarString($product_avg_rating);
$product_img_link = $items[0]->imageLink;
} else {
// product id not found
header('Location: signIn.php');
}
$product_img_uri = "imgs/" . $product_img_link;
} else {
// $product_name = 'Product Name';
// $product_price = '$24.99';
// $product_description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente dicta fugit fugiat hic aliquam itaque facere, soluta. Totam id dolores, sint aperiam sequi pariatur praesentium animi perspiciatis molestias iure, ducimus!';
// $product_avg_rating = 4.0;
// $product_rating_string = getRatingStarString($product_avg_rating);
// $product_id = '-1';
// $product_img_uri = "http://placehold.it/900x400";
// redirect back to home (no valid product to show)
header('Location: index.php');
}
?>
<img class="card-img-top img-fluid col-sm-6" src="<?php echo $product_img_uri; ?>" alt="">
<div class="card-body">
<h3 class="card-title"><?php echo $product_name; ?></h3>
<h4>$<?php echo number_format((float)$product_price, 2, '.', ''); ?></h4>
<p class="card-text line-breaks-wrap"><?php echo $product_description; ?></p>
<span id="product-avg-rating" class="<?php echo ($product_avg_rating > 0 ? 'text-warning' : 'text-muted'); ?>"><?php echo $product_rating_string; ?></span>
<?php
if ($product_avg_rating!=0){
echo number_format((float)$product_avg_rating, 1, '.', ''); ?> stars
<?php
}
else{
echo "This product has not been rated yet";
}
?>
<hr>
<span class="itemid" hidden><?php echo $product_id; ?></span>
<button type="button" id="add-to-cart-btn" class="btn btn-success">Add to Cart</button>
</div>
</div>
<!-- /.card -->
<div class="card card-outline-secondary my-4">
<div class="card-header">
Product Reviews
</div>
<div class="card-body">
<?php
$result = mysqli_query($con, "SELECT * FROM user_rating WHERE product_id= ".$_GET["id"].";");
if ( mysqli_num_rows($result)== 0) {
echo "This product has not been rated yet";
} else {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
?>
<span class="text-warning"><?php
$rating=(int)$row['rating'];
for($stars=5;$stars>0;$stars--){
if ($rating>0){
$rating--;
?>
★
<?php
}
else{
?>
☆
<?php
}
}
?></span>
<p class="line-breaks-wrap"><?php echo $row['description']?></p>
<?php $user=mysqli_query($con, "SELECT * FROM users WHERE users.user_id= ".$row['user_id'].";");
$username=mysqli_fetch_array($user, MYSQLI_ASSOC)?>
<small class="text-muted">Posted by <?php echo $username['username']?></small>
<hr>
<?php }
}?>
</div>
</div>
</div>
<!-- /.card -->
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © Maxinami Games 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="scripts/product.js"></script>
</body>
</html>
<file_sep>/admin_update_itemlist.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
function update_inventory() {
if(isset($_POST['id']) && isset($_POST['inventory'])) {
$itemid = $_POST['id'];
// User is logged in as admin, proceed
if (isset($_SESSION['user_name']) && $_SESSION['user_status'] == 0) {
$inventory = (int)$_POST['inventory'];
if ($inventory >= 0) {
require_once 'itemService.php';
$itemService = new itemService();
$itemService->adjustInventory($itemid, $inventory);
exit();
}
die("Invalid inventory value");
}
// User is not logged in, can't perform action
else {
die("Not logged in!");
}
}
}
function disable_item() {
// User is logged in as admin, proceed
if (isset($_SESSION['user_name']) && $_SESSION['user_status'] == 0) {
if(isset($_POST['id'])) {
$itemid = $_POST['id'];
require_once 'itemService.php';
$itemService = new itemService();
$itemService->makeInactive($itemid);
exit("Disabled item " . $itemid);
} else {
die("Error");
}
} else {
die("Not logged in!");
}
}
function add_item() {
// User uploaded a file
if (is_uploaded_file($_FILES['product-image']['tmp_name'])) {
echo "file found\n";
$result = upload_file();
$success = $result['upload_successful'];
if ($success) {
$pictureLink = $result['filename'];
} else {
$pictureLink = "_placeholder_image.png";
}
} else { // No file was selected
$pictureLink = "_placeholder_image.png";
}
//exit("Picture: " . $pictureLink);
$name = $_POST['product-name'];
$type = $_POST['product-type'];
$description = $_POST['product-description'];
$inventory = $_POST['product-inventory'];
$price = $_POST['product-price'];
$rating = 0;
require_once 'itemService.php';
$itemService = new itemService();
$itemService->addItem($name,$description,$price,$inventory,$pictureLink,$type,$rating);
}
function upload_file() {
$target_dir = getcwd() . "/imgs/";
$target_file = $target_dir . basename($_FILES["product-image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["product-image"]["tmp_name"]);
if($check == false) {
echo "File is not an image.\n";
return array('upload_successful' => false);
}
}
// If file already exists, append (different) number to end
while (file_exists($target_file)) {
// fakepath/imgs/imagefile(2).png
if (preg_match("/^(.*)\(([0-9]+)\).(png|jpg|jpeg|gif)$/", $target_file, $matches)) {
$nextnum = (int)$matches[2] + 1;
$target_file = $matches[1] . "(" . $nextnum . ")." . $matches[3];
} else { // fakepath/imgs/imagefile.png
preg_match("/^(.*).(png|jpg|jpeg|gif)$/", $target_file, $matches);
$target_file = $matches[1] . "(1)." . $matches[2];
}
}
// Check file size
if ($_FILES["product-image"]["size"] > 500000) {
echo "File is too large.\n";
return array('upload_successful' => false);
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Unsupported file extension. Only .jpg, .jpeg, .png, and .gif are supported.\n";
return array('upload_successful' => false);
}
if (move_uploaded_file($_FILES["product-image"]["tmp_name"], $target_file)) {
echo "The file " . basename($target_file) . " has been uploaded.\n";
return array('upload_successful' => true, 'filename' => basename($target_file));
} else {
echo "Error uploading file.\n";
return array('upload_successful' => false);
}
}
function update_item() {
require_once 'itemDAO.php';
require_once 'databaseConnector.php';
$db = new databaseConnector();
$con = $db->getConnection();
$itemDAO = new itemDAO();
$items = $itemDAO->selectByID($_POST['id'], $con);
if (count($items) == 1) {
$pictureLinkLabel=$items[0]->imageLink;
$rating=$items[0]->rating;
} elseif (count($items) == 0) {
die("ERROR: ID not found.");
} else {
die("ERROR: Duplicate ID found.");
}
// User uploaded a file
if (is_uploaded_file($_FILES['product-image']['tmp_name'])) {
echo "file found\n";
$result = upload_file();
$success = $result['upload_successful'];
if ($success) {
$pictureLink = $result['filename'];
} else {
// keep old image
$pictureLink = $pictureLinkLabel;
}
} else { // No file was selected, keep old image
$pictureLink = $pictureLinkLabel;
}
//exit("Picture: " . $pictureLink);
$name = $_POST['product-name'];
$type = $_POST['product-type'];
$description = $_POST['product-description'];
$description = htmlentities($description);
$inventory = $_POST['product-inventory'];
$price = $_POST['product-price'];
require_once 'itemService.php';
$itemService = new itemService();
$itemService->modifyItem($_POST['id'],$name,$description,$price,$inventory,$pictureLink,$type,$rating);
}
switch($_POST['action']) {
case 'update_inventory':
update_inventory();
break;
case 'disable_item':
disable_item();
break;
case 'add_item':
add_item();
break;
case 'update_item':
update_item();
break;
default:
die("No matching action");
}
} else {
die();
}
?><file_sep>/checkout.php
<?php session_start();
$signedIn = isset($_SESSION['user_id']);
if (!isset($_SESSION['cart']) || count($_SESSION['cart']) == 0) {
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Icon set -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<link href="css/cart.css" rel="stylesheet">
<link href="css/account.css" rel="stylesheet">
<link href="css/checkout.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item active">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4">
<div class="card-body">
<h1>Checkout</h1>
<hr>
<form id="checkout-form" method="post" action="checkoutitems.php">
<div class="form-group">
<label for="name">*Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" value="<?php echo ($signedIn ? $_SESSION['fullname'] : ''); ?>">
</div>
<div class="form-group">
<label for="address">*Address</label>
<input name="address" type="address" class="form-control" id="address" aria-describedby="address" value="<?php echo ($signedIn ? $_SESSION['address'] : ''); ?>">
</div>
<div class="form-group">
<label for="email">*Email</label>
<input name="username" type="email" class="form-control" id="email" aria-describedby="email" value="<?php echo ($signedIn ? $_SESSION['user_name'] : ''); ?>">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="tel" class="form-control" id="phone" aria-describedby="phone" value="<?php echo ($signedIn ? $_SESSION['phone'] : ''); ?>">
</div>
<div class="form-group">
<label for="credit-card">*Credit Card</label>
<input type="credit-card" class="form-control" id="credit-card" aria-describedby="credit-card">
</div>
<div <?php echo (isset($_SESSION['user_id']) ? "hidden" : ""); ?> class="form-group">
<label for="create-account-check">Create Account</label>
<input name="create-check" type="checkbox" class="form-control" id="create-account-check" aria-describedby="createAccount">
</div>
<div id="password-input-group" class="hidden">
<div class="form-group">
<label for="password">*Create a password</label>
<input name="password" type="<PASSWORD>" class="form-control" id="password" aria-describedby="password">
</div>
<div class="form-group">
<label for="password-verify">*Verify password</label>
<input name="confirm" type="<PASSWORD>" class="form-control" id="password-verify" aria-describedby="password">
</div>
</div>
<p class="text-muted">*Required Fields</p>
<?php
if (!isset($_SESSION['cart']) || count($_SESSION['cart']) < 1) {
// if cart does not exist or is empty, go back to cart
header('Location: cart.php');
}
?>
<br>
<hr>
<h2>Order</h2>
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<?php
require_once 'databaseConnector.php';
require_once 'itemDAO.php';
$db = new databaseConnector();
$con = $db->getConnection();
$item_dao = new itemDAO();
$subtotal = 0.0;
foreach($_SESSION['cart'] as $itemid => $qty) {
$items = $item_dao->selectByID($itemid, $con);
if (count($items) == 1) {
$product_name = $items[0]->name;
$product_description = $items[0]->description;;
$product_price = "$" . $items[0]->price;
?>
<tr>
<td class="itemid" hidden><?php echo $itemid ?></td>
<td><?php echo $product_name; ?></td>
<td><?php echo $qty; ?></td>
<td><?php echo $product_price; ?></td>
</tr>
<?php
$subtotal += doubleval($items[0]->price) * (int)$qty;
}
}
?>
</tbody>
</table>
<div class="container subtotal">
<p id="subtotal-label"><strong>Subtotal:</strong>
<span id="subtotal-value">$<?php echo number_format($subtotal, 2, '.', ''); ?></span></p>
<p id="tax-label"><strong>Sales Tax:</strong>
<span id="tax-value">$<?php echo number_format(0.0825 * $subtotal, 2, '.', ''); ?></span></p>
<p id="shipping-label"><strong>Shipping:</strong>
<span id="shipping-value">FREE</span></p>
<h2 id="total-label">Total:</h2>
<p id="total-value">$<?php echo number_format(1.0825 * $subtotal, 2, '.', ''); ?></p>
</div>
<button type="button" class="btn btn-primary" id="checkout-btn" disabled=true>Checkout</button>
</form>
</div>
</div>
<!-- /.card -->
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © <NAME> 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="scripts/checkout.js"></script>
</body>
</html><file_sep>/userService.php
<?php
require_once 'databaseConnector.php';
require_once 'userDAO.php';
class userService {
var $connector;
var $userAccess;
public function __construct() {
$this->connector=new databaseConnector();
$this->userAccess=new userDAO();
}
function addUser($email,$name,$address,$password,$phoneNum,$status){
try{
$con= $this->connector->getConnection();
$result= $this->userAccess->selectByUsername($email, $con);
if(mysqli_num_rows($result)>0){
echo "An user with username ".$email." is already in the system";
return -1;
}
else{
return $this->userAccess->createUser($email, $name, $address, $password, $phoneNum, $status, $con);
}
}
finally {
mysqli_free_result($result);
$con->close();
}
}
function login($email,$password){
try{
$con= $this->connector->getConnection();
$result= $this->userAccess->selectByUsername($email, $con);
if(mysqli_num_rows($result)>0){
while($row= mysqli_fetch_array($result,MYSQLI_ASSOC)){
$hashedpassword=$row["<PASSWORD>"];
$id=$row["user_id"];
}
if(password_verify($password, $hashedpassword)){
return $id;
}
}
echo "Username-password combination is invalid";
return -1;
}
finally {
mysqli_free_result($result);
$con->close();
}
}
function getInfo($id){
try{
$con= $this->connector->getConnection();
$result= $this->userAccess->selectByID($id, $con);
if(mysqli_num_rows($result)>0){
return mysqli_fetch_array($result,MYSQLI_ASSOC);
}
return ["status"=>1];
}
finally {
mysqli_free_result($result);
$con->close();
}
}
function updateInfo($id,$email,$name,$address,$password,$phoneNum,$status){
try{
$con= $this->connector->getConnection();
$con->begin_transaction();
$result= $this->userAccess->updateUser($id, $email, $name, $address, $password, $phoneNum, $status, $con);
if($result!=1){
//If there was no change return true anyways
if($result == 0)
{
echo "There was no change";
return true;
}
else
{
//If there was an error
$con->rollback();
echo "An error has occured while updating your info";
return false;
}
}
else{
$con->commit();
echo "Your information has been updated";
return true;
}
}
finally {
$con->close();
}
}
function createAnonymousUser(){
try{
$con= $this->connector->getConnection();
return $this->userAccess->createUser("", "", "", null, "", 1, $con);
}
finally {
$con->close();
}
}
function deleteAnonymousUser($id){
if($this->isAnonymous($id))
try{
$con= $this->connector->getConnection();
$con->begin_transaction();
$this->userAccess->deleteUser($id, $con);
if($con->affected_rows>1){
$con->rollback();
return 0;
}
$con->commit();
return $con->affected_rows;
}
finally {
$con->close();
}
return 0;
}
function convertAnonymousToKnown($anonymousID,$userID){
if(!$this->isAnonymous($userID)&&$this->isAnonymous($anonymousID)){
//move all related items over
$this->deleteAnonymousUser($anonymousID);
return true;
}
return false;
}
function isAnonymous($id){
try{
$con= $this->connector->getConnection();
$result=$this->userAccess->selectByID($id, $con);
if(mysqli_num_rows($result)>0&& mysqli_fetch_array($result,MYSQLI_ASSOC)["hashedpass"]==null){
return true;
}
return false;
}
finally {
mysqli_free_result($result);
$con->close();
}
}
}
<file_sep>/logout.php
<?php
session_start();
//Unset session variables
$_SESSION = array();
//Destroy session
session_destroy();
//Send user back to main page.
header('Location: index.php');
?><file_sep>/product_info_form.php
<?php session_start();
if (!isset($_SESSION['user_status']) || $_SESSION['user_status'] != 0) {
header('Location: signin.php');
}
if (!isset($_GET['action'])) {
header('Location: index.php');
}
if ($_GET['action'] != 'add_new_product' && $_GET['action'] != 'update_product') {
header('Location: index.php');
}
if ($_GET['action'] == 'update_product') {
if(!isset($_GET['id'])) {
header('Location: index.php');
} else {
require_once 'itemDAO.php';
require_once 'databaseConnector.php';
$db = new databaseConnector();
$con = $db->getConnection();
$itemDAO = new itemDAO();
$items = $itemDAO->selectByID($_GET['id'], $con);
if (count($items) == 1) {
$name = $items[0]->name;
$type = $items[0]->type;
$description = $items[0]->description;
$inventory = $items[0]->number;
$price = $items[0]->price;
$pictureLinkLabel=$items[0]->imageLink;
} else {
die("ERROR: Duplicate id found.");
}
}
} else {
$name = '';
$type = '-1';
$description = '';
$inventory = '';
$price = '';
$pictureLinkLabel = 'Choose file';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<link href="css/review.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4">
<div class="card-body">
<h1><?php
if ($_GET['action'] == 'add_new_product') {
echo 'Add New Product';
} else {
echo 'Update Product';
}
?></h1>
<hr>
<form id="product-form" enctype="multipart/form-data" action="admin_update_itemlist.php" method="POST">
<input name="action" value=<?php
if ($_GET['action'] == 'update_product')
echo 'update_item';
else
echo 'add_item';
?> hidden>
<?php if ($_GET['action'] == 'update_product') { ?>
<input name="id" value=<?php echo $_GET['id']; ?> hidden>
<?php } ?>
<div class="form-group">
<label for="product-name">Product Name</label>
<input name="product-name" type="text" class="form-control" id="product-name" aria-describedby="productName" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label for="product-type">Type</label>
<select name="product-type" class="custom-select" name="rating" id="product-type">
<option <?php if ($type == '-1') echo 'selected'; ?> disabled hidden>Select a product type...</option>
<option <?php if ($type == '1') echo 'selected'; ?> value="1">Board Game</option>
<option <?php if ($type == '2') echo 'selected'; ?> value="2">Video Game</option>
<option <?php if ($type == '3') echo 'selected'; ?> value="3">Card Game</option>
<option <?php if ($type == '4') echo 'selected'; ?> value="4">Gift Card</option>
</select>
</div>
<div class="form-group">
<label for="product-description">Description</label>
<textarea name="product-description" class="form-control" rows="6" id="product-description"><?php echo $description; ?></textarea>
</div>
<div class="form-group">
<label for="product-inventory">Inventory</label>
<input name="product-inventory" type="text" class="form-control" id="product-inventory" aria-describedby="inventory" value="<?php echo $inventory; ?>">
</div>
<div class="form-group">
<label for="product-price">Price</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input name="product-price" id="product-price" type="text" class="form-control" aria-label="price" aria-describedby="productPrice" value="<?php echo $price; ?>">
</div>
</div>
<div class="form-group">
<label for="product-image">Image</label>
<div class="input-group mb-3">
<div class="custom-file">
<input name="product-image" type="file" class="custom-file-input" id="product-image">
<label id="product-image-label" class="custom-file-label" for="product-image"><?php echo $pictureLinkLabel; ?></label>
</div>
</div>
</div>
<button id="submit-btn" name="submit" type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<!-- /.card -->
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © <NAME> 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="scripts/product_info_form.js"></script>
</body>
</html><file_sep>/config.php
<?php
define("DB_SERVER", "localhost");
define("DB_USER","root");
define("DB_PASSWORD", "");
define("DB_SCHEMA","maxinami_games");
?>
<file_sep>/ratingDAO.php
<?php
/**
* Description of ratingDAO
*
* @author Nathan
*/
class ratingDAO {
private $createSQL="INSERT INTO user_rating (user_id,product_id,rating,description) VALUES (?,?,?,?)";
private $selectByUserSQL="SELECT * FROM user_rating WHERE user_id=?";
private $selectByItemSQL="SELECT * FROM user_rating WHERE product_id=?";
private $selectByUserItem="SELECT * FROM user_rating WHERE user_id=? AND product_id=?";
private $updateSQL="UPDATE user_rating SET user_id=?,product_id=?,rating=?,description=? WHERE user_id=? AND product_id=?";
private $deleteSQL="DELETE FROM user_rating WHERE user_id=? AND product_id=?";
private $itemRating="SELECT AVG(rating) FROM user_rating WHERE product_id=?";
function createRating($userID,$itemID,$rating,$description,$con) {
$statement=mysqli_prepare($con, $this->createSQL);
$statement->bind_param("iids",$userID,$itemID,$rating,$description);
$statement->execute();
$statement->close();
return $itemID; // Which ID is supposed to be returned?
}
function selectByUser($userId,$con){
$statement= mysqli_prepare($con, $this->selectByUserSQL);
$statement->bind_param("i", $userId);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function selectByItem($itemId,$con){
$statement= mysqli_prepare($con, $this->selectByItemSQL);
$statement->bind_param("i", $itemId);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function selectByUserItem($userId, $itemId,$con){
$statement= mysqli_prepare($con, $this->selectByUserItem);
$statement->bind_param("ii", $userId, $itemId);
$statement->execute();
$result=$statement->get_result();
$statement->close();
return $result;
}
function deleteRating($userId,$productId,$con){
$statement= mysqli_prepare($con, $this->deleteSQL);
$statement->bind_param("ii", $userId,$productId);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
function updateRating($userID,$itemID,$newUserId,$newItemId,$rating,$description,$con) {
$statement=mysqli_prepare($con, $this->updateSQL);
$statement->bind_param("iidsii",$newUserId,$newItemId,$rating,$description,$userID,$itemID);
$statement->execute();
$result=$statement->affected_rows;
$statement->close();
return $result;
}
function getItemAverage($itemID,$con){
$statement= mysqli_prepare($con, $this->itemRating);
$statement->bind_param("i",$itemID);
$statement->execute();
$result=$statement->get_result();
if(mysqli_num_rows($result)>0){
return mysqli_fetch_array($result,MYSQLI_NUM)[0];
}
}
}
<file_sep>/cart.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Icon set -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<link href="css/cart.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item active">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4">
<div class="card-body">
<h1>Shopping Cart</h1>
<?php
if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {
// if cart exists and is not empty, display contents
?>
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
<th scope="col">Remove</th>
</tr>
</thead>
<tbody>
<?php
require_once 'databaseConnector.php';
require_once 'itemDAO.php';
$db = new databaseConnector();
$con = $db->getConnection();
$item_dao = new itemDAO();
$subtotal = 0.0;
foreach($_SESSION['cart'] as $itemid => $qty) {
$items = $item_dao->selectByID($itemid, $con);
if (count($items) == 1) {
$product_name = $items[0]->name;
$product_description = $items[0]->description;;
$product_price = "$" . $items[0]->price;
?>
<tr>
<td class="itemid" hidden><?php echo $itemid ?></td>
<td><?php echo $product_name; ?></td>
<td><input type="text" class="form-control qty-input" value="<?php echo $qty; ?>"></td>
<td><?php echo $product_price; ?></td>
<td><button type="button" class="btn btn-danger btn-sm delete-btn"><i class="fa fa-trash"></i></button></td>
</tr>
<?php
$subtotal += doubleval($items[0]->price) * (int)$qty;
}
}
?>
</tbody>
</table>
<div class="container subtotal">
<h2 id="subtotal-label">Subtotal:</h2>
<p id="subtotal-value">$<?php echo $subtotal; ?></p>
</div>
<button id="<?php echo (isset($_SESSION['user_name']) ? "checkout-btn" : "checkout-prompt-btn"); ?>" type="button" class="btn btn-success btn-block">Checkout</button>
<?php
} // end if
else {
// No items in cart!
echo 'No items in cart.';
}
?>
</div>
</div>
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © <NAME> 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="scripts/cart.js"></script>
</body>
</html>
<file_sep>/validate_edit.php
<?php
require_once 'userService.php';
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$ERR="";
$servername = 'localhost';
$serverusername = 'root';
$serverpassword = '';
if(empty($_POST["name"])){
//Do nothing
}
else{
$username = test_input($_POST["name"]);
}
if(empty($_POST["phone"])){
//Do nothing
}
else{
$phone = test_input($_POST["phone"]);
}
if(empty($_POST["address"])){
//Do nothing
}
else{
$address = test_input($_POST["address"]);
}
if(empty($_POST["password"])){
//Do nothing
}
else{
$password = test_input($_POST["password"]);
if(empty($_POST["confirm"])){
}
else{
$confirm = test_input($_POST["confirm"]);
//Test if confirm password is the same as password and the passsword is changed
if(strcmp($password, $confirm))
{
$ERR = "Password and Confirm Password are different!";
}
}
}
//If required fields are empty or passwords are different, return to account create
if(!empty($ERR)){
header('Location: account_edit.php');
exit();
}
else{
//Gain access to userService.php
$userService = new userService();
//Store user info
$id = $_SESSION['user_id'];
//Abort if id is not found *This should not happen
if($id == -1)
{
echo 'id not found';
}
else
{
$row = $userService->getInfo($id);
$username = $row["username"];
$fullname = $row['fullname'];
$address = $row['address'];
$phone = $row['phonenumber'];
$password = $row['<PASSWORD>'];
$status = $row['status'];
//Change variables if there is a change
if(!empty($_POST["name"]))
{
$fullname = $_POST['name'];
}
if(!empty($_POST["phone"]))
{
$phone = $_POST['phone'];
}
if(!empty($_POST["address"]))
{
$address= $_POST['address'];
}
if(!empty($_POST["password"]))
{
//Encrypt password
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
}
echo $username, $fullname, $password, $address, $phone, $status ."<br />";
//Update user info
$update = $userService->updateInfo($id, $username, $fullname, $address, $password, $phone, $status);
//If update did not succeed, give error
if(!$update)
{
echo "Fatal Error: Update did not complete";
}
else
{
session_regenerate_id();
$_SESSION['user_name'] = $username;
$_SESSION['fullname'] = $fullname;
$_SESSION['phone'] = $phone;
$_SESSION['user_status'] = $status;
$_SESSION['address'] = $address;
$_SESSION['user_id'] = $id;
session_write_close();
header('Location: index.php');
}
}
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?><file_sep>/removefromcart.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'])) {
$itemid = $_POST['id'];
if (!isset($_SESSION['cart']) || !isset($_SESSION['cart'][$itemid])) {
header('Location: cart.php');
}
// User is logged in, remove from session and database
if (isset($_SESSION['user_name'])) {
require_once 'databaseConnector.php';
require_once 'shoppingCartDAO.php';
$db = new databaseConnector();
$con = $db->getConnection();
$cartDAO = new shoppingCartDAO();
unset($_SESSION['cart'][$itemid]);
$cartDAO->deleteCartItem($_SESSION['user_id'],$itemid,$con);
session_write_close();
//var_dump($_SESSION['cart']);
header('Location: cart.php');
}
// User is not logged in, just remove from session
else {
unset($_SESSION['cart'][$itemid]);
session_write_close();
//var_dump($_SESSION['cart']);
header('Location: cart.php');
}
} else {
header('Location: cart.php');
}
?><file_sep>/ratingService.php
<?php
require_once 'ratingDAO.php';
require_once 'purchaseHistoryDAO.php';
require_once 'itemDAO.php';
require_once 'databaseConnector.php';
/*
* 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.
*/
/**
* Description of ratingService
*
* @author Nathan
*/
class ratingService {
var $ratingAccess;
var $purchaseAccess;
var $itemAccess;
var $connector;
function __construct() {
$this->ratingAccess=new ratingDAO();
$this->purchaseAccess=new purchaseHistoryDAO();
$this->itemAccess=new itemDAO();
$this->connector=new databaseConnector();
}
function addRating($userID,$itemID,$ratingVal,$comment){
try{
$con=$this->connector->getConnection();
if($this->hasPurchased($userID, $itemID, $con)){
$this->ratingAccess->createRating($userID, $itemID, $ratingVal, $comment, $con);
$rating=$this->ratingAccess->getItemAverage($itemID, $con);
$items= $this->itemAccess->selectByID($itemID, $con);
if (count($items) == 1) {
$items[0]->rating=$rating;
} else {
return FALSE;
}
$this->itemAccess->updateUsingItem($items[0], $con);
}
else {
return FALSE;
}
}
finally{
$con->close();
}
}
function refreshItemRating($itemID) {
try{
$con=$this->connector->getConnection();
$rating=$this->ratingAccess->getItemAverage($itemID, $con);
$items= $this->itemAccess->selectByID($itemID, $con);
if (count($items) == 1) {
$items[0]->rating=$rating;
} else {
return FALSE;
}
$this->itemAccess->updateUsingItem($items[0], $con);
}
finally{
$con->close();
}
}
function updateRating($userID,$itemID,$ratingVal,$comment){
try{
$con=$this->connector->getConnection();
if($this->hasPurchased($userID, $itemID, $con)){
$affected_rows = $this->ratingAccess->updateRating($userID, $itemID, $userID, $itemID, $ratingVal, $comment, $con);
if ($affected_rows == 1) {
$rating=$this->ratingAccess->getItemAverage($itemID, $con);
$items= $this->itemAccess->selectByID($itemID, $con);
if (count($items) == 1) {
$items[0]->rating=$rating;
} else {
return FALSE;
}
$this->itemAccess->updateUsingItem($items[0], $con);
}
else {
return FALSE;
}
}
else {
return FALSE;
}
}
finally{
$con->close();
}
}
private function hasPurchased($userID,$itemID,$con) {
try{
$result=$this->purchaseAccess->selectUserItem($userID, $itemID, $con);
echo(mysqli_num_rows($result));
if(mysqli_num_rows($result)>0){
return TRUE;
}
return FALSE;
}
finally {
mysqli_free_result($result);
}
}
function hasReviewed($userID,$itemID,$con) {
try{
$result=$this->ratingAccess->selectByUserItem($userID, $itemID, $con);
if(mysqli_num_rows($result)>0){
return TRUE;
}
return FALSE;
}
finally {
mysqli_free_result($result);
}
}
function getRatings($userID){
$con= $this->connector->getConnection();
$result=$this->ratingAccess->selectByUser($userID, $con);
$con->close();
return $result;
}
}
<file_sep>/pages.php
<?php
class pages{
private $currentPage =1;
private $perPage = 6;
private $arraySize = 0;
private $pages = 1;
function setItemsPerPage($argument){
$this->perPage = $argument;
}
function getItemsPerPage(){
return $this->perPage;
}
function setArraySize($argument){
$this->arraySize = $argument;
}
function setPages(){
$this->pages = ceil($this->arraySize/$this->perPage);
return $this->pages;
}
function setCurrentPage($argument){
$this->currentPage=$argument;
}
function getCurrentPage(){
return $this->currentPage;
}
}
?>
<file_sep>/purchaseService.php
<?php
/*
* 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.
*/
require_once 'databaseConnector.php';
require_once 'purchaseHistoryDAO.php';
require_once 'shoppingCartDAO.php';
require_once 'itemDAO.php';
require_once 'userDAO.php';
/**
* Description of PurchaseService
*
* @author Nathan
*/
class purchaseService {
var $connector;
var $purchaseAccess;
var $cartAccess;
var $itemAccess;
public function __construct() {
$this->connector=new databaseConnector();
$this->purchaseAccess=new purchaseHistoryDAO();
$this->cartAccess=new shoppingCartDAO();
$this->itemAccess=new itemDAO;
}
public function getPurchases($userId){
try{
$con=$this->connector->getConnection();
return $this->purchaseAccess->selectByUser($userId,$con);
}
finally {
$con->close();
}
}
/*
* the purchase function
* either returns true if the purchase is made
*/
public function userPurchase($userID){
try{
$con=$this->connector->getConnection();
$con->autocommit(FALSE);
$result= $this->cartAccess->selectByUser($userID, $con);
$record=[];
if(mysqli_num_rows($result)<1){
return FALSE;
}
while($row= mysqli_fetch_array($result,MYSQLI_ASSOC)){
array_push($record, $this->purchaseItem($userID, $row["product_id"], $row["quantity"], $con));
}
return $this->successfulPurchase($record, $con);
}
finally {
mysqli_free_result($result);
$con->close();
}
}
public function anonymousPurchase($cart){
try{
$con=$this->connector->getConnection();
$con->autocommit(FALSE);
$result=(new userDAO())->selectByUsername('anonymous', $con);
if(mysqli_num_rows($result)>0){
$id=mysqli_fetch_array($result,MYSQLI_ASSOC)["user_id"];
}
$record=[];
if(count($cart)<1){
return FALSE;
}
foreach ($cart as $key => $value) {
array_push($record, $this->purchaseItem($id, $key, $value, $con));
}
return $this->successfulPurchase($record, $con);
}
finally {
$con->close();
}
}
private function purchaseItem($userID,$itemID,$quantity,$con) {
$name="none";
$inventory=0;
$outcome=FALSE;
$result= $this->itemAccess->selectByID($itemID, $con);
$num=$this->itemAccess->reduceQuantity($itemID, $quantity, $con);
$this->cartAccess->deleteCartItem($userID, $itemID, $con);
if(count($result)==1){
$name=$result[0]->name;
$inventory=$result[0]->number;
if($num>0){
$this->purchaseAccess->createPurchase($userID,$itemID,$quantity,$con);
$outcome=TRUE;
}
}
return ["id"=>$itemID, "name"=>$name,"outcome"=>$outcome,"inventory"=>$inventory,"quantity"=>$quantity];
}
private function successfulPurchase($record,$con) {
foreach ($record as $value) {
if(!$value["outcome"]){
$con->rollback();
return $record;
}
}
$con->commit();
return TRUE;
}
}
<file_sep>/updatecart.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id']) && isset($_POST['qty'])) {
$itemid = $_POST['id'];
// User is logged in, store in session and database
if (isset($_SESSION['user_name'])) {
require_once 'cartService.php';
$cartService = new cartService();
if (!isset($_SESSION['cart']) || !isset($_SESSION['cart'][$itemid])) {
header('Location: cart.php');
}
$_SESSION['cart'][$itemid] = $_POST['qty'];
$cartService->updateItem($_SESSION['user_id'],$itemid,$_POST['qty']);
session_write_close();
echo $_SESSION['cart'][$itemid];
}
// User is not logged in, just store in session
else {
if (!isset($_SESSION['cart']) || !isset($_SESSION['cart'][$itemid])) {
header('Location: cart.php');
}
$_SESSION['cart'][$itemid] = $_POST['qty'];
session_write_close();
echo $_SESSION['cart'][$itemid];
}
} else {
header('Location: cart.php');
}
?><file_sep>/cartService.php
<?php
/*
* 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.
*/
require_once 'databaseConnector.php';
require_once 'shoppingCartDAO.php';
/**
* Description of cartService
*
* @author Nathan
*/
class cartService {
var $connector;
var $cartAccess;
public function __construct() {
$this->connector=new databaseConnector();
$this->cartAccess=new shoppingCartDAO();
}
public function addItem($userID,$itemID,$quantity){
try{
$con=$this->connector->getConnection();
$num= $this->addCartItem($userID, $itemID, $quantity, $con);
if($num==1){
$con->commit();
}
else{
$con->rollback();
return 0;
}
return $num;
}
finally {
$con->close();
}
}
public function getCart($userID){
try{
$con=$this->connector->getConnection();
return $this->cartAccess->selectByUser($userID, $con);
}
finally {
$con->close();
}
}
public function updateItem($userID,$itemID,$quantity) {
try{
$con=$this->connector->getConnection();
$con->begin_transaction();
$quantities= $this->changeQuantity($userID, $itemID, $quantity, $con);
$newQuantity=min([$quantities[2],$quantity]);
$num= $this->updateCartItem($userID, $itemID, $newQuantity, $con);
if($num==1){
$con->commit();
}
else {
$con->rollback();
return 0;
}
return $num;
}
finally {
$con->close();
}
}
private function updateCartItem($userID,$itemID,$quantity,$con) {
$num= $this->cartAccess->updatePurchase($userID, $itemID, $quantity, $con);
return $num;
}
private function addCartItem($userID,$itemID,$quantity,$con) {
$quantities= $this->changeQuantity($userID, $itemID, $quantity, $con);
if($quantities[0]<=0){
$this->cartAccess->deleteCartItem($userID, $itemID, $con);
return 1;
}
elseif ($quantities[1]==0) {
$num= $this->cartAccess->createCartItem($userID, $itemID, $quantities[0], $con);
}
else {
$num= $this->updateCartItem($userID, $itemID, $quantities[0], $con);
}
return $num;
}
private function getQuantity($userID, $itemID, $con){
$result=$this->cartAccess->selectByUserAndItem($userID, $itemID, $con);
if(mysqli_num_rows($result)==0){
mysqli_free_result($result);
return 0;
}
$Currquantity=0;
while($row= mysqli_fetch_array($result,MYSQLI_ASSOC)){
$Currquantity+=$row["quantity"];
}
mysqli_free_result($result);
return $Currquantity;
}
private function changeQuantity($userID,$itemID,$quantity,$con){
require_once 'itemDAO.php';
$existing= $this->getQuantity($userID, $itemID, $con);
$result= (new itemDAO())->selectByID($itemID, $con);
if(count($result)==1){
$inventoryBound= $result[0]->number;
}
$newQuantity=min([$quantity+$existing,$inventoryBound]);
return [$newQuantity,$existing,$inventoryBound];
}
public function moveCartToUser($userID,$cart){
if(is_array($cart)){
$con= $this->connector->getConnection();
foreach ($cart as $key => $value) {
$this->addCartItem($userID, $key, $value, $con);
}
return TRUE;
}
return FALSE;
}
public function removeItem($userID,$itemID){
$con= $this->connector->getConnection();
$con->begin_transaction();
$num= $this->cartAccess->deleteCartItem($userID, $itemID, $con);
if($num!=1){
$con->rollback();
return FALSE;
}
$con->commit();
return TRUE;
}
}
<file_sep>/scripts/review.js
$(document).ready( function() {
$("#submit-btn").click( function(event) {
event.preventDefault();
var rating = $("#rating").val();
var description = $("#review-description").val();
var id = $("#item-id").html();
var action = "";
if ($("#submit-btn").html() == "Submit") {
action = "add_review";
}
if ($("#submit-btn").html() == "Update"){
action = "update_review";
}
$.ajax({
url: "review_item.php",
type: "post",
data: encodeURI("action=" + action + "&id=" + id + "&rating=" + rating + "&description=" + description),
success: function(data) {
alert("Review submitted");
location.href = "account.php";
},
error: function(data) {
alert("error! " + data);
}
});
});
});<file_sep>/review_item.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
function add_review() {
if(!isset($_POST['id']) ||
!isset($_POST['rating']) ||
!isset($_POST['description']) )
{
die("Error adding review.");
}
$userID = $_SESSION['user_id'];
$itemID = $_POST['id'];
$ratingVal = $_POST['rating'];
$comment = htmlentities($_POST['description']);
require_once 'ratingService.php';
$ratingService = new ratingService();
$ratingService->addRating($userID,$itemID,$ratingVal,$comment);
exit("UID: $userID IID: $itemID R: $ratingVal C: $comment");
}
function update_review() {
if(!isset($_POST['id']) ||
!isset($_POST['rating']) ||
!isset($_POST['description']) )
{
die("Error updating review.");
}
$userID = $_SESSION['user_id'];
$itemID = $_POST['id'];
$ratingVal = $_POST['rating'];
$comment = htmlentities($_POST['description']);
require_once 'ratingService.php';
$ratingService = new ratingService();
$ratingService->updateRating($userID,$itemID,$ratingVal,$comment);
exit("UID: $userID IID: $itemID R: $ratingVal C: $comment");
}
if ($_POST['action'] == 'add_review')
add_review();
elseif ($_POST['action'] == 'update_review')
update_review();
else
die();
} else {
die();
}
?><file_sep>/find_user.php
<?php
require_once 'userService.php';
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$ERR="";
$servername = 'localhost';
$serverusername = 'root';
$serverpassword = '';
if(empty($_POST["username"])){
$ERR = "Username is Required";
}
else{
$username = test_input($_POST["username"]);
}
if(empty($_POST["password"])){
$ERR = "Password is Required";
}
else{
$password = test_input($_POST["password"]);
}
//If fields are empty return to sign in
if(!empty($ERR)){
$_SESSION['errorMessage'] = "Username/password is empty.";
header('Location: signIn.php');
exit();
}
else{
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$login = new userService();
$id = $login->login($username,$password);
//If user is found in database
if($id != -1){
$row = $login->getInfo($id);
$user_status = $row['status'];
$fullname = $row['fullname'];
$address = $row['address'];
$phone = $row['phonenumber'];
session_regenerate_id();
$_SESSION['user_id'] = $id;
$_SESSION['user_status'] = $user_status;
$_SESSION['user_name'] = $username;
$_SESSION['fullname'] = $fullname;
$_SESSION['phone'] = $phone;
$_SESSION['address'] = $address;
load_cart();
session_write_close();
header('Location: index.php');
echo 'login success';
}
else{
$_SESSION['errorMessage'] = "Username/password is invalid.";
header('Location: signIn.php');
exit();
}
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function load_cart() {
// Load cart from database
require_once 'cartService.php';
$cartService = new cartService();
if (!isset($_SESSION['cart'])) { // create cart if not created yet
$_SESSION['cart'] = [];
}
$cartService->moveCartToUser($_SESSION['user_id'],$_SESSION['cart']);
$result = $cartService->getCart($_SESSION['user_id']);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$itemid = $row['product_id'];
$quantity = $row['quantity'];
$_SESSION['cart'][$itemid] = $quantity;
}
}
?><file_sep>/scripts/account.js
$(document).ready(function() {
// Toggle content when respective tab is clicked
$("#order-history-tab").click(function(event) {
event.preventDefault();
$("#order-history-tab").addClass("active");
$("#account-info-tab").removeClass("active");
$("#account-info-card").addClass("hidden");
$("#order-history-card").removeClass("hidden");
});
$("#account-info-tab").click(function(event) {
event.preventDefault();
$("#account-info-tab").addClass("active");
$("#order-history-tab").removeClass("active");
$("#order-history-card").addClass("hidden");
$("#account-info-card").removeClass("hidden");
});
$(".review-btn").click(function() {
var item_id = $(this).parent().siblings(".item-id").html();
// <form method="post" action="review.php">
// <input type="hidden" name="item-id" value="<?php echo $row['product_id']; ?>">
// <input type="hidden" name="action" value="add_review">
// </form>
var form = "<form method='post' action='review.php'>";
form += "<input type='hidden' name='item-id' value='" + item_id + "'>";
form += "<input type='hidden' name='action' value='add_review'></form>";
$(form).appendTo($(document.body)).submit();
});
});<file_sep>/fail.php
<?php session_start();
if (!isset($_SESSION['cart']) || count($_SESSION['cart']) == 0) {
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Icon set -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4 text-center text-white border-danger">
<div class="card-body text-danger">
<h1>Uh-oh! :(</h1>
<p>You tried to order following items, but the quantity in your cart exceeded our stock:</p>
<?php
$result = json_decode(urldecode($_POST['result_arr']), true);
foreach ($result as $item) {
if($item['outcome'] == false) {
echo "<p><strong>" . $item['name'] . "</strong></p>";
}
}
?>
<p>Item quantities have been adjusted to the number we have in stock.<br />
Please check your cart, and re-order.</p>
</div>
</div>
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © <NAME> 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<file_sep>/index.php
<?php session_start();
function getRatingStarString($rating) {
/*
1 star: 0 - 1.49999
2 star: 1.5 - 2.499999
3 star: 2.5. - 3.499999
4 star: 3.5 - 4.499999
5 star: 4.5 - 5
*/
if($rating==0)
return "☆ ☆ ☆ ☆ ☆";
else if ($rating < 1.5)
return "★ ☆ ☆ ☆ ☆";
else if ($rating < 2.5)
return "★ ★ ☆ ☆ ☆";
else if ($rating < 3.5)
return "★ ★ ★ ☆ ☆";
else if ($rating < 4.5)
return "★ ★ ★ ★ ☆";
else
return "★ ★ ★ ★ ★";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Icon set -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div id="carouselExampleIndicators" class="carousel slide my-4" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<?php
$servername = 'localhost';
$serverusername = 'root';
$serverpassword = '';
$con = new mysqli($servername, $serverusername, $serverpassword, "<PASSWORD>");
$result = mysqli_query($con, "SELECT product_id,SUM(quantity) as amt,pictureLink FROM purchase_history,items WHERE purchase_history.product_id=items.itemid GROUP BY product_id ORDER BY amt DESC");
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
?>
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<a href="product.php?action=get_product&id=<?php echo $row['product_id']; ?>"><img class="d-block img-fluid" src=<?php echo 'imgs/'.$row['pictureLink']?> alt="First slide"></a>
</div>
<?php $row = mysqli_fetch_array($result, MYSQLI_ASSOC); ?>
<div class="carousel-item">
<a href="product.php?action=get_product&id=<?php echo $row['product_id']; ?>"><img class="d-block img-fluid" src=<?php echo 'imgs/'.$row['pictureLink']?> alt="Second slide"></a>
</div>
<?php $row = mysqli_fetch_array($result, MYSQLI_ASSOC); ?>
<div class="carousel-item">
<a href="product.php?action=get_product&id=<?php echo $row['product_id']; ?>"><img class="d-block img-fluid" src=<?php echo 'imgs/'.$row['pictureLink']?> alt="Third slide"></a>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span aria-hidden="true"><i class="fa fa-chevron-left"></i></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span aria-hidden="true"><i class="fa fa-chevron-right"></i></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="row">
<?php
$result = mysqli_query($con, "SELECT * FROM items ORDER BY inventory DESC;");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
?>
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<a href=<?php echo "product.php?action=get_product&id=" . $row["itemid"] ?>><img class="card-img-top" src=<?php echo 'imgs/'.$row['pictureLink']?> alt=""></a>
<div class="card-body">
<h4 class="card-title">
<a href=<?php echo "product.php?action=get_product&id=" . $row["itemid"] ?>><?php echo $row['name']?></a>
</h4>
<h5>$<?php echo number_format($row['price'], 2, '.', '');?></h5>
<p class="card-text" id="description"><?php echo $row['description']?></p>
</div>
<div class="card-footer">
<small class="<?php echo ($row['rating'] > 0 ? 'text-warning' : 'text-muted'); ?>">
<?php echo getRatingStarString($row['rating']); ?>
</small>
</div>
</div>
</div>
<?php
}
mysqli_close($con);
?>
</div>
<!-- /.row -->
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © Maxinami Games 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<file_sep>/scripts/edit_account.js
//This script stops users from editing their account if phone number is invalid
//or password and confirm password mismatch.
$(document).ready(function(){
//Create boolean vars for password and phone
var phoneCorrect = true;
var passCorrect = true;
//For number relation teet
var isNumber = /^[0-9]+$/;
//For phone field
$("#phone").keyup(function(){
var phoneText = "";
var phone = document.getElementById("phone").value;
//If phone field is empty, phoneCorrect is true
if($(this).val() === '')
{
//Empty text
phoneText = "";
$("#phoneerror").css({"color": "green"});
document.getElementById("phoneerror").innerHTML = phoneText;
phoneCorrect = true;
}
else//If phone is filled, check to see if the entry is valid
{
var isCorrect = isNumber.test(phone);
//If phone number is invalid stop user from entering data
if(!isCorrect)
{
phoneText = "Phone number can only consist of numbers";
$("#phoneerror").css({"color": "red"});
document.getElementById("phoneerror").innerHTML = phoneText;
phoneCorrect = false;
}
else//phoneCorrect is true
{
//Empty text
phoneText = "";
$("#phoneerror").css({"color": "green"});
document.getElementById("phoneerror").innerHTML = phoneText;
phoneCorrect = true;
}
}
//Check to see if both password and phone are correct and enable user to edit if so
if(phoneCorrect && passCorrect)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
//For the password field
$("#password").keyup(function(){
//For password error
var text = "";
var pass = document.getElementById("password").value;
var confirm = document.getElementById("confirm").value;
var passverify = "";
//Contains the text for password strength
var passverify = "";
//Determines the strength of the password by checking for special character or number
var numberTest = /\d+/;
var specialTest = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;
var hasNumber = numberTest.test(pass);
var hasSpecial = specialTest.test(pass);
var hasLength = false;
//Check for password length
if (pass.length >= 8)//Check for length
{
hasLength = true;
}
else
{
hasLength = false;
}
//Show password strength
//If password is long and contains either a special character or number
if((hasSpecial || hasNumber) && hasLength)
{
passverify = "<PASSWORD>";
$("#passverification").css({"color": "green"});
document.getElementById("passverification").innerHTML = passverify;
}
else if(hasLength)//If password is long
{
passverify = "<PASSWORD>";
$("#passverification").css({"color": "orange"});
document.getElementById("passverification").innerHTML = passverify;
}
else
{
passverify = "<PASSWORD>";
$("#passverification").css({"color": "red"});
document.getElementById("passverification").innerHTML = passverify;
}
if (pass === "")
{
//Empty Text
passverify = "";
$("#passverification").css({"color": "red"});
document.getElementById("passverification").innerHTML = passverify;
}
//If password and confirm are empty passCorrect is true
if($(this).val() === '' && confirm === "")
{
text = "";
document.getElementById("test").innerHTML = text;
passCorrect = true;
}
else
{
//If both password and confirm are filled check for match and
//change password filled to true if so or show error text if not
//Test if confirm password is the same as password
if(pass === confirm)
{
text = "";
document.getElementById("test").innerHTML = text;
passwordFilled = true;
passCorrect = true;
}
else
{
text = "Password and Confirm Password are different!";
$("#test").css({"color": "red"});
document.getElementById("test").innerHTML = text;
passCorrect = false;
}
}
//Check to see if both password and phone are correct and enable user to edit if so
if(phoneCorrect && passCorrect)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
//For the confirm field
$("#confirm").keyup(function(){
var text = "";
var pass = document.getElementById("password").value;
var confirm = document.getElementById("confirm").value;
//If both password and confirm are filled check for match and
//change password filled to true if so or show error text if not
if($(this).val() === '' && pass === "")
{
text = "";
document.getElementById("test").innerHTML = text;
passCorrect = true
}
else
{
//Test if confirm password is the same as password
if(pass === confirm)
{
text = "";
document.getElementById("test").innerHTML = text;
passCorrect = true;
}
else
{
text = "Password and Confirm Password are different!";
$("#test").css({"color": "red"});
document.getElementById("test").innerHTML = text;
passCorrect = false;
}
}
//Check to see if both password and phone are correct and enable user to edit if so
if(phoneCorrect && passCorrect)
{
$("#userSubmit").prop("disabled", false);
}
else
{
$("#userSubmit").prop("disabled", true);
}
});
});<file_sep>/sort_item.php
<?php
function sortByPrice($minPrice,$maxPrice,$array){
$sortedArray=array();
for($i=0;$i<sizeof($array);$i++){
if($array[$i]['price']>=$minPrice&&$array[$i]['price']<=$maxPrice)
$sortedArray[]=($array[$i]);
}
return $sortedArray;
}
function sortByRating($minRating,$array){
$sortedArray=array();
for($i=0;$i<sizeof($array);$i++){
if($array[$i]['rating']>=$minRating)
$sortedArray[]=($array[$i]);
}
return $sortedArray;
}
?>
<file_sep>/account.php
<?php session_start();
if (!isset($_SESSION['user_status'])) {
header('Location: signin.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Maxinami Games</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Icon set -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<link href="css/account.css" rel="stylesheet">
<link href="css/adminproductlist.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Maxinami Games</a>
<form class="form-inline" method ="get" action="search.php">
<input class="form-control mr-sm-2" id="search-bar" placeholder="Search" aria-label="Search" name="search item">
<button class="btn btn-outline-secondary my-2 my-sm-2" id="button" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item active">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"account.php\">Your Account</a>";
else
echo "<a class=\"nav-link\" href=\"signIn.php\">Sign In</a>";
?>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">Cart</a>
</li>
<li class="nav-item">
<?php
if (isset($_SESSION['user_name']))
echo "<a class=\"nav-link\" href=\"logout.php\">Log Out</a>";
?>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Maxinami Games</h1>
<div class="list-group">
<a href="search.php?search+item=%boardgame" class="list-group-item" name="board games">Board Games</a>
<a href="search.php?search+item=%25cardgame" class="list-group-item" name="card games">Card Games</a>
<a href="search.php?search+item=%videogame" class="list-group-item" name="video games">Video Games</a>
<a href="search.php?search+item=%giftcard" class="list-group-item" name="gift cards">Gift Cards</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div class="card mt-4">
<ul class="nav nav-tabs">
<li class="nav-item">
<a id="account-info-tab" class="nav-link active" href="#">Account Info</a>
</li>
<li class="nav-item">
<a id="order-history-tab" class="nav-link" href="#">Order History</a>
</li>
<?php
if (isset($_SESSION['user_status']) && $_SESSION['user_status'] == 0) {
?>
<li class="nav-item">
<a id="modify-items-tab" class="nav-link" href="#">Modify Items</a>
</li>
<?php } ?>
</ul>
<div class="card-body" id="account-info-card">
<div class="container">
<p class="card-text">Username: <?php echo $_SESSION['user_name']?></p>
<p class="card-text">Name: <?php echo $_SESSION['fullname']?></p>
<p class="card-text">Phone #: <?php echo $_SESSION['phone']?></p>
<p class="card-text">Address: <?php echo $_SESSION['address']?></p>
<a class="btn btn-primary" href="account_edit.php">Edit</a>
</div>
</div>
<div class="card-body hidden" id="order-history-card">
<div class="container">
<?php
$servername = 'localhost';
$serverusername = 'root';
$serverpassword = '';
$con = new mysqli($servername, $serverusername, $serverpassword, "<PASSWORD>");
$result=mysqli_query($con, "SELECT * FROM users WHERE username= \"".$_SESSION['user_name']."\";");
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
$id=$row['user_id'];
$result=mysqli_query($con, "SELECT * FROM purchase_history WHERE user_id= ".$id.";");
$numPurchases = mysqli_num_rows($result);
if ( $numPurchases == 0) {
echo "No purchases have been made";
echo "<br>";
} else {
?>
<table class="table">
<thead>
<tr>
<th scope="col">Date Purchased</th>
<th scope="col">Product</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
<th scope="col">Write Review</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
?>
<tr>
<?php
$query = mysqli_query($con, "SELECT * FROM items WHERE itemid=".$row['product_id'].";");
$product = mysqli_fetch_array($query, MYSQLI_ASSOC);
?><td class="item-id" hidden><?php echo $row['product_id']; ?></td>
<td><?php echo $row['time_of_purchase']?></td>
<td><?php echo $product['name']?></td>
<td><?php echo $row['quantity']?></td>
<td><?php echo $product['price']?></td>
<td><button type="button" class="btn btn-primary btn-sm review-btn"><i class="fa fa-pencil"></i></button></td>
</tr>
<?php
}
}
mysqli_close($con);
?>
</tbody>
</table>
</div>
</div>
<?php
if (isset($_SESSION['user_status']) && $_SESSION['user_status'] == 0) {
?>
<div class="card-body hidden" id="modify-items-card">
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Stock</th>
<th scope="col">Price</th>
<th scope="col">Update</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<?php
require_once 'itemService.php';
$itemService = new itemService();
$result = $itemService->searchItem("%all%");
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
?><tr>
<td class="item-id" hidden><?php echo $row['itemid']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><input type="text" class="form-control stock-num-input inventory" value="<?php echo $row['inventory']; ?>"></td>
<td>$<?php echo number_format($row['price'], 2, '.', ''); ?></td>
<td><button type="button" class="btn btn-secondary btn-sm update-btn"><i class="fa fa-pencil"></i></button></td>
<td><button type="button" class="btn btn-danger btn-sm delete-btn"><i class="fa fa-trash"></i></button></td>
</tr>
<?php } ?>
</tbody>
</table>
<a href="product_info_form.php?action=add_new_product" role="button" class="btn btn-primary btn-block"><i class="fa fa-plus"></i> Add New Product</a>
</div>
<?php } ?>
</div>
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-4 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © <NAME> 2018</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<?php
if (isset($_SESSION['user_status']) && $_SESSION['user_status'] == 0) {
?>
<script src="scripts/adminaccount.js"></script>
<?php } else { ?>
<script src="scripts/account.js"></script>
<?php } ?>
</body>
</html><file_sep>/validate_create.php
<?php
require_once 'userService.php';
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$ERR="";
$servername = 'localhost';
$serverusername = 'root';
$serverpassword = '';
if(empty($_POST["username"])){
$ERR = "Username is Required";
}
else{
$username = test_input($_POST["username"]);
}
if(empty($_POST["name"])){
$ERR = "Name is Required";
}
else{
$fullname = test_input($_POST["name"]);
}
if(empty($_POST["address"])){
$ERR = "Address is Required";
}
else{
$address = test_input($_POST["address"]);
}
if(empty($_POST["password"])){
$ERR = "Password is Required";
}
else{
$password = test_input($_POST["password"]);
}
if(empty($_POST["confirm"])){
$ERR = "Confirm password is Required";
}
else{
$confirm = test_input($_POST["confirm"]);
}
//Test if confirm password is the same as password
if(strcmp($password, $confirm))
{
$ERR = "Password and Confirm Password are different!";
}
//If required fields are empty or passwords are different, return to account create
if(!empty($ERR)){
header('Location: account_create.php');
exit();
}
else{
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$fullname = $_POST['name'];
$address= $_POST['address'];
$phone = $_POST['phone'];
//Encrypt password
$userpass = password_hash($_POST['password'], PASSWORD_BCRYPT);
//Gain access to userService.php
$add = new userService();
$id = $add->addUser($username,$fullname,$address,$userpass,$phone,1);
if($id != -1)
{
session_regenerate_id();
$_SESSION['user_name'] = $username;
$_SESSION['fullname'] = $fullname;
$_SESSION['phone'] = $phone;
$_SESSION['user_status'] = 1;
$_SESSION['address'] = $address;
$_SESSION['user_id'] = $id;
session_write_close();
header('Location: index.php');
}
else//An error occurred for adding account into database
{
header('Location: account_create.php');
exit();
}
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
|
e95118be07dfba44b249fbb7bb1ab720ef93fb15
|
[
"JavaScript",
"Markdown",
"PHP"
] | 42
|
PHP
|
mavisfrancia/maxinami_games
|
909de0c546207455201433b4f1026e0b9f04c73d
|
7a2fd2df2adfd9da7f5f86d45602d92e7a303afc
|
refs/heads/master
|
<file_sep>var ProtractorPerf = require('protractor-perf');
describe('angularjs homepage todo list', function() {
var perf = new ProtractorPerf(protractor,browser); // Initialize the perf runner
it('should add a todo', function() {
browser.driver.sleep(5000);
perf.start();
browser.get('http://www.angularjs.org');
// Start measuring the metrics
perf.stop(); // Stop measuring the metrics
if (perf.isEnabled) { // Is perf measuring enabled ?
// Check for perf regressions, just like you check for functional regressions
expect(perf.getStats('meanFrameTime')).toBeLessThan(30);
};
});
});<file_sep>exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['spec.js'],
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
binary:'C:/Users/sauravk/Documents/CEF/Debug/cefclient.exe'
}
},
}
|
a20a891c30af98e395e503da087653c702431884
|
[
"JavaScript"
] | 2
|
JavaScript
|
sauravbms/protractor-perf-test
|
596137da823ab28c70cc010e480ef12f0ab89d0e
|
8a729d0df52b6c86bc256ee6b9eb1733b348298e
|
refs/heads/master
|
<repo_name>NavneetPrakashSingh/hackerEarth<file_sep>/src/Arrays/GoogleSample.java
package Arrays;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
//link of the question: https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
public class GoogleSample {
private static final Scanner scanner = new Scanner(System.in);
public void PairSocks() throws IOException {
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] ar = new int[n];
String inputString = scanner.nextLine().replaceAll("\\-","");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
String result = solution(inputString, n);
System.out.println(result);
// bufferedWriter.write(String.valueOf(result));
// bufferedWriter.newLine();
//
// bufferedWriter.close();
scanner.close();
}
private String solution(String inputString, int n) {
System.out.println("Input String"+inputString+"Number"+n);
return null;
}
}
<file_sep>/src/LinkedList/LinkedList.java
package LinkedList;
public class LinkedList {
Node head;
//insert at the start of the node
public void push(int newData) {
Node nodeAtStart = new Node(newData);
nodeAtStart.next = head;
head = nodeAtStart;
}
//insert at the end of the node
public void insertAtEnd(int dataForNode) {
Node newNode = new Node(dataForNode);
Node lastNode = head;
if(lastNode == null) {
push(newNode.data);
return;
}
while(lastNode.next!=null) {
lastNode = lastNode.next;
}
lastNode.next = newNode;
}
//insert at nth position of the node
public void insertAtPosition(int dataForNode, int positionForNode) {
Node currentNode = head;
Node nodeToBeInserted = new Node(dataForNode);
int countForNode = 0;
while(currentNode.next != null) {
if(countForNode == positionForNode) {
// nodeToBeInserted.next = currentNode.next;
// currentNode.next = nodeToBeInserted;
System.out.println("Count for node is"+countForNode+ "current value of node"+ currentNode.data);
}
countForNode ++;
}
}
//print linked list
public void printLinkedList() {
System.out.println("Printing Linked List");
Node headNode = head;
while(headNode!=null) {
System.out.println(headNode.data+" ");
headNode = headNode.next;
}
}
}
<file_sep>/src/Practice/BFS.java
package Practice;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.LinkedList;
/*
* Problem reference: https://leetcode.com/problems/binary-tree-level-order-traversal/
*/
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) {
this.val = x;
this.left = null;
this.right = null;
}
}
class BinaryTree {
TreeNode currentNode;
public BinaryTree(int x) {
currentNode = new TreeNode(x);
}
}
public class BFS {
public List<List<Integer>> levelOrder(BinaryTree node){
List<List<Integer>> returningList = new ArrayList<List<Integer>>();
if(node == null) {
return returningList;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(node.currentNode);
while(!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> level = new ArrayList<Integer>();
for(int i=0;i<levelSize;i++) {
TreeNode currentNode = queue.poll();
level.add(currentNode.val);
if(currentNode.left!=null) {
queue.add(currentNode.left);
}
if(currentNode.right != null) {
queue.add(currentNode.right);
}
}
returningList.add(level);
}
return returningList;
}
public static void main(String[] args) {
BinaryTree node = new BinaryTree(3);
node.currentNode.left = new TreeNode(9);
node.currentNode.right = new TreeNode(20);
node.currentNode.right.right = new TreeNode(7);
node.currentNode.right.left = new TreeNode(15);
BFS BFSObj = new BFS();
List<List<Integer>> returnOutput = BFSObj.levelOrder(node);
System.out.println(returnOutput);
}
}
<file_sep>/src/Graphs/DFS.java
package Graphs;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;
import java.util.Vector;
public class DFS {
int numberOfVertices;
LinkedList<Integer>[] adjacencyList;
public DFS(int v) {
numberOfVertices = v;
adjacencyList = new LinkedList[numberOfVertices];
for(int i=0;i<numberOfVertices;i++) {
adjacencyList[i] = new LinkedList<Integer>();
}
}
public void printAdjacencyList() {
for(int i=0;i<numberOfVertices;i++) {
System.out.println(adjacencyList[i]);
}
}
public void addEdge(int firstEdge, int secondEdge) {
adjacencyList[firstEdge].add(secondEdge);
}
public void executeDFS(int startingNode) {
Stack<Integer> stack = new Stack<Integer>();
Vector<Boolean> visited = new Vector<Boolean>();
for(int i=0;i<numberOfVertices;i++) {
visited.add(false);
}
stack.push(startingNode);
while(!stack.isEmpty()) {
int currentElement =stack.pop();
if(visited.get(currentElement)==false) {
visited.set(currentElement, true);
System.out.println(currentElement);
}
Iterator<Integer> iterateOverAdjacencyList = adjacencyList[currentElement].iterator();
while(iterateOverAdjacencyList.hasNext()) {
int nextElement = iterateOverAdjacencyList.next();
// System.out.println(nextElement);
if(visited.get(nextElement) == false) {
stack.push(nextElement);
}
}
}
}
public static void main(String[] args) {
DFS dfs = new DFS(4);
dfs.addEdge(0, 1);
dfs.addEdge(0, 3);
dfs.addEdge(2, 3);
dfs.addEdge(1, 2);
dfs.printAdjacencyList();
dfs.executeDFS(1);
}
}
<file_sep>/src/Arrays/HackerRankSockMerchant.java
package Arrays;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
//link of the question: https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
public class HackerRankSockMerchant {
private static final Scanner scanner = new Scanner(System.in);
public void PairSocks() throws IOException {
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] ar = new int[n];
String[] arItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arItems[i]);
ar[i] = arItem;
}
int result = sockMerchant(n, ar);
System.out.println(result);
// bufferedWriter.write(String.valueOf(result));
// bufferedWriter.newLine();
//
// bufferedWriter.close();
scanner.close();
}
private int sockMerchant(int n, int[] ar) {
int[] sockPair = new int[100000];
for(int i=0;i<sockPair.length;i++) {
sockPair[i] = 0;
}
for(int i=0;i<ar.length;i++) {
sockPair[ar[i]] = sockPair[ar[i]] + 1;
}
int count = 0;
for(int i=0;i<sockPair.length;i++) {
count = count + (sockPair[i] /2);
}
return count;
}
}
<file_sep>/src/Practice/BuySellStock.java
package Practice;
import java.util.Arrays;
/*
* Problem reference: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
*/
public class BuySellStock {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int minValue = 9999;
for(int i=0;i<prices.length;i++) {
minValue = Math.min(minValue, prices[i]);
maxProfit = Math.max(maxProfit, prices[i]-minValue);
}
return maxProfit;
}
public static void main (String[] args) {
int[] input = new int[] {7,1,5,3,6,4};
BuySellStock stockObj = new BuySellStock();
System.out.println(stockObj.maxProfit(input));
}
}
<file_sep>/src/Google/Main.java
package Google;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
// Memorize memorize = new Memorize();
// memorize.MemorizeHackerEarth();
// memorize.optimizedHackerRankMemorizeSolution();
// MonkAndWelcome monkWelcomes = new MonkAndWelcome();
// monkWelcomes.MonkWelcome();
Solution newSolution = new Solution();
System.out.println(newSolution.solution("abcdefghijklmnopqrstuvwxyz", "cba"));
}
}
<file_sep>/src/Practice/LInkedList.java
package Practice;
/*
* Question link: https://leetcode.com/problems/design-linked-list/
*/
class Node{
int val;
Node next;
Node(int x){
val = x;
next = null;
}
Node(){
next = null;
}
}
class MyLinkedList {
Node head;
Node currentList;
/** Initialize your data structure here. */
public MyLinkedList() {
currentList = new Node();
head = new Node();
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int get(int index) {
return 0;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
public void addAtHead(int val) {
head.val = val;
head.next = currentList;
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
Node addNode = new Node(val);
Node tempNode = new Node();
while(currentList.next!=null) {
tempNode = currentList;
}
currentList.next = addNode;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
public void addAtIndex(int index, int val) {
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
}
/*
* Custom function
*/
public void printList() {
while(currentList.next!=null) {
System.out.println(currentList.val);
}
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
public class LInkedList {
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.addAtTail(1);
list.printList();
}
}
<file_sep>/src/LeetCode/Permutation.java
package LeetCode;
import java.util.ArrayList;
import java.util.List;
public class Permutation {
public List<List<Integer>> PermutationFormed(int[] nums){
List<List<Integer>> listToBeRetured = new ArrayList<List<Integer>>();
List<Integer> currentCombination;
return listToBeRetured;
}
public static void main(String[] args) {
// List<List<Integer>> intNestedList = new ArrayList<>();
//
// List<Integer> newList;
// for(int i=0;i<3;i++) {
// newList = new ArrayList<Integer>();
// for(int j=0;j<3;j++) {
// newList.add(j);
// }
// intNestedList.add(newList);
// }
//
// System.out.println(intNestedList);
}
}
<file_sep>/src/Tree/Main.java
package Tree;
public class Main {
public static void main(String[] args) {
BinaryTree root = new BinaryTree(10);
root.node.left = new Node(1);
root.node.right = new Node(2);
System.out.println(root.node.value);
}
}
<file_sep>/src/LinkedList/Insert.java
package LinkedList;
public class Insert {
//Insert node at the front of the linked list
public void Push(int newData) {
}
}
<file_sep>/src/Arrays/MonkAndWelcome.java
package Arrays;
import java.util.Scanner;
public class MonkAndWelcome {
public void MonkWelcome() {
Scanner inputSizeOfArray = new Scanner(System.in);
int sizeOfArray = inputSizeOfArray.nextInt();
int[] inputArray = new int[sizeOfArray];
for(int i=0;i<sizeOfArray;i++) {
inputArray[i] = 0;
}
Scanner scanInputValues = new Scanner(System.in);
for(int i=0;i<sizeOfArray;i++) {
int inputValues = scanInputValues.nextInt();
inputArray[i] = inputArray[i] + inputValues;
}
Scanner scanSecondInput = new Scanner(System.in);
for(int i=0;i<sizeOfArray;i++) {
int inputValues = scanSecondInput.nextInt();
inputArray[i] = inputArray[i] + inputValues;
}
for(int i=0;i<sizeOfArray;i++) {
System.out.print(inputArray[i]+" ");
}
}
}
<file_sep>/src/Arrays/TwoDArray.java
package Arrays;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class TwoDArray {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int[][] arr = new int[6][6];
for (int i = 0; i < 6; i++) {
String[] arrRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 6; j++) {
int arrItem = Integer.parseInt(arrRowItems[j]);
arr[i][j] = arrItem;
}
}
int result = hourglassSum(arr);
System.out.println(result);
scanner.close();
}
private static int hourglassSum(int[][] arr) {
// TODO Auto-generated method stub
int max = -9999999;
// for(int outer = 0; outer<4;outer++) {
// max = arr[]
// }
int currentValue = 0;
int count =0;
for(int i=0;i<4;i++) {
for(int j=i;j<i+3;j++) {
System.out.println(i+"----------------"+j);
currentValue = currentValue + arr[i][j] + arr[i+2][j];
if(count == 1) {
currentValue = currentValue + arr[i+1][j];
}
count = count +1;
}
count =0;
}
return 0;
}
}
<file_sep>/src/LinkedList/Main.java
package LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.push(1);
linkedList.push(2);
// linkedList.insertAtEnd(3);
linkedList.insertAtPosition(4, 2);
linkedList.printLinkedList();
}
}
<file_sep>/src/LeetCode/ReverseString.java
package LeetCode;
public class ReverseString {
public void reverseString(char[] s) {
char temp;
for(int i=0;i<s.length/2;i++) {
temp = s[i];
s[i] = s[s.length-1-i];
s[s.length-1-i] = temp;
}
System.out.println(s);
}
public static void main(String[] args) {
char[] currentArray = new char[5];
currentArray[0] = 'h';
currentArray[1] = 'e';
currentArray[2] = 'l';
currentArray[3] = 'l';
currentArray[4] = 'o';
ReverseString reverseObj = new ReverseString();
reverseObj.reverseString(currentArray);
}
}
|
d036a6e3fa99bdc4bf1c98a0e679b4ab0cb9dfaa
|
[
"Java"
] | 15
|
Java
|
NavneetPrakashSingh/hackerEarth
|
e8af54ca8c0451e5494de6d839ca1ba0afef5049
|
9a6b14b3f4a6e29cb535caea59b92443b4f6913a
|
refs/heads/master
|
<file_sep>import React from 'react';
import FeatureGive from '../images/Django.png';
import Give1 from '../images/give1.png';
import Give2 from '../images/give2.png';
import Give3 from '../images/give3.png';
import Give4 from '../images/give4.png';
const Give = (props) => (
<section className="container u-m-t-100">
<div className="columns is-mobile is-centered is-vcentered">
<div className="column">
<h1>{props.title}</h1>
<p>Your support helps develop STEAM-based solutions for a healthy, safe, and sustainable future. – please know that every little bit counts.</p>
<p>Ask your employer if they have a matching program in place, our <strong>Federal Taxpayer ID is 82-4398280</strong>. See our listing on the nation's premier nonprofit database <strong><a href="https://www.guidestar.org/profile/82-4398280">GuidStar</a></strong>.</p>
</div>
<div className="column">
<figure className="image">
<img src={FeatureGive} alt="" />
<figcaption className="has-text-centered">Board members Rebecca, Carol and Brent at Spokanes’ first Django Girls Workshop, summer 2018</figcaption>
</figure>
</div>
</div>
<div className="container has-text-centered">
<h2 className="">MAKE A DONATION</h2>
<div className="columns is-multiline">
<div className="column is-half is-multiline">
<div class="columns is-multiline">
<div className="column is-half">
<img src={Give1} alt="" />
</div>
<div className="column is-half">
<img src={Give2} alt="" />
</div>
<div className="column is-half">
<img src={Give3} alt="" />
</div>
<div className="column is-half">
<img src={Give4} alt="" />
</div>
</div>
</div>
<div className="column is-half has-text-left">
<div className="column notification u-p-b-30" >
<h4>Our community is strong because your support makes all the difference.</h4>
<hr className="hrline" />
<p>Future Ada relies heavily on the generosity of our donors to be able to provide education to create awareness, excitement, and opportunities among women and non-binaries to pursue successful STEAM-related careers.</p>
<p>Our secure online donation system is managed through Stripe. Your donation will show up as “<strong>FutureADA ORG</strong>” on your statement.</p>
<a href="" className="clicky">MAKE A DONATION</a>
</div>
</div>
{/* End the colum */}
</div>
<article className="message">
<div className="message-body has-text-centered cta u-p-t-30 u-p-b-30">
<div class="columns">
<div className="column is-half">
<blockquote className="quote u-p-t-20">
Art + Design are poised to transform our economy in the 21st century just as science and technology did in the last century. To do this We need to add Art + Design to the equation — to transform STEM into STEAM.
</blockquote>
</div>
<div className="column is-half">
<img src={Give1} alt="" />
</div>
</div>
</div>
</article>
</div>
</section>
);
export default Give;<file_sep>import React from 'react';
import FeatureAbout from '../images/Science.png';
import Board from './Board';
import boardmember from '../data/board.json';
const About = (props) => (
<section className="container u-m-t-100">
<div className="columns is-mobile is-centered is-vcentered">
<div className="column">
<h1>{props.title}</h1>
<p>It is our belief that the fields of science, technology, engineering, art and mathematics are stronger when they are both diverse and inclusive.</p>
<p>We want to do our part to help ensure that these fields are open, available, and safe for women and non-binary individuals to be a part of.</p>
</div>
<div className="column">
<figure className="image">
<img src={FeatureAbout} alt="" />
<figcaption className="has-text-centered">Girl Scouts of America STEM program</figcaption>
</figure>
</div>
</div>
<article className="message">
<div className=" has-text-left cta u-p-50">
<h2>Our Vision</h2>
<p>To create a diverse and inclusive environment within all of the STEAM fields.</p>
<h2>Our Mission</h2>
<p>To secure space for women and non-binary individuals in the STEAM (science, technology, engineering, art, and mathematics) fields.</p>
<h2>Why it matters</h2>
<p>STEAM, which involves a collaborative mix of Science, Technology, Engineering, Art, and Mathematics, is vital to our future. Diversity expands worldliness, expands social development, promotes creative thinking and prepairs us for the global society.</p>
</div>
</article>
<section>
<h2>Board of Directors</h2>
<p>Future Ada is led by a volunteer Board of Directors who determine policies, guide financial decisions, and oversee the success of the organization.</p>
<section className="section has-text-centered">
<h2 className="has-text-centered u-p-30">WHO WE ARE</h2>
<div className="container">
<div className="columns is-multiline">
{boardmember.map((boardmember, idx) => {
return <Board key={idx} boardmember={boardmember} />
})}
</div>
</div>
</section>
</section>
</section>
);
export default About;<file_sep>import React from 'react';
import FeatureNASA from '../images/NASA.png';
const Hangout = (props) => (
<section className="container u-m-t-100">
<div className="columns is-mobile is-centered is-vcentered">
<div className="column">
<h1>{props.title}</h1>
<p>Connect with like minded groups below, don't see one your interested in, let us know – we can help connect you or set something up.</p>
</div>
<div className="column">
<figure className="image">
<img src={FeatureNASA} alt="" />
<figcaption className="has-text-centered">2018 Women in Science Day. <br />Image credit: NASA/JPL-Caltech</figcaption>
</figure>
</div>
</div>
<section className="resource u-m-t-20 u-p-b-20">
<h1>Connect on Facebook</h1>
<p>We are a non-profit organization based in Spokane, Washington. Our mission is in securing space for women and non-binary individuals in the science, technology, engineering, arts and mathematics (STEAM) fields.</p>
<a href="https://business.facebook.com/futureada/" target="_blank" className="clicky u-m-t-20" rel="noopener noreferrer">FACEBOOK PAGE</a>
</section>
<section className="resource u-m-t-20 u-p-b-20">
<h1>Follow on Twitter</h1>
<p>It is our belief that the fields of science, technology, engineering, arts and mathematics are stronger when they are both diverse and inclusive.</p>
<a href="https://twitter.com/futureada" target="_blank" className="clicky u-m-t-20" rel="noopener noreferrer">TWITTER</a>
</section>
<section className="resource u-p-b-20">
<h1>Linkedin</h1>
<p>We want to do our part to help ensure that these fields are open, available, and safe for women and non-binary individuals to be a part of.</p>
<a href="https://www.linkedin.com/company/futureada/" target="_blank" className="clicky u-m-t-20" rel="noopener noreferrer">LINKEDIN</a>
</section>
</section>
);
export default Hangout;<file_sep>import React from 'react';
import { Timeline } from 'react-twitter-widgets';
import FeatureHome from '../images/FutureAdaOrg.png';
const Home = (props) => (
<section className="container u-m-t-100">
<div className="columns is-mobile is-centered is-vcentered">
<div className="column">
<h1>{props.title}</h1>
<p>Hi, our mission is to secure space for women and non-binary individuals in the STEAM (science, technology, engineering, art, and mathematics) fields.
</p>
<p>We stand by the following values, through collaboration we aim to create a diverse and inclusive environment within all of the STEAM fields.</p>
</div>
<div className="column">
<figure className="image">
<img src={FeatureHome} alt="" />
<figcaption className="has-text-centered">We draw our inspiration from <br /><NAME> and <NAME></figcaption>
</figure>
</div>
</div>
<article className="message">
<div className="message-body has-text-centered cta u-p-t-50 u-p-b-50">
<blockquote className="quote ">
The Analytical Engine weaves algebraic patterns, just as the Jacquard loom weaves flowers and leaves. <span className="is-small">– Ada Lovelace (<a href="https://en.wikipedia.org/wiki/Ada_Lovelace" target="_blank" rel="noopener noreferrer">Wikipedia </a> </span>
</blockquote>
</div>
</article>
<section>
<h2 className="has-text-centered u-p-30">WHO WE ARE</h2>
<div className="container">
<div className="columns">
<div className="column has-text-centered is-flex">
<div className="notification">
<h4>Who we are</h4>
<p className="has-text-left">
Our mission is in securing space for women and non-binary individuals in the science, technology, engineering, arts and mathematics (STEAM) fields.</p>
<a href="https://brentschneider.github.io/about" className="clicky" rel="noopener noreferrer">WHAT WE STAND FOR</a>
</div>
</div>
<div className="column has-text-centered is-flex">
<div className="notification has-text-centerd">
<h4>Board of Directors</h4>
<p className="has-text-left">We want to do our part to help ensure that these fields are open, available, and safe for women and non-binary individuals to be a part of.</p>
<a href="https://brentschneider.github.io/about" className="clicky" rel="noopener noreferrer">ABOUT US</a>
</div>
</div>
<div className="column has-text-centered is-flex">
<div className="notification has-text-centerd">
<h4>Code of Conduct</h4>
<p className="has-text-left">
Future Ada is dedicated to providing an inclusive, safe, welcoming, harassment free space where community members feel comfortable participating and being themselves.</p>
<a href="https://github.com/futureada/Code-of-Conduct" className="clicky" target="_blank" rel="noopener noreferrer">CODE OF CONDUCT</a>
</div>
</div>
</div>
</div>
</section>
{/* GIT HUB PAGES DOESN'T RENDER THIS – bug */}
<div className="card u-m-t-30">
<div className="card-content">
<div className="media has-text-centerd">
<Timeline
dataSource={{
sourceType: 'profile',
screenName: 'futureada'
}}
options={{
username: 'futureada',
height: '520',
width: 900
}}
// Removed after testing
// onLoad={() => console.log('Timeline is loaded!')}
/>
</div>
</div>
</div>
</section>
);
export default Home;<file_sep>This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
# Project Codename: Future Ada
Future Ada is a non-profit startup, focusing on securing space for women and non-binary individuals in the STEAM fields.
## 📝 Wireframes

★ [View high-fidelity composition on InVision](https://invis.io/BRKX7C0U4GS#/303030945_HOME)
## 🐙 Dependencies
* Create React APP using `npm install -g create-ceact-app`
* [react-twitter-widgets](https://www.npmjs.com/package/react-twitter-widgets)
using `npm install --save react-twitter-widgets`
* [bulma](https://www.npmjs.com/package/react-bulma-components) using `npm install react-bulma-components`
* [gitpages](https://www.npmjs.com/package/gitpages) using `npm install gh-pages --save-dev`
## 🦉 Task List
A list of tasks that need to be completed for your project.
- [x] Setup `create-react-app` scaffold add BrowserRouter
- [x] Render React state
- [x] Design Wireframe layout
- [x] Develop Content for pages
- [x] Create design patterns html css (using Bulma)
- [x] Develop page components
- [x] Pull twitter news feed
~~- [ ] Setup VPS environment~~
~~- [ ] Deploy to server via git~~
- [x] Deploy to GitHub Pages
## The Result
👆 First deployment was a sucess setting up a Virtual Private Server, untill the site domane name was changed to another partner hosting.
🤞 Second try was setting up another VPS instance under a different domaine, with no sucess.
🎉 After some rethinking I decided to try deploying to Github pages.
View on: [brentschneider.github.io/futureada/](https://brentschneider.github.io/futureada/)<file_sep>import React from 'react';
import FeatureResource from '../images/NASA.png';
const Resources = (props) => (
<section className="container u-m-t-100">
<div className="columns is-mobile is-centered is-vcentered">
<div className="column">
<h1>{props.title}</h1>
<p>Interested in volunteering, partnering, or learning more? Contact us to find out more about what we currently have going on for opportunities!</p>
</div>
<div className="column">
<figure className="image">
<img src={FeatureResource} alt="" />
<figcaption className="has-text-centered">2018 Women in Science Day. <br />Image credit: NASA/JPL-Caltech</figcaption>
</figure>
</div>
</div>
<section className="resource u-m-t-20 u-p-b-20">
<h1>DjangoGirls Workshop</h1>
<h2>Workshop – Sept 28 & 29, 2018</h2>
<p>A one-day free workshop for women on programming to learn Python and Django. More details and registration information coming soon! @ Startup Spokane.</p>
<a href="https://djangogirls.org/events/" target="_blank"className="clicky u-m-t-20" rel="noopener noreferrer">WORKSHOP INFORMATION</a>
</section>
<section className="resource u-m-t-20 u-p-b-20">
<h1>CODE: Debugging the Gender Gap</h1>
<h2>Event: TBA Fall, 18</h2>
<p>CODE documentary exposes the dearth of American female and minority software engineers and explores the reasons for this gender gap.</p>
<a href="https://www.facebook.com/futureada/" target="_blank" className="clicky u-m-t-20" rel="noopener noreferrer">UPCOING EVENTS</a>
</section>
<section className="resource u-p-b-20">
<h1>Want to be a developer?</h1>
<h2>Partner – Ada Developers Academy</h2>
<p>The Ada program consists of six months of classroom training followed by five months in a paid, learning internship in the greater Seattle area as a software developer.</p>
<a href="https://www.adadevelopersacademy.org/" target="_blank" className="clicky u-m-t-20" rel="noopener noreferrer">SEATTLE PARTNER</a>
</section>
</section>
);
export default Resources;<file_sep>import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom'
import './css/App.css';
import 'bulma/css/bulma.css'
// App components
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './components/Home';
import About from './components/About';
import Give from './components/ways-to-give';
import Resources from './components/Resources';
import Hangout from './components/Hangout';
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Header />
<switch>
{/* LOCAL DEV*/}
{/* <Route exact path="/" render={ () => <Home title='Future Ada' /> } />
<Route path="/about" render={ () => <About title='About US' /> } />
<Route path="/resources" render={ () => <Resources title='Resources' /> } />
<Route path="/ways-to-give" render={ () => <Give title='Ways to Give' /> } />
<Route path="/hangout" render={ () => <Hangout title="Let's Hangout" /> } />
*/}
{/* GITHUB PAGES */}
<Route path="/futureada/" render={ () =>
<Home title='Future Ada' /> } />
<Route path="/futureada/about" render={ () => <About title='About US' /> } />
<Route path="/futureada/resources" render={ () => <Resources title='Resources' /> } />
<Route path="/futureada/ways-to-give" render={ () => <Give title='Ways to Give' /> } />
<Route path="/futureada/hangout" render={ () => <Hangout title="Let's Hangout" /> } />
</switch>
<Footer />
</div>
</BrowserRouter>
);
}
}
export default App;
|
99dd119e4250c3145d51a11d5f204730d2895b3e
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
brentschneider/futureada
|
6011d795d46e0aa30290effc0aa97de8052399ae
|
10ac0112d5ffbcc1787542f20785f06ac4c934c7
|
refs/heads/master
|
<repo_name>zackdraper/pysed<file_sep>/pysed.py
from astroquery.vizier import Vizier
from astropy.coordinates import Angle
import numpy as np
import matplotlib.pyplot as plt
import sys
from scipy.interpolate import interp1d
from astropy import units as u
from scipy.optimize import curve_fit
from scipy.integrate import simps
from scipy.io import readsav
from scipy.interpolate import interp1d
from scipy import arange, array, exp
from scipy.interpolate import InterpolatedUnivariateSpline
def dered_extinc(wave,mag,color):
wave = 1/wave # inverse microns
inv_lam = [0.00,0.377,0.820,1.667,1.828,2.141,2.433,3.0704,3.846]
extn_ratio = [0.00,0.265,0.829,2.688,3.055,3.806,4.315,6.625,6.591]
f = interp1d(inv_lam, extn_ratio, kind='cubic')
print 'org: ',mag,'f: ',f(1/wave),'new: ',mag+f(1/wave)*color
return mag+f(1/wave)*color
def mag2mJy(mag,f_zpt):
return f_zpt*10**(mag/(-2.5))*1000
def sed_catalog_search(target):
#print target
wave = np.array([])*u.nm
phot = np.array([])*u.mJy
phot_e = np.array([])*u.mJy
notes = np.array([])
#Thompson TD1 UV Catalog ----------
cat = 'II/59B'
v = Vizier(columns=['F2740','e_F2740','F2365','e_F2365','F1965','e_F1965','F1565','e_F1565'])
res = v.query_object(target,catalog=[cat])
if not not res:
TD1_2740 = res[0]['F2740'][0]
TD1_2740_e = res[0]['e_F2740'][0]
TD1_2365 = res[0]['F2365'][0]
TD1_2365_e = res[0]['e_F2365'][0]
TD1_1965 = res[0]['F1965'][0]
TD1_1965_e = res[0]['e_F1965'][0]
TD1_1565 = res[0]['F1565'][0]
TD1_1565_e = res[0]['e_F1565'][0]
print "TD1"
print TD1_2740,TD1_2365,TD1_1965,TD1_1565
print TD1_2740_e,TD1_2365_e,TD1_1965_e,TD1_1565_e
u_wave = ([2740, 2365, 1965, 1565,]*u.AA).to('micron')
u_phot = np.array([TD1_2740,TD1_2365,TD1_1965,TD1_1565])*1e-2 #centiWatts to Watts
u_phot_e = np.array([TD1_2740_e,TD1_2365_e,TD1_1965_e,TD1_1565_e])*1e-2 #centiWatts to Watts
u_phot = u_phot * (u.Watt/u.meter**2/u.nm).to('mJy', equivalencies= u.spectral_density(u_wave) )
u_phot_e = u_phot_e * (u.Watt/u.meter**2/u.nm).to('mJy', equivalencies= u.spectral_density(u_wave) )
wave = np.append(wave,u_wave)
phot = np.append(phot,u_phot)
phot_e = np.append(phot_e,u_phot_e)
notes = np.append(notes,['TD 1','TD 1','TD 1','TD 1'])
#Tycho Catalog --------------------
cat = 'I/259'
v = Vizier(columns=['BTmag','e_BTmag','VTmag','e_VTmag'])
res = v.query_object(target,catalog=[cat])
if not not res:
tychoB = res[0]['BTmag'][0]
tychoV = res[0]['VTmag'][0]
BmV = tychoB - tychoV
tychoV = tychoV-0.090*(BmV)
tychoB = 0.850*(BmV)+tychoV
color = BmV-0.438
tychoB = dered_extinc(4400*0.0001,tychoB,color)
tychoV = dered_extinc(5500*0.0001,tychoV,color)
tychoB_e = res[0]['e_BTmag'][0]
tychoV_e = res[0]['e_VTmag'][0]
tychoB_e = mag2mJy(tychoB+tychoB_e,4130)
tychoV_e = mag2mJy(tychoV+tychoV_e,3781)
tychoB = mag2mJy(tychoB,4130)
tychoV = mag2mJy(tychoV,3781)
tychoB_e = np.abs(tychoB - tychoB_e)
tychoV_e = np.abs(tychoV - tychoV_e)
print "Tycho"
print tychoV,tychoB
print tychoB_e,tychoV_e
wave = np.append(wave,np.array([4400,5500])*0.0001) #angstroms to microns
phot = np.append(phot,[tychoB,tychoV])
phot_e = np.append(phot_e,[tychoB_e,tychoV_e])
notes = np.append(notes,['Tycho B','Tycho V'])
#ASAA of ROSAT Catalog --------------------
cat = 'J/AcA/62/67'
v = Vizier(columns=['__Vmag_','__Imag_','sVmag','sImag'])
res = v.query_object(target,catalog=[cat])
if not not res:
asasV = res[0]['__Vmag_'][0]
asasI = res[0]['__Imag_'][0]
asasV_e = res[0]['sVmag'][0]
asasI_e = res[0]['sImag'][0]
asasV_e = mag2mJy(asasV_e+asasV,3781)
asasI_e = mag2mJy(asasI_e+asasI,2635)
asasV = mag2mJy(asasV,3781)
asasI = mag2mJy(asasI,2635)
asasV_e = np.abs(asasV - asasV_e)
asasI_e = np.abs(asasI - asasI_e)
print "ROSAT"
print asasV,asasI
print asasV_e,asasI_e
wave = np.append(wave,np.array([5500,9700])*0.0001) #angstroms to microns
phot = np.append(phot,[asasV,asasI])
phot_e = np.append(phot_e,[asasV_e,asasI_e])
notes = np.append(notes,['ASAS V','ASAS I'])
# 2MASS Catalog --------------------
cat = 'II/246'
v = Vizier(columns=['Jmag','Hmag','Kmag','e_Jmag','e_Hmag','e_Kmag'])
res = v.query_object(target,catalog=[cat],radius=Angle(3, "arcsec"))
if not not res:
twomassJ = res[0]['Jmag'][0]
twomassH = res[0]['Hmag'][0]
twomassK = res[0]['Kmag'][0]
twomassJ_e = res[0]['e_Jmag'][0]
twomassH_e = res[0]['e_Hmag'][0]
twomassK_e = res[0]['e_Kmag'][0]
#twomassJ = dered_extinc(1.235,twomassJ,color)
#twomassH = dered_extinc(1.662,twomassH,color)
#twomassK = dered_extinc(2.159,twomassK,color)
print 'J-H',twomassJ-twomassH
print 'H-K',twomassH-twomassK
twomassJ_e = mag2mJy(twomassJ_e+twomassJ,1594)
twomassH_e = mag2mJy(twomassH_e+twomassH,1024)
twomassK_e = mag2mJy(twomassK_e+twomassK,666.7)
twomassJ = mag2mJy(twomassJ,1594)
twomassH = mag2mJy(twomassH,1024)
twomassK = mag2mJy(twomassK,666.7)
twomassJ_e = np.abs(twomassJ - twomassJ_e)
twomassH_e = np.abs(twomassH - twomassH_e)
twomassK_e = np.abs(twomassK - twomassK_e)
print "2MASS"
print twomassJ,twomassH,twomassK
print twomassJ_e,twomassH_e,twomassK_e
wave = np.append(wave,[1.235,1.662,2.159])
phot = np.append(phot,[twomassJ,twomassH,twomassK])
phot_e = np.append(phot_e,[twomassJ_e,twomassH_e,twomassK_e])
notes = np.append(notes,['2MASS J','2MASS H','2MASS K'])
#Spitzer Catalog --------------------
cat = 'J/ApJS/211/25/catalog' # Chen 2014 Catalog; units microns and mJy
v = Vizier(columns=['F13','e_F13','F24','e_F24','F31','e_F31','F70','e_F70'])
res = v.query_object(target,catalog=[cat],radius=Angle(3, "arcsec"))
if not not res:
sptzr13irs = res[0]['F13'][0] # mJy to Jy
sptzr24mips = res[0]['F24'][0]
sptzr31irs = res[0]['F31'][0]
sptzr70mips = res[0]['F70'][0]
sptzr13irs_e = res[0]['e_F13'][0]
sptzr24mips_e = res[0]['e_F24'][0]
sptzr31irs_e = res[0]['e_F31'][0]
sptzr70mips_e = res[0]['e_F70'][0]
print "Spitzer"
print sptzr13irs,sptzr24mips,sptzr31irs,sptzr70mips
print sptzr13irs_e,sptzr24mips_e,sptzr31irs_e,sptzr70mips_e
wave = np.append(wave,[10.75,24,32,70])
phot = np.append(phot,[sptzr13irs,sptzr24mips,sptzr31irs,sptzr70mips])
phot_e = np.append(phot_e,[sptzr13irs_e,sptzr24mips_e,sptzr31irs_e,sptzr70mips_e])
notes = np.append(notes,['Spitzer IRS 13','Spitzer MIPS 24','Spitzer IRS 31','Spitzer MIPS 70'])
#WISE Catalog --------------------------
cat ='II/328/allwise'
v = Vizier(columns=['W1mag','e_W1mag','W2mag','e_W2mag','W3mag','e_W3mag','W4mag','e_W4mag'])
res = v.query_object(target,catalog=[cat],radius=Angle(3, "arcsec"))
if not not res:
w1mag = res[0]['W1mag'][0]
w2mag = res[0]['W2mag'][0]
w3mag = res[0]['W3mag'][0]
w4mag = res[0]['W4mag'][0]
w1mag = mag2mJy(w1mag,309.540)
w2mag = mag2mJy(w2mag,171.787)
w3mag = mag2mJy(w3mag,31.674)
w4mag = mag2mJy(w4mag,8.363)
w1mag_e = res[0]['e_W1mag'][0]
w2mag_e = res[0]['e_W2mag'][0]
w3mag_e = res[0]['e_W3mag'][0]
w4mag_e = res[0]['e_W4mag'][0]
print "WISE"
print w1mag,w2mag,w3mag,w4mag
print w1mag_e,w2mag_e,w3mag_e,w4mag_e
wave = np.append(wave,[3.3526,4.6028,11.5608,22.0883])
phot = np.append(phot,[w1mag,w2mag,w3mag,w4mag])
phot_e = np.append(phot_e,[w1mag_e,w2mag_e,w3mag_e,w4mag_e])
notes = np.append(notes,['WISE 1','WISE 2','WISE 3','WISE 4'])
#AKARI data
cat='II/297'
v = Vizier(columns=['S09','e_S09','S18','e_S18'])
res = v.query_object(target,catalog=[cat],radius=Angle(3, "arcsec"))
if not not res:
#Jy to mJy
S09mag = res[0]['S09'][0]*1000
S18mag = res[0]['S18'][0]*1000
S09mag_e = np.float(res[0]['e_S09'][0])*1000
S18mag_e = np.float(res[0]['e_S18'][0])*1000
if ((S09mag > 0) and (S09mag_e > 0)):
wave = np.append(wave,[8.61])
phot = np.append(phot,[S09mag])
phot_e = np.append(phot_e,[S09mag_e])
notes = np.append(notes,['AKARI S9'])
if ((S18mag > 0) and (S18mag_e > 0)):
wave = np.append(wave,[18.39])
phot = np.append(phot,[S18mag])
phot_e = np.append(phot_e,[S18mag_e])
notes = np.append(notes,['AKARI L18'])
print "AKARI"
print S09mag,S18mag
print S09mag_e,S18mag_e
# END catalogs -------------------------------------
sed_data = [wave, phot, phot_e, notes]
print np.transpose(sed_data)
return sed_data
def pow_law(x,exp,C):
return 10**(-2*np.log10(x)+C)
def extrap1d(interpolator):
xs = interpolator.x
ys = interpolator.y
def pointwise(x):
if x < xs[0]:
x=np.log(x)
y=np.log(y)
xs2=np.log(xs)
ys2=np.log(ys)
return 10**(ys2[0]+(x-xs2[0])*(ys2[1]-ys2[0])/(xs2[1]-xs2[0]))
elif x > xs[-1]:
x=np.log(x)
y=np.log(y)
xs2=np.log(xs)
ys2=np.log(ys)
return 10**(ys2[-1]+(x-xs2[-1])*(ys2[-1]-ys2[-2])/(xs2[-1]-xs2[-2]))
else:
return interpolator(x)
def ufunclike(xs):
return array(map(pointwise, array(xs)))
return ufunclike
def read_spitzer_irsa(file):
archive = zipfile.ZipFile(file,'r')
files = zipfile.ZipFile.namelist(archive)
tables = [s for s in files if 'tune.tbl' in s]
data = [0,0,0,0,0]
for t in tables:
tabletoread = zipfile.ZipFile.read(archive,t)
lines = tabletoread.split('\n')
for l in lines:
if ('char' in l) or ('|' in l) or ('\\' in l):
pass
else:
dataline = filter( None,l.split(' ') )
if (np.size(dataline) > 3):
data = np.vstack((data,dataline))
return (data[1:,0:]).astype(np.float)
def add_photometry(result,phot_arr):
wave, phot, phot_e, notes = list(result)
wave = np.append(wave,phot_arr[0])
phot = np.append(phot,phot_arr[1])
phot_e = np.append(phot_e,phot_arr[2])
notes = np.append(notes,phot_arr[3])
return [wave, phot, phot_e, notes]
def fit_sed(target,result,nbb='single',star_type='bb',star_models={},distance=100):
wave, phot, phot_e, notes = list(result)
def sed_bb(lam,T,area):
#lam in microns
#T in Kelvin
k=1.3806488*10**(-16) #boltzmann erg/K
h=6.62606957*10**(-27) #plank erg*s
c=2.99792458*10**14 #speed of light micron/s
f=((2*h*c**2)/lam**5)/(np.exp((h*c)/(lam*k*T))-1) # F_nu in mJy
f = f*lam**2
return f*area
def mod_sed_bb(lam,T,area,lam_o,beta):
#lam in microns
#T in Kelvin
k=1.3806488*10**(-16) #boltzmann erg/K
h=6.62606957*10**(-27) #plank erg*s
c=2.99792458*10**14 #speed of light micron/s
f=((2*h*c**2)/lam**5)*(1/(np.exp(h*c/(lam*k*T))-1)) # F_nu in mJy
f = f*lam**2
id = np.where(lam > lam_o)
f[id] = f[id]*(lam[id]/lam_o)**beta
return f*area
def dub_mod_sed_bb(lam,T1,area1,T2,area2,lam_o,beta):
#lam in microns
#T in Kelvin
#lam_o=210.0
#beta=0.8
k=1.3806488*10**(-16) #boltzmann erg/K
h=6.62606957*10**(-27) #plank erg*s
c=2.99792458*10**14 #speed of light micron/s
f1=((2*h*c**2)/lam**5)*(1/(np.exp(h*c/(lam*k*T1))-1)) # F_nu in mJy
f1=f1*lam**2*area1
f2=((2*h*c**2)/lam**5)*(1/(np.exp(h*c/(lam*k*T2))-1)) # F_nu in mJy
f2=f2*lam**2*area2
id = np.where(lam > lam_o)
f1[id] = f1[id]*(lam[id]/lam_o)**beta
f2[id] = f2[id]*(lam[id]/lam_o)**beta
return f1+f2
#--------------------
x1 = np.arange(0.1,2500,0.05)
fig, ax = plt.subplots(1,1,figsize=(8, 6),dpi=300)
if star_type.lower() == "bb":
#plot bb fit
x0 = [5500,1]
id = np.where(wave < 11)
starpopt, pcov = curve_fit(sed_bb,wave[id],phot[id],sigma=phot_e[id],p0=x0)
#starpopt = [5500,45]
starbb = sed_bb(wave,*starpopt)
fstar = sed_bb(x1,*starpopt)
ax.loglog(x1,fstar,'r-')
print 'Stellar Teff: '+str(starpopt[0])
elif star_type.lower() == "stellar":
id = np.where(wave < 11)
x_m,f_m,temp_str = chisqr_stellar_models(wave[id],phot[id],phot_e[id],star_models,pin_wave = 1.5)
print 'Stellar Teff: '+temp_str
starbb_func = interp1d(x_m,f_m)
starbb = starbb_func(wave)
fstar = starbb_func(x1)
ax.loglog(x_m,f_m,'r-')
if nbb.lower() == "single":
#x0 = [300,1*10**6,150,1*10**7,210,1]
x0 = [50,1*10**6,210.0,0.0]
id = np.where(wave > 12)
dustpopt, pcov = curve_fit(mod_sed_bb,wave[id],phot[id]-starbb[id],sigma=phot_e[id],p0=x0)
f2 = mod_sed_bb(x1,*dustpopt)
diskbb = mod_sed_bb(wave,*dustpopt)
#residual points
resid = np.abs(phot-starbb-diskbb)
ids = np.where(resid < 3*phot_e)
ax.loglog(wave[ids],resid[ids],'yv',markersize=5)
ids = np.where(resid > 3*phot_e)
ax.loglog(wave[ids],resid[ids],'yo',markersize=5)
ftot = fstar+f2
#ax.loglog(x_m,f*x_m**2,'b-')
ax.loglog(x1,f2,'g--')
ax.loglog(x1,ftot,'k-')
#ax.loglog(x1,mod_sed_bb(x1,dustpopt[0],dustpopt[1],210,-1.0),'k--')
#ax.loglog(x1,mod_sed_bb(x1,dustpopt[0],dustpopt[1],210,-2.0),'k-.')
print 'Dust Teff: '+str(dustpopt[0])
print "Output File: "+str(target+'_'+nbb+'.png')
elif nbb.lower() == "double":
x0 = [200,1E6,50,1E7,210,0]
id = np.where(wave > 10)
bounds = ((5,0,5,0,120,-5),(2000,np.inf,2000,np.inf,500,5))
dustpopt, dustpcov = curve_fit(dub_mod_sed_bb,wave[id],phot[id]-starbb[id],sigma=phot_e[id],p0=x0,bounds=bounds)
f2 = dub_mod_sed_bb(x1,*dustpopt)
diskbb = dub_mod_sed_bb(wave,*dustpopt)
#residual points
resid = np.abs(phot-starbb-diskbb)
ids = np.where(resid < 3*phot_e)
ax.loglog(wave[ids],resid[ids],'yv',markersize=5)
ids = np.where(resid > 3*phot_e)
ax.loglog(wave[ids],resid[ids],'yo',markersize=5)
resid = np.abs(phot-starbb)
ax.loglog(wave,resid,'yo',markersize=2)
ftot = fstar+f2
diskbb1 = mod_sed_bb(x1,dustpopt[2],dustpopt[3],dustpopt[4],dustpopt[5])
diskbb2 = mod_sed_bb(x1,dustpopt[0],dustpopt[1],dustpopt[4],dustpopt[5])
ax.loglog(x1,diskbb1,'g--')
ax.loglog(x1,diskbb2,'g--')
ax.loglog(x1,ftot,'k-',markersize=2)
frac_lum = (get_lum(x1,diskbb1,distance)+get_lum(x1,diskbb2,distance))/get_lum(x1,ftot,distance)
#print 'Stellar Teff: '+str(starpopt[0])
print 'Warm Dust Teff: '+"{:.2f}".format(dustpopt[0])
print 'Cold Dust Teff: '+"{:.2f}".format(dustpopt[2])
print 'Modified BB Wavelength: '+"{:.2f}".format(dustpopt[4])
print 'Modified BB Slope: '+"{:.2f}".format(dustpopt[5])
print 'Log Fractional Luminosity: '+"{:.2f}".format(np.log10(frac_lum))
#print dustpopt
print "Output File: "+str(target+'_'+nbb+'.png')
ax.loglog(wave,phot,'co')
ax.set_xlabel(r'wavelength ($\mu$m)',fontsize="20")
ax.set_ylabel('F (mJy)',fontsize="20")
ax.set_title(target,fontsize="20")
ax.set_ylim([np.min(phot).value/10, np.max(phot).value*10])
ax.set_xlim([np.min(wave).value/10, np.max(wave).value*10])
plt.savefig(target+'_'+nbb+'.png')
return ax
def compile_stellar_models(folder):
import pyfits
import glob
star_models = {}
files = glob.glob(folder+'lte*.fits')
if (np.size(files) < 1):
raise ValueError('No stellar models have been found. Go download them.')
for f in files:
print f
hdulist = pyfits.open(f)
flx = hdulist[0].data
x = hdulist[0].header['CRVAL1']+np.arange(hdulist[0].header['NAXIS1'])*hdulist[0].header['CDELT1']
x_m = x.astype(np.float)*0.0001 #Ang to microns
flx = np.sum(flx,axis=0)*((x_m*10000)**2)/2.998E14 # convert to mJy
hdulist.close()
f2 = np.convolve(flx, np.ones((15,))/15)
sz1 = np.shape(flx)[0]
sz2 = np.shape(f2)[0]
bound = np.int(np.abs(sz1-sz2))
f2 = f2[bound:-bound-1]
x_m = x_m[bound/2:-bound/2-1]
#print np.size(x_m),np.size(f2)
rjtw = np.logspace(np.log10(np.max(x_m)),np.log10(2500),100)
rtpopt,rtpcov = curve_fit(pow_law,x_m[-2000:],f2[-2000:],p0=[2.00,9])
rjtf = pow_law(rjtw,*rtpopt)
f2 = np.append(f2,rjtf)
x_m = np.append(x_m,rjtw)
#plt.loglog(x_m,f2,'b-')
#plt.show
temp = np.float((str(f).replace(folder,'').split('-')[0]).replace('lte',''))
star_models[str(temp)] = np.vstack((x_m,f2))
return star_models
def chisqr_stellar_models(star_wave,star_phot,star_phot_e,star_models,pin_wave = 1.5):
model_flx = np.arange(np.size(star_wave))
temps = np.array([0])
for star in star_models.iteritems():
temp = star[0]
x_m,f2 = star[1]
func = interp1d(x_m,f2,kind='nearest')
model_flx = np.vstack((model_flx,[func(star_wave)]))
temps = np.vstack((temps,np.float(temp)))
model_flx = model_flx[1:,0:]
temps = temps[1:,0:]
pin_id = np.where(np.min(star_wave-pin_wave) == (star_wave-pin_wave))
diff_flx = model_flx[0:,pin_id]/star_phot[pin_id]
#print diff_flx[0:,0]
diff_flx_arr = np.repeat(diff_flx[0:,0],np.shape(model_flx)[1],axis=1)
star_phot_arr = np.repeat([star_phot],np.shape(model_flx)[0],axis=0)
star_phot_e_arr = np.repeat([star_phot_e/star_phot**2],np.shape(model_flx)[0],axis=0)
#print (model_flx/diff_flx_arr-star_phot_arr)
chisqr = np.sum(((model_flx/diff_flx_arr-star_phot_arr)**2)*star_phot_e_arr,axis=1)
min_id = np.where(np.min(chisqr) == chisqr)[0][0]
temp_str = str(temps[min_id][0])
model_diff = diff_flx[min_id][0][0]
x_m, f_m = star_models[temp_str]
return x_m,f_m/model_diff,temp_str
def get_lum(x1,f1,distance):
import numpy as np
lightspeed = 2.99792458*10**14 #micron/s
fq = lightspeed/x1**2
f1b = (f1/10**29)*fq #(F_nu to F_lam)
Jysum = np.trapz(x1,f1b)
return (Jysum*4*np.pi*distance**2)/(3.826*10**26)
<file_sep>/setup.py
from setuptools import setup,find_packages
setup(name='pysed',
version='1.0',
description='SED fitting or stellar photometry',
author="<NAME>",
author_email='<EMAIL>',
url='',
packages=find_packages(),
classifiers=[
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Astronomy',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
],
install_requires=['numpy', 'scipy', 'astropy', 'astroquery', 'matplotlib']
)
|
64f01709eabc2b24621aa3eacbb3699870e00803
|
[
"Python"
] | 2
|
Python
|
zackdraper/pysed
|
7cee46f9bc425b2f2a037f572a0cc37153a0a36d
|
8d5bc35a591dd20692cf4df263c26e5a49173625
|
refs/heads/master
|
<repo_name>MarriaMarria/exo_python_groups_json<file_sep>/exo_names.py
import random
import logging
import json
logging.basicConfig(filename='text.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
logging.info("getting text file: start")
f = open("list_of_names.txt", "r")
names = f.read()
print(names)
logging.info("getting text file: end")
logging.info("getting a list: start")
my_list = names.split(",") # list of names to divide in groups
logging.info("getting a list: end")
# I create dictionary to store the data from the loop
my_dict = dict()
def group_division():
nb_par_group = 2
nb_of_groups = 1
file_with_groups = open("file_groups.txt", "w")
out_file = open("myfile.json", "w") # I will save my data in JSON file
logging.info("loop to divide ppl in groups: start")
while my_list:
if len(my_list) >= nb_par_group: # if I have 2+ ppl left
selected = random.sample(my_list, nb_par_group) # I choose randomly two ppl from my list of names
else:
selected = my_list # if one person rest he forms his own group of one
my_dict['group'] = selected # I add names to my dict
print(my_dict)
json.dump(my_dict, out_file, indent=4, sort_keys=False)
logging.info("GROUP #%s : %s" % (nb_of_groups, selected))
for sel in selected:
my_list.remove(sel)
file_with_groups.write(f"Group {nb_of_groups}: {selected} \r")
nb_of_groups = nb_of_groups + 1
file_with_groups.close()
return my_dict
group_division()
logging.info("loop to divide ppl in groups: end")
|
bddbc953dc014a823dbc5d04d8ddff423ad3a106
|
[
"Python"
] | 1
|
Python
|
MarriaMarria/exo_python_groups_json
|
55b0f8b899734a07a9439bab75c901d4b763e4be
|
290ffc7a58996eec06d4c81f6d66ebd9105eca6f
|
refs/heads/master
|
<repo_name>Joshuaasare/portfolio-v1<file_sep>/src/features/Root/routes/index.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-17 13:56:44
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-25 22:17:59
*/
export { routes } from './routes';
export { refs } from './routes';
<file_sep>/src/features/Home/Navigation.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-24 01:17:09
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-09 09:02:51
*/
import React from 'react';
import './css/Navigation.css';
import PropTypes from 'prop-types';
import { useScrollTop, useScrollToRef } from '../_shared/hooks';
import { refs } from '../Root/routes';
import { images } from '../_shared/assets';
const Navigation = (props) => {
const distance = useScrollTop();
const altClass = distance && distance > 15 ? '--alt' : '';
const { filterBarActive } = props;
const [onClick] = useScrollToRef();
function renderNavigationItems() {
return refs.map((route, index) => (
<li className="navigation__item" key={index}>
<div
className={`navigation__link${altClass}`}
onClick={() => onClick(props[route.ref])}
>
<span className="nav">{route.routeName}</span>
</div>
</li>
));
}
return (
<div className={`navigation${altClass}`}>
{filterBarActive ? <div className="navigation__overlay" /> : null}
<div className="row navigation__row">
<div className="col-1-of-2 menu-toggle">
<span className="navigation__user">
<img className="navigation__logo" src={images.logo} alt="" />
</span>
</div>
<div className="col-1-of-2 navigation__list-container">
<input
type="checkbox"
className="navigation__checkbox"
id="navi-toggle"
/>
<label
id="navi-label"
htmlFor="navi-toggle"
className="navigation__button-container"
>
<span className="navigation__button"> </span>
</label>
<ul className="navigation__list">{renderNavigationItems()}</ul>
</div>
</div>
</div>
);
};
Navigation.propTypes = {
filterBarActive: PropTypes.bool,
};
Navigation.defaultProps = {
filterBarActive: false,
};
export default Navigation;
<file_sep>/src/features/_shared/reducers/index.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-07-31 15:56:05
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-08 21:14:50
*/
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import UserReducer from './user_reducer';
import RefReducer from './ref_reducer';
export default combineReducers({
user: UserReducer,
refs: RefReducer,
form: formReducer,
});
<file_sep>/src/features/_shared/hooks/useScrollToTop.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-09-07 20:46:37
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-07 20:54:07
*/
import { useEffect } from 'react';
const useScrollToTop = () => {
useEffect(() => {
window.scrollTo(0, 0);
}, []);
};
export default useScrollToTop;
<file_sep>/src/features/_shared/components/Input.js
/*
* @Author: Joshua
* @Date: 2019-09-09 16:13:23
* @Last Modified by: Joshua
* @Last Modified time: 2019-09-10 01:37:06
*/
import React from 'react';
import PropTypes from 'prop-types';
import './css/Input.css';
const Input = (props) => {
const {
placeholder, value, onChange, type, required
} = props;
return (
<div id="input">
<input
className="input"
placeholder={placeholder}
value={value}
onChange={onChange}
type={type}
required={required}
/>
</div>
);
};
Input.propTypes = {
placeholder: PropTypes.string.isRequired,
onChange: PropTypes.func,
value: PropTypes.string,
type: PropTypes.string,
required: PropTypes.string,
};
Input.defaultProps = {
onChange: () => {},
value: null,
type: 'text',
required: false,
};
export default Input;
<file_sep>/src/features/_shared/services/imageService.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-06 18:28:34
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-06 18:29:37
*/
export function pickRandomAvatarColor(id: ?number): string {
const colors = [
'#e53935',
'#d81b60',
'#8e24aa',
'#5e35b1',
'#1e88e5',
'#43a047',
'#fb8c00',
'#f4511e',
'#6d4c41',
'#546e7a',
];
return colors[id % 10];
}
<file_sep>/src/features/_shared/hooks/index.js
export { default as useBodyScroll } from './useBodyScroll';
export { default as useScrollToTop } from './useScrollToTop';
export { default as useScrollTop } from './useScrollTop';
export { default as useScrollToRef } from './useScrollToRef';
<file_sep>/src/features/Root/Root.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-17 16:23:59
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-07 23:59:46
*/
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import { routes } from './routes';
type Props = {
history: Object,
};
type State = {};
class Root extends Component<Props, State> {
state = {};
componentDidMount() {
this.unlisten = this.props.history.listen((location) => {});
}
componentWillUnmount() {
this.unlisten();
}
renderRoutes(routes) {
return routes.map((route: Object, id: number) => (
<Route
exact={route.isExact}
key={`route-${id}`}
path={route.path}
component={route.component}
/>
));
}
render() {
return (
<div style={styles.container}>
<div style={styles.container}>
<Switch>{this.renderRoutes(routes)}</Switch>
</div>
</div>
);
}
}
const styles = {
container: {},
};
export default Root;
<file_sep>/src/__tests__/mocks/reviewDataMock.js
import img1 from '../../features/_shared/assets/images/tailor4.jpg';
import img2 from '../../features/_shared/assets/images/tailor5.jpg';
export default {
clientReviews: [
{
description: `Labore iis est veniam probant. Fugiat quibusdam ut enim irure.
Te a exercitation. Qui irure incurreret expetendis ad quae
singulis id dolore quae iis minim excepteur laboris, arbitror
o quid expetendis, duis a possumus`,
name: 'Mrs. <NAME>',
occupation: 'News Anchor',
image: img1,
alt: 'client1',
},
{
description: `Labore iis est veniam probant. Fugiat quibusdam ut enim irure.
Te a exercitation. Qui irure incurreret expetendis ad quae
singulis id dolore quae iis minim excepteur laboris, arbitror
o quid expetendis, duis a possumus`,
name: 'Mrs. <NAME>',
occupation: 'News Anchor',
image: img2,
alt: 'client2',
},
],
};
<file_sep>/src/features/_shared/services/index.js
export * from './authService';
export * from './utilities';
export * from './imageService';
export * from './uiService';
<file_sep>/src/features/_shared/hooks/useScrollTop.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-27 03:08:01
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-31 20:21:17
*/
import { useEffect, useRef, useState } from 'react';
const useScrollTop = () => {
const [distance, setDistance] = useState(0);
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
const initialScrollPosition = document.documentElement.scrollTop;
if (mounted.current) {
setDistance(initialScrollPosition);
}
const onScroll = () => {
const { scrollTop } = document.documentElement;
console.log(scrollTop);
if (mounted.current) {
setDistance(scrollTop);
}
};
window.addEventListener('scroll', onScroll);
return () => {
mounted.current = false;
window.removeEventListener('scroll', onScroll);
};
}, []);
return distance;
};
export default useScrollTop;
<file_sep>/src/__tests__/mocks/teamDataMock.js
import img from '../../features/_shared/assets/images/team2.jpg';
import img1 from '../../features/_shared/assets/images/team3.jpg';
import img2 from '../../features/_shared/assets/images/team4.jpg';
import img3 from '../../features/_shared/assets/images/team5.jpg';
import img4 from '../../features/_shared/assets/images/team6.jpg';
import img5 from '../../features/_shared/assets/images/team7.jpg';
import img6 from '../../features/_shared/assets/images/team8.jpg';
import img7 from '../../features/_shared/assets/images/team9.jpg';
export default {
team: [
{ name: '<NAME>', position: 'C.E.O', image: img },
{ name: '<NAME>', position: 'C.0.O', image: img1 },
{ name: '<NAME>', position: 'Head of Tailoring', image: img2 },
{ name: '<NAME>', position: 'Creative Design Lead', image: img3 },
{ name: '<NAME>', position: 'HR Manager', image: img4 },
{ name: '<NAME>', position: 'Head of Marketing', image: img5 },
{ name: '<NAME>', position: 'Seamstress', image: img6 },
{ name: '<NAME>', position: 'Seamstress', image: img7 },
],
};
<file_sep>/src/features/_shared/hocs/withLazyLoad.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-09-07 22:11:19
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-07 23:59:32
*/
import React, { lazy, Suspense } from 'react';
import { Loader } from 'semantic-ui-react';
const withLazyLoad = component => (props) => {
const { ...passThroughProps } = props;
const WrappedComponent = lazy(component);
return (
<Suspense fallback={<Loader active size="massive" />}>
<WrappedComponent {...passThroughProps} />
</Suspense>
);
};
export default withLazyLoad;
<file_sep>/src/features/_shared/components/SecuredRoute.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-03 00:57:07
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-03 01:27:53
*/
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const isAuthenticated = false;
type Props = {
component: React.Component,
};
const SecuredRoute = ({ component: Component, ...rest }: Props) => (
<Route
{...rest}
render={props => (isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/login',
}}
/>
))
}
/>
);
export default SecuredRoute;
<file_sep>/src/features/_shared/actions/user_action.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-07-11 23:39:22
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-02 23:42:02
*/
export const Actions = {
SET_USER: 'set_user',
CLEAR_USER: 'clear_user',
};
export const setUser = user => ({
type: Actions.SET_USER,
payload: user,
});
<file_sep>/src/features/_shared/components/index.js
export * from './Icon';
export * from './GenericButton';
export * from './FormButton';
export { default as SecuredRoute } from './SecuredRoute';
export { default as CircularButton } from './CircularButton';
export { default as Select } from './Select';
export { default as CustomRheostat } from './CustomRheostat';
export { default as Input } from './Input';
export { default as Ikon } from './Ikon';
<file_sep>/src/features/_shared/components/Select.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-31 22:47:29
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-31 22:49:59
*/
import React from 'react';
import './css/Select.css';
const Select = () => {
return (
<div className="select">
<select>{}</select>
</div>
);
};
export default Select;
<file_sep>/src/features/_shared/actions/ref_action.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-09-08 20:50:40
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-09 08:58:12
*/
export const Actions = {
SET_REF: 'set_ref',
};
export const setRef = ref => ({
type: Actions.SET_REF,
payload: ref,
});
<file_sep>/src/features/_shared/services/uiService.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-06 07:26:53
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-06 08:01:35
*/
import React from 'react';
import { Icon } from '../components';
export function renderStars(name, type, rating) {
// rating will come from api and the logic below will render the stars based on them
// const rating = 2; // asumming the average star rating is 2
const stars = [];
for (let i = 0; i < 5; i += 1) {
const colorType = rating >= i + 1 ? `${type}` : `${type}-inactive`;
const star = <Icon name={name} type={colorType} />;
stars.push(star);
}
return stars;
}
<file_sep>/src/features/_shared/components/CircularButton.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-20 08:12:53
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-03 18:50:51
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Icon } from '.';
import './css/CircularButton.css';
const CircularButton = (props) => {
const {
size, backgroundColor, iconName, iconType, shadowed, fixed
} = props;
function renderSize(size, fixed) {
if (fixed) {
return {
width: `${size}px`,
height: `${size}px`,
};
}
return {
width: `${size}rem`,
height: `${size}rem`,
borderRadius: `${size}rem`,
};
}
return (
<div
style={{
...renderSize(size, fixed),
backgroundColor,
...styles.buttonContainer,
boxShadow: shadowed ? '1px 3px 5px rgba(0, 0, 0, 0.3)' : null,
}}
className="circular-button"
onClick={props.onClick}
>
<Icon name={iconName} type={iconType} />
</div>
);
};
CircularButton.propTypes = {
size: PropTypes.number.isRequired,
backgroundColor: PropTypes.string,
iconName: PropTypes.string.isRequired,
iconType: PropTypes.string.isRequired,
shadowed: PropTypes.bool,
onClick: PropTypes.func,
fixed: PropTypes.bool,
};
CircularButton.defaultProps = {
backgroundColor: '#fff',
shadowed: true,
onClick: () => {},
fixed: false,
};
const styles = {
buttonContainer: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
};
export default CircularButton;
<file_sep>/src/__tests__/mocks/index.js
export { default as collectionDataMock } from './collectionDataMock';
export { default as reviewDataMock } from './reviewDataMock';
export { default as teamDataMock } from './teamDataMock';
export { default as workDataMock } from './workDataMock';
<file_sep>/src/features/_shared/constants.js
export const constants = {
ui: {
colors: {},
},
validators: {
/* eslint-disable no-useless-escape */
email:
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
phone: /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{3,6}$/im,
},
app: {
API_TOKEN: '<PASSWORD>',
// BASE_API_URL: 'http://192.168.1.105:8080'
},
email: {
USER_ID: 'user_IthvegI82GXXBWlqLEHJS',
ACCESS_TOKEN: '<PASSWORD>',
ADDRESS: '<EMAIL>',
},
};
export const experience = {
ColorElephant: {
title: 'Senior Software Engineer - React-Native',
company: ' @ ColorElephant Internacional Lda',
link: 'https://colorelephant.com',
duration: 'May 2020 - Present | Porto, Portugal',
tasks: [
'Led a team of 3 front-end engineers to develop the mobile client of an AI-driven custom financial analysis tool.',
'Developed a offline/online political crowd support application with react and react-native using realm offline mobile database for data persistence.',
'Set-up pipelines with automated unit and integration tests in bitbucket for safe deployments.',
'Implemented a comprehensive over-the-air updates automated pipeline for non-native updates in mobile applications using Microsoft Appcenter and code push.',
],
},
Asqii: {
title: 'Front-end Engineer',
company: ' @ Asqii LLC',
link: 'https://asqii.com',
duration: 'May 2019 - May 2020 | Remote',
tasks: [
'Develop hybrid apps for Android and IOS platforms using react-native.',
'Implement backend systems mainly using Node JS, typescript, and MySQL database.',
'Write high quality, documented and maintainable code using SOLID principles and Test-driven development.',
'Set up CI/CD with GitLab for fast and safe deployments.',
'Collaborate with other remote team members and engineers using tools like slack and Trello.',
],
},
ISTC: {
title: 'Software Development Support',
company: ' @ Intercity STC Coaches',
link: 'https://stc.gov.gh',
duration: 'May - Sept 2018 | Accra (GH)',
tasks: [
'Built a web application for the administration of the technical services department using HTML, CSS and jQuery.',
'Worked closely with 2 other developers to engineer a real-time application for bus scheduling and keeping track of moving buses for STC bus terminals.',
'Implemented a strategic plan for component development practices to support future projects.',
'Reduced institutions expense by ~2.3% and increased efficiency through digitization.',
],
},
Schooldesk: {
title: 'Front-end Engineer',
company: ' @ Schooldesk',
link: 'https://schooldesk.cc',
duration: 'May - October 2017 | Kumasi (GH)',
tasks: [
'Collaborated with a team of 6 made up of interns and engineers to develop a school management system for elite schools.',
'Proposed and implemented project structure for front-end and backend applications.',
'Developed, tested and maintained code for client and internal websites mainly using React and Node JS.',
'Interfaced with clients to author well documented software requirement specifications for projects.',
],
},
};
export const projects = [
{
title: 'Featured Project',
name: 'Schooldesk',
image: 'schooldesk',
description:
'Currently operating in Ghana and DR Congo, SchoolDesk is a suite of applications that can be used for managing a school. It includes a desktop application for the school, mobile apps for both teachers and parents, and an offline encyclopaedia for students.',
icons: [
'react',
'electron',
'mysql',
'travisci',
'swift',
'python',
'travis',
],
list: ['GCP', 'Microservices', 'DataStore'],
},
{
title: 'Featured Project',
name: 'STC Operations',
image: 'stcOperations',
description:
'STC Operations is a realtime bus scheduling application for intercity STC Coaches limted, one of the largest transport companies in Ghana. Features include tracking trip details, recording, scheduling and analyzing maintenance and general administration.',
icons: ['html5', 'heroku', 'mysql', 'node-dot-js', 'css3', 'jquery'],
list: ['Gearhost', 'Express'],
},
{
title: 'Own Project',
name: 'Asset Manager',
image: 'assetsManager',
description:
'Desktop application used to manage fixed assets in an organization. Features tracking life-cycle of an asset, scheduled maintainance, automated accounting and user management ',
icons: [
'react',
'node-dot-js',
'electron',
'postgresql',
'heroku',
'gitlab',
],
list: ['Gitlab CI', 'Heroku'],
},
{
title: 'Own Project',
name: 'RevApp',
image: 'mmda',
description:
'Navigation aided online/offline revenue collection software suite for district assemblies in Ghana.',
icons: ['react', 'node-dot-js', 'mysql', 'googlecloud', 'gitlab'],
list: ['Gitlab CI', 'React Native', 'Realm DB'],
},
];
export const otherProjects = [
{
name: 'STC Technical Services',
github: '',
website: '',
description:
'A web app for managing the technical services of intercity STC. Features include administration, stores and control.',
techList: ['Html', 'Css', 'Jquery', 'Node Js', 'Express'],
},
];
export const skills = [
'HTML, CSS, Javascript',
'Node JS',
'React',
'React Native',
'Vue JS',
'Electron JS',
'GCP and AWS',
'DBMS(MySQL,Mongo,Realm)',
'CI/CD (Gitlab, Travis)',
'Microservices',
'Dev Ops',
];
<file_sep>/src/App.js
import React from 'react';
import { Router, Switch, Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import history from './features/_shared/history';
import store from './features/store';
import 'semantic-ui-css/semantic.min.css';
import './features/_shared/css/main.css';
import './features/_shared/css/grid.css';
import {} from './features/_shared/components';
import { Root } from './features/Root';
const App = () => (
<Provider store={store}>
<Router history={history}>
<Switch>
<Route path="/" component={Root} />
</Switch>
</Router>
</Provider>
);
export default App;
<file_sep>/src/features/_shared/history/index.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-17 14:07:45
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-20 05:49:58
*/
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
<file_sep>/src/features/_shared/services/utilities.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-17 11:25:58
* @Last modified by: joshuaasare
* @Last modified time: 2019-08-29 12:08:08
*/
<file_sep>/src/features/_shared/assets/index.js
import schooldesk from './images/schooldesk_cover.jpg';
import stcOperations from './images/stc_operations.jpg';
import assetsManager from './images/assets_manager.jpg';
import mmda from './images/mmda.jpg';
import dev from './animations/dev.json';
import program from './animations/program.json';
import resume from './animations/Joshua_resume.pdf';
import exp1 from './images/exp1.png';
export const images = {
mmda,
schooldesk,
stcOperations,
assetsManager,
logo: exp1,
};
export const files = {
resume,
};
export const svg = {};
export const animations = {
dev,
program,
};
<file_sep>/src/features/Home/Projects.js
/*
* @Author: <NAME>
* @Date: 2020-04-06 12:46:16
* @Last Modified by: <NAME>
* @Last Modified time: 2020-04-09 10:46:50
*/
import React from 'react';
import './css/Projects.css';
import { images } from '../_shared/assets';
import { Ikon } from '../_shared/components';
import { projects } from '../_shared/constants';
const Projects = () => {
function renderProjectContent(alt?: string = '', project) {
return (
<div className="projects__text-container">
<div className={`projects__title ${alt}`}>
<span className="title">{project.title}</span>
<span className="name">{project.name}</span>
</div>
<div className={`projects__info ${alt}`}>{project.description}</div>
<div className={`projects__tech ${alt}`}>
<div className="icons">
{project.icons.map((icon) => {
return (
<div>
<Ikon
name={icon}
color="#ffae57"
size={2.5}
className={`projects__tech-icon ${alt}`}
/>
</div>
);
})}
</div>
<div className="list">
{project.list.map((item) => (
<span>{item}</span>
))}
</div>
</div>
</div>
);
}
function renderProjectImage(alt? = '', project) {
return (
<div className="project__image-container">
<img
alt=""
src={images[project.image]}
className={`projects__image ${alt}`}
/>
</div>
);
}
return (
<div className="projects">
<div className="projects__header">
<span className="name">Some stuff i've built</span>
<span className="line" />
</div>
{projects.map((project, index) => {
const alt = index % 2 === 0 ? 'alt' : '';
if (alt) {
return (
<div className="row projects__row">
<div className="col-1-of-2 project__text">
{renderProjectContent(alt, project)}
</div>
<div className="col-1-of-2 project__img">
{renderProjectImage(alt, project)}
</div>
</div>
);
}
return (
<div className="row projects__row">
<div className="col-1-of-2 project__img">
{renderProjectImage(alt, project)}
</div>
<div className="col-1-of-2 project__text">
{renderProjectContent(alt, project)}
</div>
</div>
);
})}
{/* <div className="projects__others">
<div className="header">Other Projects</div>
<div className="row">
{otherProjects.map((item) => (
<div className="col-1-of-3">
<div className="projects__box">
<div className="top">
<span className="single">
<Ikon
name="folder-open"
size={2}
className="icon"
color="#fff"
/>
</span>
<span className="group">
<Ikon
name="github"
size={2}
className="icon"
color="#fff"
/>
<Ikon name="link" size={2} className="icon" color="#fff" />
</span>
</div>
<div className="mid">{item.name}</div>
<div className="desc">{item.description}</div>
<div className="bottom">
<div>
{item.techList.map((list) => (
<span>{list}</span>
))}
</div>
</div>
</div>
</div>
))}
</div>
</div> */}
</div>
);
};
export default Projects;
<file_sep>/src/__tests__/mocks/workDataMock.js
import img1 from '../../features/_shared/assets/svg/ad-img1.svg';
import img3 from '../../features/_shared/assets/svg/ad-img3.svg';
import img5 from '../../features/_shared/assets/svg/ad-img5.svg';
export default {
work: [
{
heading: 'Experienced Tailors',
mainText: `Constias ab eram. Legam commodo est ingeniis do dolore
appellat si laboris sed nulla exercitation admodum noster
excepteur, excepteur enim velit officia fugiat, nam ullamco
illustriora do deserunt exercitation o mentitum, arbitror`,
image: img3,
alt: 'design1',
},
{
heading: 'Design Variety',
mainText: `Constias ab eram. Legam commodo est ingeniis do dolore
appellat si laboris sed nulla exercitation admodum noster
excepteur, excepteur enim velit officia fugiat, nam ullamco
illustriora do deserunt exercitation o mentitum, arbitror`,
image: img5,
alt: 'design2',
},
{
heading: '100% Customer satisfaction',
mainText: `Constias ab eram. Legam commodo est ingeniis do dolore
appellat si laboris sed nulla exercitation admodum noster
excepteur, excepteur enim velit officia fugiat, nam ullamco
illustriora do deserunt exercitation o mentitum, arbitror`,
image: img1,
alt: 'design3',
},
],
};
<file_sep>/src/features/_shared/components/Icon.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-08-20 09:18:55
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-03 18:52:52
*/
import React from 'react';
import PropTypes from 'prop-types';
import Icons from '../assets/svg/symbol-defs.svg';
import './css/Icon.css';
const Icon = ({ name, type, active }) => (
<svg
className={
active
? `icomoon-icon icomoon-icon-${type}-active`
: `icomoon-icon icomoon-icon-${type}`
}
>
<use xlinkHref={`${Icons}#icon-${name}`} />
</svg>
);
Icon.propTypes = {
name: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
active: PropTypes.bool,
};
Icon.defaultProps = {
active: false,
};
export { Icon };
<file_sep>/src/features/_shared/hocs/index.js
export { default as withLazyLoad } from './withLazyLoad';
<file_sep>/src/features/_shared/initialStoreState.js
/**
* @Author: <NAME> <joshuaasare>
* @Date: 2019-07-11 23:40:36
* @Last modified by: joshuaasare
* @Last modified time: 2019-09-08 21:01:22
*/
export default {
user: {
currentUser: null,
isLoading: false,
},
refs: {
qualityRef: null,
},
};
<file_sep>/src/features/Home/About.js
/*
* @Author: <NAME>
* @Date: 2020-04-06 07:43:24
* @Last Modified by: <NAME>
* @Last Modified time: 2020-04-08 10:14:51
*/
import React from 'react';
import './css/About.css';
import Lottie from 'react-lottie';
import { Ikon } from '../_shared/components';
import { skills } from '../_shared/constants';
import { animations } from '../_shared/assets';
const defaultOptions = {
loop: true,
autoplay: true,
animationData: animations.program,
rendererSettings: {
preserveAspectRatio: 'xMidYMid slice',
},
};
const About = (props) => (
<div className="about">
<div className="row">
<div className="col-1-of-2">
<div className="about__title">
<span className="name"> About Me</span>
<span className="line" />
</div>
<div className="about__info">
<span className="para">
I'm a software engineer who loves working on challenging problems,
cracking them into simpler solutions. I build scalable frontend and
mobile applications, using state of the art technologies with
security in mind.
</span>
<span className="para">
I graduated from Kwame Nkrumah University of Science and Technology
with a bachelor's in Computer Engineering, and for the past 3+
years, I've been among several teams engineering the next big stuff.
</span>
<span className="para">
A glimpse of some of the things i'm experienced with
</span>
<div className="about__skills">
<div className="row">
{skills.map((skill) => (
<div className="col-1-of-2">
<div className="about__skill">
<Ikon
name="play"
color="#f4a01d"
size={1.5}
className="about__skill-icon"
/>
<span>{skill}</span>
</div>
</div>
))}
</div>
</div>
</div>
</div>
<div className="col-1-of-2">
<div className="about__image-container">
<Lottie options={defaultOptions} />
</div>
</div>
</div>
</div>
);
export default About;
|
b5e2d5b0e1a517afc2f7f5c27ba0f7c29c305674
|
[
"JavaScript"
] | 32
|
JavaScript
|
Joshuaasare/portfolio-v1
|
b82b4c80daa0f4e817d13d13d09df88c0d8bea67
|
2763b5565517970f6c9cfb4111ce114d721d2807
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BidHub.API.Domain
{
public class Bid
{
public Buyer BuyerInfo { get; set; }
public int EventId { get; private set; }
public decimal StartingBid { get; private set; }
public decimal MaxBid { get; private set; }
public decimal AutoIncrementAmount { get; private set; }
public decimal CurrentBid { get; private set; }
public bool HasExceededMaxBid { get; private set; }
public Bid(int eventId, decimal startingBid, decimal maxBid, decimal autoIncrementAmount)
{
EventId = eventId;
StartingBid = startingBid;
MaxBid = maxBid;
AutoIncrementAmount = AutoIncrementAmount;
}
/// <summary>
/// Get the next bid and also increment the CurrentBid
/// </summary>
/// <returns></returns>
public decimal GetNextBidPrice()
{
if (CurrentBid == 0)
{
CurrentBid = StartingBid;
}
else if (MaxBid <= (CurrentBid + AutoIncrementAmount))
{
CurrentBid = CurrentBid + AutoIncrementAmount;
}
else
{
HasExceededMaxBid = true;
}
return CurrentBid;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BidHub.API.Domain
{
public class SellerItem
{
public int Id { get; set; }
public String Name { get; set; }
public decimal BasePrice { get; set; }
}
}
<file_sep>using BidHub.API.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BidHub.API.Application
{
public class EventsService
{
public Event ProcessBiddings(Event eventInfo)
{
do
{
decimal currentMaxBid = 0;
decimal buyerNextBid = 0;
foreach (var bid in eventInfo.Bids)
{
if (bid.HasExceededMaxBid) continue;
buyerNextBid = bid.GetNextBidPrice();
if (currentMaxBid < buyerNextBid)
{
currentMaxBid = buyerNextBid;
eventInfo.Winner = bid.BuyerInfo;
eventInfo.WinningBid = currentMaxBid;
}
}
} while (eventInfo.Bids.Count(buyer => !buyer.HasExceededMaxBid) > 1);
return eventInfo;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BidHub.API.Domain
{
public class Event
{
public int Id { get; set; }
public String Name { get; set; }
public short MaxBidders { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public int AutoIncrementLimit { get; set; }
public SellerItem SellerItemInfo { get; set; }
public ICollection<Bid> Bids { get; set; }
public decimal WinningBid { get; set; }
public Buyer Winner { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BidHub.API.Application
{
public class BuyersService
{
}
}
<file_sep>using BidHub.API.Domain;
using System;
using Xunit;
namespace BidHub.Domain.UnitTests
{
public class EventTests
{
[Fact]
public void ProcessBids_Should_Return_WinningBid()
{
//Arrange
Event eventInfo = new Event()
Bid bid1 = new Bid()
//Act
//Assert
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BidHub.API.Infrastructure.Repository
{
public class RepositoryBase
{
}
}
|
c1ebf0eab6a90e0092108648c748aaff11a76180
|
[
"C#"
] | 7
|
C#
|
saravanakumarrc/BidHub
|
9c907d7182534abcc3a0a2b4b1fbf39fee4d9e2d
|
f74db4bb657a972c0599f21b2166695806a66785
|
refs/heads/master
|
<repo_name>stven0king/designmode<file_sep>/src/com/tzx/factory/Main.java
package com.tzx.factory;
import com.tzx.factory.abstractfactory.Color;
import com.tzx.factory.abstractfactory.RedCircleFactory;
import com.tzx.factory.methodfactory.CircleFactory;
import com.tzx.factory.simplefactory.Shape;
import com.tzx.factory.simplefactory.ShapeFactory;
/**
* Created by tanzhenxing on 17-4-26.
*/
public class Main {
public static void main(String[] args) {
simplefactory();
System.out.println("-------------------------");
methodfactory();
System.out.println("-------------------------");
abstractfactory();
}
/**
* 简单工厂模式
*/
public static void simplefactory() {
Shape shape = ShapeFactory.create(ShapeFactory.CIRCLE);
shape.sayHello();
}
/**
* 工厂方法模式
*/
public static void methodfactory() {
Shape shape = new CircleFactory().create();
shape.sayHello();
}
/**
* 抽象工程模式
*/
public static void abstractfactory() {
com.tzx.factory.abstractfactory.ShapeFactory factory = new RedCircleFactory();
Shape shape = factory.createShape();
shape.sayHello();
Color color = factory.createColor();
color.sayHello();
}
}
<file_sep>/src/com/tzx/flyweight/Main.java
package com.tzx.flyweight;
/**
* Created by tanzhenxing on 17-5-27.
*
* 享元模式(Flywight),运用共享技术有效地支持大量细粒度的对象。
*
* 抽象享元(Flyweihgt)角色:是给实现享元提供的接口
*
* 具体享元(concreateFlyweight)角色:实现抽象角色,次对象必须是共享的,所含的状态必须是内部状态。
*
* 不共享享元(UnSharedConcreateFlyweight)角色:此对象不可共享,不是所有实现抽象共享接口的对象都要共享,此对象通常将ConreateFlyweight作为组成元素。
*
* 享元工厂(FlyweightFactory)角色:负责床架和管理享元角色,确保合理共享。
*
* 客户端(client)角色:维持一个Flyweight对象的引用,计算或存储一个(多个)外部存储状态。
*/
public class Main {
public static void main(String[] args) {
Row r = new Row();
GlyphFactory factory = new GlyphFactory();
Context context = new Context(12, 'a');
Glyph glyph = factory.getGlyph(context);
r.setCharacter(glyph);
Context context2 = new Context(13, 'a');
Glyph glyph2 = factory.getGlyph(context2);
r.setCharacter(glyph2);
Context context3 = new Context(13, 'b');
Glyph glyph3 = factory.getGlyph(context3);
r.setCharacter(glyph3);
System.out.println(r.getRow());
}
}
<file_sep>/src/com/tzx/State/eg/VoteState.java
package com.tzx.State.eg;
/**
* Created by tanzhenxing on 17-5-31.
*/
public interface VoteState {
/**
* 处理状态对应的行为
* @param user 投票人
* @param voteItem 投票项
* @param voteManager 投票上下文,用来在实现状态对应的功能处理的时候,可以回调上下文的数据。
*/
public void vote(String user, String voteItem, VoteManager voteManager);
}
<file_sep>/src/com/tzx/State/Main.java
package com.tzx.State;
/**
* Created by tanzhenxing on 17-5-31.
*
* 状态模式(State):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
*
* 状态模式主要解决的是当控制一个对象的状态转化的条件表达式国语复杂时的情况。
* 把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把负责的判断逻辑简单化。
*
* 环境(Context)角色,也成上下文:定义客户端所感兴趣的接口,并且保留一个具体状态类的实例。这个具体状态类的实例给出此环境对象的现有状态。
*
* 抽象状态(State)角色:定义一个接口,用以封装环境(Context)对象的一个特定的状态所对应的行为。
*
* 具体状态(ConcreateState)角色:每一ugejuti状态类都实现了环境(Context)的一个状态所对应的行为。
*/
public class Main {
public static void main(String[] args) {
State state = new ConcreteStateA();
Context context = new Context();
context.setState(state);
context.request("test");
}
}
<file_sep>/src/com/tzx/State/State.java
package com.tzx.State;
/**
* Created by tanzhenxing on 17-5-31.
*/
public interface State {
public void handle(String sampleParameter);
}
<file_sep>/src/com/tzx/component/Leaf.java
package com.tzx.component;
/**
* Created by im on 17-3-13.
*/
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
}
@Override
public void remove(Component component) {
}
@Override
public void foreach() {
System.out.println("self name-->"+this.name);
}
}
<file_sep>/src/com/tzx/build/Employee.java
package com.tzx.build;
public class Employee extends Builder {
private String name;
private String age;
private double height;
private double weight;
public Person create() {
Person person = new Person();
person.setAge(age);
person.setName(name);
person.setHeight(height);
person.setWeight(weight);
return person;
}
@Override
public void buildName() {
name = "保险员";
}
@Override
public void buildAge() {
age = "25";
}
@Override
public void builHeight() {
height = 1.72;
}
@Override
public void buildWeight() {
weight = 60;
}
}
<file_sep>/src/com/tzx/decorator/Employee.java
package com.tzx.decorator;
/**
* Created by tanzhenxing on 17-4-25.
*/
public class Employee implements Person {
@Override
public void doCoding() {
System.out.println("程序员加班写程序啊,写程序,终于写完了~!~!~!");
}
}
<file_sep>/src/com/tzx/observer/ConcreateObserver.java
package com.tzx.observer;
/**
* Created by tanzhenxing on 17-5-26.
*/
public class ConcreateObserver implements Observer {
private String observerState;
@Override
public void update(String state) {
observerState= state;
System.out.println("状态为:" + observerState);
}
}
<file_sep>/README.md
# designmode
## 工厂模式(Factory)
### 模式定义
包路径:`com.tzx.factory`
工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
> **简单工厂模式**、**工厂模式**和**抽象工厂模式**,它们都属于创建型模式,其主要功能都是将对象的实例化部分抽取出来。简单工厂模式也称为静态工厂模式,包含三种角色:
>
> - Factory工厂角色——负责实现创建所有实例的内部逻辑;
> - Product抽象产品角色——创建的所有对象的父类,负责描述所有实例所共有的公共接口;
> - ConcreteProduct具体产品角色——继承自Product,负责具体产品的创建。
> - ConcreteFactory具体工厂类——继承自Factory,实现不同特性的工厂。
### 简单工厂模式

实例化对象的时候不再使用 new Object()形式,可以根据用户的选择条件来实例化相关的类。对于客户端来说,去除了具体的类的依赖。只需要给出具体实例的描述给工厂,工厂就会自动返回具体的实例对象。
这样的话,当子类的类名更换或者增加子类时我们都无需修改客户端代码,只需要在简单工厂类上增加一个分支判断代码即可。
- 优点:我们可以对创建的对象进行一些 “加工” ,而且客户端并不知道,因为工厂隐藏了这些细节。如果,没有工厂的话,那我们是不是就得自己在客户端上写这些代码,这就好比本来可以在工厂里生产的东西,拿来自己手工制作,不仅麻烦以后还不好维护。
- 缺点:如果需要在方法里写很多与对象创建有关的业务代码,而且需要的创建的对象还不少的话,我们要在这个简单工厂类里编写很多个方法,每个方法里都得写很多相应的业务代码,而每次增加子类或者删除子类对象的创建都需要打开这简单工厂类来进行修改。这会导致这个简单工厂类很庞大臃肿、耦合性高,而且增加、删除某个子类对象的创建都需要打开简单工厂类来进行修改代码也违反了开-闭原则。
#### 举例说明
用 `Retrofit` 进行举例:
```java
private static final Platform PLATFORM = findPlatform();
static Platform get() {
return PLATFORM;
}
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
return new Java8();
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("org.robovm.apple.foundation.NSObject");
return new IOS();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
```
`findPlatform` 相当于一个**简单工厂** ,用来产生:
```java
static class Java8 extends Platform {}
static class Android extends Platform {}
static class IOS extends Platform {}
```
### 工厂模式
如果上面的**简单工厂**模式中,创建每一个 `Shape` 都需要大量的逻辑代码,而且 `Shape` 的类型还不少。那么这个时候我们维护这个 `Factroy` 就比较费力了。

抽象产品类派生出多个具体产品类;
抽象工厂类派生出多个具体工厂类;
每个具体工厂类只能创建一个具体产品类的实例;
即定义一个创建对象的接口(即抽象工厂类),让其子类(具体工厂类)决定实例化哪一个类(具体产品类)。“一对一”的关系。
#### 举例说明
我们继续用 `Retrofit` 中的例子做参考,如果使用**简单工厂**构造 `CallAdapter` ,那么这个工厂类将维护多个复杂的逻辑。
```java
public interface CallAdapter<T> {
Type responseType();
<R> T adapt(Call<R> call);
abstract class Factory {
public abstract CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit);
protected static Type getParameterUpperBound(int index, ParameterizedType type) {
return Utils.getParameterUpperBound(index, type);
}
protected static Class<?> getRawType(Type type) {
return Utils.getRawType(type);
}
}
}
```
- CallAdapter作为抽象产品
- CallAdapter.Factory作为抽象工厂
- CallAdapter.Factory的get方法相当于create,不同的factory构造不同的product
```java
public final class RxJavaCallAdapterFactory extends CallAdapter.Factory {
// 省略代码
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit){
// 省略代码
return new RxJavaCallAdapter;
}
// 省略代码
}
```
使用**工厂模式**让每个工厂维护自己的产品,这里把**简单工厂**中的选择逻辑放在的客户端自己处理。**工厂方法模式**克服了**简单工厂**会违背**开-闭原则**的缺点,又保持了封装对象创建过程的优点。但**工厂方法模式**的缺点是每增加一个产品类,就需要增加一个对应的工厂类,增加了额外的开发量。
### 抽象工厂模式
相比于工厂模式,具体工厂负责生产具体的产品,每一个具体工厂对应一种具体产品,工厂方法也具有唯一性,一般情况下,一个具体工厂中只有一个工厂方法或者一组重载的工厂方法。但是有时候我们需要一个工厂可以提供多个产品对象,而不是单一的产品对象。

- 一个系统不应当依赖于产品类实例如何被创建、组合和表达的细节,这对于所有形态的工厂模式都是重要的。
- 这个系统有多于一个的产品族,而系统只消费其中某一产品族。
- 注意,这里生产的是相关的两个对象,这一约束必须在系统的设计中体现出来。
- 当一个产品族中的多个对象被设计成一起工作时, 系统提供一个产品类的库,所有的产品以同样的接口出现,从而使客户端不依赖于实现。
#### 举例说明
继续用 `Retrofit` 举例说明:
```java
public interface Converter<F, T> {
T convert(F value) throws IOException;
abstract class Factory {
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(Type type,
Annotation[] annotations, Retrofit retrofit) {
return null;
}
public @Nullable Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return null;
}
/***部分代码省略***/
}
}
```
上述 `Converter.Factory` 需要同时提供**请求内容**和**返回内容**的转换类。
- `responseBodyConverter` 产生**返回内容**
- `requestBodyConverter` 产生**请求内容**
```java
public final class GsonConverterFactory extends Converter.Factory {
/***部分代码省略***/
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonResponseBodyConverter<>(gson, adapter);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonRequestBodyConverter<>(gson, adapter);
}
}
```
- `Converter.Factory` :抽象工厂
- `GsonConverterFactory` :具体工厂类
- `ResponseBody` 和 `T` 相当于产品抽象类
### 为什么要工厂模式?
- 到处用 `new class()` 的方式,一旦要改 `class`,要到处替换,非常不方便,容易错;
- 使用工厂模式,可以轻松的增加一个新的产品,不需要改原来的代码,符合开放封闭原则。
- 工厂这个模式它可以隐藏函数的具体实现,并且更加具有封装性,更加的面向对象,这些东西在基础的编写小程序上并体现不出什么优越性,但在一个大项目中,就显得很重要了,打个比方就像你如果说只有两三本书,你不需要什么归类放着,但你如果有一个图书管那么多书的话,放书就要有一定的规章,章法,这样就好管理,变更,查找。
## 适配器模式(Adapter)
包路径:` com.tzx.adapter`
### 模式定义
将一个类的接口转化为客户希望的另一个接口。Adapter模式使得原本由于接口不同而不能一起工作的那些类可以在一起工作。
### 模式结构
适配器模式包含如下角色:
>- Target:目标抽象类
>- Adapter:适配器类,模式核心
>- Adaptee:需要适配的对象
>- Client:客户类
适配器模式有对象适配器和类适配器两种实现:
### 类适配器

类适配器,Adapter 类既继承了 Adaptee (被适配类),也实现了 Target 接口
### 对象适配器

### 优点
- 更好的复用性
系统需要使用现有的类,而此类的接口不符合系统的需要。那么通过适配器模式就可以让这些功能得到更好的复用。
- 更好的扩展性
在实现适配器功能的时候,可以调用自己开发的功能,从而自然地扩展系统的功能。
### 缺点
类适配器一次最多只能适配一个适配者类,使用有一定的局限性。(不能多继承)
而对象适配器虽然可以把适配者类和它的子类都适配到目标接口,但是更改适配者的方法十分麻烦,既需要更改适配器,也需要更改适配者
### 权衡
- **类适配器**使用对象继承的方式,是静态的定义方式;
**对象适配器**使用对象组合的方式,是动态组合的方式。
- **对于类适配器**,由于适配器直接继承了`Adaptee`,使得适配器不能和`Adaptee`的子类一起工作,因为继承是静态的关系,当适配器继承了`Adaptee`后,就不可能再去处理 `Adaptee`的子类了。
**对于对象适配器**,一个适配器可以把多种不同的源适配到同一个目标。换言之,同一个适配器可以把源类和它的子类都适配到目标接口。因为对象适配器采用的是对象组合的关系,只要对象类型正确,是不是子类都无所谓。
- **对于类适配器**,适配器可以重定义`Adaptee`的部分行为,相当于子类覆盖父类的部分实现方法。
**对于对象适配器**,要重定义`Adaptee`的行为比较困难,这种情况下,需要定义`Adaptee`的子类来实现重定义,然后让适配器组合子类。虽然重定义`Adaptee`的行为比较困难,但是想要增加一些新的行为则方便的很,而且新增加的行为可同时适用于所有的源。
- **对于类适配器**,仅仅引入了一个对象,并不需要额外的引用来间接得到`Adaptee`。
**对于对象适配器**,需要额外的引用来间接得到`Adaptee`。
建议尽量使用对象适配器的实现方式,多用合成/聚合、少用继承。当然,具体问题具体分析,根据需要来选用实现方式,最适合的才是最好的。
### 举例说明
我们用 `Retrofit` 框架作参考:
```java
public interface Call<T> extends Cloneable {
Response<T> execute() throws IOException;
void enqueue(Callback<T> callback);
boolean isExecuted();
void cancel();
boolean isCanceled();
Call<T> clone();
Request request();
}
//接口定义
public interface CallAdapter<R, T> {
Type responseType();
T adapt(Call<R> call);
}
//安卓适配器,ExecutorCallAdapterFactory
CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public Call<Object> adapt(Call<Object> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
```
- Call:Adaptee
- CallAdapter:Target
- CallAdapter匿名类:Adapter
`Android`平台下默认的`CallAdapter`会将`OkHttpCall` 和 `MainThreadExecutor`两个实例对象适配成一个新的`Call`实例,这个新的`Call`实例在执行过程中就具备了切换到UI线程的功能。
那`Retrofit`在这个地方为什么要使用适配器模式将`OkHttpCall`进行适配了,直接拿过来用不就可以了吗?
前面讲过`OkHttpCall`仅仅只是对`OkHttp.Call`执行网络请求操作的封装,没有其他功能,也就是说`OkHttpCall`也只有网络请求的功能,而`Retrofit`是支持多个平台的(安卓,Java8,IOS,甚至包括支持RxJava特性),而不同的平台可能具有不同的特性。
如果在请求过程中需要用到这些特性的话,那么单靠`OkHttp.Call`是无法完成的,而如果在其他地方柔和进这些特性的支持可能就会使得框架结构不那么严谨平台解耦性比较差,甚至有可能会增加更多的接口。
`Retrofit`通过使用适配器模式将平台特性与`OkHttpCall`适配成一个最终我们需要的`Call`实例,这样的话我们在使用过程中只需要关注最后拿到的`Call`对象,而不需要关注底层这个`Call`实例到底是什么样的,这也就为我们支持更多的特性提供了可能。比如对RxJava特性的支持,我们只需要提供一个支持`RxJava`特性的`CallAdapter`适配器即可,所以我们就可以通过`addCallAdapterFactory()`配置我们提供的支持`RxJava`特性的`CallAdapter.Factory`
### 缺省适配器
> 缺省适配(Default Adapter)模式为一个接口提供缺省实现,这样子类型可以从这个缺省实现进行扩展,而不必从原有接口进行扩展。作为适配器模式的一个特例,缺省是适配模式在JAVA语言中有着特殊的应用。
在任何时候,如果不准备实现一个接口的所有方法时,就可以使用**缺省适配模式**制造一个抽象类,给出所有方法的平庸的具体实现。这样,从这个抽象类再继承下去的子类就不必实现所有的方法了。
## 外观模式-门面模式(Facade)
包路径:` com.tzx.facade `
### 模式定义
外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得子系统更加容易使用。外观模式又称为门面模式,它是一种对象结构型模式。
### 模式结构
外观模式包含如下角色:
> - Facade: 外观角色
> - SubSystem:子系统角色

### 模式分析
据“单一职责原则”,在软件中将一个系统划分为若干个子系统有利于降低整个系统的复杂性,一个常见的设计目标是使子系统间的通信和相互依赖关系达到最小,而达到该目标的途径之一就是引入一个外观对象,它为子系统的访问提供了一个简单而单一的入口。
外观模式也是“迪米特法则”的体现,通过引入一个新的外观类可以降低原有系统的复杂度,同时降低客户类与子系统类的耦合度。
外观类将客户端与子系统的内部复杂性分隔开,使得客户端只需要与外观对象打交道,而不需要与子系统内部的很多对象打交道。
### 优点
对客户屏蔽子系统组件,实现了子系统与客户之间的松耦合关系
### 缺点
在不引入抽象外观类的情况下,增加新的子系统可能需要修改外观类的源代码,违背了“开闭原则”。
### 扩展
- 1. 一个系统有多个外观类
在一个系统中可以设计多个外观类,每个外观类都负责和一些特定的子系统交互,向用户提供相应的业务功能。
- 2. 不要通过继承一个外观类在子系统中加入新的行为
外观模式的用意是为子系统提供一个集中化和简化的沟通渠道,而不是向子系统加入新的行为,新的行为的增加应该通过修改原有子系统类或增加新的子系统类来实现,不能通过外观类来实现。
- 3. 外观模式与迪米特法则(最少知道原则)
外观类充当了客户类与子系统类之间的“第三者”,降低了客户类与子系统类之间的耦合度,外观模式就是实现代码重构以便达到“迪米特法则”要求的一个强有力的武器。
- 4. 抽象外观类的引入
外观模式最大的缺点在于违背了“开闭原则”,当增加新的子系统或者移除子系统时需要修改外观类,可以通过引入抽象外观类在一定程度上解决该问题,客户端针对抽象外观类进行编程。对于新的业务需求,不修改原有外观类,而对应增加一个新的具体外观类,由新的具体外观类来关联新的子系统对象,同时可以通过修改配置文件来达到不修改源代码并更换外观类的目的。
### 举例说明
`Retrofit` 的 `create` 方法包含了:
- 判断定义的接口服务是否可用;
- 动态代理的构造;
- 代理内部进行平台的判断、 `ServiceMethod` 的缓存和 `OkhttpCall` 的实例生成;
## 建造者模式(builder)
### 模式定义
包路径:`com.tzx.build`
建造者模式属于创建型模式,将构建复杂对象的过程和它的部件解耦,使构建过程和部件的表示隔离。
### 模式结构
>- Product产品类——该类为一般为抽象类,定义Product的公共属性配置;
>- Builder建造类——该类同样为抽象类,规范Product的组建,一般由子类实现具体Product的构建过程;
>- ConcreteBuilder实际建造类——继承自Builder,构建具体的Product;
>- Director组装类——统一组装过程。

主要解决在软件系统中,有时候面临着"一个复杂对象"的创建工作,其通常由各个部分的子对象用一定的算法构成;由于需求的变化,这个复杂对象的各个部分经常面临着剧烈的变化,但是将它们组合在一起的算法却相对稳定。
**优点:**
- 建造者独立,易扩展。
- 便于控制细节风险。
**缺点:**
- 产品必须有共同点,范围有限制。
- 如内部变化复杂,会有很多的建造类。
**使用场景:**
- 需要生成的对象具有复杂的内部结构。
- 需要生成的对象内部属性本身相互依赖。
### 举例说明
继续用 `Retrofit` 说明:
```java
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(ByteArrayConverterFactory.create())
.addConverterFactory(StringResponseConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
```
## 代理模式(proxy)
包路径: `com.tzx.proxy`
### 模式定义
为其他对象提供一种代理以控制对这个对象的访问,并由代理对象控制对原对象的引用。它是一种对象结构型模式。
### 模式结构
代理模式包含如下角色:
>- Subject: 抽象主题角色,声明了目标对象和代理对象的共同接口,这样一来在任何可以使用目标对象的地方都可以使用代理对象。
>- Proxy: 代理主题角色,代理对象内部含有目标对象的引用,从而可以在任何时候操作目标对象;代理对象提供一个与目标对象相同的接口,以便可以在任何时候替代目标对象。代理对象通常在客户端调用传递给目标对象之前或之后,执行某个操作,而不是单纯地将调用传递给目标对象。
>- RealSubject: 真实主题角色,定义了代理对象所代表的目标对象。

### 分类
代理类按照创建时期分为两种:静态代理类和动态代理类。
> 静态代理类:由程序员创建或由特定工具自动生成源代码,在对其编译。在程序运行前,代理类的.class文件就已经存在。
> 动态代理类:在程序运行时,运用反射机制动态创建而成。
### 静态代理举例
继续使用 `Retrofit` 举例,在前面的 `适配器模式` 中有讲到
```java
//安卓适配器,ExecutorCallAdapterFactory
CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public Call<Object> adapt(Call<Object> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
```
其中 `ExecutorCallbackCall` 的实现就是 `静态代理模式` ,最终的逻辑是有由 `callbackExecutor` 实现的。
### 静态代理的特点
- 协调调用者与被调用者,降低系统耦合度
- 减小外部接口与内部接口实现的关联,降低耦合
- 委托对象与代理对象需要实现相同的接口,当接口类增加方法时,除了所有实现类需要增加该方法外,所有代理类也需要实现此方法,增加了维护难度
- 一个代理类只能代理一种类型的对象
### 动态代理举例
还用 `Retrofit` 举例,在前面的 `外观模式` 中有讲到 `Retrofit.create` 中就是用了动态代理:
```java
public <T> T create(final Class<T> service) {
//判断定义的接口服务是否可用
Utils.validateServiceInterface(service);
if (validateEagerly) {
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
//判断Android,IOS,java8
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, Object... args)
throws Throwable {
//如果是对象里的方法直接调用
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
/**
* 对java8做兼容,android和ios值恒为false
*/
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
//主要看这三行代码
/**
* 1、生成获取缓存中的method对应的ServiceMethod或者生产method对应的ServiceMethod
* 2、生成OkHttpCall的实例
* 3、根据生成的ServiceMethod实例中的callAdapter对象,调用callAdapter.adapt方法创建
* 对应的Observable
*/
ServiceMethod serviceMethod = loadServiceMethod(method);
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
```
#### 动态代理特点
运行期由JVM通过反射机制动态生成,可以代理多种类型,代码复用性高。但是只能代理Java接口,不能代理Java实现类
### 代理方式的选择
静态代理特点一个代理对应一种类型,如果有多个类需要代理则需要多个代理,而且维护成本高,而动态代理就是来解决此类问题。
## 策略模式(Strategy)
包路径: `com.tzx.strategy`
### 模式定义
策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
### 模式结构
代理模式包含如下角色:
>- 环境(Context)角色:持有一个Strategy的引用。
>- 抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
>- 具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。

### 认识策略模式
- **策略模式的重心**
策略模式的重心不是如何实现算法,而是如何组织、调用这些算法,从而让程序结构更灵活,具有更好的维护性和扩展性。
- **算法的平衡性**
策略模式一个很大的特点就是各个策略算法的平等性。对于一系列具体的策略算法,大家的地位是完全一样的,正因为这个平等性,才能实现算法之间可以相互替换。所有的策略算法在实现上也是相互独立的,相互之间是没有依赖的。
所以可以这样描述这一系列策略算法:策略算法是相同行为的不同实现。
- **运行时策略的唯一性**
运行期间,策略模式在每一个时刻只能使用一个具体的策略实现对象,虽然可以动态地在不同的策略实现中切换,但是同时只能使用一个。
- **公有行为 **
经常见到的是,所有的具体策略类都有一些公有的行为。这时候,就应当把这些公有的行为放到共同的抽象策略角色 `Strategy` 类里面。当然这时候抽象策略角色必须要用 `Java` 抽象类实现,而不能使用接口。
这其实也是典型的将代码向继承等级结构的上方集中的标准做法。
### 策略模式的优点
- 策略模式提供了管理相关的算法族的办法。策略类的等级结构定义了一个算法或行为族。恰当使用继承可以把公共的代码移到父类里面,从而避免代码重复。
- 使用策略模式可以避免使用多重条件(if-else)语句。多重条件语句不易维护,它把采取哪一种算法或采取哪一种行为的逻辑与算法或行为的逻辑混合在一起,统统列在一个多重条件语句里面,比使用继承的办法还要原始和落后。
### 策略模式的缺点
- 客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。换言之,策略模式只适用于客户端知道算法或行为的情况。
- 由于策略模式把每个具体的策略实现都单独封装成为类,如果备选的策略很多的话,那么对象的数目就会很可观。
### 策略模式举例
继续用 `Retrofit` 举例, 不同的 `CallAdapter` 是不是代表着不同的策略,当我们调用这些不同的适配器的方法时,就能得到不同的结果,这个是策略模式。
```java
//接口定义
public interface CallAdapter<R, T> {
Type responseType();
T adapt(Call<R> call);
}
//rxjava的适配器
final class RxJavaCallAdapter<R> implements CallAdapter<R, Object> {
/****部分内容省略******/
}
//默认的适配器,DefaultCallAdapterFactory
CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public Call<Object> adapt(Call<Object> call) {
return call;
}
};
//安卓适配器,ExecutorCallAdapterFactory
CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public Call<Object> adapt(Call<Object> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
```
在这里看到的也有有人看到你这个 `Retrofit` 中的 `CallAdapter` 到底讲了多少**设计模式**。
- 工厂模式:强调产生了多个不同的 `CallAdapter` ,作用在创建对象之前。
- 代理模式:某一个`CallAdapter` 的 `adapt` 方法实现利用了代理模式。
- 策略模式:强调的是这些多个不同的 `CallAdapter` 的那个方法的具体实现,在创建对象之后。
## 享元模式(Flyweight)
包路径: `com.tzx.flyweight`
### 模式定义
通过共享技术以便有效的支持大量细粒度的对象。
### 模式结构
享元模式包含如下角色:
>- Flyweight: 抽象享元类
>- ConcreteFlyweight: 具体享元类
>- UnsharedConcreteFlyweight: 非共享具体享元类
>- FlyweightFactory: 享元工厂类

### 优点
可以极大减少内存中对象的数量,使得相同对象或相似对象在内存中只保存一份。
### 缺点
享元模式需要将享元对象的状态外部化,而读取外部状态使得运行时间变长。
### 应用
享元模式在编辑器软件中大量使用,如在一个文档中多次出现相同的图片,则只需要创建一个图片对象,通过在应用程序中设置该图片出现的位置,可以实现该图片在不同地方多次重复显示。
### 举例说明
```java
private final Map<Method, ServiceMethod> serviceMethodCache = new LinkedHashMap<>();
ServiceMethod loadServiceMethod(Method method) {
ServiceMethod result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
```
- `serviceMethodCache` : `FlyweightFactory` 享元工厂类
- `ServiceMethod` : `Flyweight` 享元抽象类
在享元模式中共享的是享元对象的内部状态,外部状态需要通过环境来设置。在实际使用中,能够共享的内部状态是有限的,因此享元对象一般都设计为较小的对象,它所包含的内部状态较少,这种对象也称为细粒度对象。享元模式的目的就是使用共享技术来实现大量细粒度对象的复用。在经典享元模式中,它的键(`Method`)是享元对象的内部状态,它的值(`ServiceMethod`)就是享元对象本身。
## 原型模式
包路径: `com.tzx.prototype`
### 模式定义
原型模式属于对象的创建模式。通过给出一个原型对象来指明所有创建的对象的类型,然后用复制这个原型对象的办法创建出更多同类型的对象。这就是选型模式的用意。
## 模式结构
原型模式要求对象实现一个可以“克隆”自身的接口,这样就可以通过复制一个实例对象本身来创建一个新的实例。这样一来,通过原型实例创建新的对象,就不再需要关心这个实例本身的类型,只要实现了克隆自身的方法,就可以通过这个方法来获取新的对象,而无须再去通过new来创建。
这种形式涉及到三个角色:
>- 客户(Client)角色:客户类提出创建对象的请求。
>- 抽象原型(Prototype)角色:这是一个抽象角色,通常由一个Java接口或Java抽象类实现。此角色给出所有的具体原型类所需的接口。
>- 具体原型(Concrete Prototype)角色:被复制的对象。此角色需要实现抽象的原型角色所要求的接口。

**优点:**
- 性能提高。
- 逃避构造函数的约束。
**缺点:**
- 配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
- 必须实现 Cloneable 接口。
### 举例说明
继续用 `Retrofit` 框架中的例子进行说明:
OkHttpCall实现了Call接口,Call接口继承自Cloneable,OkHttpCall的clone方法实现如下:
```
@Override
public OkHttpCall<T> clone() {
return new OkHttpCall<>(serviceMethod, args);
}
```
clone的实现就是重新new了一个一样的对象,用于其他地方重用相同的Call,在ExecutorCallbackCall中有用到:
```java
static final class ExecutorCallbackCall<T> implements Call<T> {
// 省略代码
@SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone.
@Override
public Call<T> clone() {
return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone());
}
}
```
使用原型模式复制对象需要主要深拷贝与浅拷贝的问题。Object类的clone方法只会拷贝对象中的基本的数据类型,对于数组、容器对象、引用对象等都不会拷贝,这就是浅拷贝。如果要实现深拷贝,必须将原型模式中的数组、容器对象、引用对象等另行拷贝。
## 单例模式(Singleton)
## 模式定义
包路径:`com.tzx.singleton`
这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
>- 1、单例类只能有一个实例。
>- 2、单例类必须自己创建自己的唯一实例。
>- 3、单例类必须给所有其他对象提供这一实例。
具体查看 [Java版的7种单例模式](https://dandanlove.blog.csdn.net/article/details/101759634)
### 举例说明
`Retrofit` 中也使用了大量的**单例模式**,比如 `BuiltInConverters` 的 `responseBodyConverter`、`requestBodyConverter` 等,并且使用了**饿汉式的单例模式**。
```java
final class BuiltInConverters extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (type == ResponseBody.class) {
return Utils.isAnnotationPresent(annotations, Streaming.class)
? StreamingResponseBodyConverter.INSTANCE
: BufferingResponseBodyConverter.INSTANCE;
}
if (type == Void.class) {
return VoidResponseBodyConverter.INSTANCE;
}
return null;
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (RequestBody.class.isAssignableFrom(Utils.getRawType(type))) {
return RequestBodyConverter.INSTANCE;
}
return null;
}
static final class VoidResponseBodyConverter implements Converter<ResponseBody, Void> {
static final VoidResponseBodyConverter INSTANCE = new VoidResponseBodyConverter();
@Override
public Void convert(ResponseBody value) throws IOException {
value.close();
return null;
}
}
/***部分代码省略***/
}
```
## 观察者模式(observer)
包路径: `com.tzx.observer`
### 模式定义
建立一种对象与对象之间的依赖关系,一个对象发生改变时将自动通知其他对象,其他对象将相应做出反应。在此,发生改变的对象称为观察目标,而被通知的对象称为观察者,一个观察目标可以对应多个观察者,而且这些观察者之间没有相互联系,可以根据需要增加和删除观察者,使得系统更易于扩展,这就是观察者模式的模式动机。
### 模式结构
观察者模式所涉及的角色有:
>- 抽象主题(Subject)角色:抽象主题角色把所有对观察者对象的引用保存在一个聚集(比如ArrayList对象)里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象,抽象主题角色又叫做抽象被观察者(Observable)角色。
>- 具体主题(ConcreteSubject)角色:将有关状态存入具体观察者对象;在具体主题的内部状态改变时,给所有登记过的观察者发出通知。具体主题角色又叫做具体被观察者(Concrete Observable)角色。
>- 抽象观察者(Observer)角色:为所有的具体观察者定义一个接口,在得到主题的通知时更新自己,这个接口叫做更新接口。
>- 具体观察者(ConcreteObserver)角色:存储与主题的状态自恰的状态。具体观察者角色实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态 像协调。如果需要,具体观察者角色可以保持一个指向具体主题对象的引用。

### **推模型和拉模型**
在观察者模式中,又分为推模型和拉模型两种方式。
**推模型**
主题对象向观察者推送主题的详细信息,不管观察者是否需要,推送的信息通常是主题对象的全部或部分数据。
**拉模型**
主题对象在通知观察者的时候,只传递少量信息。如果观察者需要更具体的信息,由观察者主动到主题对象中获取,相当于是观察者从主题对象中拉数据。一般这种模型的实现中,会把主题对象自身通过update()方法传递给观察者,这样在观察者需要获取数据的时候,就可以通过这个引用来获取了。
### 举例说明
网络请求相关的库一般都是会支持请求的异步发送,通过在库内部维护一个队列,将请求添加到该队列,同时注册一个回调接口,以便执行引擎完成该请求后,将请求结果进行回调。
`Retrofit` 的网络请求执行引擎是 `OkHttp` ,请求类是 `OkHttpCall` ,其实现了 `Call` 接口,`enqueue` 方法如下,入参为 `Callback`对象。
```java
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "callback == null");
okhttp3.Call call;
Throwable failure;
/***部分代码省略***/
call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
throws IOException {
Response<T> response;
try {
response = parseResponse(rawResponse);
} catch (Throwable e) {
callFailure(e);
return;
}
callSuccess(response);
}
@Override public void onFailure(okhttp3.Call call, IOException e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
private void callFailure(Throwable e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
private void callSuccess(Response<T> response) {
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
```
- `Call`:`Subject` 抽象的被观察者;
- `OkHttpCall`:`ConcreteSubject` 具体的被观察者;
- `Callback`:`Observer` 抽象的观察者;
- `Callback`的实现类:`ConcreteObserver` 具体观察者的实现;<file_sep>/src/com/tzx/templatemethod/TestPageB.java
package com.tzx.templatemethod;
/**
* Created by tanzhenxing on 17-4-26.
*/
public class TestPageB extends TestPaper {
@Override
public String Answer1() {
return "D";
}
@Override
public String Answer2() {
return "E";
}
@Override
public String Answer3() {
return "F";
}
}
<file_sep>/src/com/tzx/factory/simplefactory/Shape.java
package com.tzx.factory.simplefactory;
/**
* Created by tanzhenxing on 17-4-26.
*/
public interface Shape {
void sayHello();
}
<file_sep>/src/com/tzx/factory/simplefactory/Triangle.java
package com.tzx.factory.simplefactory;
/**
* Created by tanzhenxing on 17-4-26.
*/
public class Triangle implements Shape {
@Override
public void sayHello() {
System.out.println("I am Triangle");
}
}
<file_sep>/src/com/tzx/strategy/PrimaryMemeberStrategy.java
package com.tzx.strategy;
/**
* Created by tanzhenxing on 17-4-25.
* 初级会员价格
*/
public class PrimaryMemeberStrategy implements MemberStrategy{
/**
* 计算图书的价格
* @param booksPrice 图书的原价
* @return 计算出打折后的价格
*/
public double calcPrice(double booksPrice) {
System.out.println("对于初级会员没有折扣");
return booksPrice;
}
}
<file_sep>/src/com/tzx/decorator/Person.java
package com.tzx.decorator;
/**
* Created by tanzhenxing on 17-4-25.
*/
public interface Person {
void doCoding();
}
<file_sep>/src/com/tzx/State/eg/BlackVoteState.java
package com.tzx.State.eg;
/**
* Created by tanzhenxing on 17-5-31.
*/
public class BlackVoteState implements VoteState {
@Override
public void vote(String user, String voteItem, VoteManager voteManager) {
System.out.println("进去黑名单,将静止登陆和使用本系统");
}
}
<file_sep>/src/com/tzx/chainOfResponsibility/Main.java
package com.tzx.chainOfResponsibility;
/**
* Created by tanzhenxing on 17-9-5.
* 职责任链模式(Chain of Responsibiblity):使多个对象都有机会处理请求,从而避免请求的发送者和接受者之前的耦合关系。
* 将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
*
* 抽象处理者(handler)角色、定义出一个处理请求的接口;如果需要,接口可以定义出一个方法,以返回对下家的引用。
* 负责规定具体处理者处理用户请求的方法以及具体处理者设置后续处理的方法。
*
* 具体处理者(ConcreateHandler)角色、处理接受到请求后,可以选择将请求处理掉,或者将请求传给下家。
* 实现处理接口的类的实例,具体处理者通过调用处理接口规定的方法处理用户请求,既在接到用户请求后,处理者将调用接口规定的方法
* 在执行方法的过程中,如果发现处理用户的请求。如果发现处理不了就交给下一个处理者进行处理。
*
* 适合使用责任链式的情况:
* 1、在许多对象可以处理用户请求的时候
* 2、希望用户不必明确处理的时候,同时向多个处理者发送请求
* 3、程序希望动态的定制可处理用户请求的集合对象
*/
public class Main {
public static void main(String[] args) {
Handler jisuanji, wenxue;
jisuanji = new JiSuanJi();
wenxue = new WenXue();
jisuanji.setNexHandler(wenxue);
jisuanji.Search(1);
}
}
<file_sep>/src/com/tzx/factory/abstractfactory/ShapeFactory.java
package com.tzx.factory.abstractfactory;
import com.tzx.factory.simplefactory.Shape;
/**
* Created by tanzhenxing on 17-4-26.
*/
public interface ShapeFactory {
Shape createShape();
Color createColor();
}
<file_sep>/src/com/tzx/State/Context.java
package com.tzx.State;
/**
* Created by tanzhenxing on 17-5-31.
*/
public class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public void request(String sampleParameter) {
state.handle(sampleParameter);
}
}
<file_sep>/src/com/tzx/observer/Main.java
package com.tzx.observer;
/**
* Created by tanzhenxing on 17-5-25.
*
* 观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使他们
* 能够自动更新自己。
*
* 抽象主题(Subject)角色:抽象主题角色把所有观察者对象的引用保存在一个聚焦(比如ArrayList对像)里,每个主题都可以有任何数量的观察者。
* 抽象主题提供一个解耦,可以增加和删除观察者对象,抽象主题角色又叫抽象被观察者(Observalbe)角色。
*
* 具体主题角色(ConcreateSubject)角色:将有关状态存入具体观察者对象;在具体主题的内部状态改变时,所有登记过的观察者发出通知。
* 具体主题角色又叫做具体被观察者(concreate Observable)角色。
*
* 抽象观察者(Observer)角色:为所有的具体观察者定义一个接口,在得到主题的通知时更新自己,这个接口叫做更新接口。
*
* 具体观察者(concreateObserver)角色:存储与主题的状态自恰的状态。具体观察者角色抽象观察者角色要求的更新接口,以便使本身的状态与主题的状态像协调。
* 如果需要,具体观察者橘色可以保持一个指向具体主题对象的引用。
*/
public class Main {
public static void main(String[] args) {
ConcreateSubject subject = new ConcreateSubject();
Observer observer = new ConcreateObserver();
subject.attach(observer);
subject.change("new State~!");
}
}
<file_sep>/src/com/tzx/facade/Camara.java
package com.tzx.facade;
/**
* Created by tanzhenxing on 17-5-25.
*/
public class Camara {
public void trunOn() {
System.out.println("开启摄像头!");
}
public void trunOff() {
System.out.println("关闭摄像头!");
}
}
<file_sep>/src/com/tzx/factory/abstractfactory/RedCircleFactory.java
package com.tzx.factory.abstractfactory;
import com.tzx.factory.simplefactory.Circle;
import com.tzx.factory.simplefactory.Shape;
/**
* Created by tanzhenxing on 17-4-26.
*/
public class RedCircleFactory implements ShapeFactory {
@Override
public Shape createShape() {
return new Circle();
}
@Override
public Color createColor() {
return new Red();
}
}
<file_sep>/src/com/tzx/factory/methodfactory/RectangleFactory.java
package com.tzx.factory.methodfactory;
import com.tzx.factory.simplefactory.Rectangle;
import com.tzx.factory.simplefactory.Shape;
/**
* Created by tanzhenxing on 17-4-26.
*/
public class RectangleFactory implements ShapeFactory {
@Override
public Shape create() {
return new Rectangle();
}
}
<file_sep>/src/com/tzx/prototype/Main.java
package com.tzx.prototype;
/**
* Created by tanzhenxing on 17-4-26.
*
* 原型模式(Prototype)用原型实例指定创建对象的种类,并且通过拷贝这些原型对象创建新的对象。
*/
public class Main {
/**
* 持有需要使用的原型接口对象
*/
private Prototype prototype;
/**
* 构造方法,传入需要使用的原型接口对象
*/
public Main(Prototype prototype){
this.prototype = prototype;
}
public void operation(Prototype example) throws CloneNotSupportedException {
//需要创建原型接口的对象
Prototype copyPrototype = prototype.clone();
}
}
<file_sep>/src/com/tzx/State/ConcreteStateA.java
package com.tzx.State;
/**
* Created by tanzhenxing on 17-5-31.
*/
public class ConcreteStateA implements State {
@Override
public void handle(String sampleParameter) {
System.out.println("ConcreateStateA handle : " + sampleParameter);
}
}
<file_sep>/src/com/tzx/flyweight/Context.java
package com.tzx.flyweight;
/**
* Created by tanzhenxing on 17-5-27.
*/
public class Context {
private int size;
private char c;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
public Context(int size, char c) {
this.size = size;
this.c = c;
}
}
<file_sep>/src/com/tzx/build/Builder.java
package com.tzx.build;
public abstract class Builder {
public abstract void buildName();
public abstract void buildAge();
public abstract void builHeight();
public abstract void buildWeight();
public abstract Person create();
}
<file_sep>/src/com/tzx/factory/simplefactory/Rectangle.java
package com.tzx.factory.simplefactory;
/**
* Created by tanzhenxing on 17-4-26.
*/
public class Rectangle implements Shape {
@Override
public void sayHello() {
System.out.println("I am Rectangle");
}
}
<file_sep>/src/com/tzx/factory/abstractfactory/Color.java
package com.tzx.factory.abstractfactory;
/**
* Created by tanzhenxing on 17-4-26.
*/
public interface Color {
void sayHello();
}
|
d854a64c30e51ee52618ee8c1bb6ff8152a01e7a
|
[
"Markdown",
"Java"
] | 29
|
Java
|
stven0king/designmode
|
215cc83eb0abe9557d9e149b6686cb2f366f69d8
|
1917c29f4355a8364267b954c1a4f61894fea3e9
|
refs/heads/master
|
<file_sep>package com.student.dao;
import java.util.List;
import com.student.model.Student;
public interface StudentDAO {
public Student addStudent( Student student );
public void deleteStudent( int studentId );
public Student updateStudent( Student student );
public List<Student> getAllStudents();
public Student getStudentById( int studentId );
}
|
28420631cdd9546760071618fbec31fca77a989f
|
[
"Java"
] | 1
|
Java
|
yogijava/Java
|
5931bf1c29b5a5c2f18384d4ffd6190b8439db35
|
9a42c2c4d4d53c47177cbbb920824ca3628fa7a2
|
refs/heads/master
|
<repo_name>tejvepa/eventuate-tram-sagas<file_sep>/eventuate-tram-sagas-spring-participant/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-spring-common")
compile project(":eventuate-tram-sagas-participant")
}<file_sep>/orders-and-customers/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-participant")
compile project(":eventuate-tram-sagas-orchestration")
compile project(":eventuate-tram-sagas-orchestration-simple-dsl")
compile 'javax.persistence:javax.persistence-api:2.2'
}
<file_sep>/build-and-test-all-activemq.sh
#! /bin/bash
set -e
. ./set-env-mysql.sh
export SPRING_PROFILES_ACTIVE=ActiveMQ
export database=mysql
export target=activemq
./_build-and-test-all.sh<file_sep>/eventuate-tram-sagas-orchestration/src/main/java/io/eventuate/tram/sagas/orchestration/SagaInstanceRepositoryJdbc.java
package io.eventuate.tram.sagas.orchestration;
import io.eventuate.common.id.IdGenerator;
import io.eventuate.common.jdbc.EventuateDuplicateKeyException;
import io.eventuate.common.jdbc.EventuateJdbcStatementExecutor;
import io.eventuate.common.jdbc.EventuateSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
public class SagaInstanceRepositoryJdbc implements SagaInstanceRepository {
private Logger logger = LoggerFactory.getLogger(getClass());
private EventuateJdbcStatementExecutor eventuateJdbcStatementExecutor;
private IdGenerator idGenerator;
private String insertIntoSagaInstanceSql;
private String insertIntoSagaInstanceParticipantsSql;
private String selectFromSagaInstanceSql;
private String selectFromSagaInstanceParticipantsSql;
private String updateSagaInstanceSql;
public SagaInstanceRepositoryJdbc(EventuateJdbcStatementExecutor eventuateJdbcStatementExecutor,
IdGenerator idGenerator,
EventuateSchema eventuateSchema) {
this.eventuateJdbcStatementExecutor = eventuateJdbcStatementExecutor;
this.idGenerator = idGenerator;
String sagaInstanceTable = eventuateSchema.qualifyTable("saga_instance");
String sagaInstanceParticipantsTable = eventuateSchema.qualifyTable("saga_instance_participants");
insertIntoSagaInstanceSql = String.format("INSERT INTO %s(saga_type, saga_id, state_name, last_request_id, saga_data_type, saga_data_json, end_state, compensating) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", sagaInstanceTable);
insertIntoSagaInstanceParticipantsSql = String.format("INSERT INTO %s(saga_type, saga_id, destination, resource) values(?,?,?,?)", sagaInstanceParticipantsTable);
selectFromSagaInstanceSql = String.format("SELECT * FROM %s WHERE saga_type = ? AND saga_id = ?", sagaInstanceTable);
selectFromSagaInstanceParticipantsSql = String.format("SELECT destination, resource FROM %s WHERE saga_type = ? AND saga_id = ?", sagaInstanceParticipantsTable);
updateSagaInstanceSql = String.format("UPDATE %s SET state_name = ?, last_request_id = ?, saga_data_type = ?, saga_data_json = ?, end_state = ?, compensating = ? where saga_type = ? AND saga_id = ?", sagaInstanceTable);
}
public String getInsertIntoSagaInstanceSql() {
return insertIntoSagaInstanceSql;
}
public void setInsertIntoSagaInstanceSql(String insertIntoSagaInstanceSql) {
this.insertIntoSagaInstanceSql = insertIntoSagaInstanceSql;
}
public String getInsertIntoSagaInstanceParticipantsSql() {
return insertIntoSagaInstanceParticipantsSql;
}
public void setInsertIntoSagaInstanceParticipantsSql(String insertIntoSagaInstanceParticipantsSql) {
this.insertIntoSagaInstanceParticipantsSql = insertIntoSagaInstanceParticipantsSql;
}
public String getSelectFromSagaInstanceSql() {
return selectFromSagaInstanceSql;
}
public void setSelectFromSagaInstanceSql(String selectFromSagaInstanceSql) {
this.selectFromSagaInstanceSql = selectFromSagaInstanceSql;
}
public String getSelectFromSagaInstanceParticipantsSql() {
return selectFromSagaInstanceParticipantsSql;
}
public void setSelectFromSagaInstanceParticipantsSql(String selectFromSagaInstanceParticipantsSql) {
this.selectFromSagaInstanceParticipantsSql = selectFromSagaInstanceParticipantsSql;
}
public String getUpdateSagaInstanceSql() {
return updateSagaInstanceSql;
}
public void setUpdateSagaInstanceSql(String updateSagaInstanceSql) {
this.updateSagaInstanceSql = updateSagaInstanceSql;
}
@Override
public void save(SagaInstance sagaInstance) {
sagaInstance.setId(idGenerator.genId().asString());
logger.info("Saving {} {}", sagaInstance.getSagaType(), sagaInstance.getId());
eventuateJdbcStatementExecutor.update(insertIntoSagaInstanceSql,
sagaInstance.getSagaType(),
sagaInstance.getId(),
sagaInstance.getStateName(),
sagaInstance.getLastRequestId(),
sagaInstance.getSerializedSagaData().getSagaDataType(),
sagaInstance.getSerializedSagaData().getSagaDataJSON(),
sagaInstance.isEndState(),
sagaInstance.isCompensating());
saveDestinationsAndResources(sagaInstance);
}
private void saveDestinationsAndResources(SagaInstance sagaInstance) {
for (DestinationAndResource dr : sagaInstance.getDestinationsAndResources()) {
try {
eventuateJdbcStatementExecutor.update(insertIntoSagaInstanceParticipantsSql,
sagaInstance.getSagaType(),
sagaInstance.getId(),
dr.getDestination(),
dr.getResource()
);
} catch (EventuateDuplicateKeyException e) {
logger.info("key duplicate: sagaType = {}, sagaId = {}, destination = {}, resource = {}",
sagaInstance.getSagaType(),
sagaInstance.getId(),
dr.getDestination(),
dr.getResource());
}
}
}
@Override
public SagaInstance find(String sagaType, String sagaId) {
logger.info("finding {} {}", sagaType, sagaId);
Set<DestinationAndResource> destinationsAndResources = new HashSet<>(eventuateJdbcStatementExecutor.query(
selectFromSagaInstanceParticipantsSql,
(rs, rownum) ->
new DestinationAndResource(rs.getString("destination"), rs.getString("resource")),
sagaType,
sagaId));
return eventuateJdbcStatementExecutor.query(
selectFromSagaInstanceSql,
(rs, rownum) ->
new SagaInstance(sagaType, sagaId, rs.getString("state_name"),
rs.getString("last_request_id"),
new SerializedSagaData(rs.getString("saga_data_type"), rs.getString("saga_data_json")), destinationsAndResources),
sagaType,
sagaId).stream().findFirst().orElse(null);
// TODO insert - sagaInstance.getDestinationsAndResources();
}
@Override
public void update(SagaInstance sagaInstance) {
logger.info("Updating {} {}", sagaInstance.getSagaType(), sagaInstance.getId());
int count = eventuateJdbcStatementExecutor.update(updateSagaInstanceSql,
sagaInstance.getStateName(),
sagaInstance.getLastRequestId(),
sagaInstance.getSerializedSagaData().getSagaDataType(),
sagaInstance.getSerializedSagaData().getSagaDataJSON(),
sagaInstance.isEndState(), sagaInstance.isCompensating(),
sagaInstance.getSagaType(), sagaInstance.getId());
if (count != 1) {
throw new RuntimeException("Should be 1 : " + count);
}
saveDestinationsAndResources(sagaInstance);
}
}
<file_sep>/eventuate-tram-sagas-orchestration/src/test/java/io/eventuate/tram/sagas/orchestration/SagaInstanceRepositoryJdbcEmptySchemaTest.java
package io.eventuate.tram.sagas.orchestration;
import io.eventuate.common.jdbc.EventuateSchema;
public class SagaInstanceRepositoryJdbcEmptySchemaTest extends SagaInstanceRepositoryJdbcSchemaTest {
@Override
protected SagaInstanceRepositoryJdbc getSagaInstanceRepositoryJdbc() {
return new SagaInstanceRepositoryJdbc(null, null, new EventuateSchema(EventuateSchema.EMPTY_SCHEMA));
}
@Override
protected String getExpectedPrefix() {
return "";
}
}
<file_sep>/orders-and-customers-spring/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-spring-participant")
compile project(":eventuate-tram-sagas-spring-orchestration")
compile project(":eventuate-tram-sagas-orchestration-simple-dsl")
compile project(":orders-and-customers")
compile "org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-spring-jdbc-kafka:$eventuateTramVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-jdbc-activemq:$eventuateTramVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-spring-in-memory:$eventuateTramVersion"
testCompile "org.springframework.boot:spring-boot-starter-test:${springBootVersion}"
testCompile "io.eventuate.util:eventuate-util-test:$eventuateUtilVersion"
testCompile project(":eventuate-tram-sagas-testing-support")
testCompile project(":eventuate-tram-sagas-spring-in-memory")
}
<file_sep>/eventuate-tram-sagas-orchestration/src/main/java/io/eventuate/tram/sagas/orchestration/SagaInstance.java
package io.eventuate.tram.sagas.orchestration;
import java.util.Set;
public class SagaInstance {
private String sagaType;
private String id;
private String lastRequestId;
private SerializedSagaData serializedSagaData;
private String stateName;
private Set<DestinationAndResource> destinationsAndResources;
private Boolean endState = false;
private Boolean compensating = false;
public void setSagaType(String sagaType) {
this.sagaType = sagaType;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public SagaInstance(String sagaType, String sagaId, String stateName, String lastRequestId, SerializedSagaData serializedSagaData, Set<DestinationAndResource> destinationsAndResources) {
this.sagaType = sagaType;
this.id = sagaId;
this.stateName = stateName;
this.lastRequestId = lastRequestId;
this.serializedSagaData = serializedSagaData;
this.destinationsAndResources = destinationsAndResources;
}
public SerializedSagaData getSerializedSagaData() {
return serializedSagaData;
}
public void setSerializedSagaData(SerializedSagaData serializedSagaData) {
this.serializedSagaData = serializedSagaData;
}
public void setId(String id) {
this.id = id;
}
public String getSagaType() {
return sagaType;
}
public String getId() {
return id;
}
public String getLastRequestId() {
return lastRequestId;
}
public void setLastRequestId(String requestId) {
this.lastRequestId = requestId;
}
public void addDestinationsAndResources(Set<DestinationAndResource> destinationAndResources) {
this.destinationsAndResources.addAll(destinationAndResources);
}
public Set<DestinationAndResource> getDestinationsAndResources() {
return destinationsAndResources;
}
public void setEndState(Boolean endState) {
this.endState = endState;
}
public Boolean isEndState() {
return endState;
}
public void setCompensating(Boolean compensating) {
this.compensating = compensating;
}
public Boolean isCompensating() {
return compensating;
}
}
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/ParticipantInvocationImpl.java
package io.eventuate.tram.sagas.simpledsl;
import io.eventuate.tram.commands.common.Command;
import io.eventuate.tram.commands.common.CommandReplyOutcome;
import io.eventuate.tram.commands.common.ReplyMessageHeaders;
import io.eventuate.tram.commands.consumer.CommandWithDestination;
import io.eventuate.tram.messaging.common.Message;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
public class ParticipantInvocationImpl<Data, C extends Command> extends AbstractParticipantInvocation<Data> {
private Function<Data, CommandWithDestination> commandBuilder;
public ParticipantInvocationImpl(Optional<Predicate<Data>> invocablePredicate, Function<Data, CommandWithDestination> commandBuilder) {
super(invocablePredicate);
this.commandBuilder = commandBuilder;
}
@Override
public boolean isSuccessfulReply(Message message) {
return CommandReplyOutcome.SUCCESS.name().equals(message.getRequiredHeader(ReplyMessageHeaders.REPLY_OUTCOME));
}
@Override
public CommandWithDestination makeCommandToSend(Data data) {
return commandBuilder.apply(data);
}
}
<file_sep>/eventuate-tram-sagas-spring-testing-support/src/main/java/io/eventuate/tram/sagas/spring/testing/SagaParticipantStubManagerConfiguration.java
package io.eventuate.tram.sagas.spring.testing;
import io.eventuate.tram.sagas.testing.SagaParticipantChannels;
import io.eventuate.tram.sagas.testing.SagaParticipantStubManager;
import io.eventuate.tram.spring.commands.producer.TramCommandProducerConfiguration;
import io.eventuate.tram.spring.events.publisher.TramEventsPublisherConfiguration;
import io.eventuate.tram.messaging.consumer.MessageConsumer;
import io.eventuate.tram.messaging.producer.MessageProducer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({TramCommandProducerConfiguration.class, TramEventsPublisherConfiguration.class,})
public class SagaParticipantStubManagerConfiguration {
@Bean
public SagaParticipantStubManager sagaParticipantStubManager(SagaParticipantChannels sagaParticipantChannels, MessageConsumer messageConsumer, MessageProducer messageProducer) {
return new SagaParticipantStubManager(sagaParticipantChannels, messageConsumer, messageProducer);
}
}
<file_sep>/eventuate-tram-sagas-spring-participant/src/main/java/io/eventuate/tram/sagas/spring/participant/SagaParticipantConfiguration.java
package io.eventuate.tram.sagas.spring.participant;
import io.eventuate.tram.messaging.consumer.MessageConsumer;
import io.eventuate.tram.messaging.producer.MessageProducer;
import io.eventuate.tram.sagas.common.SagaLockManager;
import io.eventuate.tram.sagas.spring.common.EventuateTramSagaCommonConfiguration;
import io.eventuate.tram.sagas.participant.SagaCommandDispatcherFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(EventuateTramSagaCommonConfiguration.class)
public class SagaParticipantConfiguration {
@Bean
public SagaCommandDispatcherFactory sagaCommandDispatcherFactory(MessageConsumer messageConsumer,
MessageProducer messageProducer,
SagaLockManager sagaLockManager) {
return new SagaCommandDispatcherFactory(messageConsumer, messageProducer, sagaLockManager);
}
}
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/StepBuilder.java
package io.eventuate.tram.sagas.simpledsl;
import io.eventuate.tram.commands.common.Command;
import io.eventuate.tram.commands.consumer.CommandWithDestination;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
public class StepBuilder<Data> implements WithCompensationBuilder<Data> {
private final SimpleSagaDefinitionBuilder<Data> parent;
public StepBuilder(SimpleSagaDefinitionBuilder<Data> builder) {
this.parent = builder;
}
public LocalStepBuilder<Data> invokeLocal(Consumer<Data> localFunction) {
return new LocalStepBuilder<>(parent, localFunction);
}
public InvokeParticipantStepBuilder<Data> invokeParticipant(Function<Data, CommandWithDestination> action) {
return new InvokeParticipantStepBuilder<>(parent).withAction(Optional.empty(), action);
}
public InvokeParticipantStepBuilder<Data> invokeParticipant(Predicate<Data> participantInvocationPredicate, Function<Data, CommandWithDestination> action) {
return new InvokeParticipantStepBuilder<>(parent).withAction(Optional.of(participantInvocationPredicate), action);
}
public <C extends Command> InvokeParticipantStepBuilder<Data> invokeParticipant(CommandEndpoint<C> commandEndpoint, Function<Data, C> commandProvider) {
return new InvokeParticipantStepBuilder<>(parent).withAction(Optional.empty(), commandEndpoint, commandProvider);
}
public <C extends Command> InvokeParticipantStepBuilder<Data> invokeParticipant(Predicate<Data> participantInvocationPredicate, CommandEndpoint<C> commandEndpoint, Function<Data, C> commandProvider) {
return new InvokeParticipantStepBuilder<>(parent).withAction(Optional.of(participantInvocationPredicate), commandEndpoint, commandProvider);
}
@Override
public InvokeParticipantStepBuilder<Data> withCompensation(Function<Data, CommandWithDestination> compensation) {
return new InvokeParticipantStepBuilder<>(parent).withCompensation(compensation);
}
@Override
public InvokeParticipantStepBuilder<Data> withCompensation(Predicate<Data> compensationPredicate, Function<Data, CommandWithDestination> compensation) {
return new InvokeParticipantStepBuilder<>(parent).withCompensation(compensation);
}
@Override
public <C extends Command> InvokeParticipantStepBuilder<Data> withCompensation(CommandEndpoint<C> commandEndpoint, Function<Data, C> commandProvider) {
return new InvokeParticipantStepBuilder<>(parent).withCompensation(commandEndpoint, commandProvider);
}
@Override
public <C extends Command> InvokeParticipantStepBuilder<Data> withCompensation(Predicate<Data> compensationPredicate, CommandEndpoint<C> commandEndpoint, Function<Data, C> commandProvider) {
return new InvokeParticipantStepBuilder<>(parent).withCompensation(compensationPredicate, commandEndpoint, commandProvider);
}
}
<file_sep>/eventuate-tram-sagas-testing-support/src/main/java/io/eventuate/tram/sagas/testing/SagaParticipantStubManager.java
package io.eventuate.tram.sagas.testing;
import io.eventuate.common.json.mapper.JSonMapper;
import io.eventuate.tram.commands.common.Command;
import io.eventuate.tram.commands.consumer.CommandMessage;
import io.eventuate.tram.messaging.common.Message;
import io.eventuate.tram.messaging.consumer.MessageConsumer;
import io.eventuate.tram.messaging.producer.MessageProducer;
import io.eventuate.tram.sagas.testing.commandhandling.SagaParticipantStubCommandHandler;
import io.eventuate.tram.sagas.testing.commandhandling.ReconfigurableCommandHandlers;
import io.eventuate.tram.sagas.testing.commandhandling.UnhandledMessageTrackingCommandDispatcher;
import javax.annotation.PostConstruct;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import static io.eventuate.tram.commands.consumer.CommandHandlerReplyBuilder.withFailure;
import static io.eventuate.tram.commands.consumer.CommandHandlerReplyBuilder.withSuccess;
/**
* Defines a DSL for configuring stubbed saga participants (more generally, recipients of command messages) that response to command messages.
* WireMock-equivalent for Tram messaging
*/
public class SagaParticipantStubManager {
private final ReconfigurableCommandHandlers commandHandlers;
private Set<String> commandChannels;
private final UnhandledMessageTrackingCommandDispatcher commandDispatcher;
private String currentCommandChannel;
public SagaParticipantStubManager(SagaParticipantChannels sagaParticipantChannels, MessageConsumer messageConsumer, MessageProducer messageProducer) {
this.commandChannels = sagaParticipantChannels.getChannels();
this.commandHandlers = new ReconfigurableCommandHandlers(this.commandChannels);
this.commandDispatcher = new UnhandledMessageTrackingCommandDispatcher("SagaParticipantStubManager-command-dispatcher-" + System.currentTimeMillis(),
commandHandlers,
messageConsumer,
messageProducer);
/// TODO handle scenario where a command is recieved for which there is not a handler.
}
@PostConstruct
public void initialize() {
commandDispatcher.initialize();
}
public void reset() {
commandHandlers.reset();
commandDispatcher.reset();
}
public SagaParticipantStubManager forChannel(String commandChannel) {
validateChannel(commandChannel);
this.currentCommandChannel = commandChannel;
return this;
}
private void validateChannel(String commandChannel) {
if (!commandChannels.contains(commandChannel))
throw new IllegalArgumentException(String.format("%s is not one of the specified channels: %s", commandChannel, commandChannels));
}
public <C extends Command> SagaParticipantStubManagerHelper<C> when(C expectedCommand) {
return new SagaParticipantStubManagerHelper<C>(this, (Class<C>) expectedCommand.getClass(),
message -> JSonMapper.fromJson(message.getPayload(), expectedCommand.getClass()).equals(expectedCommand));
}
public <C extends Command> SagaParticipantStubManagerHelper<C> when(Class<C> expectedCommandClass) {
return new SagaParticipantStubManagerHelper<C>(this, expectedCommandClass, message -> true);
}
public <C extends Command> void verifyCommandReceived(String channel, Class<C> commandClass) {
commandHandlers.findCommandHandler(channel, commandClass)
.map(handler -> {
handler.verifyCommandReceived();
return true;
})
.orElseThrow(() -> new RuntimeException(String.format("no handler for channel %s command class %s", channel, commandClass)));
}
public class SagaParticipantStubManagerHelper<C> {
private Class<C> expectedCommandClass;
private final Predicate<Message> expectedCommand;
private SagaParticipantStubManager sagaParticipantStubManager;
public SagaParticipantStubManagerHelper(SagaParticipantStubManager sagaParticipantStubManager, Class<C> expectedCommandClass, Predicate<Message> expectedCommand) {
this.sagaParticipantStubManager = sagaParticipantStubManager;
this.expectedCommandClass = expectedCommandClass;
this.expectedCommand = expectedCommand;
}
public SagaParticipantStubManager replyWith(Function<CommandMessage<C>, Message> replyBuilder) {
SagaParticipantStubCommandHandler<C> commandHandler = new SagaParticipantStubCommandHandler<>(currentCommandChannel, expectedCommandClass, expectedCommand, replyBuilder);
sagaParticipantStubManager.commandHandlers.add(commandHandler);
commandDispatcher.noteNewCommandHandler(commandHandler);
return sagaParticipantStubManager;
}
public SagaParticipantStubManager replyWithSuccess() {
return replyWith(cm -> withSuccess());
}
public SagaParticipantStubManager replyWithFailure() {
return replyWith(cm -> withFailure());
}
}
}
<file_sep>/eventuate-tram-sagas-participant/src/main/java/io/eventuate/tram/sagas/participant/SagaCommandHandler.java
package io.eventuate.tram.sagas.participant;
import io.eventuate.tram.commands.consumer.CommandHandler;
import io.eventuate.tram.commands.consumer.CommandMessage;
import io.eventuate.tram.commands.consumer.PathVariables;
import io.eventuate.tram.messaging.common.Message;
import io.eventuate.tram.sagas.common.LockTarget;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
public class SagaCommandHandler extends CommandHandler {
private Optional<BiFunction<CommandMessage, PathVariables, LockTarget>> preLock = Optional.empty();
private Optional<PostLockFunction> postLock = Optional.empty();
public <C> SagaCommandHandler(String channel, String resource, Class<C> commandClass, BiFunction<CommandMessage<C>, PathVariables, List<Message>> handler) {
super(channel, Optional.of(resource), commandClass, handler);
}
public <C> SagaCommandHandler(String channel, Class<C> commandClass, Function<CommandMessage<C>, List<Message>> handler) {
super(channel, Optional.empty(), commandClass, (c, pv) -> handler.apply(c));
}
public void setPreLock(BiFunction<CommandMessage, PathVariables, LockTarget> preLock) {
this.preLock = Optional.of(preLock);
}
public void setPostLock(PostLockFunction postLock) {
this.postLock = Optional.of(postLock);
}
public Optional<BiFunction<CommandMessage, PathVariables, LockTarget>> getPreLock() {
return preLock;
}
public Optional<PostLockFunction> getPostLock() {
return postLock;
}
}
<file_sep>/README.adoc
= Eventuate Tram Saga
image::https://api.bintray.com/packages/eventuateio-oss/eventuate-maven-release/eventuate-tram-sagas/images/download.svg[link="https://bintray.com/eventuateio-oss/eventuate-maven-release/eventuate-tram-sagas/_latestVersion"]
The Eventuate Tram Saga framework is a saga framework for Java microservices that use JDBC/JPA.
A major challenge when implementing business applications using the microservice architecture is maintaining data consistency across services.
Each service has its own private data and you can't use distributed transactions.
The solution is to use sagas.
A http://microservices.io/patterns/data/saga.html[saga] maintains consistency across multiple microservices by using a series of a local transactions that are coordinated using messages or events.
A saga consists of a series of steps.
Each step consists of either transaction, a compensating transaction or both.
Each transaction is the invocation of a saga participant using a command message.
A saga executes the forward transactions sequentially.
If one of them fails then the saga executes the compensating transactions in reverse order to rollback the saga.
Eventuate Tram Saga is described in more detail in my book https://www.manning.com/books/microservice-patterns[Microservice Patterns].
It is built on the https://github.com/eventuate-tram/eventuate-tram-core[Eventuate Tram framework], which enables an application to atomically update a database and publish a message without using JTA.
== Learn more
Recent presentations:
* QCONSF 2017 - http://microservices.io/microservices/news/2017/12/04/qconsf2017-presentation.html[slides]
* JavaOne 2017 - https://www.slideshare.net/chris.e.richardson/javaone2017-acid-is-so-yesterday-maintaining-data-consistency-with-sagas[slides] and https://www.youtube.com/watch?v=6P6dvNyvtps[video]
Example applications:
* https://github.com/eventuate-tram/eventuate-tram-sagas-examples-customers-and-orders[Customers and Orders]
* https://github.com/microservice-patterns/ftgo-application[FTGO Example application for Microservice Patterns book]
== Writing an orchestrator
The https://github.com/eventuate-tram/eventuate-tram-sagas-examples-customers-and-orders[Customers and Orders] uses a saga to create an `Order` in the `Order Service` and reserve credit in the `Customer Service`.
The `CreateOrderSaga` consists of the following three steps:
1. The `CreateOrderSaga` is instantiated after the `Order` is created.
Consequently, the first step is simply a compensating transaction, which is executed in the credit cannot be reserved to reject the order.
2. Requests the `CustomerService` to reserve credit for the order.
If the reservation is success, the next step is executed.
Otherwise, the compensating transactions are executed to roll back the saga.
3. Approves the order, if the credit is reserved.
Here is part of the definition of `CreateOrderSaga`.
```java
public class CreateOrderSaga implements SimpleSaga<CreateOrderSagaData> {
private SagaDefinition<CreateOrderSagaData> sagaDefinition =
step()
.withCompensation(this::reject)
.step()
.invokeParticipant(this::reserveCredit)
.step()
.invokeParticipant(this::approve)
.build();
@Override
public SagaDefinition<CreateOrderSagaData> getSagaDefinition() {
return this.sagaDefinition;
}
private CommandWithDestination reserveCredit(CreateOrderSagaData data) {
long orderId = data.getOrderId();
Long customerId = data.getOrderDetails().getCustomerId();
Money orderTotal = data.getOrderDetails().getOrderTotal();
return send(new ReserveCreditCommand(customerId, orderId, orderTotal))
.to("customerService")
.build();
...
```
The `reserveCredit()` creates a message to send to the `Customer Service` to reserve credit.
== Creating an saga orchestrator
The `OrderService` creates the saga:
```java
public class OrderService {
@Autowired
private SagaManager<CreateOrderSagaData> createOrderSagaManager;
@Autowired
private OrderRepository orderRepository;
@Transactional
public Order createOrder(OrderDetails orderDetails) {
ResultWithEvents<Order> oe = Order.createOrder(orderDetails);
Order order = oe.result;
orderRepository.save(order);
CreateOrderSagaData data = new CreateOrderSagaData(order.getId(), orderDetails);
createOrderSagaManager.create(data, Order.class, order.getId());
return order;
}
}
```
== Writing a saga participant
Here is the `CustomerCommandHandler`, which handles the command to reserve credit:
```java
public class CustomerCommandHandler {
@Autowired
private CustomerRepository customerRepository;
public CommandHandlers commandHandlerDefinitions() {
return SagaCommandHandlersBuilder
.fromChannel("customerService")
.onMessage(ReserveCreditCommand.class, this::reserveCredit)
.build();
}
public Message reserveCredit(CommandMessage<ReserveCreditCommand> cm) {
...
}
...
```
== Maven/Gradle artifacts
The artifacts are in https://bintray.com/eventuateio-oss/eventuate-maven-release/eventuate-tram-sagas[JCenter].
The latest version is:
image::https://api.bintray.com/packages/eventuateio-oss/eventuate-maven-release/eventuate-tram-sagas/images/download.svg[link="https://bintray.com/eventuateio-oss/eventuate-maven-release/eventuate-tram-sagas/_latestVersion"]
If you are writing a Saga orchestrator add this dependency to your project:
* `io.eventuate.tram.sagas:eventuate-tram-sagas-orchestration-simple-dsl:$eventuateTramSagasVersion`
If you are writing a saga participant then add this dependency:
* `io.eventuate.tram.sagas:eventuate-jpa-sagas-framework:$eventuateTramSagasVersion`
You must also include one of the https://github.com/eventuate-tram/eventuate-tram-core[Eventuate Tram] 'implementation' artifacts:
* `io.eventuate.tram.core:eventuate-tram-jdbc-kafka:$eventuateTramVersion` - JDBC database and Apache Kafka message broker
* `io.eventuate.tram.core:eventuate-tram-in-memory:$eventuateTramVersion` - In-memory JDBC database and in-memory messaging for testing
== Running the CDC service
In addition to a database and message broker, you will need to run the Eventuate Tram CDC service.
It reads messages and events inserted into the database and publishes them to Apache Kafka.
It is written using Spring Boot.
The easiest way to run this service during development is to use Docker Compose.
The https://github.com/eventuate-tram/eventuate-tram-core-examples-basic[Eventuate Tram Code Basic examples] project has an example https://github.com/eventuate-tram/eventuate-tram-core-examples-basic/blob/master/docker-compose.yml[docker-compose.yml file].
<file_sep>/eventuate-tram-sagas-micronaut-orchestration/src/main/java/io/eventuate/tram/sagas/micronaut/orchestration/SagaOrchestratorFactory.java
package io.eventuate.tram.sagas.micronaut.orchestration;
import io.eventuate.common.id.IdGenerator;
import io.eventuate.common.jdbc.EventuateJdbcStatementExecutor;
import io.eventuate.common.jdbc.EventuateSchema;
import io.eventuate.tram.commands.producer.CommandProducer;
import io.eventuate.tram.messaging.consumer.MessageConsumer;
import io.eventuate.tram.sagas.common.SagaLockManager;
import io.eventuate.tram.sagas.orchestration.*;
import io.micronaut.context.annotation.Factory;
import javax.inject.Singleton;
@Factory
public class SagaOrchestratorFactory {
@Singleton
public SagaInstanceRepository sagaInstanceRepository(EventuateJdbcStatementExecutor eventuateJdbcStatementExecutor,
IdGenerator idGenerator,
EventuateSchema eventuateSchema) {
return new SagaInstanceRepositoryJdbc(eventuateJdbcStatementExecutor, idGenerator, eventuateSchema);
}
@Singleton
public SagaCommandProducer sagaCommandProducer(CommandProducer commandProducer) {
return new SagaCommandProducer(commandProducer);
}
@Singleton
public SagaInstanceFactory sagaInstanceFactory(SagaInstanceRepository sagaInstanceRepository,
CommandProducer commandProducer, MessageConsumer messageConsumer,
SagaLockManager sagaLockManager, SagaCommandProducer sagaCommandProducer) {
SagaManagerFactory smf = new SagaManagerFactory(sagaInstanceRepository, commandProducer, messageConsumer,
sagaLockManager, sagaCommandProducer);
return new SagaInstanceFactory(smf);
}
}
<file_sep>/eventuate-tram-sagas-participant/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-common")
}<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-orchestration")
testCompile project(":eventuate-tram-sagas-testing-support")
}<file_sep>/gradle.properties
org.gradle.jvmargs=-XX:MaxPermSize=512m
deployUrl=file:///Users/cer/.m2/testdeploy
bintrayRepoType=defineMe
eventuateMavenRepoUrl=https://dl.bintray.com/eventuateio-oss/eventuate-maven-release/,https://dl.bintray.com/eventuateio-oss/eventuate-maven-milestone,https://dl.bintray.com/eventuateio-oss/eventuate-maven-rc/,file:///Users/cer/.m2/testdeploy,https://snapshots.repositories.eventuate.io/repository
springBootVersion=2.1.1.RELEASE
eventuateUtilVersion=0.3.0.RELEASE
eventuateClientVersion=0.23.0.RC4
eventuateTramVersion=0.24.0.BUILD-SNAPSHOT
eventuateCommonImageVersion=0.9.0.RC4
eventuateCommonVersion=0.9.0.RC4
eventuateMessagingKafkaImageVersion=0.9.0.RC4
version=0.12.0-SNAPSHOT
<file_sep>/set-env-postgres.sh
. ./set-env.sh
export SPRING_DATASOURCE_URL=jdbc:postgresql://${DOCKER_HOST_IP}/eventuate
export SPRING_DATASOURCE_USERNAME=eventuate
export SPRING_DATASOURCE_PASSWORD=<PASSWORD>
export SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver
export SPRING_DATASOURCE_TEST_ON_BORROW=true
export SPRING_DATASOURCE_VALIDATION_QUERY="SELECT 1"
export EVENTUATELOCAL_CDC_POLLING_INTERVAL_IN_MILLISECONDS=500
export EVENTUATELOCAL_CDC_MAX_EVENTS_PER_POLLING=1000
export EVENTUATELOCAL_CDC_MAX_ATTEMPTS_FOR_POLLING=100
export EVENTUATELOCAL_CDC_POLLING_RETRY_INTERVAL_IN_MILLISECONDS=500
export SPRING_PROFILES_ACTIVE=EventuatePolling
export DB_URL=jdbc:postgresql://${DOCKER_HOST_IP}/eventuate
export DB_USERNAME=eventuate
export DB_PASSWORD=<PASSWORD>
export DB_DRIVERCLASSNAME=org.postgresql.Driver<file_sep>/set-env-mysql.sh
. ./set-env.sh
export SPRING_DATASOURCE_URL=jdbc:mysql://${DOCKER_HOST_IP}/eventuate
export SPRING_DATASOURCE_USERNAME=mysqluser
export SPRING_DATASOURCE_PASSWORD=<PASSWORD>
export SPRING_DATASOURCE_DRIVER_CLASS_NAME=com.mysql.jdbc.Driver
export EVENTUATELOCAL_CDC_DB_USER_NAME=root
export EVENTUATELOCAL_CDC_DB_PASSWORD=<PASSWORD>
export EVENTUATE_CURRENT_TIME_IN_MILLISECONDS_SQL="ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000)"
export DB_URL=jdbc:mysql://${DOCKER_HOST_IP}/eventuate
export DB_USERNAME=mysqluser
export DB_PASSWORD=<PASSWORD>
export DB_DRIVERCLASSNAME=com.mysql.jdbc.Driver<file_sep>/eventuate-tram-sagas-testing-support/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-orchestration")
compile "io.eventuate.tram.core:eventuate-tram-testing-support:$eventuateTramVersion"
}
<file_sep>/settings.gradle
include 'eventuate-tram-sagas-common'
include 'eventuate-tram-sagas-spring-common'
include 'eventuate-tram-sagas-micronaut-common'
include 'eventuate-tram-sagas-orchestration'
include 'eventuate-tram-sagas-spring-orchestration'
include 'eventuate-tram-sagas-micronaut-orchestration'
include 'eventuate-tram-sagas-participant'
include 'eventuate-tram-sagas-spring-participant'
include 'eventuate-tram-sagas-micronaut-participant'
include 'eventuate-tram-sagas-micronaut-configuration-tests'
include 'eventuate-tram-sagas-orchestration-simple-dsl'
include 'eventuate-tram-sagas-spring-orchestration-simple-dsl'
include 'eventuate-tram-sagas-spring-in-memory'
include 'eventuate-tram-sagas-micronaut-in-memory'
include "eventuate-tram-sagas-event-sourcing-support"
include 'eventuate-tram-sagas-testing-support'
include 'eventuate-tram-sagas-spring-testing-support'
include 'eventuate-tram-sagas-micronaut-testing-support'
include 'orders-and-customers'
include 'orders-and-customers-spring'
include 'orders-and-customers-micronaut'
include 'orders-and-customers-micronaut-integration-tests'
include 'orders-and-customers-micronaut-in-memory-integration-tests'
include 'orders-and-customers-micronaut-local-saga-in-memory-integration-tests'
<file_sep>/eventuate-tram-sagas-micronaut-participant/src/main/java/io/eventuate/tram/sagas/micronaut/participant/SagaParticipantFactory.java
package io.eventuate.tram.sagas.micronaut.participant;
import io.eventuate.tram.messaging.consumer.MessageConsumer;
import io.eventuate.tram.messaging.producer.MessageProducer;
import io.eventuate.tram.sagas.common.SagaLockManager;
import io.eventuate.tram.sagas.participant.SagaCommandDispatcherFactory;
import io.micronaut.context.annotation.Factory;
import javax.inject.Singleton;
@Factory
public class SagaParticipantFactory {
@Singleton
public SagaCommandDispatcherFactory sagaCommandDispatcherFactory(MessageConsumer messageConsumer, MessageProducer messageProducer, SagaLockManager sagaLockManager) {
return new SagaCommandDispatcherFactory(messageConsumer, messageProducer, sagaLockManager);
}
}
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/StepToExecute.java
package io.eventuate.tram.sagas.simpledsl;
import io.eventuate.tram.sagas.orchestration.SagaActions;
import java.util.Optional;
import static io.eventuate.tram.sagas.simpledsl.SagaExecutionStateJsonSerde.encodeState;
public class StepToExecute<Data> {
private final Optional<SagaStep<Data>> step;
private final int skipped;
private final boolean compensating;
public StepToExecute(Optional<SagaStep<Data>> step, int skipped, boolean compensating) {
this.compensating = compensating;
this.step = step;
this.skipped = skipped;
}
private int size() {
return step.map(x -> 1).orElse(0) + skipped;
}
public boolean isEmpty() {
return !step.isPresent();
}
public SagaActions<Data> executeStep(Data data, SagaExecutionState currentState) {
SagaExecutionState newState = currentState.nextState(size());
SagaActions.Builder<Data> builder = SagaActions.builder();
boolean compensating = currentState.isCompensating();
step.get().makeStepOutcome(data, this.compensating).visit(builder::withIsLocal, builder::withCommands);
return builder
.withUpdatedSagaData(data)
.withUpdatedState(encodeState(newState))
.withIsEndState(newState.isEndState())
.withIsCompensating(compensating)
.build();
}
}
<file_sep>/eventuate-tram-sagas-common/src/test/java/io/eventuate/tram/sagas/common/SagaLockManagerImplSchemaTest.java
package io.eventuate.tram.sagas.common;
import io.eventuate.tram.sagas.common.SagaLockManagerImpl;
import org.junit.Assert;
import org.junit.Test;
public abstract class SagaLockManagerImplSchemaTest {
@Test
public void testInsertIntoSagaLockTable() {
Assert.assertEquals(getExpectedInsertIntoSagaLockTable(), getSagaLockManager().getInsertIntoSagaLockTableSql());
}
@Test
public void testInsertIntoSagaStashTable() {
Assert.assertEquals(getExpectedInsertIntoSagaStashTable(), getSagaLockManager().getInsertIntoSagaStashTableSql());
}
@Test
public void testSelectFromSagaLockTable() {
Assert.assertEquals(getExpectedSelectFromSagaLockTable(), getSagaLockManager().getSelectFromSagaLockTableSql());
}
@Test
public void testSelectFromSagaStashTable() {
Assert.assertEquals(getExpectedSelectFromSagaStashTable(), getSagaLockManager().getSelectFromSagaStashTableSql());
}
@Test
public void testUpdateSagaLockTable() {
Assert.assertEquals(getExpectedUpdateSagaLockTable(), getSagaLockManager().getUpdateSagaLockTableSql());
}
@Test
public void testDeleteFromSagaLockTable() {
Assert.assertEquals(getExpectedDeleteFromSagaLockTable(), getSagaLockManager().getDeleteFromSagaLockTableSql());
}
@Test
public void testDeleteFromSagaStashTable() {
Assert.assertEquals(getExpectedDeleteFromSagaStashTable(), getSagaLockManager().getDeleteFromSagaStashTableSql());
}
protected abstract SagaLockManagerImpl getSagaLockManager();
protected abstract String getExpectedInsertIntoSagaLockTable();
protected abstract String getExpectedInsertIntoSagaStashTable();
protected abstract String getExpectedSelectFromSagaLockTable();
protected abstract String getExpectedSelectFromSagaStashTable();
protected abstract String getExpectedUpdateSagaLockTable();
protected abstract String getExpectedDeleteFromSagaStashTable();
protected abstract String getExpectedDeleteFromSagaLockTable();
}
<file_sep>/eventuate-tram-sagas-participant/src/main/java/io/eventuate/tram/sagas/participant/AbstractSagaCommandHandlersBuilder.java
package io.eventuate.tram.sagas.participant;
import io.eventuate.tram.commands.consumer.CommandMessage;
import io.eventuate.tram.messaging.common.Message;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
public interface AbstractSagaCommandHandlersBuilder {
<C> SagaCommandHandlerBuilder<C> onMessageReturningMessages(Class<C> commandClass,
Function<CommandMessage<C>, List<Message>> handler);
<C> SagaCommandHandlerBuilder<C> onMessageReturningOptionalMessage(Class<C> commandClass,
Function<CommandMessage<C>, Optional<Message>> handler);
<C> SagaCommandHandlerBuilder<C> onMessage(Class<C> commandClass,
Function<CommandMessage<C>, Message> handler);
<C> SagaCommandHandlerBuilder<C> onMessage(Class<C> commandClass, Consumer<CommandMessage<C>> handler);
}
<file_sep>/_build-and-test-all.sh
#! /bin/bash
set -e
. "./set-env-${database}.sh"
./gradlew testClasses
./gradlew "${database}AllComposeDown"
./gradlew "${target}InfrastructureComposeBuild"
./gradlew "${target}InfrastructureComposeUp"
"./wait-for-${database}.sh"
./gradlew "${database}AllComposeUp"
if [[ "${SPRING_PROFILES_ACTIVE}" != "ActiveMQ" ]]; then
./gradlew :orders-and-customers-spring:cleanTest :orders-and-customers-micronaut:cleanTest build
else
./gradlew -x orders-and-customers-micronaut-integration-tests:test -x :orders-and-customers-micronaut:test -x :eventuate-tram-sagas-micronaut-common:test :orders-and-customers-spring:cleanTest build
fi
./gradlew "${database}AllComposeDown"
<file_sep>/eventuate-tram-sagas-spring-orchestration/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-orchestration")
compile project(":eventuate-tram-sagas-spring-common")
compile "io.eventuate.tram.core:eventuate-tram-spring-events:$eventuateTramVersion"
compile "io.eventuate.common:eventuate-common-spring-jdbc:$eventuateCommonVersion"
testCompile "org.springframework.boot:spring-boot-starter-test:$springBootVersion"
testCompile project(":eventuate-tram-sagas-spring-in-memory")
}<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/test/java/io/eventuate/tram/sagas/simpledsl/WithHandlersSagaTest.java
package io.eventuate.tram.sagas.simpledsl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static io.eventuate.tram.sagas.testing.SagaUnitTestSupport.given;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class WithHandlersSagaTest {
private Handlers handlers;
@Before
public void setup() {
this.handlers = mock(Handlers.class);
}
@After
public void tearDown() {
verifyNoMoreInteractions(handlers);
}
@Test
public void shouldExecuteAllStepsSuccessfully() {
given().
saga(new WithHandlersSaga(handlers), new ConditionalSagaData(true)).
expect().
command(new Do1Command()).
to("participant1").
withExtraHeaders(ConditionalSagaData.DO1_COMMAND_EXTRA_HEADERS).
andGiven().
successReply().
expect().
command(new Do2Command()).
to("participant2").
andGiven().
successReply().
expectCompletedSuccessfully()
;
expectSuccess1();
expectSuccess2();
}
private void expectSuccess1() {
Mockito.verify(handlers).success1(any(), any());
}
@Test
public void shouldRollback() {
given().
saga(new WithHandlersSaga(handlers), new ConditionalSagaData(true)).
expect().
command(new Do1Command()).
to("participant1").
andGiven().
successReply().
expect().
command(new Do2Command()).
to("participant2").
andGiven().
failureReply().
expect().
command(new Undo1Command()).
to("participant1").
andGiven().
successReply().
expectRolledBack()
;
expectSuccess1();
expectFailure2();
Mockito.verify(handlers).compensating1(any(), any());
}
private void expectFailure2() {
Mockito.verify(handlers).failure2(any(), any());
}
@Test
public void shouldExecuteAllStepsExcept1Successfully() {
given().
saga(new WithHandlersSaga(handlers), new ConditionalSagaData(false)).
expect().
command(new Do2Command()).
to("participant2").
andGiven().
successReply().
expectCompletedSuccessfully()
;
expectSuccess2();
}
private void expectSuccess2() {
Mockito.verify(handlers).success2(any(), any());
}
@Test
public void shouldRollbackExcept1() {
given().
saga(new WithHandlersSaga(handlers), new ConditionalSagaData(false)).
expect().
command(new Do2Command()).
to("participant2").
andGiven().
failureReply().
expectRolledBack()
;
expectFailure2();
}
@Test
public void shouldFailOnFirstStep() {
given().
saga(new WithHandlersSaga(handlers), new ConditionalSagaData(true)).
expect().
command(new Do1Command()).
to("participant1").
andGiven().
failureReply().
expectRolledBack()
;
expectFailure1();
}
private void expectFailure1() {
Mockito.verify(handlers).failure1(any(), any());
}
}
<file_sep>/eventuate-tram-sagas-micronaut-configuration-tests/build.gradle
plugins {
id "io.spring.dependency-management" version "1.0.6.RELEASE"
}
dependencyManagement {
imports {
mavenBom 'io.micronaut:micronaut-bom:1.2.0'
}
}
apply plugin: PublicModulePlugin
dependencies {
testCompile project(":eventuate-tram-sagas-micronaut-common")
compile "io.eventuate.common:eventuate-common-micronaut-spring-jdbc:$eventuateCommonVersion"
testCompile project(":eventuate-tram-sagas-orchestration-simple-dsl")
testCompile project(":eventuate-tram-sagas-micronaut-participant")
testCompile project(":eventuate-tram-sagas-micronaut-orchestration")
testCompile "io.eventuate.tram.core:eventuate-tram-micronaut-events:$eventuateTramVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-micronaut-producer-jdbc:$eventuateTramVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-micronaut-consumer-jdbc:$eventuateTramVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-micronaut-messaging:$eventuateTramVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-micronaut-consumer-kafka:$eventuateTramVersion"
testCompile "io.eventuate.tram.core:eventuate-tram-micronaut-events:$eventuateTramVersion"
compile 'mysql:mysql-connector-java:5.1.36'
compile ('org.postgresql:postgresql:9.4-1200-jdbc41') {
exclude group: "org.slf4j", module: "slf4j-simple"
}
annotationProcessor "io.micronaut:micronaut-inject-java"
annotationProcessor "io.micronaut:micronaut-validation"
annotationProcessor "io.micronaut.configuration:micronaut-openapi"
compile "io.micronaut:micronaut-inject"
compile "io.micronaut:micronaut-validation"
compile "io.micronaut:micronaut-runtime"
testAnnotationProcessor "io.micronaut:micronaut-inject-java"
testAnnotationProcessor "io.micronaut:micronaut-validation"
testAnnotationProcessor "io.micronaut.configuration:micronaut-openapi"
testCompile "io.micronaut:micronaut-inject"
testCompile "io.micronaut:micronaut-validation"
testCompile "io.micronaut:micronaut-runtime"
testAnnotationProcessor "io.micronaut:micronaut-inject-java"
testCompile "org.junit.jupiter:junit-jupiter-api"
testCompile "io.micronaut.test:micronaut-test-junit5"
testRuntime "org.junit.jupiter:junit-jupiter-engine"
testRuntime 'io.micronaut.configuration:micronaut-jdbc-hikari'
}
// use JUnit 5 platform
test {
useJUnitPlatform()
}
<file_sep>/eventuate-tram-sagas-orchestration/src/main/java/io/eventuate/tram/sagas/orchestration/SagaDefinition.java
package io.eventuate.tram.sagas.orchestration;
import io.eventuate.tram.messaging.common.Message;
public interface SagaDefinition<Data> {
SagaActions<Data> start(Data sagaData);
SagaActions<Data> handleReply(String currentState, Data sagaData, Message message);
}
<file_sep>/eventuate-tram-sagas-testing-support/src/main/java/io/eventuate/tram/sagas/testing/commandhandling/ReconfigurableCommandHandlers.java
package io.eventuate.tram.sagas.testing.commandhandling;
import io.eventuate.tram.commands.common.Command;
import io.eventuate.tram.commands.consumer.CommandExceptionHandler;
import io.eventuate.tram.commands.consumer.CommandHandler;
import io.eventuate.tram.commands.consumer.CommandHandlers;
import io.eventuate.tram.messaging.common.Message;
import java.util.*;
public class ReconfigurableCommandHandlers extends CommandHandlers {
private final Set<String> commandChannels;
private List<SagaParticipantStubCommandHandler> handlers = new ArrayList<>();
public ReconfigurableCommandHandlers(Set<String> commandChannels) {
super(Collections.emptyList());
this.commandChannels = commandChannels;
}
@Override
public Set<String> getChannels() {
return commandChannels;
}
public void add(SagaParticipantStubCommandHandler commandHandler) {
this.handlers.add(commandHandler);
}
@Override
public Optional<CommandHandler> findTargetMethod(Message message) {
return handlers.stream().filter(h -> h.handles(message)).findFirst().map(x -> (CommandHandler)x);
}
@Override
public Optional<CommandExceptionHandler> findExceptionHandler(Throwable cause) {
return super.findExceptionHandler(cause);
}
public void reset() {
handlers.clear();
}
public <C extends Command> Optional<SagaParticipantStubCommandHandler> findCommandHandler(String channel, Class<C> commandClass) {
return handlers.stream().filter(h -> h.handles(channel, commandClass)).findFirst();
}
}
<file_sep>/build-and-test-all-mysql.sh
#! /bin/bash
set -e
. ./set-env-mysql.sh
export database=mysql
export target=mysql
./_build-and-test-all.sh<file_sep>/eventuate-tram-sagas-event-sourcing-support/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile "io.eventuate.client.java:eventuate-client-java:$eventuateClientVersion"
compile "io.eventuate.tram.core:eventuate-tram-spring-commands:$eventuateTramVersion"
}
<file_sep>/eventuate-tram-sagas-orchestration/src/test/java/io/eventuate/tram/sagas/orchestration/SagaInstanceRepositoryJdbcSchemaTest.java
package io.eventuate.tram.sagas.orchestration;
import org.junit.Assert;
import org.junit.Test;
public abstract class SagaInstanceRepositoryJdbcSchemaTest {
@Test
public void testInsertIntoSagaInstance() {
Assert.assertEquals(getExpectedInsertIntoSagaInstance(), getSagaInstanceRepositoryJdbc().getInsertIntoSagaInstanceSql());
}
@Test
public void testInsertIntoSagaInstanceParticipants() {
Assert.assertEquals(getExpectedInsertIntoSagaInstanceParticipants(), getSagaInstanceRepositoryJdbc().getInsertIntoSagaInstanceParticipantsSql());
}
@Test
public void testSelectFromSagaInstance() {
Assert.assertEquals(getExpectedSelectFromSagaInstance(), getSagaInstanceRepositoryJdbc().getSelectFromSagaInstanceSql());
}
@Test
public void testSelectFromSagaInstanceParticipants() {
Assert.assertEquals(getExpectedSelectFromSagaInstanceParticipants(), getSagaInstanceRepositoryJdbc().getSelectFromSagaInstanceParticipantsSql());
}
@Test
public void testUpdateSagaInstance() {
Assert.assertEquals(getExpectedUpdateSagaInstance(), getSagaInstanceRepositoryJdbc().getUpdateSagaInstanceSql());
}
protected abstract SagaInstanceRepositoryJdbc getSagaInstanceRepositoryJdbc();
private String getExpectedInsertIntoSagaInstance() {
return String.format("INSERT INTO %ssaga_instance(saga_type, saga_id, state_name, last_request_id, saga_data_type, saga_data_json, end_state, compensating) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", getExpectedPrefix());
}
private String getExpectedInsertIntoSagaInstanceParticipants() {
return String.format("INSERT INTO %ssaga_instance_participants(saga_type, saga_id, destination, resource) values(?,?,?,?)", getExpectedPrefix());
}
private String getExpectedSelectFromSagaInstance() {
return String.format("SELECT * FROM %ssaga_instance WHERE saga_type = ? AND saga_id = ?", getExpectedPrefix());
}
private String getExpectedSelectFromSagaInstanceParticipants() {
return String.format("SELECT destination, resource FROM %ssaga_instance_participants WHERE saga_type = ? AND saga_id = ?", getExpectedPrefix());
}
private String getExpectedUpdateSagaInstance() {
return String.format("UPDATE %ssaga_instance SET state_name = ?, last_request_id = ?, saga_data_type = ?, saga_data_json = ?, end_state = ?, compensating = ? where saga_type = ? AND saga_id = ?", getExpectedPrefix());
}
protected abstract String getExpectedPrefix();
}
<file_sep>/eventuate-tram-sagas-orchestration/src/main/java/io/eventuate/tram/sagas/orchestration/SagaCommandProducer.java
package io.eventuate.tram.sagas.orchestration;
import io.eventuate.tram.commands.consumer.CommandWithDestination;
import io.eventuate.tram.commands.producer.CommandProducer;
import io.eventuate.tram.sagas.common.SagaCommandHeaders;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SagaCommandProducer {
private CommandProducer commandProducer;
public SagaCommandProducer(CommandProducer commandProducer) {
this.commandProducer = commandProducer;
}
public String sendCommands(String sagaType, String sagaId, List<CommandWithDestination> commands, String sagaReplyChannel) {
String messageId = null;
for (CommandWithDestination command : commands) {
Map<String, String> headers = new HashMap<>(command.getExtraHeaders());
headers.put(SagaCommandHeaders.SAGA_TYPE, sagaType);
headers.put(SagaCommandHeaders.SAGA_ID, sagaId);
messageId = commandProducer.send(command.getDestinationChannel(), command.getResource(), command.getCommand(), sagaReplyChannel, headers);
}
return messageId;
}
}
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/SagaExecutionStateJsonSerde.java
package io.eventuate.tram.sagas.simpledsl;
import io.eventuate.common.json.mapper.JSonMapper;
public class SagaExecutionStateJsonSerde {
static SagaExecutionState decodeState(String currentState) {
return JSonMapper.fromJson(currentState, SagaExecutionState.class);
}
public static String encodeState(SagaExecutionState state) {
return JSonMapper.toJson(state);
}
}
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/LocalStepBuilder.java
package io.eventuate.tram.sagas.simpledsl;
import io.eventuate.tram.sagas.orchestration.SagaDefinition;
import java.util.Optional;
import java.util.function.Consumer;
public class LocalStepBuilder<Data> {
private final SimpleSagaDefinitionBuilder<Data> parent;
private final Consumer<Data> localFunction;
private Optional<Consumer<Data>> compensation = Optional.empty();
public LocalStepBuilder(SimpleSagaDefinitionBuilder<Data> parent, Consumer<Data> localFunction) {
this.parent = parent;
this.localFunction = localFunction;
}
public LocalStepBuilder<Data> withCompensation(Consumer<Data> localCompensation) {
this.compensation = Optional.of(localCompensation);
return this;
}
public StepBuilder<Data> step() {
parent.addStep(new LocalStep<>(localFunction, compensation));
return new StepBuilder<>(parent);
}
public SagaDefinition<Data> build() {
// TODO - pull up with template method for completing current step
parent.addStep(new LocalStep<>(localFunction, compensation));
return parent.build();
}
}
<file_sep>/orders-and-customers/src/main/java/io/eventuate/examples/tram/sagas/ordersandcustomers/orders/service/OrderService.java
package io.eventuate.examples.tram.sagas.ordersandcustomers.orders.service;
import io.eventuate.common.jdbc.EventuateTransactionTemplate;
import io.eventuate.examples.tram.sagas.ordersandcustomers.orders.domain.Order;
import io.eventuate.examples.tram.sagas.ordersandcustomers.orders.domain.OrderDao;
import io.eventuate.examples.tram.sagas.ordersandcustomers.orders.sagas.createorder.CreateOrderSagaData;
import io.eventuate.examples.tram.sagas.ordersandcustomers.orders.sagas.createorder.LocalCreateOrderSaga;
import io.eventuate.examples.tram.sagas.ordersandcustomers.orders.sagas.createorder.LocalCreateOrderSagaData;
import io.eventuate.tram.events.publisher.ResultWithEvents;
import io.eventuate.tram.sagas.orchestration.SagaInstanceFactory;
import io.eventuate.tram.sagas.orchestration.SagaManager;
public class OrderService {
private SagaManager<CreateOrderSagaData> createOrderSagaManager;
private OrderDao orderRepository;
private EventuateTransactionTemplate eventuateTransactionTemplate;
private SagaInstanceFactory sagaInstanceFactory;
private LocalCreateOrderSaga localCreateOrderSaga;
public OrderService(SagaManager<CreateOrderSagaData> createOrderSagaManager,
OrderDao orderDao,
EventuateTransactionTemplate eventuateTransactionTemplate,
SagaInstanceFactory sagaInstanceFactory,
LocalCreateOrderSaga localCreateOrderSaga) {
this.createOrderSagaManager = createOrderSagaManager;
this.orderRepository = orderDao;
this.eventuateTransactionTemplate = eventuateTransactionTemplate;
this.sagaInstanceFactory = sagaInstanceFactory;
this.localCreateOrderSaga = localCreateOrderSaga;
}
public Order createOrder(OrderDetails orderDetails) {
return eventuateTransactionTemplate.executeInTransaction(() -> {
ResultWithEvents<Order> oe = Order.createOrder(orderDetails);
Order order = oe.result;
orderRepository.save(order);
CreateOrderSagaData data = new CreateOrderSagaData(order.getId(), orderDetails);
createOrderSagaManager.create(data, Order.class, order.getId());
return order;
});
}
public Order localCreateOrder(OrderDetails orderDetails) {
return eventuateTransactionTemplate.executeInTransaction(() -> {
LocalCreateOrderSagaData data = new LocalCreateOrderSagaData(orderDetails);
sagaInstanceFactory.create(localCreateOrderSaga, data);
return orderRepository.findById(data.getOrderId());
});
}
}
<file_sep>/mysql/Dockerfile
ARG EVENTUATE_COMMON_VERSION
FROM eventuateio/eventuate-mysql:$EVENTUATE_COMMON_VERSION
COPY tram-saga-schema.sql /docker-entrypoint-initdb.d
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/SagaExecutionState.java
package io.eventuate.tram.sagas.simpledsl;
import org.apache.commons.lang.builder.ToStringBuilder;
public class SagaExecutionState {
private int currentlyExecuting;
private boolean compensating;
private boolean endState;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public SagaExecutionState() {
}
public SagaExecutionState(int currentlyExecuting, boolean compensating) {
this.currentlyExecuting = currentlyExecuting;
this.compensating = compensating;
}
public int getCurrentlyExecuting() {
return currentlyExecuting;
}
public void setCurrentlyExecuting(int currentlyExecuting) {
this.currentlyExecuting = currentlyExecuting;
}
public boolean isCompensating() {
return compensating;
}
public void setCompensating(boolean compensating) {
this.compensating = compensating;
}
public SagaExecutionState startCompensating() {
return new SagaExecutionState(currentlyExecuting, true);
}
public SagaExecutionState nextState(int size) {
return new SagaExecutionState(compensating ? currentlyExecuting - size : currentlyExecuting + size, compensating);
}
public boolean isEndState() {
return endState;
}
public void setEndState(boolean endState) {
this.endState = endState;
}
public static SagaExecutionState makeEndState() {
SagaExecutionState x = new SagaExecutionState();
x.setEndState(true);
return x;
}
}
<file_sep>/eventuate-tram-sagas-spring-orchestration-simple-dsl/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-orchestration-simple-dsl")
compile project(":eventuate-tram-sagas-spring-orchestration")
}<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/ParticipantInvocation.java
package io.eventuate.tram.sagas.simpledsl;
import io.eventuate.tram.commands.consumer.CommandWithDestination;
import io.eventuate.tram.messaging.common.Message;
public interface ParticipantInvocation<Data> {
boolean isSuccessfulReply(Message message);
boolean isInvocable(Data data);
CommandWithDestination makeCommandToSend(Data data);
}
<file_sep>/eventuate-tram-sagas-common/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile "io.eventuate.tram.core:eventuate-tram-commands:$eventuateTramVersion"
compile "io.eventuate.common:eventuate-common-jdbc:$eventuateCommonVersion"
}
<file_sep>/build-and-test-all-postgres.sh
#! /bin/bash
set -e
. ./set-env-postgres.sh
export database=postgres
export target=postgres
./_build-and-test-all.sh<file_sep>/eventuate-tram-sagas-participant/src/main/java/io/eventuate/tram/sagas/participant/SagaCommandHandlersBuilder.java
package io.eventuate.tram.sagas.participant;
import io.eventuate.tram.commands.consumer.CommandHandler;
import io.eventuate.tram.commands.consumer.CommandHandlers;
import io.eventuate.tram.commands.consumer.CommandMessage;
import io.eventuate.tram.messaging.common.Message;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
public class SagaCommandHandlersBuilder implements AbstractSagaCommandHandlersBuilder {
private String channel;
private List<CommandHandler> handlers = new ArrayList<>();
public static SagaCommandHandlersBuilder fromChannel(String channel) {
return new SagaCommandHandlersBuilder().andFromChannel(channel);
}
private SagaCommandHandlersBuilder andFromChannel(String channel) {
this.channel = channel;
return this;
}
@Override
public <C> SagaCommandHandlerBuilder<C> onMessageReturningMessages(Class<C> commandClass,
Function<CommandMessage<C>, List<Message>> handler) {
SagaCommandHandler h = new SagaCommandHandler(channel, commandClass, handler);
this.handlers.add(h);
return new SagaCommandHandlerBuilder<C>(this, h);
}
@Override
public <C> SagaCommandHandlerBuilder<C> onMessageReturningOptionalMessage(Class<C> commandClass,
Function<CommandMessage<C>, Optional<Message>> handler) {
SagaCommandHandler h = new SagaCommandHandler(channel, commandClass, (c) -> handler.apply(c).map(Collections::singletonList).orElse(Collections.EMPTY_LIST));
this.handlers.add(h);
return new SagaCommandHandlerBuilder<C>(this, h);
}
@Override
public <C> SagaCommandHandlerBuilder<C> onMessage(Class<C> commandClass,
Function<CommandMessage<C>, Message> handler) {
SagaCommandHandler h = new SagaCommandHandler(channel, commandClass,
(c) -> Collections.singletonList(handler.apply(c)));
this.handlers.add(h);
return new SagaCommandHandlerBuilder<C>(this, h);
}
@Override
public <C> SagaCommandHandlerBuilder<C> onMessage(Class<C> commandClass, Consumer<CommandMessage<C>> handler) {
SagaCommandHandler h = new SagaCommandHandler(channel, commandClass,
(c) -> {
handler.accept(c);
return Collections.emptyList();
});
this.handlers.add(h);
return new SagaCommandHandlerBuilder<C>(this, h);
}
public CommandHandlers build() {
return new CommandHandlers(handlers);
}
}
<file_sep>/eventuate-tram-sagas-spring-in-memory/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile "org.springframework.boot:spring-boot-starter-jdbc:$springBootVersion"
implementation "io.eventuate.tram.core:eventuate-tram-spring-in-memory:$eventuateTramVersion"
implementation "com.h2database:h2:1.3.166"
}<file_sep>/eventuate-tram-sagas-spring-orchestration/src/main/java/io/eventuate/tram/sagas/spring/orchestration/SagaOrchestratorConfiguration.java
package io.eventuate.tram.sagas.spring.orchestration;
import io.eventuate.common.id.IdGenerator;
import io.eventuate.common.jdbc.EventuateJdbcStatementExecutor;
import io.eventuate.common.jdbc.EventuateSchema;
import io.eventuate.tram.commands.producer.CommandProducer;
import io.eventuate.tram.spring.commands.producer.TramCommandProducerConfiguration;
import io.eventuate.tram.messaging.consumer.MessageConsumer;
import io.eventuate.tram.sagas.common.SagaLockManager;
import io.eventuate.tram.sagas.spring.common.EventuateTramSagaCommonConfiguration;
import io.eventuate.tram.sagas.orchestration.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({TramCommandProducerConfiguration.class, EventuateTramSagaCommonConfiguration.class})
public class SagaOrchestratorConfiguration {
@Bean
public SagaInstanceRepository sagaInstanceRepository(EventuateJdbcStatementExecutor eventuateJdbcStatementExecutor,
IdGenerator idGenerator,
EventuateSchema eventuateSchema) {
return new SagaInstanceRepositoryJdbc(eventuateJdbcStatementExecutor, idGenerator, eventuateSchema);
}
@Bean
public SagaCommandProducer sagaCommandProducer(CommandProducer commandProducer) {
return new SagaCommandProducer(commandProducer);
}
@Bean
public SagaInstanceFactory sagaInstanceFactory(SagaInstanceRepository sagaInstanceRepository, CommandProducer
commandProducer, MessageConsumer messageConsumer,
SagaLockManager sagaLockManager, SagaCommandProducer sagaCommandProducer) {
SagaManagerFactory smf = new SagaManagerFactory(sagaInstanceRepository, commandProducer, messageConsumer,
sagaLockManager, sagaCommandProducer);
return new SagaInstanceFactory(smf);
}
}
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/test/java/io/eventuate/tram/sagas/simpledsl/LocalSagaTest.java
package io.eventuate.tram.sagas.simpledsl;
import org.junit.Before;
import org.junit.Test;
import static io.eventuate.tram.sagas.testing.SagaUnitTestSupport.given;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
public class LocalSagaTest {
private LocalSagaSteps steps;
@Before
public void setUp() throws Exception {
steps = mock(LocalSagaSteps.class);
}
@Test
public void shouldExecuteAllStepsSuccessfully() {
given().
saga(new LocalSaga(steps), new LocalSagaData()).
expect().
command(new Do2Command()).
to("participant2").
andGiven().
successReply().
expectCompletedSuccessfully()
;
}
@Test
public void shouldRollbackFromStep2() {
given().
saga(new LocalSaga(steps), new LocalSagaData()).
expect().
command(new Do2Command()).
to("participant2").
andGiven().
failureReply().
andGiven().
expectRolledBack()
;
}
@Test
public void shouldHandleFailureOfFirstLocalStep() {
LocalSagaData data = new LocalSagaData();
RuntimeException expectedCreateException = new RuntimeException("Failed local step");
doThrow(expectedCreateException).when(steps).localStep1(data);
given().
saga(new LocalSaga(steps), data).
expectException(expectedCreateException)
;
}
@Test
public void shouldHandleFailureOfLastLocalStep() {
LocalSagaData data = new LocalSagaData();
doThrow(new RuntimeException()).when(steps).localStep3(data);
given().
saga(new LocalSaga(steps), data).
expect().
command(new Do2Command()).
to("participant2").
andGiven().
successReply().
expect().
command(new Undo2Command()).
to("participant2").
andGiven().
successReply().
expectRolledBack()
;
}
}
<file_sep>/mysql-cli.sh
#! /bin/bash -e
docker run $* \
--name mysqlterm --rm \
-e MYSQL_PORT_3306_TCP_ADDR=$DOCKER_HOST_IP -e MYSQL_PORT_3306_TCP_PORT=3306 -e MYSQL_ENV_MYSQL_ROOT_PASSWORD=<PASSWORD> \
mysql:5.7.13 \
sh -c 'exec mysql -h"$MYSQL_PORT_3306_TCP_ADDR" -P"$MYSQL_PORT_3306_TCP_PORT" -uroot -p"$MYSQL_ENV_MYSQL_ROOT_PASSWORD" '
<file_sep>/eventuate-tram-sagas-orchestration/build.gradle
apply plugin: PublicModulePlugin
dependencies {
compile project(":eventuate-tram-sagas-common")
compile "io.eventuate.tram.core:eventuate-tram-events:$eventuateTramVersion"
}<file_sep>/eventuate-tram-sagas-orchestration/src/main/java/io/eventuate/tram/sagas/orchestration/Saga.java
package io.eventuate.tram.sagas.orchestration;
public interface Saga<Data> {
SagaDefinition<Data> getSagaDefinition();
default String getSagaType() {
return getClass().getName().replace("$", "_DLR_");
}
default void onStarting(String sagaId, Data data) { }
default void onSagaCompletedSuccessfully(String sagaId, Data data) { }
default void onSagaRolledBack(String sagaId, Data data) { }
}
<file_sep>/eventuate-tram-sagas-orchestration-simple-dsl/src/main/java/io/eventuate/tram/sagas/simpledsl/LocalStep.java
package io.eventuate.tram.sagas.simpledsl;
import io.eventuate.tram.commands.common.CommandReplyOutcome;
import io.eventuate.tram.commands.common.ReplyMessageHeaders;
import io.eventuate.tram.messaging.common.Message;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import static io.eventuate.tram.sagas.simpledsl.StepOutcome.makeLocalOutcome;
public class LocalStep<Data> implements SagaStep<Data> {
private Consumer<Data> localFunction;
private Optional<Consumer<Data>> compensation;
public LocalStep(Consumer<Data> localFunction, Optional<Consumer<Data>> compensation) {
this.localFunction = localFunction;
this.compensation = compensation;
}
@Override
public boolean hasAction(Data data) {
return true;
}
@Override
public boolean hasCompensation(Data data) {
return compensation.isPresent();
}
@Override
public boolean isSuccessfulReply(boolean compensating, Message message) {
return CommandReplyOutcome.SUCCESS.name().equals(message.getRequiredHeader(ReplyMessageHeaders.REPLY_OUTCOME));
}
@Override
public Optional<BiConsumer<Data, Object>> getReplyHandler(Message message, boolean compensating) {
return Optional.empty();
}
@Override
public StepOutcome makeStepOutcome(Data data, boolean compensating) {
try {
if (compensating) {
compensation.ifPresent(localStep -> localStep.accept(data));
} else {
localFunction.accept(data);
}
return makeLocalOutcome(Optional.empty());
} catch (RuntimeException e) {
return makeLocalOutcome(Optional.of(e));
}
}
}
|
00fae9a15dcb596c48d4a6a6db8ebb7c9d36e1de
|
[
"AsciiDoc",
"INI",
"Gradle",
"Java",
"Dockerfile",
"Shell"
] | 53
|
Gradle
|
tejvepa/eventuate-tram-sagas
|
c263549c2ed691d36704feb26c49ed9e35543bb4
|
a194c87393b91d65fd73273616e3349b670d8213
|
refs/heads/master
|
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Figure;
namespace FigureTest
{
[TestClass]
public class FigureTest
{
public void ExceptionTest(Action a)
{
Assert.ThrowsException<FormatException>(a);
}
public void AreaTest<T>(double expectedArea, T figure)
where T: Figure.Figure
{
Assert.AreEqual(expectedArea, Math.Round(figure.Area(), 4));
}
[TestMethod]
public void InvalidTriangleSides()
{
ExceptionTest(() => new Triangle(1, 1, 1));
ExceptionTest(() => new Triangle(4, 2, 2));
}
[TestMethod]
public void ZeroTriangleParams()
{
ExceptionTest(() => new Triangle(4, 0, 1));
ExceptionTest(() => new Triangle(0, 4, 4));
ExceptionTest(() => new Triangle(9, 3, 0));
}
[TestMethod]
public void ZeroCircleParams()
{
ExceptionTest(() => new Circle(0));
ExceptionTest(() => new Circle(3).Radius = 0);
}
[TestMethod]
public void NegativeTriangleParams()
{
ExceptionTest(() => new Triangle(-5,-4, -3));
ExceptionTest(() => new Triangle(-5, 4, 3));
ExceptionTest(() => new Triangle(5, -4, 3));
ExceptionTest(() => new Triangle(5, 4, -3));
}
[TestMethod]
public void NegativeCircleParams()
{
ExceptionTest(() => new Circle(-5));
ExceptionTest(() => new Circle(3).Radius = -2);
}
[TestMethod]
public void CircleAreaCalculate()
{
Circle c = new Circle(2);
AreaTest(12.5664, c);
c.Radius= 3.412;
AreaTest(36.5736, c);
}
[TestMethod]
public void TriangleAreaCalculate()
{
AreaTest(6, new Triangle(5, 4, 3));
AreaTest(1.548, new Triangle(3.5557840204376867, 3.44, 0.9));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Figure
{
public abstract class Figure
{
protected bool IsValidParams (params double[] arr)
{
return arr.All(x => x>0) ? true :false;
}
public abstract double Area();
}
public sealed class Circle : Figure
{
double radius;
public double Radius
{
get => radius;
set {
if (value>0)
radius = value;
else
throw new FormatException();
}
}
public Circle (double rad)
{
Radius = rad;
}
public override double Area()
{
return Math.PI * radius * radius;
}
}
public sealed class Triangle : Figure
{
public double Cathetus1 { get; private set; }
public double Cathetus2 { get; private set; }
public double Hypotenuse { get; private set; }
public Triangle(double h, double c1, double c2)
{
if (IsValidParams(h, c1, c2) &&
(Math.Pow(h, 2) == Math.Pow(c1, 2) + Math.Pow(c2, 2)))
{
Hypotenuse = h;
Cathetus1 = c1;
Cathetus2 = c2;
}
else
throw new FormatException();
}
public override double Area()
{
return 0.5*Cathetus1*Cathetus2;
}
}
}
|
86ddb67d3a77d8b656c29b7c32b79f04d1f81332
|
[
"C#"
] | 2
|
C#
|
Bulat94/GeoTest
|
1d4dee191b923391e487643306a66b36bf509374
|
45dedb0bdef23d635830184ab32bc8a3e3de9ccd
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\TareaPendiente;
use App\TareaHistorial;
use Illuminate\Support\Facades\Auth;
use DataTables;
class ControlProtocoloController extends Controller
{
public function index()
{
return view('lestoma.ControlProtocolos.index');
}
public function data(Request $request)
{
}
public function enviar_protocolo(Request $request)
{
$tarea = new TareaPendiente();
$tarea->fk_protocolo = $request->get('id_protocolo');
$tarea->fk_user = Auth::user()->id;
$tarea->save();
return response([
'msg' => 'Protocolo enviado exitosamente.',
'title' => '¡Protocolo enviado!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
public function enviar_tareas_pendientes()
{
$tarea = TareaPendiente::with('protocolo')
->orderBy('created_at', 'asc')
->take(1)
->get();
return view('lestoma.ControlProtocolos.enviar_arduino', compact('tarea'));
}
public function terminar_tarea($id)
{
$tarea = TareaPendiente::with('protocolo')
->where('id', '=', $id)
->get();
$tarea_historial = new TareaHistorial();
$tarea_historial->nombre_tarea = $tarea[0]->protocolo->nombre;
$tarea_historial->protocolo = $tarea[0]->protocolo->protocolo;
$tarea_historial->fk_users = $tarea[0]->fk_user;
$tarea_historial->save();
TareaPendiente::destroy($id);
return('exito');
}
public function tareasTerminadas()
{
return view('lestoma.DatosHistoricos.tareas_terminadas');
}
public function tareasTerminadasData(Request $request)
{
if ($request->ajax() && $request->isMethod('GET')) {
$tareasTerminadas = TareaHistorial::with('user')
->orderBy('created_at' , 'desc')
->get();
return DataTables::of($tareasTerminadas)
->addColumn('usuario', function ($tareaTerminada) {
return $tareaTerminada->user->name . ' ' . $tareaTerminada->user->lastname;
})
->make(true);
}
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TareaPendiente extends Model
{
/**
* Tabla asociada con el modelo.
*
* @var string
*/
protected $table = 'tareas_pendientes';
/**
* LLave primaria del modelo.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Atributos del modelo que no pueden ser asignados en masa.
*
* @var array
*/
protected $guarded = ['id', 'created_at', 'updated_at'];
public function protocolo()
{
return $this->belongsTo(Protocolo::class, 'fk_protocolo', 'id');
}
/**
* se ejecuta cada vez que se elimina un proceso verifica si existe
* un archivo de autoevaluacion y lo elimina en
* caso de existir del servidor
*/
public static function boot()
{
parent::boot();
// static::deleting(function ($model) {
// $procesos = $model::
// });
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DatosHistorico extends Model
{
/**
* Tabla asociada con el modelo.
*
* @var string
*/
protected $table = 'datos_historicos';
/**
* LLave primaria del modelo.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Atributos del modelo que no pueden ser asignados en masa.
*
* @var array
*/
protected $guarded = ['id', 'created_at', 'updated_at'];
public function sede()
{
return $this->belongsTo(Sede::class, 'fk_sede', 'id');
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use App\User;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$user1 = User::create([
'name' => 'Alejandro',
'lastname' => '2',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'id_estado' => '1'
]);
$user1->assignRole('ADMINISTRADOR');
$user1 = User::create([
'name' => 'Liz',
'lastname' => 'Quintero',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'id_estado' => '1'
]);
$user1->assignRole('USUARIO_ESTANDAR');
}
}
<file_sep>var ChartFiltro;
var limite;
var url_base64 = [];
function crearGrafica(canvas = null, tipo, titulo = null, etiquetas, etiquetasData, data = null) {
var dynamicColorsArray = function (cantidad) {
let colors =[];
for (let i = 0; i < cantidad; i++) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
colors.push("rgb(" + r + "," + g + "," + b + ")");
}
return colors
};
var dynamicColors = function () {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
};
var dataset = [];
for (let i = 0; i < etiquetasData.length; i++){
let aux = {};
aux['label'] = etiquetasData[i];
aux['data'] = data[i];
if(tipo != 'line'){
aux['backgroundColor'] = dynamicColorsArray(data[i].length);
}
else{
aux['borderColor'] = dynamicColors();
aux['fill'] = false;
}
dataset.push(aux);
}
var jsonChart = {
type: tipo,
data: {
labels: etiquetas,
datasets: dataset,
},
options:{
title:{
display:true,
text: titulo
},
animation: {
onComplete: function (animation) {
if(url_base64.length < limite)
url_base64.push(this.toBase64Image());
}
},
"scales": {
}
},
};
if (tipo == 'bar' || tipo == 'horizontalBar'){
jsonChart.options.scales = {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}],
"xAxes": [{
"ticks": {
"beginAtZero": true
}
}]
};
}
var ctx = document.getElementById(canvas).getContext('2d');
var myChart = new Chart(ctx, jsonChart);
return myChart;
}
function peticionGraficas(ruta) {
$.ajax({
url: ruta,
type: 'GET',
dataType: 'json',
success: function (r) {
$('#graficas').removeClass('hidden');
crearGrafica('pie_completado', 'pie', 'Grado de completitud', ['Completado', 'Faltante'], ['adasd'], r.dataPie);
crearGrafica('fechas_cantidad', 'line', 'Cantidad de archivos subidos por fecha',
r.labels_fecha, ['cantidad'], r.data_fechas);
ChartFiltro = crearGrafica('documentos_indicador', 'bar', 'Documentos subidos por indicador', r.labels_indicador,
['Cantidad'], r.data_indicador
);
},
error: function () {
alert('Ocurrio un error en el servidor ...');
}
});
}
function peticionGraficasDocumentales(ruta) {
$.ajax({
url: ruta,
type: 'GET',
dataType: 'json',
success: function (r) {
$('.progress-bar').css('width', r.completado + '%').attr('aria-valuenow', r.completado);
$('#graficas').removeClass('hidden');
$('.progress-bar').text(r.completado + '% completado')
crearGrafica('pie_completado', 'pie', 'Grado de completitud', ['Completado', 'Faltante'], ['adasd'], r.dataPie);
crearGrafica('fechas_cantidad', 'line', 'Cantidad de archivos subidos por fecha',
r.labels_fecha, ['cantidad'], r.data_fechas);
ChartFiltro = crearGrafica('documentos_indicador', 'bar', 'Documentos subidos por indicador', r.labels_indicador,
['Cantidad'], r.data_indicador
);
},
error: function () {
alert('Ocurrio un error en el servidor ...');
}
});
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Sede extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'nombre', 'descripcion'
];
public function users()
{
return $this->belongsToMany(User::class, 'sedes_usuarios', 'fk_sede', 'fk_usuario');
}
}
<file_sep>function mostrarSedes(ruta) {
var form = $('#form_mostrar_proceso');
$('#sedes_usuario').find('option').remove();
$.ajax({
url: ruta,
type: 'GET',
dataType: 'json',
success: function (r) {
console.log(r);
$.each(r, function (key, data) { // indice, valor
$("#sedes_usuario").append('<option value="' + key + '">' + data + '</option>');
})
$('#modal_mostrar_sedes').modal('toggle');
},
error: function () {
alert('Ocurrio un error en el servidor ..');
}
});
}
function fecha(nombre) {
$(nombre).daterangepicker({
"locale": {
"format": "DD/MM/YYYY",
"separator": " - ",
"applyLabel": "Aplicar",
"cancelLabel": "Cancelar",
"fromLabel": "De",
"toLabel": "A",
"customRangeLabel": "Custom",
"weekLabel": "S",
"daysOfWeek": [
"Do",
"Lu",
"Ma",
"Mi",
"ju",
"Vi",
"Sa"
],
"monthNames": [
"Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre"
],
"firstDay": 1
},
singleDatePicker: true,
showDropdowns: true,
maxDate: moment(),
"drops": "down"
});
}<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contacto extends Model
{
/**
* Tabla asociada con el modelo.
*
* @var string
*/
protected $table = 'contactos';
/**
* LLave primaria del modelo.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Atributos del modelo que no pueden ser asignados en masa.
*
* @var array
*/
protected $guarded = ['id', 'created_at', 'updated_at'];
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Estado extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'nombre', 'valor'
];
/**
* Tabla asociada con el modelo.
*
* @var string
*/
protected $table = 'estados';
/**
* LLave primaria del modelo.
*
* @var string
*/
protected $primaryKey = 'id';
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class TareasHistorialTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tareas_historial', function (Blueprint $table) {
$table->increments('id');
$table->string('nombre_tarea');
$table->string('protocolo');
$table->unsignedInteger('fk_users');
$table->timestamps();
$table->foreign('fk_users')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tareas_historial');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\DatosHistorico;
use Illuminate\Support\Facades\Session;
class GraficaController extends Controller
{
public function index()
{
$fechaInicio = Carbon::now();
$tipo = collect([
['nombre' => 'Temperatura ambiente'],
['nombre' => 'Temperatura agua'],
['nombre' => 'PH'],
['nombre' => 'Conductividad'],
['nombre' => 'Turbiedad'],
['nombre' => 'Calidad del aire'],
['nombre' => 'Propano'],
['nombre' => 'Monoxido de carbono'],
['nombre' => 'Flujo del agua'],
['nombre' => 'Luminosidad'],
['nombre' => 'Flujo lluvia'],
['nombre' => 'Flujo tanque'],
['nombre' => 'Voltaje']
]);
$tipos = $tipo->pluck('nombre', 'nombre');
return view('lestoma.Graficas.index', compact('fechaInicio', 'tipos'));
}
public function obtenerDatos(Request $request)
{
$fechaInicio = Carbon::createFromFormat('d/m/Y', $request->get('fecha_inicio'));
$fechaFin = Carbon::createFromFormat('d/m/Y', $request->get('fecha_fin'));
$datos = DatosHistorico::whereDate('created_at', '>=', $fechaInicio)
->whereDate('created_at', '<=', $fechaFin)
->where('fk_sede', '=', session()->get('id_sede'))
->get();
$data_grafica = [];
$fechas = [];
foreach ($datos as $key => $data) {
$array = json_decode($data->atributos, true);
if(isset($array[$request->get('tipo')])){
array_push($data_grafica, $array[$request->get('tipo')]);
array_push($fechas, (string)$data->created_at);
}
}
$datos = [];
$datos['data'] = array($data_grafica);
$datos['fechas'] = $fechas;
$datos['tipo'] = $request->get('tipo');
return json_encode($datos);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Sede;
use DataTables;
use Illuminate\Support\Facades\Auth;
class SedeController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
/**
* Permisos asignados en el constructor del controller para poder controlar las diferentes
* acciones posibles en la aplicación como los son:
* Acceder, ver, crea, modificar, eliminar
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('lestoma.Sedes.index');
}
/**
* Process datatables ajax request.
*
* @return \Illuminate\Http\JsonResponse
*/
/**
* Esta funcion muestra en el datatable todos los usuarios
* depende de si eres administrador
*/
public function data(Request $request)
{
if ($request->ajax() && $request->isMethod('GET')) {
$sedes = Sede::all();
return DataTables::of($sedes)
->removeColumn('created_at')
->removeColumn('updated_at')
->make(true);
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
/**
* Cuando se crea un usuario se debe saber de que programa va a ser
* y que rol va a tener
* depende si es administrador
*/
public function create()
{
return view('lestoma.Sedes.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion crea los usuarios
*/
public function store(Request $request)
{
$sede = new Sede();
$sede->nombre = $request->get('nombre');
$sede->descripcion = $request->get('descripcion');
$sede->save();
return response([
'msg' => 'Sede registrada correctamente.',
'title' => '¡Registro exitoso!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion muestra en el datatable todos los usuarios
* depende de si eres administrador
*/
/**
* Cuando se edita un usuario se debe saber de que programa va a ser
* y que rol va a tener
* depende si es administrador
*/
public function edit($id)
{
$sede = Sede::findOrFail($id);
return view(
'lestoma.Sedes.edit',
compact('sede')
);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion edita los usuarios
*/
public function update(Request $request, $id)
{
$sede = Sede::find($id);
$sede->nombre = $request->get('nombre');
$sede->descripcion = $request->get('descripcion');
$sede->update();
return response([
'msg' => 'La sede se ha sido modificado exitosamente.',
'title' => 'Sede Modificada!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion elimina
*/
public function destroy($id)
{
Sede::destroy($id);
return response([
'msg' => 'La sede se ha sido eliminado exitosamente.',
'title' => 'Sede Eliminada!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
public function sedesUsuario()
{
$procesos_usuario = Auth::user()->sedes()->get()->pluck('nombre', 'id');
return json_encode($procesos_usuario);
}
public function seleccionarSede(Request $request)
{
$sede = new Sede();
$sede = $sede->findOrFail($request->get('sede'))->nombre;
session(['sede' => $sede]);
session(['id_sede' => $request->get('sede')]);
return redirect()->back();
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'Publica\HomeController@index')->name('home');
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login')->name('login.in');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
Route::get('/home', 'HomeController@index')->name('admin.home');
Route::get('admin/datos_historicos/guardar', array(
'as' => 'admin.datos_historicos.guardar',
'uses' => 'DatosHistoricoController@guardarDatos'
));
Route::resource('admin/contactenos', 'ContactoController', ['as' => 'admin'])->except([
'show'
]);
Route::get('admin/contactenos/data', array('as' => 'admin.contactenos.data', 'uses' => 'ContactoController@data'));
Route::middleware(['auth'])->group(function () {
//Usuarios
Route::resource('admin/usuarios', 'UserController', ['as' => 'admin'])->except([
'show'
]);
Route::get('admin/usuarios/data', array('as' => 'admin.usuarios.data', 'uses' => 'UserController@data'));
Route::get('admin/usuario/perfil', array('as' => 'admin.usuario.perfil', 'uses' => 'UserController@perfil'));
Route::post('admin/usuario/perfil', array(
'as' => 'admin.usuario.modificar_perfil',
'uses' => 'UserController@modificarPerfil'
));
//Protocolos
Route::resource('admin/protocolos', 'ProtocoloController', ['as' => 'admin'])->except([
'show'
]);
Route::get('admin/protocolos/data', array('as' => 'admin.protocolos.data', 'uses' => 'ProtocoloController@data'));
//Sedes
Route::resource('admin/sedes', 'SedeController', ['as' => 'admin'])->except([
'show'
]);
Route::get('admin/sedes/data', array('as' => 'admin.sedes.data', 'uses' => 'SedeController@data'));
Route::get('admin/mostrar_sedes', array('as' => 'admin.sedes.mostrar', 'uses' => 'SedeController@sedesUsuario'));
Route::post('admin/seleccionar_sede', array(
'as' => 'admin.mostrar_sedes.seleccionar_sede',
'uses' => 'SedeController@seleccionarSede'
));
//Datos historicos
Route::get('admin/datos_historicos', array(
'as' => 'admin.datos_historicos.index',
'uses' => 'DatosHistoricoController@index'
));
Route::get('admin/datos_historicos/data', array(
'as' => 'admin.datos_historicos.data',
'uses' => 'DatosHistoricoController@data'
));
//Enviar protocolo
Route::get('admin/enviar_protocolo', array(
'as' => 'admin.enviar_protocolo.index',
'uses' => 'ControlProtocoloController@index'
));
Route::get('admin/enviar_protocolo/data', array(
'as' => 'admin.enviar_protocolo.data',
'uses' => 'ControlProtocoloController@data'
));
Route::post('admin/enviar_protocolo', array(
'as' => 'admin.enviar_protocolo.post',
'uses' => 'ControlProtocoloController@enviar_protocolo'
));
//Historial tareas terminadas
Route::get('admin/historial_tareas', array(
'as' => 'admin.tareas_historial.index',
'uses' => 'ControlProtocoloController@tareasTerminadas'
));
Route::get('admin/historial_tareas/data', array(
'as' => 'admin.tareas_historial.data',
'uses' => 'ControlProtocoloController@tareasTerminadasData'
));
//Graficas
Route::get('admin/graficas', array(
'as' => 'admin.graficas.index',
'uses' => 'GraficaController@index'
));
Route::post('admin/graficas/data', array(
'as' => 'admin.graficas.data',
'uses' => 'GraficaController@obtenerDatos'
));
});
Route::get('control/tareas_pendientes', 'ControlProtocoloController@enviar_tareas_pendientes');
Route::get('control/tarea_terminada/{id}', 'ControlProtocoloController@terminar_tarea');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\DatosHistorico;
use DataTables;
use Illuminate\Support\Facades\Session;
class DatosHistoricoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('lestoma.DatosHistoricos.index');
}
public function guardarDatos(Request $request)
{
$datos = [];
if($request->query('temperatura_ambiente')){
$datos['Temperatura ambiente'] = $request->query('temperatura_ambiente');
}
if ($request->query('temperatura_agua')) {
$datos['Temperatura agua'] = $request->query('temperatura_agua');
}
if ($request->query('ph')) {
$datos['PH'] = $request->query('ph');
}
if ($request->query('conductividad')) {
$datos['Conductividad'] = $request->query('conductividad');
}
if ($request->query('turbiedad')) {
$datos['Turbiedad'] = $request->query('turbiedad');
}
if ($request->query('calidad_aire')) {
$datos['Calidad del aire'] = $request->query('calidad_aire');
}
if ($request->query('propano')) {
$datos['Propano'] = $request->query('propano');
}
if ($request->query('monoxido_carbono')) {
$datos['Monoxido de carbono'] = $request->query('monoxido_carbono');
}
if ($request->query('flujo_agua')) {
$datos['Flujo del agua'] = $request->query('flujo_agua');
}
if ($request->query('luminosidad')) {
$datos['Luminosidad'] = $request->query('luminosidad');
}
if ($request->query('flujo_lluvia')) {
$datos['Flujo lluvia'] = $request->query('flujo_lluvia');
}
if ($request->query('flujo_tanque')) {
$datos['Flujo tanque'] = $request->query('flujo_tanque');
}
if ($request->query('voltaje')) {
$datos['Voltaje'] = $request->query('voltaje');
}
$id_sede = $request->query('sede');
$datos_historicos = new DatosHistorico();
$datos_historicos->fk_sede = $id_sede;
$datos_historicos->atributos = json_encode($datos);
$datos_historicos->save();
}
public function data(Request $request)
{
if ($request->ajax() && $request->isMethod('GET')) {
$datos_historicos = DatosHistorico::where('fk_sede', session('id_sede'));
return DataTables::of($datos_historicos)
->make(true);
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Protocolo;
use DataTables;
use App\Http\Requests\ProtocoloRequest;
class ProtocoloController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
/**
* Permisos asignados en el constructor del controller para poder controlar las diferentes
* acciones posibles en la aplicación como los son:
* Acceder, ver, crea, modificar, eliminar
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('lestoma.Protocolos.index');
}
/**
* Process datatables ajax request.
*
* @return \Illuminate\Http\JsonResponse
*/
/**
* Esta funcion muestra en el datatable todos los usuarios
* depende de si eres administrador
*/
public function data(Request $request)
{
if ($request->ajax() && $request->isMethod('GET')) {
$protocolos = Protocolo::all();
return DataTables::of($protocolos)
->removeColumn('created_at')
->removeColumn('updated_at')
->make(true);
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
/**
* Cuando se crea un usuario se debe saber de que programa va a ser
* y que rol va a tener
* depende si es administrador
*/
public function create()
{
return view('lestoma.Protocolos.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion crea los usuarios
*/
public function store(ProtocoloRequest $request)
{
$protocolo = new Protocolo();
$protocolo->nombre = $request->get('nombre');
$protocolo->protocolo = $request->get('protocolo');
$protocolo->descripcion = $request->get('descripcion');
$protocolo->save();
return response([
'msg' => 'Protocolo registrado correctamente.',
'title' => '¡Registro exitoso!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion muestra en el datatable todos los usuarios
* depende de si eres administrador
*/
/**
* Cuando se edita un usuario se debe saber de que programa va a ser
* y que rol va a tener
* depende si es administrador
*/
public function edit($id)
{
$protocolo = Protocolo::findOrFail($id);
return view(
'lestoma.Protocolos.edit',
compact('protocolo')
);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion edita los usuarios
*/
public function update(ProtocoloRequest $request, $id)
{
$protocolo = Protocolo::find($id);
$protocolo->nombre = $request->get('nombre');
$protocolo->protocolo = $request->get('protocolo');
$protocolo->descripcion = $request->get('descripcion');
$protocolo->update();
return response([
'msg' => 'El protocolo se ha sido modificado exitosamente.',
'title' => '¡Protocolo Modificado!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion elimina
*/
public function destroy($id)
{
Protocolo::destroy($id);
return response([
'msg' => 'El protocolo se ha sido eliminado exitosamente.',
'title' => '¡Protocolo Eliminado!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Estado;
class EstadosTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Estado::insert([
['nombre' => 'HABILITADO', 'valor' => '1'],
['nombre' => 'DESHABILITADO', 'valor' => '0']
]);
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class SedesUsuarios extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sedes_usuarios', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('fk_usuario');
$table->unsignedInteger('fk_sede');
$table->foreign('fk_usuario')->references('id')->on('users')->onDelete('cascade');
$table->foreign('fk_sede')->references('id')->on('sedes')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sedes_usuarios');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use DataTables;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\PerfilUsuarioRequest;
use Illuminate\Support\Facades\Gate;
use App\User;
use App\Estado;
use App\Sede;
class UserController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
/**
* Permisos asignados en el constructor del controller para poder controlar las diferentes
* acciones posibles en la aplicación como los son:
* Acceder, ver, crea, modificar, eliminar
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('lestoma.Users.index');
}
/**
* Process datatables ajax request.
*
* @return \Illuminate\Http\JsonResponse
*/
/**
* Esta funcion muestra en el datatable todos los usuarios
* depende de si eres administrador
*/
public function data(Request $request)
{
if ($request->ajax() && $request->isMethod('GET')) {
$users = User::where('id', '!=', Auth::id())->with('sedes');
return DataTables::of($users)
->addColumn('roles', function ($users) {
if (!$users->roles) {
return '';
}
return $users->roles->map(function ($rol) {
return "<span class='label label-sm label-info'>" . $rol->name . "</span>" ;
})->implode(', ');
})
->addColumn('sedes', function ($users) {
if (!$users->sedes) {
return '';
}
return $users->sedes->map(function ($sede) {
return "<span class='label label-sm label-info'>" . $sede->nombre . "</span>";
})->implode(', ');
})
->rawColumns(['sedes', 'roles'])
->removeColumn('cedula')
->removeColumn('created_at')
->removeColumn('updated_at')
->removeColumn('id_estado')
->make(true);
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
/**
* Cuando se crea un usuario se debe saber de que programa va a ser
* y que rol va a tener
* depende si es administrador
*/
public function create()
{
$roles = Role::pluck('name', 'name');
$estados = Estado::pluck('nombre', 'id');
$sedes = Sede::pluck('nombre', 'id');
return view('lestoma.Users.create', compact('estados', 'roles', 'sedes'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion crea los usuarios
*/
public function store(UserRequest $request)
{
$user = new User();
$user->name = $request->get('name');
$user->lastname = $request->get('lastname');
$user->email = $request->get('email');
$user->password = <PASSWORD>($request->get('<PASSWORD>'));
$user->id_estado = $request->get('id_estado');
$user->save();
$sedes = $request->input('sedes')? $request->input('sedes') : [];
$user->sedes()->sync($sedes);
$roles = $request->input('roles') ? $request->input('roles') : [];
$user->assignRole($roles);
return response([
'msg' => 'Usuario registrado correctamente.',
'title' => '¡Registro exitoso!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion muestra en el datatable todos los usuarios
* depende de si eres administrador
*/
/**
* Cuando se edita un usuario se debe saber de que programa va a ser
* y que rol va a tener
* depende si es administrador
*/
public function edit($id)
{
$estados = Estado::pluck('nombre', 'id');
$roles = Role::pluck('name', 'name');
$user = User::findOrFail($id);
$sedes = Sede::pluck('nombre', 'id');
$edit = true;
return view(
'lestoma.Users.edit',
compact('user', 'estados', 'roles', 'edit', 'sedes')
);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion edita los usuarios
*/
public function update(UserRequest $request, $id)
{
$user = User::find($id);
$user->fill($request->except('password'));
if ($request->get('password')) {
$user->password = $request->get('password');
}
$user->update();
$roles = $request->input('roles') ? $request->input('roles') : [];
$user->syncRoles($roles);
$sedes = $request->input('sedes') ? $request->input('sedes') : [];
$user->sedes()->sync($sedes);
return response([
'msg' => 'El usuario ha sido modificado exitosamente.',
'title' => '¡Usuario Modificado!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Esta funcion elimina los usuarios
*/
public function destroy($id)
{
User::destroy($id);
return response([
'msg' => 'El usuario se ha sido eliminado exitosamente.',
'title' => '¡Usuario Eliminado!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
public function perfil()
{
$sedes = Sede::pluck('nombre', 'id');
$roles = Role::pluck('name', 'name');
$user = User::findOrFail(Auth::id());
$edit = true;
return view(
'lestoma.Users.perfil',
compact('user', 'sedes', 'roles', 'edit')
);
}
public function modificarPerfil(Request $request)
{
$user = User::find(Auth::id());
$user->fill($request->except('password'));
if ($request->get('password')) {
$user->password = $<PASSWORD>');
}
if ($request->get('PK_ESD_Id')) {
$user->id_estado = $request->get('PK_ESD_Id') ? $request->get('PK_ESD_Id') : null;
}
$user->update();
if ($request->input('roles')) {
$roles = $request->input('roles') ? $request->input('roles') : [];
$user->syncRoles($roles);
}
$sedes = $request->input('sedes') ? $request->input('sedes') : [];
$user->sedes()->sync($sedes);
return response([
'msg' => 'El usuario se ha sido modificado exitosamente.',
'title' => '¡Usuario Modificado!'
], 200)// 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
}
|
497a680236187511f519123b33b97647523bc462
|
[
"JavaScript",
"PHP"
] | 18
|
PHP
|
ivancup/lestoma
|
b25ec1631f9090e6fdfc9b7d0fc640707ffbc9fe
|
e8185268511987ca75caaa454fd5c7ca3c6a0fc4
|
refs/heads/master
|
<file_sep>package com.tot.view;
/**
* Created by apple on 2016/4/2.
*/
public interface ClickTextListener {
public void onTextClick(String text, int postionX, int postionY);
}
<file_sep>package com.tot.transjam.adapter;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.tot.transjam.CatActivity;
import com.tot.transjam.R;
import com.tot.transjam.data.ArticleData;
import com.tot.transjam.data.CategoryData;
import com.tot.unit.UiTool;
import java.util.List;
import jp.wasabeef.recyclerview.animators.holder.AnimateViewHolder;
/**
* Created by apple on 2016/3/10.
*/
public class ArticleListAdapter extends RecyclerView.Adapter<ArticleListAdapter.ArticleViewHolder> {
Context context;
OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
public List<ArticleData> articleList;
public ArticleListAdapter(Context context) {
this.context = context;
}
public void setData(List<ArticleData> articleList) {
this.articleList = articleList;
}
public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
}
@Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(CatActivity.TAG, "onCreateViewHolder");
View itemLayoutView = LayoutInflater.from(context).inflate(R.layout.article_item, parent, false);
ArticleViewHolder viewHolder = new ArticleViewHolder(itemLayoutView);
return viewHolder;
}
@Override
public void onBindViewHolder(final ArticleViewHolder holder, final int position) {
final ArticleData articleData = articleList.get(position);
Log.d(CatActivity.TAG, "position=" + position);
holder.title.setText(articleData.title);
holder.newsDate.setText("2015/01/01 19:00");
holder.newsFront.setText("by <NAME> from TOT Studio.");
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(CatActivity.TAG, "position=" + position);
if (onRecyclerViewItemClickListener != null) {
onRecyclerViewItemClickListener.onItemClick(v, articleData);
}
}
});
holder.setPosition(position);
UiTool.imageLoad(context, holder.image,articleData.imageUrl);
UiTool.setRipple(holder.itemView);
// setAnimation(holder.catTitle, position);
}
/**
* Here is the key method to apply the animation
*/
private int lastPosition = -1;
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
@Override
public int getItemCount() {
return articleList.size();
}
public static class ArticleViewHolder extends AnimateViewHolder {
public View itemLayoutView;
public TextView newsDate;
public TextView newsFront;
public TextView title;
public ImageView image;
public LinearLayout itemView;
private int position;
public ArticleViewHolder(View itemLayoutView) {
super(itemLayoutView);
this.itemLayoutView = itemLayoutView;
newsDate = (TextView) itemLayoutView.findViewById(R.id.newsDate);
newsFront = (TextView) itemLayoutView.findViewById(R.id.newsFront);
title = (TextView) itemLayoutView.findViewById(R.id.title);
image = (ImageView) itemLayoutView.findViewById(R.id.image);
itemView = (LinearLayout) itemLayoutView.findViewById(R.id.itemView);
}
public void setPosition(int position) {
this.position = position;
}
@Override
public void animateAddImpl(ViewPropertyAnimatorListener listener) {
ViewCompat.animate(itemView)
.translationY(0)
.alpha(1)
.setDuration(300)
.setListener(listener)
.start();
}
@Override
public void animateRemoveImpl(ViewPropertyAnimatorListener listener) {
ViewCompat.animate(itemView)
.translationY(0)
.alpha(1)
.setDuration(300)
.setListener(listener)
.start();
}
}
}
<file_sep>package com.tot.transjam.data;
/**
* Created by apple on 2016/3/13.
*/
public class ArticleData extends BaseObject {
public String updated;
public String articleId;
public String imageUrl;
public String title;
}
<file_sep>package com.tot.transjam.data;
/**
* Created by apple on 2016/3/20.
*/
public class ArticleDetail extends BaseObject {
public String updated;
public String from;
public String title;
public String imageUrl;
public String article;
public String by;
}
<file_sep>package com.tot.transjam;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.nineoldandroids.view.ViewHelper;
import com.tot.base.BaseActivity;
import com.tot.transjam.data.ArticleData;
import com.tot.transjam.data.ArticleDetail;
import com.tot.transjam.view.Toolbar;
import com.tot.transjam.view.TransView;
import com.tot.unit.UiTool;
import com.tot.view.ClickTextListener;
import com.tot.view.ClickTextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.GsonConverterFactory;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* Created by apple on 2016/1/7.
*/
public class ContentActivity extends BaseActivity implements Callback,ObservableScrollViewCallbacks, View.OnClickListener,ClickTextListener {
public final static String TAG="ContentActivity";
ImageView image;
ObservableScrollView scrollable;
ArticleData articleData;
ArticleDetail articleDetail;
Toolbar toolbar;
ClickTextView title;
TextView newsDate;
TextView newsFrom;
ClickTextView article;
TransView transView;
public static final String BASE_URL = "https://bbsvacsho2.execute-api.ap-northeast-1.amazonaws.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
showLoadingBar();
articleData = (ArticleData)getIntent().getSerializableExtra("articleData");
scrollable=(ObservableScrollView)findViewById(R.id.scrollable);
scrollable.setScrollViewCallbacks(this);
toolbar= (Toolbar) findViewById(R.id.toolbar);
toolbar.setContentTitle();
toolbar.leftButton.setOnClickListener(this);
title = (ClickTextView)findViewById(R.id.title);
title.setClickTextListener(this);
newsDate = (TextView)findViewById(R.id.newsDate);
newsFrom = (TextView)findViewById(R.id.newsFrom);
article = (ClickTextView)findViewById(R.id.article);
article.setClickTextListener(this);
image = (ImageView)findViewById(R.id.image);
transView = (TransView)findViewById(R.id.transView);
}
@Override
protected void onStart() {
super.onStart();
getData();
}
private void getData(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
TransJamApiInterface transJamApiInterface = retrofit.create(TransJamApiInterface.class);
Call<ArticleDetail> call = transJamApiInterface.getarticledetail();
call.enqueue(this);
}
@Override
public void onResponse(Response response) {
Log.d(TAG, "onResponse");
if (response.body() instanceof ArticleDetail) {
articleDetail = (ArticleDetail) response.body();
Log.d(TAG, "title=" + articleDetail.title);
title.setClickText(articleDetail.title, Color.BLACK);
newsDate.setText(articleDetail.updated);
newsFrom.setText("from " + articleDetail.from + ", by " + articleDetail.by);
// article.setClickText(Html.fromHtml("<h2 style=\"color:black;\">" + articleDetail.title + "</h2>" +
// "<font color=\"#4c4c4c\">"+articleDetail.article+"</font>"));
article.setClickText(Html.fromHtml(articleDetail.article));
UiTool.imageLoad(this, image, articleDetail.imageUrl);
}
dismissLoadingBar();
}
@Override
public void onFailure(Throwable t) {
Log.d(TAG,"onFailure: "+t.getMessage());
dismissLoadingBar();
}
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
if(transView.getVisibility()==View.VISIBLE){
transView.setVisibility(View.GONE);
}
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
if (scrollState == ScrollState.UP) {
if (toolbarIsShown()) {
hideToolbar();
}
} else if (scrollState == ScrollState.DOWN) {
if (toolbarIsHidden()) {
showToolbar();
}
}
}
private boolean toolbarIsShown() {
return ViewHelper.getTranslationY(toolbar) == 0;
}
private boolean toolbarIsHidden() {
return ViewHelper.getTranslationY(toolbar) == -toolbar.getHeight();
}
private void showToolbar() {
moveToolbar(0);
}
private void hideToolbar() {
moveToolbar(-toolbar.getHeight());
}
private void moveToolbar(float toTranslationY) {
if (ViewHelper.getTranslationY(toolbar) == toTranslationY) {
return;
}
ValueAnimator animator = ValueAnimator.ofFloat(ViewHelper.getTranslationY(toolbar), toTranslationY).setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float translationY = (float) animation.getAnimatedValue();
ViewHelper.setTranslationY(toolbar, translationY);
ViewHelper.setTranslationY((View) scrollable, translationY);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) ((View) scrollable).getLayoutParams();
lp.height = (int) -translationY + getScreenHeight() - lp.topMargin;
((View) scrollable).requestLayout();
}
});
animator.start();
}
protected int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
@Override
public void onClick(View v) {
if(v==toolbar.leftButton){
onBackPressed();
}
}
@Override
public void onTextClick(String text, int postionX, int postionY) {
Log.d(TAG, "text: "+text);
Log.d(TAG, "postionX: "+postionX);
Log.d(TAG, "postionY: "+postionY);
transView.setVocabulary(text);
transView.setPosition(postionX, postionY);
transView.setVisibility(View.VISIBLE);
}
private void popGoogleTranslate(String word){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
String url=String.format("https://translate.google.com.tw/?hl=zh-TW#en/zh-TW/%s", word);
Log.d(TAG, "url=" + url);
WebView webView = new WebView(this);
webView.loadUrl("https://translate.google.com.tw/m/translate?hl=zh-TW#auto/zh-TW/"+word);
webView.getSettings().setJavaScriptEnabled(true);
WebViewClient webViewClient = new WebViewClient();
webView.setWebViewClient(webViewClient);
WebChromeClient webChromeClient=new WebChromeClient();
webView.setWebChromeClient(webChromeClient);
alert.setView(webView);
alert.show();
}
}
<file_sep>package com.tot.base;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.tot.transjam.R;
import fr.castorflex.android.circularprogressbar.CircularProgressDrawable;
/**
* Created by apple on 2016/1/2.
*/
public class BaseActivity extends AppCompatActivity {
ProgressBar progressBar;
RelativeLayout loadingLayout;
boolean isLoading=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// Window window = getWindow();
// // Translucent status bar
// window.setFlags(
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// // Translucent navigation bar
// window.setFlags(
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// }
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
public void showLoadingBar(){
isLoading=true;
if(loadingLayout==null){
loadingLayout=(RelativeLayout)findViewById(R.id.loadingLayout);
}
loadingLayout.setVisibility(View.VISIBLE);
if(progressBar==null){
progressBar = (ProgressBar)findViewById(R.id.progressbar);
progressBar.setIndeterminateDrawable(new CircularProgressDrawable
.Builder(this)
.colors(getResources().getIntArray(R.array.gplus_colors))
.sweepSpeed(1f).build());
}
}
public void dismissLoadingBar(){
loadingLayout.setVisibility(View.GONE);
isLoading=false;
}
@Override
public void onBackPressed() {
if(!isLoading){
super.onBackPressed();
}
}
}
<file_sep>package com.tot.transjam;
import com.tot.transjam.data.ArticleDetail;
import com.tot.transjam.data.ArticleListData;
import com.tot.transjam.data.StartData;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.GET;
/**
* Created by apple on 2016/1/28.
*/
public interface TransJamApiInterface {
@GET("prod/getstart")
Call<StartData> getstart();
@GET("prod/getarticle")
Call<ArticleListData> getarticle();
@GET("prod/getarticledetail")
Call<ArticleDetail> getarticledetail();
}
<file_sep>package com.tot.transjam.data;
import java.io.Serializable;
/**
* Created by apple on 2016/3/15.
*/
public class BaseObject implements Serializable {
}
<file_sep>package com.tot.view;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by apple on 2016/3/29.
*/
public class ClickTextView extends TextView {
private static final int MAX_CLICK_DURATION = 300;
private long startClickTime;
public ClickTextListener clickTextListener;
String TAG = "ClickTextView";
int positionX;
int positionY;
int fontColor = Color.parseColor("#4c4c4c");
private Context context;
public ClickTextView(Context context) {
super(context);
this.context = context;
init();
}
public ClickTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public ClickTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
public void setClickTextListener(ClickTextListener clickTextListener) {
this.clickTextListener = clickTextListener;
}
private void init() {
setMovementMethod(LinkMovementMethod.getInstance());
}
public void setClickText(CharSequence text, int color) {
this.fontColor = color;
setClickText(text);
}
public void setClickText(CharSequence text) {
setText(text, BufferType.SPANNABLE);
Spannable spans = (Spannable) getText();
Integer[] indices = getIndices(getText().toString(), ' ');
int start = 0;
int end = 0;
for (int i = 0; i <= indices.length; i++) {
ClickableSpan clickSpan = getClickableSpan();
// to cater last/only word
end = (i < indices.length ? indices[i] : spans.length());
spans.setSpan(clickSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = end + 1;
}
}
private ClickableSpan getClickableSpan() {
return new ClickableSpan() {
private Rect getPosition(TextView parentTextView) {
Rect parentTextViewRect = new Rect();
SpannableString completeText = (SpannableString) (parentTextView).getText();
Layout textViewLayout = parentTextView.getLayout();
double startOffsetOfClickedText = completeText.getSpanStart(this);
double endOffsetOfClickedText = completeText.getSpanEnd(this);
double startXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal((int) startOffsetOfClickedText);
double endXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal((int) endOffsetOfClickedText);
// Get the rectangle of the clicked text
int currentLineStartOffset = textViewLayout.getLineForOffset((int) startOffsetOfClickedText);
int currentLineEndOffset = textViewLayout.getLineForOffset((int) endOffsetOfClickedText);
boolean keywordIsInMultiLine = currentLineStartOffset != currentLineEndOffset;
textViewLayout.getLineBounds(currentLineStartOffset, parentTextViewRect);
// Update the rectangle position to his real position on screen
int[] parentTextViewLocation = {0, 0};
parentTextView.getLocationOnScreen(parentTextViewLocation);
double parentTextViewTopAndBottomOffset = (
parentTextViewLocation[1] -
parentTextView.getScrollY() +
parentTextView.getCompoundPaddingTop()
);
parentTextViewRect.top += parentTextViewTopAndBottomOffset;
parentTextViewRect.bottom += parentTextViewTopAndBottomOffset;
// In the case of multi line text, we have to choose what rectangle take
if (keywordIsInMultiLine) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int screenHeight = metrics.heightPixels;
int dyTop = parentTextViewRect.top;
int dyBottom = screenHeight - parentTextViewRect.bottom;
boolean onTop = dyTop > dyBottom;
if (onTop) {
endXCoordinatesOfClickedText = textViewLayout.getLineRight(currentLineStartOffset);
} else {
parentTextViewRect = new Rect();
textViewLayout.getLineBounds(currentLineEndOffset, parentTextViewRect);
parentTextViewRect.top += parentTextViewTopAndBottomOffset;
parentTextViewRect.bottom += parentTextViewTopAndBottomOffset;
startXCoordinatesOfClickedText = textViewLayout.getLineLeft(currentLineEndOffset);
}
}
parentTextViewRect.left += (
parentTextViewLocation[0] +
startXCoordinatesOfClickedText +
parentTextView.getCompoundPaddingLeft() -
parentTextView.getScrollX()
);
parentTextViewRect.right = (int) (
parentTextViewRect.left +
endXCoordinatesOfClickedText -
startXCoordinatesOfClickedText
);
Log.v("characters position", "this.parentTextViewRect.top="+parentTextViewRect.top);
Log.v("characters position", "this.parentTextViewRect.bottom="+parentTextViewRect.bottom);
Log.v("characters position", "this.parentTextViewRect.right="+parentTextViewRect.right);
Log.v("characters position", "this.parentTextViewRect.left="+parentTextViewRect.left);
return parentTextViewRect;
}
@Override
public void onClick(View widget) {
TextView tv = (TextView) widget;
String string = tv.getText().subSequence(tv.getSelectionStart(),
tv.getSelectionEnd()).toString();
SpannableString completeText = (SpannableString) ((TextView) widget).getText();
Log.v("characters position", completeText.getSpanStart(this) + " / " + completeText.getSpanEnd(this));
Rect rect = getPosition(tv);
if (clickTextListener != null) {
clickTextListener.onTextClick(string, rect.left+((rect.right-rect.left)/2), rect.top);
}
}
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(fontColor);
ds.setUnderlineText(false);
}
};
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
startClickTime = Calendar.getInstance().getTimeInMillis();
break;
}
case MotionEvent.ACTION_UP: {
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if (clickDuration < MAX_CLICK_DURATION) {
//click event has occurred
positionX = x;
positionY = y;
}
}
}
return super.onTouchEvent(event);
}
public static Integer[] getIndices(String s, char c) {
int pos = s.indexOf(c, 0);
List<Integer> indices = new ArrayList<Integer>();
while (pos != -1) {
indices.add(pos);
pos = s.indexOf(c, pos + 1);
}
return (Integer[]) indices.toArray(new Integer[0]);
}
}
<file_sep>package com.tot.unit;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import com.balysv.materialripple.MaterialRippleLayout;
import com.bumptech.glide.Glide;
/**
* Created by apple on 2016/3/13.
*/
public class UiTool {
public static void setRipple(View view){
MaterialRippleLayout.on(view)
.rippleOverlay(true)
.rippleAlpha(0.2f)
.rippleColor(0xFF585858)
.rippleHover(true)
.create();
}
/**
* load wiyh Glide
* @param context
* @param view
* @param url
*/
public static void imageLoad(Context context ,ImageView view, String url){
Glide.with(context)
.load(url)
.crossFade()
.into(view);
}
/**
* Covert dp to px
* @param dp
* @param context
* @return pixel
*/
public static float convertDpToPixel(float dp, Context context){
float px = dp * getDensity(context);
return px;
}
/**
* Covert px to dp
* @param px
* @param context
* @return dp
*/
public static float convertPixelToDp(float px, Context context){
float dp = px / getDensity(context);
return dp;
}
/**
* 取得螢幕密度
* 120dpi = 0.75
* 160dpi = 1 (default)
* 240dpi = 1.5
* @param context
* @return
*/
public static float getDensity(Context context){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return metrics.density;
}
}
<file_sep>package com.tot.transjam.data;
import java.util.List;
/**
* Created by apple on 2016/3/13.
*/
public class ArticleListData {
public List<ArticleData> articleList;
}
<file_sep>package com.tot.transjam.adapter;
import android.view.View;
/**
* Created by apple on 2016/3/13.
*/
public interface OnRecyclerViewItemClickListener {
void onItemClick(View view , Object data);
}
<file_sep>package com.tot.transjam.view;
import android.content.Context;
import android.media.Image;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.clans.fab.FloatingActionButton;
import com.tot.transjam.R;
/**
* Created by apple on 2016/1/9.
*/
public class Toolbar extends RelativeLayout {
Context context;
public FloatingActionButton leftButton;
public ImageView logo;
public TextView title;
public Toolbar(Context context) {
super(context);
init(context);
}
public Toolbar(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public Toolbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
this.context = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.layout_toolbar, this, true);
leftButton = (FloatingActionButton) findViewById(R.id.leftButton);
logo = (ImageView) findViewById(R.id.logo);
title = (TextView) findViewById(R.id.title);
}
public void setTitle(String text) {
logo.setVisibility(View.GONE);
title.setVisibility(View.VISIBLE);
title.setText(text);
}
public void setBlurryTitle() {
this.setBackgroundResource(R.drawable.bar_1);
}
public void setBack() {
leftButton.setImageResource(R.drawable.back);
}
public void setContentTitle() {
leftButton.setImageResource(R.drawable.back);
logo.setVisibility(View.GONE);
title.setVisibility(View.GONE);
}
}
<file_sep>package com.tot.transjam.adapter;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import com.balysv.materialripple.MaterialRippleLayout;
import com.tot.transjam.CatActivity;
import com.tot.transjam.R;
import com.tot.transjam.data.CategoryData;
import com.tot.unit.UiTool;
import java.util.List;
import jp.wasabeef.recyclerview.animators.holder.AnimateViewHolder;
/**
* Created by apple on 2016/3/10.
*/
public class CatAdapter extends RecyclerView.Adapter<CatAdapter.CatViewHolder> {
Context context;
OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
int color[] = {
Color.parseColor("#cbc6c0"),
Color.parseColor("#8d807a"),
Color.parseColor("#6f6c67"),
Color.parseColor("#9f968f"),
Color.parseColor("#967a6f"),
Color.parseColor("#a48b77")
};
public List<CategoryData> categoryList;
public CatAdapter(Context context) {
this.context = context;
}
public void setData(List<CategoryData> categoryList) {
Log.d(CatActivity.TAG, "setData");
this.categoryList = categoryList;
}
public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
}
@Override
public CatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(CatActivity.TAG, "onCreateViewHolder");
View itemLayoutView = LayoutInflater.from(context).inflate(R.layout.cat_item, parent,false);
CatViewHolder viewHolder = new CatViewHolder(itemLayoutView);
return viewHolder;
}
@Override
public void onBindViewHolder(final CatViewHolder holder, final int position) {
Log.d(CatActivity.TAG, "position=" + position);
Log.d(CatActivity.TAG, "categoryName=" + categoryList.get(position).categoryName);
Log.d(CatActivity.TAG, "color size=" + color.length);
UiTool.setRipple(holder.catTitle);
holder.catTitle.setText(categoryList.get(position).categoryName);
holder.catTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onRecyclerViewItemClickListener != null) {
onRecyclerViewItemClickListener.onItemClick(v, categoryList.get(position));
}
}
});
holder.setPosition(position);
if (position < color.length) {
holder.catTitle.setBackgroundColor(color[position]);
} else {
int p = position % color.length;
holder.catTitle.setBackgroundColor(color[p]);
}
setAnimation(holder.catTitle, position);
}
/**
* Here is the key method to apply the animation
*/
private int lastPosition = -1;
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
@Override
public int getItemCount() {
return categoryList.size();
}
public static class CatViewHolder extends AnimateViewHolder {
public TextView catTitle;
private int position;
// public MaterialRippleLayout ripple;
public CatViewHolder(View itemLayoutView) {
super(itemLayoutView);
catTitle = (TextView) itemLayoutView.findViewById(R.id.catTitle);
// ripple = (MaterialRippleLayout) itemLayoutView.findViewById(R.id.ripple);
}
public void setPosition(int position) {
this.position = position;
}
@Override
public void animateAddImpl(ViewPropertyAnimatorListener listener) {
ViewCompat.animate(itemView)
.translationY(0)
.alpha(1)
.setDuration(300)
.setListener(listener)
.start();
}
@Override
public void animateRemoveImpl(ViewPropertyAnimatorListener listener) {
ViewCompat.animate(itemView)
.translationY(0)
.alpha(1)
.setDuration(300)
.setListener(listener)
.start();
}
}
}
<file_sep>package com.tot.transjam.data;
import java.util.List;
/**
* Created by apple on 2016/1/28.
*/
public class StartData {
public List<CategoryData> categoryList;
public String apiUrl;
public String updateState;
}
|
746f77c02918cf2b60ec334510abf74235f9e888
|
[
"Java"
] | 15
|
Java
|
hahaelx/TransJam-Android
|
d74f040b90f754a91fadbb7e8ec04dcf1c28cf82
|
84fdba4e063d3b9c4e92c508be9f90511e94697c
|
refs/heads/main
|
<file_sep>#include <stdio.h>
//2020.12.27 22:13
//scanf("%d", &NumList[i]);
int main(void) {
int n = 0, m = 0;
int max = 0, sum = 0;
int NumList[100] = {0,};
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++)
scanf("%d", &NumList[i]);
for (int i = 0; i < n-2; i++) {
for (int j = i+1; j < n-1; j++) {
for (int k = j+1; k < n; k++) {
sum = NumList[i] + NumList[j] + NumList[k];
if (m >= sum && sum > max)
max = sum;
}
}
}
printf("%d\n", max);
return 0;
}
<file_sep>
# 백준 10872번 문제
---
### 문제 해결 날짜 및 시간
- 2020년 12월 27일 17시 48분
---
### 접근 방식
- 이러쿵 저러쿵
<file_sep>
# gukbbap

**갠지스호떡**과 **국밥**을 좋아하는 부산 사람들의 **알고리즘 저장소**입니다
팀원들은 `gukbbap`에 바로 `push` 하지말고 각자 `fork`하여 일일 커밋한 뒤, [gangeshotteok/gukbbap](https://github.com/GANGESHOTTEOK/gukbbap) 으로 당일 00:00 부터 23:59 전 까지 Pull request 할 것!
---
### 팀원
- 이준영 : rubinstory
- 홍유준 : kick-snare
- 박동한 : DonghanPark
- 안현주 : muzee99
---
### 푼 문제들
- 12월 28일 백준 [2798 블랙잭](https://www.acmicpc.net/problem/2798) **브루트포스**<file_sep>#include <iostream>
using namespace std;
int main(){
int N , M;
int C[100];
cin >> N >> M;
for(int i=0; i<N; i++) cin >> C[i];
int max = 0;
for(int i=0; i<N-2; i++){
for(int j=i+1; j<N-1; j++){
for(int k=j+1; k<N; k++){
if(M >= C[i]+C[j]+C[k] && max < C[i]+C[j]+C[k])
max = C[i]+C[j]+C[k];
}
}
}
cout << max;
return 0;
}<file_sep>
# 백준 10872번 문제
---
### 문제 해결 날짜 및 시간
- 2020년 12월 28일
---
### 접근 방식
N개의 카드 중에 3장을 뽑아서 조합을 보아야하기 때문에 3중 반복문을 돌려야한다. 처음보는 문제였다면 이 방법으로 풀지 않았을 것이지만 Brute Force 문제임을 알고 있었기에 3중 for 문을 돌렸다.
```c++
#include <iostream>
using namespace std;
int main(){
int N , M;
int C[100];
cin >> N >> M;
for(int i=0; i<N; i++) cin >> C[i];
int max = 0;
for(int i=0; i<N-2; i++){
for(int j=i+1; j<N-1; j++){
for(int k=j+1; k<N; k++){
if(M >= C[i]+C[j]+C[k] && max < C[i]+C[j]+C[k])
max = C[i]+C[j]+C[k];
}
}
}
cout << max;
return 0;
}
```
`j`는 `i+1` 부터, `k`는 `j+1`부터 시작하여 중복하여 카운트하는 경우가 없게 하였다.
`M`을 오버하지 않으면서, 기존의 `max`보다 클 경우 값을 대체한다. 마지막에는 `max`를 출력한다.
|
4341f166a796341847dc7b12940d2c7fed60a048
|
[
"Markdown",
"C",
"C++"
] | 5
|
C
|
Kick-snare/gukbbap
|
0f3ad0202da067ca045935657f3fba4c76aac5c7
|
7bcb99ab9815291c7bad87dc8f3e919382b98f97
|
refs/heads/master
|
<repo_name>sransara/microbe<file_sep>/submit.bash
#! /usr/bin/bash
make clean
make rsubmit
cd sabeysir
make
echo
echo "---- Testing 1 2 3----"
make test
echo "---- All checked ----"
echo
make clean
rm -rf test
cd ..
echo
echo "---- Submission is ready to land ----"
read -p "What's the project step #: " p
while true; do
read -p "turnin -c EE468 -p step$p -v sabeysir ? " yn
case $yn in
[Yy]* ) turnin -c EE468 -p step$p -v sabeysir; echo; exit;;
[Nn]* ) exit;;
* ) echo "Please answer (y)es or (n)o.";;
esac
done
<file_sep>/README.md
# Microbe
**A Micro lang compiler**
The one and only Micro lang compiler that you will need for compiling your precious Micro code in to almighty tiny assembly
Microbe can
- Handle complex expressions
- Build IR
- Build Control Flow Graph
- Do liveness analysis
- Do register allocation
- Produce assembly (tiny)
And also Microbe
- can be easily extended to produce other assembly with (2 or 3 operands)
- IR generation and Tiny Code generation across functions can possibly be parallelized to increase code generation speed
And did you know that microbe can [eat electricity](http://www.iflscience.com/chemistry/scientists-reveal-how-microbe-eats-electricity)?
See some sample micro code
```
#!micro
PROGRAM p
BEGIN
STRING prompt := "Give me a number to output bitstring in LSB to MSB: ";
STRING eol := "\n";
STRING one := "1";
STRING zero := "0";
FUNCTION VOID main()
BEGIN
INT a;
WRITE(prompt);
READ(a);
WHILE(a > 0)
IF(IsEven(a) = 1)
WRITE(zero);
ELSE
WRITE(one);
ENDIF
a := a / 2;
ENDWHILE
WRITE(eol);
END
-- mutually recursive functions
FUNCTION INT IsEven(INT a)
BEGIN
IF(a = 0)
RETURN 1;
ELSE
RETURN IsOdd(a - 1);
ENDIF
END
FUNCTION INT IsOdd(INT a)
BEGIN
IF(a = 0)
RETURN 0;
ELSE
RETURN IsEven(a - 1);
ENDIF
END
END
```
Follows the specification provided at https://engineering.purdue.edu/~milind/ece573/2014fall/project/
Check under test folder for sample Micro code or how to test Micro
```
#!bash
make
make test
```
---
Side notes (things to read before being alarmed)
- In spite of common standard to use ArrayList you will observe frequent use of LinkedList in IR Generation because of the frequent *adding* to lists instead of *iterating* through the list
- This program is neither a virus nor a bacterium
<file_sep>/src/AST/CallAstNode.java
package AST;
import IR.*;
import Nucleus.Operand;
import Nucleus.Symbol;
import SymbolScope.FunctionScopeNode;
import SymbolScope.ScopeNode;
import SymbolScope.SymbolScopeTree;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class CallAstNode extends AstNode{
public static enum OpType {
RET, CALL
}
OpType op;
String function;
LinkedList<AstNode> exprs;
AstNode returnExpr;
public CallAstNode(OpType op, String function, LinkedList<AstNode> exprs) {
this.op = op;
this.function = function;
this.exprs = exprs;
}
public CallAstNode(OpType op, AstNode returnExpr) {
this.op = op;
this.returnExpr = returnExpr;
}
@Override
public IrCode generateIrCode(ScopeNode scope) {
IrCode c = null;
switch (op) {
case RET: c = generateRetIrCode(scope); break;
case CALL: c = generateCallIrCode(scope); break;
}
return c;
}
private IrCode generateRetIrCode(ScopeNode scope) {
IrCode self = new IrCode();
FunctionScopeNode fscope = scope.getParentFunction();
IrCode r = returnExpr.generateIrCode(scope);
self.irNodeList.addAll(r.irNodeList);
Operand.DataType resultDataType = r.result.dataType;
String rref = "$R" + scope.getParentFunction().parameter_x;
Symbol dr = new Symbol(resultDataType, rref, null, Operand.OperandType.SYMBOL);
if(r.result.operandType == Operand.OperandType.TEMPORARY) {
if (resultDataType == Operand.DataType.INT) {
self.irNodeList.add(new MTypeIrNode(IrNode.Opcode.STOREI, fscope, r.result, dr));
} else if (resultDataType == Operand.DataType.FLOAT) {
self.irNodeList.add(new MTypeIrNode(IrNode.Opcode.STOREF, fscope, r.result, dr));
}
}
else {
if (resultDataType == Operand.DataType.INT) {
self.irNodeList.add(new MTypeIrNode(IrNode.Opcode.STOREI, fscope, r.result, scope.createTemp(resultDataType)));
self.irNodeList.add(new MTypeIrNode(IrNode.Opcode.STOREI, fscope, scope.getCurrentTemp(), dr));
} else if (resultDataType == Operand.DataType.FLOAT) {
self.irNodeList.add(new MTypeIrNode(IrNode.Opcode.STOREF, fscope, r.result, scope.createTemp(resultDataType)));
self.irNodeList.add(new MTypeIrNode(IrNode.Opcode.STOREF, fscope, scope.getCurrentTemp(), dr));
}
}
self.irNodeList.add(new STypeIrNode(IrNode.Opcode.RET, fscope, null));
return self;
}
private IrCode generateCallIrCode(ScopeNode scope) {
IrCode self = new IrCode();
FunctionScopeNode fscope = scope.getParentFunction();
// saved registers
// result
// arg n
// arg n-1
// arg 1
// ret address
// prev stack pointer <- bp
self.irNodeList.add(new STypeIrNode(IrNode.Opcode.PUSH, fscope, null));
List<Operand> tempResults = new LinkedList<Operand>();
Iterator<AstNode> iexprs = exprs.descendingIterator();
while (iexprs.hasNext()) {
// Build code right to left
AstNode n = iexprs.next();
IrCode nc = n.generateIrCode(scope);
self.irNodeList.addAll(nc.irNodeList);
tempResults.add(nc.result);
}
for(Operand t : tempResults) {
self.irNodeList.add(new STypeIrNode(IrNode.Opcode.PUSH, fscope, t));
}
self.irNodeList.add(new JTypeIrNode(IrNode.Opcode.JSR, fscope, function));
for(Operand t : tempResults) {
self.irNodeList.add(new STypeIrNode(IrNode.Opcode.POP, fscope, null));
}
FunctionScopeNode f = (FunctionScopeNode)SymbolScopeTree.GlobalScope.children.get(function);
Operand.DataType returnType = f.returnType;
if(returnType != Operand.DataType.VOID){
self.irNodeList.add(new STypeIrNode(IrNode.Opcode.POP, fscope, scope.createTemp(returnType)));
self.result = scope.getCurrentTemp();
}
else {
self.irNodeList.add(new STypeIrNode(IrNode.Opcode.POP, fscope, null));
self.result = null;
}
return self;
}
}
<file_sep>/src/SymbolScope/FunctionScopeNode.java
package SymbolScope;
import AST.AstNode;
import IR.IrCode;
import IR.IrNode;
import IR.LTypeIrNode;
import IR.STypeIrNode;
import Nucleus.Operand;
import Nucleus.Symbol;
import Nucleus.Temporary;
import java.util.*;
public class FunctionScopeNode extends ScopeNode {
public Operand.DataType returnType = null;
private Temporary currentTemp = null;
public int size;
public int local_x = 1;
public int parameter_x = 1;
public int temp_x = 1;
private IrCode functionHeader;
FunctionScopeNode(ScopeNode parent, Operand.DataType rt, String name) {
this.scopeType = SymbolScopeTree.ScopeType.FUNCTION;
this.parent = parent;
this.returnType = rt;
this.name = name;
}
public Temporary getCurrentTemp() {
return currentTemp;
}
public Temporary createTemp(Operand.DataType t) {
currentTemp = new Temporary(t, temp_x);
temp_x++;
return currentTemp;
}
@Override
public void addVariables(String type, List<String> ids) {
Operand.DataType t = Operand.DataType.valueOf(type);
for (String id : ids) {
addVariable(t, id, null);
}
}
public String addVariable(Operand.DataType t, String id, String value) {
String ref = String.format("$L%d", local_x);
addSymbol(t, id, ref, value, Operand.OperandType.SYMBOL);
local_x++;
return ref;
}
public String addParameter(String type, String id) {
String ref = String.format("$P%d", parameter_x);
Operand.DataType t = Operand.DataType.valueOf(type);
addSymbol(t, id, ref, null, Operand.OperandType.SYMBOL);
parameter_x += 1;
return ref;
}
@Override
public String addString(String id, String value) {
String ref = String.format("%s.%s", this.name, id);
Operand.DataType t = Operand.DataType.STRING;
addSymbol(t, id, ref, value, Operand.OperandType.SYMBOL);
// add it to the global scope to put it in data segment
ScopeNode g = this;
while(g.parent != null) {
g = g.parent;
}
// reference and reference are the same for global variables
g.addString(ref, value);
return ref;
}
@Override
public FunctionScopeNode getParentFunction() {
return this;
}
private void generateFunctionHeader() {
functionHeader = new IrCode();
IrNode label = new LTypeIrNode(IrNode.Opcode.LABEL, this, name);
IrNode link = new STypeIrNode(IrNode.Opcode.LINK, this, null);
label.starter = true;
label.ender = true;
label.nexts.add(link);
link.prevs.add(label);
functionHeader.irNodeList.add(label);
functionHeader.irNodeList.add(link);
}
@Override
public void generateIrCode() {
generateFunctionHeader();
irCode = new IrCode();
for(AstNode n : statements) {
irCode.irNodeList.addAll(n.generateIrCode(this).irNodeList);
}
if(returnType == Operand.DataType.VOID){
irCode.irNodeList.add(new STypeIrNode(IrNode.Opcode.RET, this, null));
}
buildControlFlowGraph();
// do liveness analysis
Queue<IrNode> workingList = new ArrayDeque<IrNode>();
for(IrNode n : irCode.irNodeList) {
if(n.isJsr()) {
for(Symbol s : parent.symbolTable.values()) {
if(s.dataType != Operand.DataType.STRING) {
n.gen.add(s);
}
}
}
else if(n.isReturn()) {
for(Symbol s : parent.symbolTable.values()) {
if(s.dataType != Operand.DataType.STRING) {
n.liveOut.add(s);
}
}
}
workingList.add(n);
}
while(!workingList.isEmpty()) {
IrNode e = workingList.remove();
for (IrNode n : e.nexts) {
e.liveOut.addAll(n.liveIn);
}
Set<Operand> tLiveIn = new HashSet<Operand>();
tLiveIn.addAll(e.liveOut);
tLiveIn.removeAll(e.kill);
tLiveIn.addAll(e.gen);
if (!tLiveIn.equals(e.liveIn)) {
e.liveIn = tLiveIn;
for (IrNode prev : e.prevs) {
workingList.add(prev);
}
}
}
// end liveness analysis
}
@Override
public void printIrCode() {
functionHeader.printIrCode();
irCode.printIrCode();
}
@Override
public void printTinyCode() {
irCode.printTinyCode(functionHeader);
}
}
<file_sep>/src/SymbolScope/SymbolScopeTree.java
package SymbolScope;
import Nucleus.Operand;
public class SymbolScopeTree {
static enum ScopeType {
GLOBAL, BLOCK, FUNCTION
}
public static ScopeNode GlobalScope;
public ScopeNode currentScope;
private int block_x = 1;
public SymbolScopeTree() {
currentScope = new GlobalScopeNode(ScopeType.GLOBAL);
GlobalScope = currentScope;
}
public void exitScope() {
currentScope = currentScope.parent;
}
public void enterScope(String rt, String name) {
Operand.DataType returnType = Operand.DataType.valueOf(rt);
ScopeNode ns = new FunctionScopeNode(currentScope, returnType, name);
currentScope.children.put(name, ns);
currentScope = ns;
}
public void enterScope() {
String name = "BLOCK_" + block_x;
block_x++;
ScopeNode ns = new BlockScopeNode(currentScope, name);
currentScope.children.put(name, ns);
currentScope = ns;
}
}
<file_sep>/src/SymbolScope/BlockScopeNode.java
package SymbolScope;
import AST.AstNode;
import IR.IrCode;
import IR.IrNode;
import IR.LTypeIrNode;
import Nucleus.Operand;
import Nucleus.Temporary;
import java.util.List;
public class BlockScopeNode extends ScopeNode {
BlockScopeNode(ScopeNode parent, String name) {
this.scopeType = SymbolScopeTree.ScopeType.BLOCK;
this.parent = parent;
this.name = name;
}
@Override
public Temporary getCurrentTemp() {
ScopeNode f = parent;
while(f.scopeType != SymbolScopeTree.ScopeType.FUNCTION) {
f = f.parent;
}
return f.getCurrentTemp();
}
@Override
public Temporary createTemp(Operand.DataType t) {
ScopeNode f = parent;
while(f.scopeType != SymbolScopeTree.ScopeType.FUNCTION) {
f = f.parent;
}
return f.createTemp(t);
}
@Override
public void addVariables(String type, List<String> ids) {
Operand.DataType t = Operand.DataType.valueOf(type);
ScopeNode f = parent;
while(f.scopeType != SymbolScopeTree.ScopeType.FUNCTION) {
f = f.parent;
}
for (String id : ids) {
String idf = String.format("%s.%s", this.name, id);
String ref = ((FunctionScopeNode)f).addVariable(t, idf, null);
addSymbol(t, id, ref, null, Operand.OperandType.SYMBOL);
}
}
@Override
public String addString(String id, String value) {
String ref = String.format("%s.%s", this.name, id);
Operand.DataType t = Operand.DataType.STRING;
// reference and reference are the same for global variables
addSymbol(t, id, ref, value, Operand.OperandType.SYMBOL);
// add it to the global scope to put it in data segment
ScopeNode g = this;
while(g.parent != null) {
g = g.parent;
}
// reference and reference are the same for global variables
((GlobalScopeNode)g).addString(ref, value);
return ref;
}
public FunctionScopeNode getParentFunction() {
ScopeNode f = this;
if(f.parent == null) {
return null;
}
while(f.scopeType != SymbolScopeTree.ScopeType.FUNCTION) {
f = f.parent;
}
return (FunctionScopeNode)f;
}
public void generateIrCode() {
irCode = new IrCode();
irCode.irNodeList.add(new LTypeIrNode(IrNode.Opcode.LABEL, getParentFunction(),name));
for(AstNode n : statements) {
irCode.irNodeList.addAll(n.generateIrCode(this).irNodeList);
}
}
@Override
public void printIrCode() {
irCode.printIrCode();
}
@Override
public void printTinyCode() {
irCode.printTinyCode();
}
}<file_sep>/src/IR/CTypeIrNode.java
package IR;
import Nucleus.Operand;
import SymbolScope.FunctionScopeNode;
import static Nucleus.Operand.DataType.FLOAT;
import static Nucleus.Operand.DataType.INT;
public class CTypeIrNode extends IrNode{
// Conditionals
Operand op1;
Operand op2;
public CTypeIrNode(Opcode opcode, FunctionScopeNode scope, Operand op1, Operand op2, String label) {
super(opcode, scope);
this.op1 = op1;
this.op2 = op2;
this.label = label;
initGen(op1, op2);
}
@Override
public String toString() {
return "; " + opcode.name() + " " + op1.reference + " " + op2.reference + " " + label;
}
@Override
public String toTiny() {
if (!isStarter()) {
registers = prevs.get(0).registers;
}
String rop1 = ensureRegister(op1, op2);
String rop2 = ensureRegister(op2, op1);
dropDeadRegisters(rop1, rop2);
String op1Ref = rop1 == null ? op1.reference : rop1;
String op2Ref = rop1 == null ? op2.reference : rop2;
if (isEnder()) {
restoreRegisteredVariables();
}
if (op1.dataType == INT) {
tinyCode.append("cmpi " + op1Ref + " " + op2Ref);
} else if (op1.dataType == FLOAT) {
tinyCode.append("cmpr " + op1Ref + " " + op2Ref);
}
tinyCode.append("\n");
switch (opcode) {
case GT:
tinyCode.append("jgt ");
break;
case LT:
tinyCode.append("jlt ");
break;
case GE:
tinyCode.append("jge ");
break;
case LE:
tinyCode.append("jle ");
break;
case NE:
tinyCode.append("jne ");
break;
case EQ:
tinyCode.append("jeq ");
break;
}
tinyCode.append(label + "\n");
return tinyCode.toString();
}
}
<file_sep>/Makefile
LIB_ANTLR := lib/antlr.jar
ANTLR_SCRIPT := Microbe
PATH_SEP := :
all: parser compiler
parser:
java -cp $(LIB_ANTLR) org.antlr.v4.Tool -o src $(ANTLR_SCRIPT).g4
compiler:
rm -rf classes
mkdir classes
javac -d classes src/SymbolScope/*.java src/AST/*.java src/IR/*.java src/Nucleus/*.java
javac -cp $(LIB_ANTLR)$(PATH_SEP)classes$(PATH_SEP) -d classes src/*.java
test:
touch 'test/temp.myout'
touch 'test/temp.out'
rm -f test/*.myout
rm -f test/*.out
python test/testall.py
rsubmit:
make clean
mkdir sabeysir
cp tosubmit_makefile sabeysir/Makefile
cp $(ANTLR_SCRIPT).g4 sabeysir/
cp -r src sabeysir/
cp -r lib sabeysir/
cp -r test sabeysir/
@echo "Folder sabeysir is ready to be submitted"
submit:
@sh submit.bash
clean:
touch 'test/temp.myout'
touch 'test/temp.out'
touch 'test/temp.m.out'
touch 'test/temp.t.out'
rm -f test/*.myout
rm -f test/*.out
rm -rf classes sabeysir
touch 'src/Microbe.temp'
rm -f src/Microbe*
.PHONY: all parser compiler clean test rsubmit submit
<file_sep>/src/AST/SystemOpAstNode.java
package AST;
import IR.ITypeIrNode;
import IR.IrCode;
import IR.IrNode;
import Nucleus.Operand;
import Nucleus.Symbol;
import SymbolScope.FunctionScopeNode;
import SymbolScope.ScopeNode;
import java.util.List;
public class SystemOpAstNode extends AstNode {
public static enum OpType {
READ, WRITE
}
OpType op;
List<String> ids;
public SystemOpAstNode(OpType op, List<String> ids) {
this.op = op;
this.ids = ids;
}
@Override
public IrCode generateIrCode(ScopeNode scope) {
IrCode c = new IrCode();
FunctionScopeNode fscope = scope.getParentFunction();
if(op == OpType.READ) {
for(String id : ids) {
Symbol symbol = scope.findSymbol(id);
if(symbol.dataType == Operand.DataType.INT) {
c.irNodeList.add(new ITypeIrNode(IrNode.Opcode.READI, fscope, symbol));
}
else if (symbol.dataType == Operand.DataType.FLOAT){
c.irNodeList.add(new ITypeIrNode(IrNode.Opcode.READF, fscope, symbol));
}
else if (symbol.dataType == Operand.DataType.STRING){
c.irNodeList.add(new ITypeIrNode(IrNode.Opcode.READS, fscope, symbol));
}
}
}
else if(op == OpType.WRITE){
for(String id : ids) {
Symbol symbol = scope.findSymbol(id);
if(symbol.dataType == Operand.DataType.INT) {
c.irNodeList.add(new ITypeIrNode(IrNode.Opcode.WRITEI, fscope, symbol));
}
else if (symbol.dataType == Operand.DataType.FLOAT){
c.irNodeList.add(new ITypeIrNode(IrNode.Opcode.WRITEF, fscope, symbol));
}
else if (symbol.dataType == Operand.DataType.STRING){
c.irNodeList.add(new ITypeIrNode(IrNode.Opcode.WRITES, fscope, symbol));
}
}
}
return c;
}
}<file_sep>/src/IR/IrNode.java
package IR;
import Nucleus.Operand;
import Nucleus.Register;
import SymbolScope.FunctionScopeNode;
import SymbolScope.ScopeNode;
import java.lang.reflect.Array;
import java.util.*;
public abstract class IrNode {
public static enum Opcode {
ADDI, SUBI, MULTI, DIVI,
ADDF, SUBF, MULTF, DIVF,
STOREI, STOREF,
GT, GE, LT, LE, NE, EQ,
JUMP,
LABEL,
READI, READF, READS, WRITEI, WRITEF, WRITES,
JSR, PUSH, POP, RET, LINK,
HALT, UNKNWN
}
public Opcode opcode;
public FunctionScopeNode functionScope;
// specifically used to build Flow Graph
public List<IrNode> nexts = new ArrayList<IrNode>();
public List<IrNode> prevs = new ArrayList<IrNode>();
public boolean starter = false;
public boolean ender = false;
public boolean isStarter() {
if(starter) {
tinyCode.append("; DBG STARTING BB\n");
}
tinyCode.append("; -- " + this + "\n; DBG liveout "+ Arrays.toString(liveOut.toArray()) + "\n");
return starter;
}
public boolean isEnder() {
tinyCode.append("; DBG END REGISTERS " + Arrays.toString(registers.toArray()) + "\n");
if(ender) {
tinyCode.append("; DBG ENDING BB\n");
}
return ender;
}
public boolean isJsr() {
return opcode == Opcode.JSR;
}
public boolean isJmp() {
return opcode == Opcode.JUMP;
}
public boolean isReturn() {
return opcode == Opcode.RET;
}
public boolean isLabel() {
return opcode == Opcode.LABEL;
}
public boolean usesLabel() {
return opcode == Opcode.JUMP
// || opcode == Opcode.JSR : Function calls should be treated as straight-line IR nodes
|| opcode == Opcode.GT
|| opcode == Opcode.GE
|| opcode == Opcode.LT
|| opcode == Opcode.LE
|| opcode == Opcode.NE
|| opcode == Opcode.EQ;
}
public String label = null;
// end used to build control flow graph
// used in liveness analysis
// Needs linked hash set data structure for optimizing register kickout
// as order is retained through liveness analysis
public Set<Operand> gen = new LinkedHashSet<Operand>();
public Set<Operand> kill = new LinkedHashSet<Operand>();
public Set<Operand> liveIn = new LinkedHashSet<Operand>();
public Set<Operand> liveOut = new LinkedHashSet<Operand>();
protected void initGen(Operand...operands) {
for(Operand o : operands) {
if(o != null && o.isRegisterable()) {
gen.add(o);
}
}
}
protected void initKill(Operand...operands) {
for(Operand o : operands) {
if(o != null && o.isRegisterable()) {
kill.add(o);
}
}
}
// end used in liveness analysis
public IrNode(Opcode opcode, FunctionScopeNode scope) {
this.opcode = opcode;
this.functionScope = scope;
}
public abstract String toString();
// Everything next is used for tiny generation
// registers
public List<Register> registers = Arrays.asList(new Register[Register.REG_N]);
// tiny code
protected StringBuilder tinyCode = new StringBuilder();
public abstract String toTiny();
protected String operandToTiny(Operand operand) {
String c = operand.reference;
if(c.startsWith("$P")) {
int p_offset = Integer.parseInt(c.replace("$P", "")) + Register.REG_N + 1; // offset by 1 for return address
c = "$" + p_offset;
}
else if(c.startsWith("$R")) {
int r_offset = Integer.parseInt(c.replace("$R", "")) + Register.REG_N + 1; // offset by 1 for return address
c = "$" + r_offset;
}
else if(c.startsWith("$L")) {
int l_offset = Integer.parseInt(c.replace("$L", ""));
c = "$-" + l_offset;
}
return c;
}
protected String ensureRegister(Operand operand, Operand...others) {
// Others is the list of operands that might be used with this operand
if(operand == null || !operand.isRegisterable()) {
return null;
}
int r = registers.indexOf(new Register(operand));
if(r > -1) {
tinyCode.append("; DBG ENSURE "+ operand.reference +" -> "+ Register.getReference(r) +"\n");
return Register.getReference(r);
}
else {
String newr = allocateRegister(operand, others);
tinyCode.append("; DBG ALLOC ENSURE "+ operand.reference + " -> "+ newr +"\n");
tinyCode.append("move " + operandToTiny(operand) + " " + newr + "\n");
return newr;
}
}
protected String allocateRegister(Operand operand, Operand...others) {
int ri = 0;
int nullri = registers.indexOf(null);
int opri = registers.indexOf(new Register(operand));
String regRef = null;
if(opri > -1) {
ri = opri;
regRef = Register.getReference(ri);
}
else if(nullri > -1) {
ri = nullri;
regRef = Register.getReference(ri);
}
else {
// the lower indexed liveOut elements are more likely to be used recently
Operand[] liveOut_a = liveOut.toArray(new Operand[liveOut.size()]);
int max_j = -1;
int max_j_i = -1;
for(int i = 0; i < Register.REG_N; i++) {
Register r = registers.get(i);
if(Arrays.asList(others).contains(r.operand)) {
continue; // others.length must be less than REG_N
}
if(!liveOut.contains(r.operand)) {
max_j_i = i;
break;
}
for(int j = 0; j < liveOut_a.length; j++) {
// as we didn't hit the `break` one of these must be true
if (r.operand.equals(liveOut_a[j])) {
if(max_j < j) {
max_j = j;
max_j_i = i;
}
}
}
}
ri = max_j_i;
regRef = Register.getReference(max_j_i);
tinyCode.append("; DBG KICK OUT " + registers.get(ri).operand + " @ " + regRef);
tinyCode.append(" others:" + Arrays.toString(others) + "\n");
freeRegister(regRef);
}
tinyCode.append("; DBG ALLOCATE "+ operand.reference +" -> "+ regRef +"\n");
registers.set(ri, new Register(operand));
return regRef;
}
protected void freeRegister(String regRef) {
int ri = Register.getDereference(regRef);
Register r = registers.get(ri);
if(r.isDirty && liveOut.contains(r.operand)) {
if(r.operand.operandType == Operand.OperandType.TEMPORARY) {
String ref = String.format("$L%d", functionScope.local_x);
tinyCode.append("; DBG SPILLING TEMP " + r.operand + " " + ref + "\n");
r.operand.reference = ref;
r.operand.operandType = Operand.OperandType.SPILLED_TEMPORARY;
functionScope.local_x++;
}
tinyCode.append("move " + regRef + " " + operandToTiny(r.operand) + " ; DBG FREE STORE \n");
}
else {
tinyCode.append("; DBG DROP "+ r.operand.reference +" @ "+ regRef +"\n");
}
registers.set(ri, null);
}
// Set dirty bit
protected void dirtRegister(String regRef) {
Register r = registers.get(Register.getDereference(regRef));
r.isDirty = true;
}
// Not live anymore
protected void dropDeadRegisters(String... regRefs) {
for(String regRef : regRefs) {
if(regRef == null) { continue; }
Register r = registers.get(Register.getDereference(regRef));
if(r != null && !liveOut.contains(r.operand)) {
freeRegister(regRef);
}
}
}
protected void restoreRegisteredVariables() {
for(int i = 0; i < Register.REG_N; i++) {
String regRef = Register.getReference(i);
Register r = registers.get(i);
if (r != null && r.operand != null) {
freeRegister(regRef);
}
}
}
protected void restoreRegisteredGlobalVariables() {
for(int i = 0; i < Register.REG_N; i++) {
String regRef = Register.getReference(i);
Register r = registers.get(i);
if(r == null || r.operand == null) { continue; }
else if (r.operand.operandType == Operand.OperandType.GLOBAL_SYMBOL && r.isDirty) {
tinyCode.append("move " + regRef + " " + operandToTiny(r.operand) + " ; DBG GLOBAL RESTORE \n");
r.isDirty = false;
}
}
}
}
<file_sep>/src/SymbolScope/ScopeNode.java
package SymbolScope;
import AST.AstNode;
import IR.IrCode;
import IR.IrNode;
import Nucleus.Operand;
import Nucleus.Symbol;
import Nucleus.Temporary;
import java.util.*;
public abstract class ScopeNode {
SymbolScopeTree.ScopeType scopeType;
ScopeNode parent;
public String name = null;
public Map<String, ScopeNode> children = new LinkedHashMap<String, ScopeNode>();
public Map<String, Symbol> symbolTable = new LinkedHashMap<String, Symbol>();
public List<AstNode> statements = null;
public IrCode irCode;
public abstract Temporary getCurrentTemp();
public abstract Temporary createTemp(Operand.DataType t);
void addSymbol(Operand.DataType type, String id, String reference, String value, Operand.OperandType operandType) {
if(symbolTable.containsKey(id)) {
System.out.println("DECLARATION ERROR " + id);
System.exit(0);
}
switch (type) {
case INT: {
Symbol s = new Symbol(type, reference, 0, operandType);
symbolTable.put(id, s);
break;
}
case FLOAT: {
Symbol s = new Symbol(type, reference, 0.0f, operandType);
symbolTable.put(id, s);
break;
}
case STRING: {
Symbol s = new Symbol(type, reference, value, operandType);
symbolTable.put(id, s);
}
}
}
public abstract void addVariables(String type, List<String> ids);
public abstract String addString(String id, String value);
public Symbol findSymbol(String id) {
Symbol s = null;
if(symbolTable.containsKey(id)) {
s = symbolTable.get(id);
}
else if(parent != null) {
s = parent.findSymbol(id);
}
return s;
}
public abstract FunctionScopeNode getParentFunction();
public abstract void generateIrCode();
public abstract void printIrCode();
public abstract void printTinyCode();
protected void buildControlFlowGraph() {
// build control flow graph
ListIterator<IrNode> irNodeListIterator = irCode.irNodeList.listIterator();
Map<String, IrNode> labelMap = new HashMap<String, IrNode>();
IrNode p = null;
if (irNodeListIterator.hasNext()) {
p = irNodeListIterator.next();
p.starter = true;
if(p.isLabel()) {
labelMap.put(p.label, p);
}
}
while(irNodeListIterator.hasNext()) {
IrNode c = irNodeListIterator.next();
if(p.isReturn() || p.isJmp()) {
// RET has no NEXT IrNode
// JMP has a label jump
c.starter = true;
p.ender = true;
}
else {
c.prevs.add(p);
p.nexts.add(c);
}
if (c.isLabel()) {
labelMap.put(c.label, c);
}
p = c;
}
for(IrNode n : irCode.irNodeList) {
if(n.usesLabel()) {
IrNode l = labelMap.get(n.label);
if(n.nexts.size() == 1) {
n.nexts.get(0).starter = true;
}
if(l.prevs.size() == 1) {
l.prevs.get(0).ender = true;
}
l.starter = true;
l.prevs.add(n);
n.nexts.add(l);
n.ender = true;
}
}
// end building the control flow graph
}
}<file_sep>/src/SymbolScope/GlobalScopeNode.java
package SymbolScope;
import IR.*;
import Nucleus.Operand;
import Nucleus.Temporary;
import java.util.List;
import java.util.Set;
public class GlobalScopeNode extends ScopeNode {
GlobalScopeNode(SymbolScopeTree.ScopeType scopeType) {
this.scopeType = scopeType;
this.parent = null;
this.name = "GLOBAL_SYMBOL";
}
@Override
public Temporary getCurrentTemp() { return null; }
@Override
public Temporary createTemp(Operand.DataType t) { return null; }
@Override
public void addVariables(String type, List<String> ids) {
Operand.DataType t = Operand.DataType.valueOf(type);
for (String id : ids) {
// reference and reference are the same for global variables
addSymbol(t, id, id, null, Operand.OperandType.GLOBAL_SYMBOL);
}
}
@Override
public String addString(String id, String value) {
Operand.DataType t = Operand.DataType.STRING;
// id and reference are the same for global variables
addSymbol(t, id, id, value, Operand.OperandType.GLOBAL_SYMBOL);
return id;
}
@Override
public FunctionScopeNode getParentFunction() {
return null;
}
@Override
public void generateIrCode() {
irCode = new IrCode();
irCode.irNodeList.add(new STypeIrNode(IrNode.Opcode.PUSH, null, null));
irCode.irNodeList.add(new JTypeIrNode(IrNode.Opcode.JSR, null, "main"));
irCode.irNodeList.add(new ITypeIrNode(IrNode.Opcode.HALT, null, null));
buildControlFlowGraph();
// rest of them
Set<String> keys = children.keySet();
for(String key: keys) {
children.get(key).generateIrCode();
}
}
@Override
public void printIrCode() {
irCode.printIrCode();
// rest of them
Set<String> keys = children.keySet();
for(String key: keys) {
children.get(key).printIrCode();
}
}
@Override
public void printTinyCode() {
Set<String> symbolNames = symbolTable.keySet();
for (String symbolName : symbolNames) {
System.out.println(symbolTable.get(symbolName));
}
irCode.printTinyCode();
Set<String> keys = children.keySet();
for(String key: keys) {
children.get(key).printTinyCode();
}
System.out.println("end");
}
}<file_sep>/src/IR/MTypeIrNode.java
package IR;
import Nucleus.Operand;
import SymbolScope.FunctionScopeNode;
public class MTypeIrNode extends IrNode{
// STOREI, STOREF
Operand op1;
Operand result;
public MTypeIrNode(Opcode opcode, FunctionScopeNode scope, Operand op1, Operand result) {
super(opcode, scope);
this.op1 = op1;
this.result = result;
initGen(op1);
initKill(result);
}
@Override
public String toString() {
return "; " + opcode.name() + " " + op1.reference + " " + result.reference;
}
@Override
public String toTiny() {
if (!isStarter()) {
registers = prevs.get(0).registers;
}
String rop1 = ensureRegister(op1);
dropDeadRegisters(rop1);
String op1Ref = rop1 == null ? op1.reference : rop1;
String rResult;
if(result.reference.startsWith("$R")) {
rResult = operandToTiny(result);
}
else {
rResult = allocateRegister(result);
dirtRegister(rResult);
}
if(op1Ref.equals(rResult)) {
tinyCode.append("; ");
}
tinyCode.append("move " + op1Ref + " " + rResult + "\n");
if (isEnder()) {
restoreRegisteredVariables();
}
return tinyCode.toString();
}
}
<file_sep>/src/Micro.java
/**
* Created by <NAME>
*/
import SymbolScope.SymbolScopeTree;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import java.io.IOException;
import java.util.Set;
public class Micro {
public static void main(String[] args) {
if(args.length < 1) {
System.err.println("File argument was not provided.");
return;
}
try {
ANTLRInputStream input = new ANTLRFileStream(args[0]);
MicrobeParser mParser = parseSource(input);
if(mParser == null) {
return;
}
SymbolScopeTree sst = mParser.sst;
printIrCode(sst);
printTinyCode(sst);
}
catch (IOException ex) {
System.err.print("To be or not to be. The file thought to not to be.");
}
}
private static void printIrCode(SymbolScopeTree sst) {
SymbolScopeTree.GlobalScope.generateIrCode();
SymbolScopeTree.GlobalScope.printIrCode();
}
private static void printTinyCode(SymbolScopeTree sst) {
SymbolScopeTree.GlobalScope.printTinyCode();
}
private static MicrobeParser parseSource(ANTLRInputStream input) {
MicrobeLexer lexer = new MicrobeLexer(input);
MicrobeParser parser = new MicrobeParser(new CommonTokenStream(lexer));
parser.setErrorHandler(new MicroErrorStrategy());
try {
parser.program();
} catch (ParseCancellationException e) {
parser = null;
System.out.print("Not accepted");
}
return parser;
}
}
<file_sep>/test/testall.py
#! /usr/bin/env python
import os
import sys
import subprocess
# For ecn server to subprocess
def fn_check_output():
def f(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd)
return output
return f
if "check_output" not in dir(subprocess):
subprocess.check_output = fn_check_output()
errors = False
testdir = '.' + os.sep + 'test' + os.sep
nonsense = 'cmd /C ' if sys.platform.startswith('win') else ''
inputfile = testdir + 'input.txt'
import random
random.seed()
randomnumbers = [random.randint(1,20) for x in xrange(20)]
f = open(inputfile,'w')
for r in randomnumbers:
f.write(str(r) + '\n')
f.close()
for fname in os.listdir(testdir):
if(fname.endswith('.micro') and (len(sys.argv) == 1 or fname.startswith(sys.argv[1]))):
micro = testdir + fname
ouout = testdir + fname.replace('.micro', '.out')
myout = testdir + fname.replace('.micro', '.myout')
mout = testdir + fname.replace('.micro', '.m.myout')
tout = testdir + fname.replace('.micro', '.t.out')
connector = ";"
if os.name == "posix": connector = ":"
oucommand = 'java -jar '+ testdir +'final.jar ' + micro + ' > ' + ouout
excommand = 'java -ea -cp lib/antlr.jar' + connector + 'classes/ Micro '+ micro + ' > ' + myout
t2xcommand = nonsense + testdir + 'tinyR ' + ouout + ' nostats < ' + inputfile + ' > ' + tout
t1xcommand = nonsense + testdir + 'tinyR ' + myout + ' nostats < ' + inputfile + ' > ' + mout
dfcommand = 'diff -y -W 150 ' + mout + ' ' + tout
print "Testing file:", fname
try:
print(oucommand)
subprocess.check_output(oucommand, shell=True);
print(excommand)
subprocess.check_output(excommand, shell=True);
print(t2xcommand)
subprocess.check_output(t2xcommand, shell=True);
print(t1xcommand)
subprocess.check_output(t1xcommand, shell=True);
except:
print "--- Run time error"
exit(1)
try:
print(dfcommand)
subprocess.check_output(dfcommand, shell=True);
print "--- PASSED TEST"
except:
print "--- FAILED TEST"
os.system(dfcommand)
print ""
exit(1)
if(errors): exit(1)
<file_sep>/src/Nucleus/Symbol.java
package Nucleus;
public class Symbol extends Operand {
public Symbol(DataType t, String n, Object v, OperandType o) {
dataType = t;
reference = n;
value = v;
operandType = o;
}
@Override
public String toString() {
switch (dataType) {
case STRING:
return "str " + reference + " " + value;
default:
return "var " + reference;
}
}
}
|
4f174766e877ff44d7549ac843a27614ce160190
|
[
"Markdown",
"Makefile",
"Java",
"Python",
"Shell"
] | 16
|
Shell
|
sransara/microbe
|
498ddd88d9622241f04f2513594b1526f80dfdc7
|
50157600f791790661b0403aaec7016b7986d135
|
refs/heads/master
|
<file_sep>var db = require("diskdb");
db.connect(
"../db",
["inventory", "valve"]
);
var valveList = db.valve.find({ _id: "2452d289c1c44cffa5bcd405d647ccf0" })[0];
// valveList = valveList[0];
// console.log(valveList.componentList);
var Check = 0;
var ValveCheck = []; //variable to hold all components for a valve
valveList.componentList.forEach(i => {
// console.log(valveList.qty);
compLength = 0;
if (i.opt) {
compLength = Number(i.optComponentList.length);
componentList = [];
i.optComponentList.forEach(k => {
componentList.push({
name: k.componentName,
invqty: 0,
opt: false,
reqqty: k.quantity,
totalreqqty: 0,
result: null,
possible: false
});
});
ValveCheck.push({
name: i.componentName,
opt: i.opt,
optCL: Number(compLength),
invqty: 0,
reqqty: i.quantity,
totalreqqty: Number(i.quantity) * Number(valveList.qty),
result: null,
possible: false,
optComponents: componentList
});
} else {
ValveCheck.push({
name: i.componentName,
invqty: 0,
opt: false,
reqqty: i.quantity,
totalreqqty: Number(i.quantity) * Number(valveList.qty),
result: null,
possible: false
});
}
});
ValveCheck.forEach(i => {
//check the inv qty before doing any calculation
i.invqty = Number(db.inventory.find({ name: i.name })[0].quantity);
//update total qty, possible and result for all components
if (i.totalreqqty <= i.invqty) {
i.possible = true;
i.result = valveList.qty;
} else if (i.totalreqqty > i.invqty) {
if (i.invqty >= i.reqqty) {
i.result = Number(i.invqty) / Number(i.reqqty);
} else if (i.invqty < i.reqqty) {
i.result = 0;
}
}
//check for options
if (i.opt) {
// console.log("Option");
//if parent component is not possible check for opt components
if (!i.possible) {
//iterate for every opt components
i.optComponents.forEach(k => {
//update the optional components inv qty
k.invqty = Number(db.inventory.find({ name: k.name })[0].quantity);
k.totalreqqty =
Number(i.result) > 0
? (Number(valveList.qty) - Number(i.result)) * Number(k.reqqty)
: 1 * Number(valveList.qty);
if (k.totalreqqty <= k.invqty) {
k.possible = true;
//Check if possible or not, if possible dont check opt, else if result >0 check opt for the remaining(valveList.qty-result)
k.result = Number(valveList.qty) - Number(i.result); //if parent comp is partial, the remaining valve can be made with opt
} else if (k.totalreqqty > k.invqty) {
if (k.invqty >= k.reqqty) {
k.result = Number(k.invqty) / Number(k.reqqty);
} else if (k.invqty < k.reqqty) {
k.result = 0;
}
}
});
}
}
});
console.log(ValveCheck);
projValue = [];
ValveCheck.forEach(m => {
if (m.opt) {
sumValue = 0;
sumValue += m.result;
m.optComponents.forEach(l => {
sumValue += l.result;
});
projValue.push(Number(sumValue));
} else {
projValue.push(Number(m.result));
}
});
shortStock = [];
goodStock = [];
badStock = [];
ValveCheck.forEach(o => {
if (o.possible) {
//good stock on component
goodStock.push({
name: o.name,
postInv:
o.invqty > o.totalreqqty
? o.invqty - o.totalreqqty
: o.totalreqqty - o.invqty,
result: o.result,
reqValve: valveList.qty
});
} else if (!o.possible) {
//check further
if (o.result > 0) {
//short stock on component
shortStock.push({
name: o.name,
postInv:
o.invqty > o.totalreqqty
? o.invqty - o.totalreqqty
: o.totalreqqty - o.invqty,
result: o.result,
reqValve: valveList.qty
});
if (o.opt) {
//check if options available for the component
o.optComponents.forEach(l => {
if (!l.possible) {
//check if result having some numbers
if (l.result > 0) {
//short stock on opt component
shortStock.push({
name: l.name,
postInv:
l.invqty > l.totalreqqty
? l.invqty - l.totalreqqty
: l.totalreqqty - l.invqty,
result: l.result,
reqValve: valveList.qty,
parent: o.name
});
} else {
//bad stock on opt component
badStock.push({
name: l.name,
postInv:
l.invqty > l.totalreqqty
? l.invqty - l.totalreqqty
: l.totalreqqty - l.invqty,
result: l.result,
reqValve: valveList.qty,
parent: o.name
});
}
} else {
//good stock on opt component
goodStock.push({
name: l.name,
postInv:
l.invqty > l.totalreqqty
? l.invqty - l.totalreqqty
: l.totalreqqty - l.invqty,
result: l.result,
reqValve: valveList.qty,
parent: o.name
});
}
});
// } else {
// //short on stock
// shortStock.push({
// name: o.name,
// postInv:
// o.invqty > o.totalreqqty
// ? o.invqty - o.totalreqqty
// : o.totalreqqty - o.invqty,
// result: o.result,
// reqValve: valveList.qty
// });
// projValue.push(o.result);
}
} else if (o.result == 0) {
if (o.opt) {
//short stock on component
badStock.push({
name: o.name,
postInv:
o.invqty > o.totalreqqty
? o.invqty - o.totalreqqty
: o.totalreqqty - o.invqty,
result: o.result,
reqValve: valveList.qty
});
o.optComponents.forEach(l => {
if (!l.possible) {
//check if result having some numbers
if (l.result > 0) {
//short stock on opt component
shortStock.push({
name: l.name,
postInv:
l.invqty > l.totalreqqty
? l.invqty - l.totalreqqty
: l.totalreqqty - l.invqty,
result: l.result,
reqValve: valveList.qty,
parent: o.name
});
} else {
//bad stock on opt component
badStock.push({
name: l.name,
postInv:
l.invqty > l.totalreqqty
? l.invqty - l.totalreqqty
: l.totalreqqty - l.invqty,
result: l.result,
reqValve: valveList.qty,
parent: o.name
});
}
} else {
//good stock on opt component
goodStock.push({
name: l.name,
postInv:
l.invqty > l.totalreqqty
? l.invqty - l.totalreqqty
: l.totalreqqty - l.invqty,
result: l.result,
reqValve: valveList.qty,
parent: o.name
});
}
});
} else {
//bad stock on component
badStock.push({
name: o.name,
postInv:
o.invqty > o.totalreqqty
? o.invqty - o.totalreqqty
: o.totalreqqty - o.invqty,
result: o.result,
reqValve: valveList.qty
});
}
}
}
// if (o.possible) {
// //good
// goodStock.push({
// name: o.name,
// postInv:
// o.invqty > o.totalreqqty
// ? o.invqty - o.totalreqqty
// : o.totalreqqty - o.invqty,
// result: o.result,
// reqValve: valveList.qty
// });
// projValue.push(o.result);
// } else if (!o.possible && o.result > 0 && !o.opt) {
// //short
// shortStock.push({
// name: o.name,
// postInv:
// o.invqty > o.totalreqqty
// ? o.invqty - o.totalreqqty
// : o.totalreqqty - o.invqty,
// result: o.result,
// reqValve: valveList.qty
// });
// projValue.push(o.result);
// } else if (!o.possible && o.result > 0 && o.opt) {
// sumValve = 0;
// sumValve += o.result;
// //for opt 3
// shortStock.push({
// name: o.name,
// postInv:
// o.invqty > o.totalreqqty
// ? o.invqty - o.totalreqqty
// : o.totalreqqty - o.invqty,
// result: o.result,
// reqValve: valveList.qty
// });
// // projValue.push(sumValve);
//
// o.optComponents.forEach(l => {
// sumValve += l.result;
// if (l.possible) {
// //good on opt component
// goodStock.push({
// name: l.name,
// postInv:
// l.invqty > l.totalreqqty
// ? l.invqty - l.totalreqqty
// : l.totalreqqty - l.invqty,
// result: l.result,
// reqValve: valveList.qty,
// parent: o.name
// });
// projValue.push(sumValve);
// } else if (!l.possible && l.result > 0) {
// //short on opt component
// shortStock.push({
// name: l.name,
// postInv:
// l.invqty > l.totalreqqty
// ? l.invqty - l.totalreqqty
// : l.totalreqqty - l.invqty,
// result: l.result,
// reqValve: valveList.qty,
// parent: o.name
// });
// projValue.push(sumValve);
// }
// });
// } else {
// //bad
// badStock.push({
// name: o.name,
// postInv:
// o.invqty > o.totalreqqty
// ? o.invqty - o.totalreqqty
// : o.totalreqqty - o.invqty,
// result: o.result,
// reqValve: valveList.qty
// });
// projValue.push(o.result);
// }
});
console.log("Valve Name: " + valveList.name);
console.log("Requested qty: " + valveList.qty);
//
// console.log("Good stocks");
// console.log(goodStock);
//
// console.log("Short on Stocks");
// console.log(shortStock);
//
// console.log("Bad stocks");
// console.log(badStock);
//
// console.log("Proj");
// console.log(projValue);
ValveCheck.forEach(u => {
console.log(u);
});
//
// // console.log(projValue.find(k => k == 0));
// console.log(projValue);
console.log(Math.min.apply(null, projValue) + " Valve can be made");
<file_sep>var db = require("diskdb");
db.connect(
"../db",
["inventory", "valve"]
);
/*
*/
var compo = {
name: "MOS2 SEAT",
measurement: "MM",
quantity: "1"
};
var valve = {
name: "CAST IRON FULL PORT THREE PIECE FLANGED",
desc: "This is a test valve for Sriram",
qty: 1,
componentList: [
{
componentName: "25 CAST IRON FULL PORT BODY",
quantity: 1
},
{
componentName: "25 CAST IRON FULL PORT END PIECE MW11",
quantity: 2
},
{
componentName: "42X25X5 PTFE SEAT",
quantity: 2,
opt: true,
optComponentList: [
{
componentName: "MOS2 SEAT",
quantity: 3
}
]
},
{
componentName: "32X22X3 PTFE SEAT",
quantity: 4
},
{
componentName: "52X48X1.5 PTFE BODY SEAL",
quantity: 2
},
{
componentName: "304 S.S HOLLOW BALL",
quantity: 1,
opt: true,
optComponentList: [
{
componentName: "316 S.S HOLLOW BALL",
quantity: 1
}
]
},
{
componentName: "202 SPINDLE DIA 18",
quantity: 45,
opt: true,
optComponentList: [
{
componentName: "304 S.S SPINDLE",
quantity: 30
}
]
},
{
componentName: "202 S.S METAL WASHER DIA 18",
quantity: 10
},
{
componentName: "M.S SPRING WASHER 10",
quantity: 1
},
{
componentName: "M.S PLATE WASHER 1/2 INCH",
quantity: 2
},
{
componentName: "M.S STOPPER PLATE 9 SQ",
quantity: 1
},
{
componentName: "M.S HAND LEVER 170 MM",
quantity: 1
},
{
componentName: "M8*48 MS STUD",
quantity: 4
},
{
componentName: "M8 MS NUT",
quantity: 8
},
{
componentName: "M10 MS NUT",
quantity: 1
}
]
};
db.valve.save(valve);
//db.inventory.save(compo);
<file_sep>var db = require("diskdb");
db.connect(
"../db",
["inventory", "valve"]
);
//accept valve ID and return the valve inv list & min projValue
// var projectionValve = (valveid, data, proj, err) => {
var projectionValve = (valveid, qty, callbackData) => {
var valveList = db.valve.find({ _id: valveid })[0];
// valveList = valveList[0];
valveList.qty = qty;
// console.log(valveList);
// console.log(valveList.componentList);
var Check = 0;
var ValveCheck = []; //variable to hold all components for a valve
valveList.componentList.forEach(i => {
// console.log(valveList.qty);
compLength = 0;
if (i.opt) {
compLength = Number(i.optComponentList.length);
componentList = [];
i.optComponentList.forEach(k => {
componentList.push({
name: k.componentName,
invqty: 0,
opt: false,
reqqty: k.quantity,
totalreqqty: 0,
result: null,
possible: false
});
});
ValveCheck.push({
name: i.componentName,
opt: i.opt,
invqty: 0,
reqqty: i.quantity,
totalreqqty: Number(i.quantity) * Number(valveList.qty),
result: null,
possible: false,
optComponents: componentList
});
} else {
ValveCheck.push({
name: i.componentName,
invqty: 0,
opt: false,
reqqty: i.quantity,
totalreqqty: Number(i.quantity) * Number(valveList.qty),
result: null,
possible: false
});
}
});
ValveCheck.forEach(i => {
//check the inv qty before doing any calculation
i.invqty = Number(db.inventory.find({ name: i.name })[0].quantity);
//update total qty, possible and result for all components
if (i.totalreqqty <= i.invqty) {
i.possible = true;
i.result = valveList.qty;
} else if (i.totalreqqty > i.invqty) {
if (i.invqty >= i.reqqty) {
i.result = Math.floor(Number(i.invqty) / Number(i.reqqty));
} else if (i.invqty < i.reqqty) {
i.result = 0;
}
}
//check for options
if (i.opt) {
// console.log("Option");
//if parent component is not possible check for opt components
if (!i.possible) {
//iterate for every opt components
i.optComponents.forEach(k => {
//update the optional components inv qty
k.invqty = Number(db.inventory.find({ name: k.name })[0].quantity);
k.totalreqqty =
Number(i.result) > 0
? (Number(valveList.qty) - Number(i.result)) * Number(k.reqqty)
: 1 * Number(valveList.qty);
if (k.totalreqqty <= k.invqty) {
k.possible = true;
//Check if possible or not, if possible dont check opt, else if result >0 check opt for the remaining(valveList.qty-result)
k.result = Math.floor(Number(valveList.qty) - Number(i.result)); //if parent comp is partial, the remaining valve can be made with opt
} else if (k.totalreqqty > k.invqty) {
if (k.invqty >= k.reqqty) {
k.result = Math.floor(Number(k.invqty) / Number(k.reqqty));
} else if (k.invqty < k.reqqty) {
k.result = 0;
}
}
});
}
}
});
// callbackData(ValveCheck);
projValue = [];
ValveCheck.forEach(m => {
if (m.opt) {
sumValue = 0;
sumValue += m.result;
m.optComponents.forEach(l => {
sumValue += l.result;
});
projValue.push(Number(sumValue));
} else {
projValue.push(Number(m.result));
}
});
callbackData(ValveCheck, projValue);
// ValveCheck.forEach(u => {
// console.log(u);
// });
// console.log(projValue);
// console.log(
// "Valve: " +
// valveList.name +
// " requested for " +
// valveList.qty +
// " but " +
// Math.min.apply(null, projValue) +
// " Valve can be made"
// );
};
projectionValve("2452d289c1c44cffa5bcd405d647ccf0", 10, (data, proj) => {
console.log("From Callback");
console.log(data);
console.log(proj);
});
module.exports = {
projectionValve
};
<file_sep>var db = require("diskdb");
db.connect(
"../db",
["inventory", "valve"]
);
var valveList = db.valve.find({ _id: "2452d289c1c44cffa5bcd405d647ccf0" })[0];
// valveList = valveList[0];
// console.log(valveList.componentList);
var Check = 0;
var ValveCheck = []; //variable to hold all components for a valve
valveList.componentList.forEach(i => {
// console.log(valveList.qty);
compLength = 0;
if (i.opt) {
compLength = Number(i.optComponentList.length);
componentList = [];
i.optComponentList.forEach(k => {
componentList.push({
name: k.componentName,
invqty: 0,
reqqty: k.quantity,
totalreqqty: 0,
result: null,
possible: false
});
});
ValveCheck.push({
name: i.componentName,
opt: i.opt,
optCL: Number(compLength),
invqty: 0,
reqqty: i.quantity,
totalreqqty: Number(i.quantity) * Number(valveList.qty),
result: null,
possible: false,
optComponents: componentList
});
} else {
ValveCheck.push({
name: i.componentName,
invqty: 0,
reqqty: i.quantity,
totalreqqty: Number(i.quantity) * Number(valveList.qty),
result: null,
possible: false
});
}
});
ValveCheck.forEach(i => {
//check the inv qty before doing any calculation
i.invqty = Number(db.inventory.find({ name: i.name })[0].quantity);
//update total qty, possible and result for all components
if (i.totalreqqty <= i.invqty) {
i.possible = true;
i.result = valveList.qty;
} else if (i.totalreqqty > i.invqty) {
if (i.invqty >= i.reqqty) {
i.result = Number(i.invqty) / Number(i.reqqty);
} else if (i.invqty < i.reqqty) {
i.result = 0;
}
}
//check for options
if (i.opt) {
// console.log("Option");
//if parent component is not possible check for opt components
if (!i.possible) {
//iterate for every opt components
i.optComponents.forEach(k => {
//update the optional components inv qty
k.invqty = Number(db.inventory.find({ name: k.name })[0].quantity);
k.totalreqqty =
Number(i.result) > 0
? (Number(valveList.qty) - Number(i.result)) * Number(k.reqqty)
: Number(i.result) * Number(valveList.qty);
if (k.totalreqqty <= k.invqty) {
k.possible = true;
//Check if possible or not, if possible dont check opt, else if result >0 check opt for the remaining(valveList.qty-result)
k.result = Number(valveList.qty) - Number(i.result); //if parent comp is partial, the remaining valve can be made with opt
} else if (k.totalreqqty > k.invqty) {
if (k.invqty >= k.reqqty) {
k.result = Number(k.invqty) / Number(k.reqqty);
} else if (k.invqty < k.reqqty) {
k.result = 0;
}
}
});
}
}
});
//
// //check against inventory
// ValveCheck.forEach(i => {
// i.invqty = Number(db.inventory.find({ name: i.name })[0].quantity);
// if (i.totalreqqty <= i.invqty) {
// i.result = valveList.qty;
// i.possible = true;
// } else if (i.totalreqqty > i.invqty) {
// if (i.invqty >= i.reqqty) {
// i.result = Number(i.invqty) / Number(i.reqqty);
// } else if (i.invqty < i.reqqty) {
// i.result = false;
// }
// }
// });
//
// var stockChecker = list => {
// list.forEach(i => {
// if (db.inventory.find({ name: i.componentName })[0].quantity > i.quantity) {
// i.possible = true; //check if the inventory is adequate for the component
// }
// });
// };
console.log(ValveCheck);
shortStock = [];
possibleStock = [];
projValue = [];
ValveCheck.forEach(o => {
//checking for opt comp
if (!o.possible && o.opt) {
//check for opt components
//check if result > 0 if so include that comp and check for opt comp
sumPartial = o.result;
//possible glitch to show if the opt is not full
if (o.result > 0) {
possibleStock.push({
name: o.name,
postInv:
o.invqty > o.totalreqqty
? o.invqty - o.totalreqqty
: o.totalreqqty - o.invqty,
result: o.result,
reqValve: valveList.qty
});
o.optComponents.forEach(m => {
if (m.result > 0) {
possibleStock.push({
name: m.name,
postInv:
m.invqty > m.totalreqqty
? m.invqty - m.totalreqqty
: m.totalreqqty - m.invqty,
result: m.result,
parent: o.name
});
}
sumPartial += m.result;
});
projValue.push(sumPartial);
} else {
projValued = 0;
o.optComponents.forEach(m => {
projValued += m.result;
possibleStock.push({
name: m.name,
postInv:
m.invqty > m.totalreqqty
? m.invqty - m.totalreqqty
: m.totalreqqty - m.invqty,
result: m.result,
parent: o.name
});
});
projValue.push(projValued);
}
} else if (o.possible && o.opt) {
projValue.push(o.result);
possibleStock.push({
name: o.name,
postInv:
o.invqty > o.totalreqqty
? o.invqty - o.totalreqqty
: o.totalreqqty - o.invqty,
result: o.result
});
} else if (!o.possible) {
projValue.push(o.result);
shortStock.push({
name: o.name,
qtyReq: o.totalreqqty,
result: o.result
});
} else if (o.possible) {
projValue.push(o.result);
possibleStock.push({
name: o.name,
postInv:
o.invqty > o.totalreqqty
? o.invqty - o.totalreqqty
: o.totalreqqty - o.invqty,
result: o.result
});
}
});
console.log("Short on Stocks");
console.log(shortStock);
console.log("Good stocks");
console.log(possibleStock);
console.log("Proj");
console.log(projValue);
//
// console.log("All with opt");
// console.log(ValveCheck.filter(i => i.opt && !i.possible));
//
// //optMain lists all the optcomponents, from the initial failed ones
// var optMain = [];
// ValveCheck.filter(i => i.opt && !i.possible).forEach((k, i) => {
// optCompName: valveList.componentList
// .find(o => o.componentName == k.name)
// .optComponentList.forEach(i => {
// optMain.push({
// optCompName: i.componentName,
// optqty: i.quantity,
// parentCompName: k.name
// });
// });
// });
//
// console.log("Optional Components");
// console.log(optMain);
// console.log(ValveCheck);
//
// //filter out all failed ones
// var shortStock = ValveCheck.filter(d => !d.possible);
//
// //check if any with opt
// var optionalExists = shortStock.filter(f => f.opt);
//
// console.log("Required Valve");
// console.log(ValveCheck);
//
// console.log("Components have less quantity and have options:");
// console.log(optionalExists);
//
// // console.log(ValveCheck);
// console.log("Components have less quantity");
// console.log(shortStock);
//
// //find the optCompname to fetch optComponents from main valvelist
// var optMain = valveList.componentList.find(
// o => o.componentName == optionalExists[0].name
// ).optComponentList;
//
// //optMain1 lists all the optcomponents, from the initial failed ones
// // var optMain1 = [];
// // optionalExists.forEach((k, i) => {
// // optMain1 = valveList.componentList.find(o => o.componentName == k.name)
// // .optComponentList;
// // });
//
// // var optMain1 = [];
// // optionalExists.forEach(k => {
// // optMain1.push(
// // valveList.componentList.find(o => o.componentName == k.name)
// // .optComponentList
// // );
// // });
//
// var optMain1 = [];
// optionalExists.forEach(k => {
// valveList.componentList
// .find(o => o.componentName == k.name)
// .optComponentList.forEach(o => {
// optMain1.push({
// componentName: o.componentName,
// quantity: o.quantity,
// parentName: k.name
// });
// });
// });
//
// console.log("Optional Componets");
// console.log(optMain1);
//
// console.log("Check optional component details");
// stockChecker(optMain1);
// console.log(optMain1);
// /*
// console.log("--------------------------------");
// console.log("Valve List");
// console.log(ValveCheck);
//
// console.log("Optional List");
// console.log(optMain1);
// */
// /*
// * ValveCheck contains the complete list of valve required Components
// * If any component from the list doesnt meet the requirement and it it contains optional components, then those are checked and stored in optMain1
// * If two optional components satisfy the rule, remove one from the list
// * Prepare a list of final lookup which should contain
// {
// Component name,
// Inventory qty post reduction
// }
// if any one of the component doesnt meet the requirement list that component with inventory, if it contain optional show all.
// */
//
// console.log("Complete List");
// var final = [];
// ValveCheck.forEach(p => {
// if (!p.possible) {
// final.push(
// optMain1.find(o => o.parentName == p.name && o.possible == true)
// );
// } else {
// final.push(p);
// }
// });
// console.log(final);
// console.log("Component short without options");
// console.log(shortStock.find(l => l.possible == false && l.opt == false));
// // if (optMain.length == optionalExists[0].optCL) {
// // console.log("Matching");
// // }
//
// //if any qty is not available for a component then, check if that component has opt.
//
// //if any qty is not available for a component and no opt then report the valve can't be manufactured due to that component qty low.
//
// //if any component has opt, replace the ValveCheck component to optcomponent
//
// // if (check === valveList.componentList.length) {
// // console.log("Valve can be done with current stock");
// // } else {
// // console.log("Sorry valve can't be done with current stock");
// // }
//
// /*
// console.log(i.componentName);
// console.log(db.inventory.find({ name: i.componentName })[0].quantity);
// if (db.inventory.find({ name: i.componentName })[0].quantity == 0) {
// if (i.opt) {
// console.log(i.optComponentName1);
// console.log(db.inventory.find({ name: i.optComponentName1 })[0].quantity);
// }
// }
// */
<file_sep>var db = require("diskdb");
db.connect(
"../db",
["inventory", "valve"]
);
var qty = 2;
var valve = db.valve.find();
valve.push({ quantity: qty });
var valveCheck = [];
valve[0].componentList.forEach(p => {
console.log("componentName:" + p.componentName);
//get this component inventory
if (p.opt) {
p.optComponentList.forEach(k => {
console.log("{");
console.log(" " + k.componentName);
console.log("}");
//get this component inventory
});
}
});
<file_sep>var express = require("express");
var router = express.Router();
var db = require("./db");
/* GET home page. */
//to get all component name, measurement and quantity
router.get("/component", (req, res) => {
// res.render("index", { title: "Inventory" });
db.getComponent((data, err) => {
if (err) {
res.status(404).send(err);
} else {
res.send(data);
}
});
});
router.get("/scomponent", (req, res) => {
// res.render("index", { title: "Inventory" });
db.getSpecificComponent(req.query.name, (data, err) => {
if (err) {
res.status(404).send(err);
} else {
res.send(data);
}
});
});
//to add component in db.
router.post("/component", (req, res) => {
db.addComponent(req.body, (data, err) => {
if (!err) {
res.send(data);
} else {
res.status(409).send(err);
}
});
});
//to update quantity for the component
router.put("/component", (req, res) => {
db.updateComponent(req.body, (data, err) => {
if (!err) {
res.send(data);
} else {
res.status(409).send(err);
}
});
});
//to delete a component from inventory
router.delete("/component", (req, res) => {
db.deleteComponent(req.body, (data, err) => {
if (!err) {
res.send(data);
} else {
res.status(409).send(err);
}
});
});
module.exports = router;
<file_sep>var db = require("diskdb");
db.connect(
"db",
["inventory"]
);
//adding component
var addComponent = (data, callback) => {
var componentN = db.inventory.find({ name: data.componentName });
if (componentN.length <= 0) {
var record = {
name: data.componentName,
measurement: data.measurement,
quantity: data.quantity
};
//get the user detail and save it in a separate table along with time and modifications
/*
For example:
If user name: Ganesh
{
updatedBy: "Ganesh",
updatedAt: Date and Time,
Details: [
{
record
}
]
}
*/
if (data.componentName) {
db.inventory.save(record);
var confirm = db.inventory.find({ name: data.componentName });
if (confirm.length > 0) {
callback("Component Added", "");
} else {
callback("", "Error while saving");
}
} else {
callback("", "Component can't be added");
}
} else {
callback("", "Component Already exists");
}
};
//list all components
var getComponent = callback => {
var componentList = db.inventory.find();
if (componentList.length > 0) {
callback(componentList, "");
} else {
callback("", "No component to list out");
}
};
//list specific component
var getSpecificComponent = (data, callback) => {
var componentList = db.inventory.find({ name: data });
if (componentList.length > 0) {
callback(componentList, "");
} else {
callback("", "No such component exists");
}
};
//update quantity for a specific component
var updateComponent = (data, callback) => {
//get the user detail and save it in a separate table along with time and modifications
/*
For example:
If user name: Ganesh
{
updatedBy: "Ganesh",
updatedAt: Date and Time,
Details: [
{
data
}
]
}
*/
var options = {
multi: false,
upsert: false
};
var updateDetail = db.inventory.update(
{ _id: data._id },
{ quantity: data.uquantity },
options
);
if (updateDetail.updated == 1) {
callback("Success", "");
} else {
callback("", "Failed to update component");
}
};
//remove a component from database
var deleteComponent = (data, callback) => {
//get the user detail and save it in a separate table along with time and modifications
/*
For example:
If user name: Ganesh
{
updatedBy: "Ganesh",
updatedAt: Date and Time,
Details: [
{
data
}
]
}
*/
/*
before deleting a component, have to check if the component has been listed for any valve
if listed: Warn user not to delete component
else delete
var drecord = db.valve.find({componentName: data.name})
if(drecord>0){
can't delete
}
else {
delete from inventory db
}
*/
db.inventory.remove({ _id: data._id });
var record = db.inventory.find({ _id: data._id });
// callback(detail, "");
if (record.length <= 0) {
callback("Component Deleted successfully", "");
} else {
callback("", "Component failed to delete");
}
};
module.exports = {
addComponent,
getComponent,
getSpecificComponent,
updateComponent,
deleteComponent
};
<file_sep>This will be document to track our work.
1: Component entry page
1A: GET to show all components with current stock.
Completed
1B: POST to add new component
Completed
1C: PUT to update component also to update stock details.
Completed
1D: DELETE to remove a component from the list.
Completed
If a component is used against a valve that component should not be able to delete.
Expect 1A all commands should track who did it in a separate table(in our case a new .db file).
2: Valve Maintenance
2A: GET to show all valve names, with all component names and required quantity
2B: POST to add new valve to our database.
{
name: <valve_name>,
desc: <desc>,
componentList: [{
componentName: <componentName>,
quantity: <quantity>,
optional: true,
optComponentList: [{optCompName1: <componentName>,optQuantity1: <quantity>},{optCompName1: <componentName>,optQuantity1: <quantity>}]
},{
componentName: <componentName>,
quantity: <quantity>
}]
}
Fetch all the componentName & quantity from the componentList, put it in a object, compare against our stock.
If the matching quantity available then good, else check if the componentName has a optional? If so replace the object.componentName
to the optComponent name and check for quantity.
2C: PUT to update a valve details.
2D: DELETE to remove a valve from our database.
Expect 2A all commands should track who did it in a separate table.
Request can be made from client using below as header.
Content-Type: application/json
<file_sep>var db = require("diskdb");
db.connect(
"../db",
["inventory", "valve"]
);
var valveList = db.valve.find({ _id: "2452d289c1c44cffa5bcd405d647ccf0" })[0];
// valveList = valveList[0];
// console.log(valveList.componentList);
var Check = 0;
var ValveCheck = []; //variable to hold all components for a valve
valveList.componentList.forEach(i => {
// console.log(valveList.qty);
compLength = 0;
if (i.opt) {
compLength = Number(i.optComponentList.length);
}
ValveCheck.push({
name: i.componentName,
quantity: Number(i.quantity) * Number(valveList.qty),
possible: false,
opt: i.opt === undefined ? false : i.opt,
optCL: Number(compLength)
});
});
//check against inventory
ValveCheck.forEach(i => {
if (db.inventory.find({ name: i.name })[0].quantity > i.quantity) {
i.possible = true; //check if the inventory is adequate for the component
}
});
var stockChecker = list => {
list.forEach(i => {
if (db.inventory.find({ name: i.componentName })[0].quantity > i.quantity) {
i.possible = true; //check if the inventory is adequate for the component
}
});
};
// console.log(ValveCheck);
//filter out all failed ones
var shortStock = ValveCheck.filter(d => !d.possible);
//check if any with opt
var optionalExists = shortStock.filter(f => f.opt);
console.log("Required Valve");
console.log(ValveCheck);
console.log("Components have less quantity and have options:");
console.log(optionalExists);
// console.log(ValveCheck);
console.log("Components have less quantity");
console.log(shortStock);
//find the optCompname to fetch optComponents from main valvelist
var optMain = valveList.componentList.find(
o => o.componentName == optionalExists[0].name
).optComponentList;
//optMain1 lists all the optcomponents, from the initial failed ones
// var optMain1 = [];
// optionalExists.forEach((k, i) => {
// optMain1 = valveList.componentList.find(o => o.componentName == k.name)
// .optComponentList;
// });
// var optMain1 = [];
// optionalExists.forEach(k => {
// optMain1.push(
// valveList.componentList.find(o => o.componentName == k.name)
// .optComponentList
// );
// });
var optMain1 = [];
optionalExists.forEach(k => {
valveList.componentList
.find(o => o.componentName == k.name)
.optComponentList.forEach(o => {
optMain1.push({
componentName: o.componentName,
quantity: o.quantity,
parentName: k.name
});
});
});
console.log("Optional Componets");
console.log(optMain1);
console.log("Check optional component details");
stockChecker(optMain1);
console.log(optMain1);
/*
console.log("--------------------------------");
console.log("Valve List");
console.log(ValveCheck);
console.log("Optional List");
console.log(optMain1);
*/
/*
* ValveCheck contains the complete list of valve required Components
* If any component from the list doesnt meet the requirement and it it contains optional components, then those are checked and stored in optMain1
* If two optional components satisfy the rule, remove one from the list
* Prepare a list of final lookup which should contain
{
Component name,
Inventory qty post reduction
}
if any one of the component doesnt meet the requirement list that component with inventory, if it contain optional show all.
*/
console.log("Complete List");
var final = [];
ValveCheck.forEach(p => {
if (!p.possible) {
final.push(
optMain1.find(o => o.parentName == p.name && o.possible == true)
);
} else {
final.push(p);
}
});
console.log(final);
console.log("Component short without options");
console.log(shortStock.find(l => l.possible == false && l.opt == false));
// if (optMain.length == optionalExists[0].optCL) {
// console.log("Matching");
// }
//if any qty is not available for a component then, check if that component has opt.
//if any qty is not available for a component and no opt then report the valve can't be manufactured due to that component qty low.
//if any component has opt, replace the ValveCheck component to optcomponent
// if (check === valveList.componentList.length) {
// console.log("Valve can be done with current stock");
// } else {
// console.log("Sorry valve can't be done with current stock");
// }
/*
console.log(i.componentName);
console.log(db.inventory.find({ name: i.componentName })[0].quantity);
if (db.inventory.find({ name: i.componentName })[0].quantity == 0) {
if (i.opt) {
console.log(i.optComponentName1);
console.log(db.inventory.find({ name: i.optComponentName1 })[0].quantity);
}
}
*/
<file_sep>var https = require("http");
var options = {
method: "POST",
host: "192.168.1.131",
port: "3007",
path: "/inventory/component",
headers: {
"Content-Type": "application/json"
}
};
var req = https.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function(chunk) {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", function(error) {
console.error(error);
});
});
var postData =
'{\n"componentName":"TEST DATA FROM WEB CALL",\n"measurement":"MM",\n"quantity":"900"\n}';
req.write(postData);
req.end();
|
1867d549b4f525e002eda2fad031f533d50e7ed5
|
[
"JavaScript",
"Text"
] | 10
|
JavaScript
|
JeraldVictor/mech-pro
|
51e464d66e21ddbe41d733ac84ca3bf860df8da4
|
e68142b9b20243046e23ade0ff68f66630104b2b
|
refs/heads/master
|
<file_sep>
# coding: utf-8
# In[1]:
print("Data Science Assignment 1")
# In[2]:
print("<NAME>")
# In[14]:
print("How to concatenate multiple strings?")#using +
# In[8]:
variable1 = 'I'
variable2 = ' <NAME>'
variable3 = ' boy'
print("About me :",variable1+variable2+variable3)
# In[15]:
print("How to capitalise ?") # using capitalize()
# In[10]:
string1='this is a beautiful place'
print("Capitalized string : ",string1.capitalize())
# In[11]:
print("How to update strings ?")
# In[13]:
string1='this is a beautiful place'
print("Updated String :",string1[:20]+'art')
# In[16]:
print("How to get a pattern of strings ?")#using *
# In[17]:
variable1 = ' boy'
print("4 times boy : ",variable1*4)
|
32deb0bfefa309a0063b5410e138903741200105
|
[
"Python"
] | 1
|
Python
|
kshitij1993/Data-Science-Projects
|
886ef9032880544a889f1f2ab84bd6b394ad9627
|
a7307e175001a1f1969a973312339f48e06abd52
|
refs/heads/master
|
<file_sep>## READ FILES
# activity labels (1st column is numeric, 2nd column is corresponding label)
ActivityLabels <- read.table("activity_labels.txt")
# feature labels (only want the labels that are in the 2nd colum)
temp <- read.table("features.txt")
FeatureLabels <- as.character(temp[,2])
#training data
TrainSubject <- read.table("train/subject_train.txt", col.names=c("SubjectID"))
TrainActivity <- read.table("train/Y_train.txt", col.names=c("Activity"))
TrainFeatures <- read.table("train/X_train.txt", col.names=FeatureLabels)
#test files
TestSubject <- read.table("test/subject_test.txt", col.names=c("SubjectID"))
TestActivity <- read.table("test/Y_test.txt", col.names=c("Activity"))
TestFeatures <- read.table("test/X_test.txt", col.names=FeatureLabels)
# Combine the training data (subject, activity, feature) in to a single data set
TrainData <- cbind(TrainSubject, TrainActivity, TrainFeatures)
# Combine the training data (subject, activity, feature) in to a single data set
TestData <- cbind(TestSubject, TestActivity, TestFeatures)
# Combine the training and test data in to a single dataset
AllData <- rbind(TrainData, TestData)
# Convert the activity column from numerics to labels
# Pick off only the features that are proper means and standard deviations
MeanFeatures <- grep("mean", names(AllData), value=TRUE)
StdFeatures <- grep("std", names(AllData), value=TRUE)
print(MeanFeatures)
print(StdFeatures)
AllData <- AllData[,c("SubjectID", "Activity", MeanFeatures, StdFeatures)]
print(dim(AllData))
print(head(AllData))<file_sep>Tidy Data Set 2
===============
Variables (columns):
- Subject ID
- Activity Label
- Mean Value of Extracted Variables from Tidy Data Set 1 for a given Subject ID and Activity Label
List of Extracted Variables:
tGravityAcc.mean.X
tGravityAcc.mean.Y
tGravityAcc.mean.Z
tBodyAcc.mean.X
tBodyAcc.mean.Y
tBodyAcc.mean.Z
tBodyGyro.mean.X
tBodyGyro.mean.Y
tBodyGyro.mean.Z
tBodyAccJerk.mean.X
tBodyAccJerk.mean.Y
tBodyAccJerk.mean.Z
tBodyGyroJerk.mean.X
tBodyGyroJerk.mean.Y
tBodyGyroJerk.mean.Z
fBodyAcc.mean.X
fBodyAcc.mean.Y
fBodyAcc.mean.Z
fBodyGyro.mean.X
fBodyGyro.mean.Y
fBodyGyro.mean.Z
fBodyAccJerk.mean.X
fBodyAccJerk.mean.Y
fBodyAccJerk.mean.Z
tGravityAccMag.mean
tBodyAccMag.mean
tBodyAccJerkMag.mean
tBodyGryoMag.mean
tBodyGyroJerkMag.mean
tGravityAcc.mean.X
tGravityAcc.mean.Y
tGravityAcc.mean.Z
tBodyAcc.mean.X
tBodyAcc.mean.Y
tBodyAcc.mean.Z
tBodyGyro.mean.X
tBodyGyro.mean.Y
tBodyGyro.mean.Z
tBodyAccJerk.mean.X
tBodyAccJerk.mean.Y
tBodyAccJerk.mean.Z
tBodyGyroJerk.mean.X
tBodyGyroJerk.mean.Y
tBodyGyroJerk.mean.Z
fBodyAcc.mean.X
fBodyAcc.mean.Y
fBodyAcc.mean.Z
fBodyGyro.mean.X
fBodyGyro.mean.Y
fBodyGyro.mean.Z
fBodyAccJerk.mean.X
fBodyAccJerk.mean.Y
fBodyAccJerk.mean.Z
tGravityAccMag.mean
tBodyAccMag.mean
tBodyAccJerkMag.mean
tBodyGryoMag.mean
tBodyGyroJerkMag.mean
<file_sep>GettingAndCleaningDataProject
=============================
Files:
======
- README.md - this file
- CodeBook.md - file describing variables, data, and transformations performed on original data set to create tidy data set
- run_analysis.R - R script used to create produce tidy data
Description of run_analysis.R:
==============================
+Reads the following input files
Labels:
- activity_labels.txt : labels associated with the 6 activities
- features.txt : labels associated with the 561 extracted features
Training Set (7352 observations):
- subject_train.txt : subject ID
- Y_train.txt : activity ID
- X_train.txt : extracted features
Test Set (2947 observations):
- subject_test.txt : subject ID
- Y_test.txt : activity ID
- X_test.txt : extracted features
+Clean-Up:
- activity IDs converted to activity labels
- extracted features named using feature labels
+Merging Data:
- training set combined in to a single data set (7352 observations on 563 variables)
- test set combined in to a single data set (2947 observations on 563 variables)
- training and test sets combined in to a single data set (10299 observations on 563 vaiables)
+Extracting 1st Tidy Data Set
- Extracted only the mean and standard deviation features (66 of the original 561 features). This data set contains 10299 obsevations on 68 variables
+Producing 2nd Tiny Data Set
- Calculate the mean for each combination of (subject ID, activity, and extracted feature)
- Write this out to a text file for upload
|
2f6bea61a0efe503c001fd5fe0b7b8d104da2ef1
|
[
"Markdown",
"R"
] | 3
|
R
|
segordon65/GettingAndCleaningDataProject
|
87c9ae9498d8da15ebf64f299d30179445be7687
|
eabf72025a3278a3e14f7d20d95bdf3bda78f47b
|
refs/heads/master
|
<file_sep>import { degreesToRad } from '../helpers/physicsHelpers';
const config = {
canvasWidth: 1200,
canvasHeight: 800,
defaultPower: 50, // percent
defaultTorque: 2, // newton meters
rotationalInertia: 0.00099117285, // kg m²
motor: {
defaultPosition: { x: -150, y: 50, z: 0 },
},
axle: {
defaultPosition: { x: 0, y: 50, z: 0 },
},
pivot: {
angularDecel: -500, // radians per second²
defaultMaxSpeed: 20, // radians per second
defaultPosition: { x: 0, y: 50, z: 0 }, // mm
defaultStartingAngle: degreesToRad(75),
defaultEndingAngle: degreesToRad(120),
},
arm: {
defaultPosition: { x: 10, y: 70, z: 0 }, // mm
},
ball: {
defaultPosition: { x: 15, y: 92.5, z: 0 }, // mm
},
target: {
defaultPosition: { x: 0, y: 200, z: -800 }, // mm
},
camera: {
fov: 40,
nearClipping: 1,
farClipping: 10000,
defaultPosition: { x: 0, y: 600, z: 1200 }, // mm
},
gridHelper: {
size: 5000,
divisions: 50,
}
};
config.camera.aspectRatio = config.canvasWidth / config.canvasHeight;
export default config;
<file_sep>import * as THREE from 'three';
import aluminum from '../images/4kAluminum2.jpg';
import { degreesToRad } from '../helpers/physicsHelpers';
class Axle {
constructor(
{
loader,
position: { x, y, z }
}
) {
this.geometry = new THREE.CylinderGeometry( 6, 6, 20, 32 );
this.material = new THREE.MeshBasicMaterial({
map: loader.load(aluminum),
color: '#7363CC'
});
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.mesh.rotation.z = degreesToRad(90);
this.mesh.position.set( x, y, z );
}
get = () => this.mesh
}
export default Axle;
<file_sep>const degreesToRad = (d) => d * Math.PI / 180;
const radToDegrees = (r) => r * 180 / Math.PI;
const getAngularVelocity = ({ dTheta, dt }) => dTheta / dt;
const getLinearVelocityFromAngularVelocity = ({ w, r }) => r * w;
export {
degreesToRad,
radToDegrees,
getAngularVelocity,
getLinearVelocityFromAngularVelocity
};<file_sep>import * as THREE from 'three';
import steel from '../images/4kSteel.jpeg';
class Ball {
constructor(
{
loader,
position: { x, y, z }
}
) {
this.geometry = new THREE.SphereGeometry( 7.5, 32, 32 );
this.material = new THREE.MeshBasicMaterial({
map: loader.load(steel),
color: '#b9ff21'
});
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.mesh.position.set( x, y, z );
}
get = () => this.mesh
calculateSpeed = () => {}
calculatePosition = () => {}
}
export default Ball;
<file_sep>import * as THREE from 'three';
import { OrbitControls } from '../utils/OrbitControls';
import Motor from '../meshes/Motor';
import Axle from '../meshes/Axle';
import Pivot from '../meshes/Pivot';
import Arm from '../meshes/Arm';
import Ball from '../meshes/Ball';
import Target from '../meshes/Target';
import GridHelper from '../meshes/GridHelper';
class Simulator {
constructor(config) {
this.config = config;
this.init();
}
init = () => {
this.isLiveMode = false;
this.isAnimated = true;
this.isLaunched = false;
this.power = this.config.defaultPower; // percent
this.torque = this.config.defaultTorque;
this.isMotorStarted = false;
// set up scene
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(
this.config.camera.fov,
this.config.camera.aspectRatio,
this.config.camera.nearClipping,
this.config.camera.farClipping
);
this.loader = new THREE.TextureLoader();
this.renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('#canvas'), antialias: true });
this.controls = new OrbitControls( this.camera, this.renderer.domElement );
// build meshes
this.pivot = new Pivot({
position: this.config.pivot.defaultPosition,
angularAccel: this.torque / this.config.rotationalInertia,
angularDecel: this.config.pivot.angularDecel,
maxSpeed: this.config.pivot.defaultMaxSpeed,
defaultStartingAngle: this.config.pivot.defaultStartingAngle,
isLiveMode: false,
});
this.motor = new Motor({
loader: this.loader,
position: this.config.motor.defaultPosition,
});
this.axle = new Axle({
loader: this.loader,
position: this.config.axle.defaultPosition,
});
this.arm = new Arm({
loader: this.loader,
position: this.config.arm.defaultPosition,
});
this.ball = new Ball({
loader: this.loader,
position: this.config.ball.defaultPosition,
});
this.target = new Target({
loader: this.loader,
position: this.config.target.defaultPosition,
});
this.gridHelper = new GridHelper({
size: this.config.gridHelper.size,
divisions: this.config.gridHelper.divisions,
});
const { x, y, z } = this.config.camera.defaultPosition;
this.camera.position.set( x, y, z );
// add meshes to scene
this.scene.add( this.motor.get() );
this.scene.add( this.axle.get() );
this.pivot.add( this.arm.get() );
this.arm.add( this.ball.get() );
this.scene.add( this.pivot.get() );
this.scene.add( this.target.get() );
this.scene.add( this.gridHelper.get() );
console.log('scene', this.scene)
this.animate();
console.log('setup complete')
}
animate = () => {
if(!this.isAnimated) return;
const dt = this.clock?.getDelta() ?? 0;
this.pivot.calculateRotation({
dt,
isMotorStarted: this.isMotorStarted,
power: this.power,
});
if(this.isLaunched) {
// calculate angular velocity -> linear velocity
this.ball.get().position.x += 3400 * dt * this.power / 100;
this.ball.get().position.y -= 1; // HOW TO ADD GRAVITY?
}
this.controls.update();
this.renderer.render( this.scene, this.camera );
requestAnimationFrame( this.animate );
}
startMotor = () => {
this.clock = new THREE.Clock();
this.isMotorStarted = true;
}
stopMotor = () => {
this.clock = new THREE.Clock();
this.isMotorStarted = false;
}
fire = () => {
this.isMotorStarted = false;
this.isLaunched = true;
}
stopAnimation = () => {
this.isAnimated = false;
}
resetScene = () => {
this.init();
}
setStartingAngle = (radians) => this.pivot?.setRotation(radians)
setEndingAngle = (radians) => this.pivot?.setEndingAngle(radians)
setPower = (power) => this.power = power;
setMaxTorque = (torque) => {
this.torque = torque;
this.pivot?.setAngularAccel(torque / this.config.rotationalInertia);
}
setMaxSpeed = (maxSpeed) => this.pivot?.setMaxSpeed(maxSpeed)
setIsLiveMode = (val) => this.pivot.setIsLiveMode(val)
runSimulation = () => {
this.startMotor();
}
}
export default Simulator;
<file_sep>import React, { useEffect, useState } from 'react';
import Header from './components/Header';
import ControlPanel from './components/ControlPanel';
import Simulator from './simulator/Simulator';
import config from './utils/config';
import 'semantic-ui-css/semantic.min.css';
import './App.css';
const App = () => {
const [simulator, setSimulator] = useState();
useEffect(() => {
console.log('set simulator')
setSimulator(new Simulator(config));
}, []);
const onContextMenu = (e) => {
e.preventDefault();
};
return (
<div className="app">
<Header />
<div style={{ position: 'relative', width: config.canvasWidth, height: config.canvasHeight }}>
<canvas width={config.canvasWidth} height={config.canvasHeight} onContextMenu={onContextMenu} id="canvas" />
<ControlPanel
stopAnimation={simulator?.stopAnimation}
startMotor={simulator?.startMotor}
stopMotor={simulator?.stopMotor}
isMotorStarted={simulator?.isMotorStarted}
fire={simulator?.fire}
resetScene={simulator?.resetScene}
setSimPower={simulator?.setPower}
setMaxTorque={simulator?.setMaxTorque}
setMaxSpeed={simulator?.setMaxSpeed}
setStartingAngle={simulator?.setStartingAngle}
setEndingAngle={simulator?.setEndingAngle}
setIsLiveMode={simulator?.setIsLiveMode}
runSimulation={simulator?.runSimulation}
config={config}
/>
</div>
</div>
);
}
export default App;
<file_sep>import * as THREE from 'three';
import aluminum from '../images/4kAluminum2.jpg';
import { degreesToRad } from '../helpers/physicsHelpers';
class Arm {
constructor(
{
loader,
position: { x, y, z },
}
) {
this.geometry = new THREE.CylinderGeometry( 7.5, 7.5, 200, 32 );
this.material = new THREE.MeshBasicMaterial({
map: loader.load(aluminum),
color: '#736337'
});
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.mesh.position.set( x, y, z );
this.mesh.rotation.y = degreesToRad(90);
}
get = () => this.mesh
add = (obj) => this.mesh.add(obj)
}
export default Arm;
<file_sep>import * as THREE from 'three';
class GridHelper {
constructor(
{
size,
divisions
}
) {
this.mesh = new THREE.GridHelper( size, divisions );
}
get = () => this.mesh
}
export default GridHelper;
<file_sep># Getting Started with Standard Bots Simulator
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
Run `yarn` and then `yarn start`.
## Goals
-Assist the Software team in modeling out launch distances as a function of the following factors: starting position, release position, and motor torque.<br>
-Assist the Hardware team in choosing the right motor for the launcher by testing various possibilities for the motor’s torque and maximum speed and simulating how these values affect the ball’s maximum travel distance.<br>
## Features
-Can use Live mode to manually activate motor, set power level, and launch ball (ball launch not fully implemented)<br>
-Can use Off-air mode to run a set simulation (ball launch not implemented)<br>
-Can use standard 3D camera movement (left and right click and drag, mousewheel to zoom in and out)<br>
### Future features:
-Save and load a set of data inputs<br>
-Save and load various scenarios<br>
-Data visualization of trajectory and speed<br>
-Plot ball trajectory without having to run simulation<br>
-Input how far you want it to go and it will calculate different scenarios on how to get there<br>
## 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 test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `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.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.<file_sep>import React, { useState } from 'react';
import { Button } from 'semantic-ui-react';
import { degreesToRad, radToDegrees } from '../helpers/physicsHelpers';
import './ControlPanel.css';
const ControlPanel = ({
stopAnimation,
startMotor,
stopMotor,
isMotorStarted,
fire,
resetScene,
setSimPower,
setMaxTorque,
setMaxSpeed,
setStartingAngle,
setEndingAngle,
setIsLiveMode,
runSimulation,
config,
}) => {
const [liveMode, setLiveMode] = useState(false);
const [power, setPower] = useState(config.defaultPower);
const [prevPower, setPrevPower] = useState(config.defaultPower);
const [motorStarted, setMotorStarted] = useState(false);
const [torque, setTorque] = useState(config.defaultTorque);
const [speed, setSpeed] = useState(config.pivot.defaultMaxSpeed);
const [startAngle, setStartAngle] = useState(radToDegrees(config.pivot.defaultStartingAngle));
const [endAngle, setEndAngle] = useState(radToDegrees(config.pivot.defaultEndingAngle));
const handleMotorStart = () => {
if(motorStarted) {
setMotorStarted(false);
stopMotor();
} else {
setMotorStarted(true);
startMotor();
}
}
const handleSetLiveMode = () => {
if(liveMode) {
// save power setting so we can come back to it
setPrevPower(power);
// set to max power for non live mode
setPower(100);
setIsLiveMode(false);
} else {
// set power back to previous level
setPower(prevPower);
setIsLiveMode(true);
}
setLiveMode(prevVal => !prevVal);
}
const handlePowerChange = (e) => {
setPower(e.target.value);
setSimPower(e.target.value);
}
const handleTorqueChange = (e) => {
setTorque(e.target.value);
setMaxTorque(e.target.value);
}
const handleSpeedChange = (e) => {
setSpeed(e.target.value);
setMaxSpeed(e.target.value);
}
const handleStartAngleChange = (e) => {
const { value } = e.target;
setStartAngle(value);
setStartingAngle(degreesToRad(value));
}
const handleEndAngleChange = (e) => {
const { value } = e.target;
setEndAngle(value);
setEndingAngle(degreesToRad(value));
}
const handleReset = () => {
resetScene();
setLiveMode(false);
setPower(config.defaultPower);
setMotorStarted(config.false);
setTorque(config.defaultTorque);
setSpeed(config.pivot.defaultMaxSpeed);
setStartAngle(radToDegrees(config.pivot.defaultStartingAngle));
setEndAngle(radToDegrees(config.pivot.defaultEndingAngle));
}
return(
<div className="control-panel">
{liveMode &&
<div className="live-mode-panel">
<div className="live-mode-container">
<Button className="margin-right" onClick={handleMotorStart}>
{motorStarted ? 'Stop motor' : 'Start motor'}
</Button>
<Button className="margin-right" onClick={fire}>Fire</Button>
<Button className="margin-right" onClick={handleReset}>Reset</Button>
<div className="power-level-panel">
<label>Power level: {power}%</label>
<div className="power-level-slider">
<input id="powerLevel" type="range" min="1" max="100" value={power} onChange={handlePowerChange}/>
</div>
</div>
</div>
</div>
}
{!liveMode &&
<div className="off-air-mode-panel">
<div className="off-air-mode-input">
<label className="off-air-mode-label">Max torque</label>
<input type="number" label="test" value={torque} onChange={handleTorqueChange} />
</div>
<div className="off-air-mode-input">
<label className="off-air-mode-label">Max speed</label>
<input type="number" label="test" value={speed} onChange={handleSpeedChange} />
</div>
<div className="off-air-mode-input">
<label className="off-air-mode-label">Starting Angle</label>
<input type="number" label="test" value={startAngle} onChange={handleStartAngleChange} />
</div>
<div className="off-air-mode-input">
<label className="off-air-mode-label">Release Angle</label>
<input type="number" label="test" value={endAngle} onChange={handleEndAngleChange} />
</div>
<div className="off-air-mode-run-button">
<Button color="teal" onClick={runSimulation}>Run</Button>
<Button className="margin-right" onClick={handleReset}>Reset</Button>
</div>
</div>
}
<div className="live-mode-button">
<Button
onClick={handleSetLiveMode}
color={liveMode ? 'red' : 'green'}
>
{liveMode ? 'Go off-air' : 'Do it live!'}
</Button>
</div>
<Button className="stop-animation-button" onClick={stopAnimation} color="red">Stop animation</Button>
</div>
);
}
export default ControlPanel;
|
51dad7c030ad6181c403706c52ceeab14bd00d12
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
eseakin/standardbots
|
e487d92c766d71fc4f588cefad237ad5eaac6fab
|
57cb60eea9a75db2cc6ea45d141e743f353e359d
|
refs/heads/master
|
<repo_name>Boshen/kata<file_sep>/timus/P636.cpp
#include <iostream>
using namespace std;
int main(){
int t1, t2, n;
int c = 0;
cin >> t1 >> t2;
for(int i=0;i<10;i++){
cin >> n;
c+=(n*20);
}
t2-=c;
cout << (t2<t1 ? "Dirty debug :(" : "No chance.") << endl;
return 0;
}
<file_sep>/timus/1119.py
import heapq as hq
import math
N, M = map(int, raw_input().split())
K = int(raw_input())
diags = {}
for i in xrange(K):
x, y = map(int, raw_input().split())
diags[(x-1,y-1)] = 1
q = []
hq.heappush(q, (0.0, 0, 0))
dists = [ [1e9 for i in xrange(N+1)] for j in xrange(M+1)]
dists[0][0] = 0
dist = lambda x1, x2, y1, y2: math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
while q:
(d, x, y) = hq.heappop(q)
dxy = dists[y][x]
if x == N and y == M:
print int((dxy*100)+0.5)
break
if (x, y) in diags:
edges = [ (x+1,y), (x,y+1), (x+1,y+1) ]
else:
edges = [ (x+1,y), (x,y+1)]
for n, m in edges:
if n <= N and m <= M:
newd = dist(x, n, y, m) + dxy
if newd < dists[m][n]:
dists[m][n] = newd
hq.heappush(q, (newd+dist(n,N,m,M), n, m))
<file_sep>/timus/P820.cpp
#include <iostream>
using namespace std;
int main(){
int n, k;
cin >> n >> k;
if(n<=k){
cout << 2 << endl;
}else{
cout << ((2*n)%k==0 ? (2*n)/k : (2*n)/k+1) << endl;
}
return 0;
}
<file_sep>/timus/P493.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
int func(void);
void func2(void);
int a[6];
int n;
int main(){
cin >> n;
if(n==999999 || n==0){
cout << "Yes" << endl;
return 0;
}
int orig = n;
n = orig+1;
func2();
if(func()){cout << "Yes" << endl;return 0;}
n = orig-1;
func2();
if(func()) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
int func(void){
return (a[0]+a[1]+a[2])==(a[3]+a[4]+a[5]);
}
void func2(void){
int i=5;
while(n!=0){
a[i] = n%10;
n/=10;
i--;
}
}
<file_sep>/timus/P787.cpp
#include <iostream>
using namespace std;
int main(){
int n, k;
int tmp;
int a[100];
a[0]=0;
cin >> n >> k;
for(int i=0;i<k;i++){
cin >> tmp;
a[i] = (tmp+a[i]-n)<0 ? 0 : tmp-n+a[i];
a[i+1] = a[i];
}
cout << a[k] << endl;
return 0;
}
<file_sep>/timus/P563.cpp
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main(){
int N;
cin >> N;
set<string> v;
string s;
cin.ignore();
while(getline(cin,s)){
//cout << s << endl;
v.insert(s);
}
//for(set<string>::iterator it=v.begin();it!=v.end();it++){
// cout << *it << endl;
//}
cout << N-v.size();
return 0;
}
<file_sep>/timus/P306.cpp
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
priority_queue<unsigned int> A;
int main(){
int n;
cin >> n;
unsigned int t;
int i;
for(i=0;i<=n/2;i++){
cin >> t;
A.push(t);
}
i=n/2+2;
while(i<=n){
cin >> t;
A.push(t);
i++;
A.pop();
}
cout.setf(ios::fixed);
cout.precision(1);
if(n%2==0){
t = A.top();
A.pop();
t += A.top();
cout << t/2.0 << endl;
}else{
cout << A.top() <<endl;
}
return 0;
}
<file_sep>/timus/P712.cpp
#include <iostream>
using namespace std;
void rot(int grid[4][4]){
int grid2[4][4];
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
grid2[i][j]=grid[i][j];
int m=0,n=0;
for(int i=0;i<4;i++){
n=0;
for(int j=3;j>=0;j--){
grid[m][n]=grid2[j][i];
n++;
}
m++;
}
}
int main(){
int grid[4][4];
char c;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
cin >> c;
grid[i][j] = (c=='X'?1:0);
}
}
char pw[4][4];
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
cin >> c;
pw[i][j] = c;
}
}
for(int k=0;k<4;k++){
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(grid[i][j]==1){
cout << pw[i][j];
}
}
}
rot(grid);
}
cout << endl;
return 0;
}
<file_sep>/timus/1935.py
n = raw_input()
l = map(int, raw_input().split())
print max(l) + sum(l)
<file_sep>/timus/P1.cpp
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
double a[128*1024];
int main(void){
int n = 0;
double x;
while(cin>>x){
a[n] = sqrt(x);
n++;
}
while(n){
printf("%.4lf\n", a[--n]);
}
return 0;
}
<file_sep>/euler/README.md
Project Euler
=============
using scala + functional programming
Problems that I have no idea how to solve so far
------------------------------------------------
* 26
* 40
* 47
<file_sep>/timus/P079.cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
int main(){
int N;
while( cin >> N){
if(N==0)break;
vector<int> v(N*2+1,0);
v[0]=0;
v[1]=1;
for(int i=1;i<=N;i++){
v[2*i]=v[i];
v[2*i+1]=v[i]+v[i+1];
}
sort(v.begin(),v.begin()+N+1,greater<int>());
cout << v[0] << endl;
}
return 0;
}
<file_sep>/timus/P243.cpp
#include <cstdio>
int main(){
char c;
char r;
while(scanf(" %c",&c)!=EOF||(printf("%d\n",r)&0))
r = (r*10+c-'0')%7;
return 0;
}
<file_sep>/timus/1910.py
N = int(raw_input())
line = map(int, raw_input().split())
maxx = 0
index = 0
for i in range(1, N-1):
s = line[i]+line[i-1]+line[i+1]
if s > maxx:
maxx = s
index = i
print maxx, index+1
<file_sep>/timus/1893.py
import re
s = raw_input()
r = re.compile("([0-9]+)([a-zA-Z]+)")
m = r.match(s)
n = int(m.group(1))
s = m.group(2)
if n <= 2:
if s in 'AD':
print 'window'
else:
print 'aisle'
elif n <= 20:
if s in 'AF':
print 'window'
else:
print 'aisle'
else:
if s in 'AK':
print 'window'
elif s in 'CDGH':
print 'aisle'
else:
print 'neither'
<file_sep>/timus/P149.cpp
#include <iostream>
#include <string>
using namespace std;
void An(int n){
for(int i=1;i<n;i++)
cout << "sin(" << i << (i%2==0?"+":"-");
cout << "sin(" << n;
for(int i=1;i<=n;i++)
cout << ")";
}
void Sn(int n){
for(int i=1;i<n;i++)
cout << "(";
for(int i=1;i<n;i++){
An(i);
cout << "+" << n-i+1 << ")";
}
An(n);
cout << "+1";
}
int main(){
int N;
cin >> N;
Sn(N);
cout << endl;
return 0;
}
<file_sep>/timus/P723.cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
vector<int> v(26,0);
string s;
cin >> s;
for(size_t i=0;i<s.length();i++){
v[s[i]-'a']++;
}
int max=0;
int k;
for(int i=0;i<26;i++){
if(v[i]>max){
k=i;
max=v[i];
}
}
cout << ((char)(k+'a')) << endl;
}
<file_sep>/codewars-rust/Makefile
start:
cargo watch -c -x test
<file_sep>/timus/1005.py
n = int(raw_input())
w = map(int, raw_input().split())
summ = sum(w)
result = summ
def dp(index, current):
global result
global summ
if index == n:
if abs(2*current-summ) < result:
result = abs(2*current-summ)
else:
dp(index+1, current)
dp(index+1, current+w[index])
dp(0, 0)
print result
<file_sep>/timus/P313.cpp
#include <iostream>
#include <queue>
using namespace std;
queue<int> a[101];
int main(){
int n, t;
cin >> n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin >> t;
a[i].push(t);
}
}
for(int i=0;i<n;i++){
for(int j=i;j>=0;j--){
cout << a[j].front() << " ";
a[j].pop();
}
}
for(int i=n-1;i>0;i--){
for(int j=n-1;j>=n-i;j--){
//cout << j << endl;
cout << a[j].front() << " ";
a[j].pop();
}
}
return 0;
}
<file_sep>/timus/1786.py
import sys
import gc
gc.disable()
s = sys.stdin.readline()
ans = 1000
sandro = 'Sandro'
for i in xrange(len(s)-6):
cost = 0
for j in xrange(6):
if s[i+j] == sandro[j]:
continue
cost += 5
if j == 0 and s[i+j].islower() and s[i+j].upper() != sandro[j]:
cost += 5
if j > 0 and s[i+j].isupper() and s[i+j].lower() != sandro[j]:
cost += 5
ans = min(ans, cost)
print ans
<file_sep>/timus/P617.cpp
#include <iostream>
#include <map>
using namespace std;
int main(){
int N;
cin >> N;
map<int,int> v;
int tmp;
for(int i=0;i<N;i++){
cin >> tmp;
if(!v.count(tmp)){
v.insert(pair<int,int>(tmp,1));
}else{
v[tmp]++;
}
}
int sum=0;
for(map<int,int>::iterator it=v.begin();it!=v.end();it++){
sum+= (it->second)/4;
}
cout << sum << endl;
}
<file_sep>/timus/P196.cpp
#include <iostream>
#include <set>
#include <map>
using namespace std;
int main(){
long long N,M;
cin >> N;
long tmp;
set<long long> v;
for(int i=0;i<N;i++){
cin >> tmp;
v.insert(tmp);
}
cin >> M;
map<long long,long long> s;
for(int i=0;i<M;i++){
cin >> tmp;
if(s.count(tmp)){
s[tmp]++;
}else{
s.insert(pair<long long ,long long>(tmp,1));
}
}
int total=0;
for(set<long long>::iterator it=v.begin();it!=v.end();it++){
if(s.count(*it)){
total+=s[*it];
}
}
cout << total << endl;
//for(map<int,int>::iterator it = s.begin();it!=s.end();it++){
// cout << it->first << " " << it->second << endl;
//}
return 0;
}
<file_sep>/timus/P014.cpp
#include <iostream>
#include <vector>
using namespace std;
int next(unsigned long int n){
for(unsigned long int i=9;i>1;i--){
if(n%i==0&&(n/i>9?next(n/i):i+=n/i*10)){
cout << i;
return 1;
}
}
return 0;
}
int main(){
unsigned long int n;
cin >> n;
if (n<10)
cout << (n==0?10:n);
else
if(!next(n))
cout << -1;
return 0;
}
<file_sep>/timus/1731.py
n, m = map(int, raw_input().split())
print ' '.join(map(str,range(1, n+1)))
print ' '.join(map(str,[1+i*n for i in range(1, m+1)]))
<file_sep>/timus/1370.py
import sys
N, M = map(int, raw_input().split())
l = map(int, sys.stdin.readlines())
for i in xrange(10):
sys.stdout.write(str(l[(i+M)%N]))
print
<file_sep>/timus/P073.cpp
#include <iostream>
#include <cmath>
using namespace std;
int data[401];
int main() {
int n;
cin>>n;
data[1]=1;
data[2]=2;
for (int i=3;i<=n;++i) {
int min=data[i-1]+1;
for (int j=2;j<=20;++j) {
if (i>=j*j) {
if (min>data[i-j*j]+1) min=data[i-j*j]+1;
}
else break;
}
data[i]=min;
}
for(int i=0;i<401;i++){
cout << data[i] <<endl;
}
return 0;
}
<file_sep>/timus/P126.cpp
#include <iostream>
#include <algorithm>
using namespace std;
int a[25000];
int main(){
int n;
cin >> n;
long i=0;
while(true){
cin >> a[i];
if(a[i]==-1)break;
i++;
}
for(long j=n-1;j<i;j++){
cout << *max_element(a+j+1-n,a+j+1) << endl;
}
return 0;
}
<file_sep>/timus/P263.cpp
#include <iostream>
#include <vector>
using namespace std;
int main(){
int N, M;
int tmp;
cin >> N;
cin >> M;
vector<int> v(N+1);
for(int i=0; i<M;i++){
cin >> tmp;
v[tmp]++;
}
cout.setf(ios::fixed);
cout.precision(2);
for(int i=1; i<=N;i++){
cout << 100*v[i]/double(M) << "%" << endl;
}
return 0;
}
<file_sep>/timus/P255.cpp
#include <iostream>
using namespace std;
int main(){
int n, t;
cin >> n;
long u =0;
long v=1;
for(int i=0;i<n-1;i++){
t = u + v;
u = v;
v = t;
}
cout << (v*2)<<endl;
return 0;
}
<file_sep>/timus/1446.py
import sys
import gc
gc.disable()
N = int(sys.stdin.readline())
Sl = []
Hu = []
Gr = []
Ra = []
for i in xrange(N):
name = sys.stdin.readline()
house = sys.stdin.readline()
if house[0:2] == 'Sl':
Sl.append(name)
if house[0:2] == 'Hu':
Hu.append(name)
if house[0:2] == 'Gr':
Gr.append(name)
if house[0:2] == 'Ra':
Ra.append(name)
print 'Slytherin:'
print ''.join(Sl)
print 'Hufflepuff:'
print ''.join(Hu)
print 'Gryffindor:'
print ''.join(Gr)
print 'Ravenclaw:'
print ''.join(Ra)
<file_sep>/timus/1494.py
import gc
import sys
gc.disable()
N = int(sys.stdin.readline())
inspects = map(int, sys.stdin.readlines())
inspect = 0
pocket = []
for i in xrange(1, N+1):
pocket.append(i)
while pocket and pocket[-1] == inspects[inspect]:
pocket.pop()
inspect += 1
print 'Cheater' if pocket else 'Not a proof'
<file_sep>/timus/P9.cpp
#include <iostream>
using namespace std;
long a[10000];
//int foo(int n, int k){
// if(n==0) return 1;
// if(n==1) return k-1;
// return (k-1)*(foo(n-1,k)+foo(n-2,k));
//}
int main(){
int n, k;
cin >> n >> k;
a[0] = 1;
a[1] = k-1;
for(int i=2;i<=n;i++){
a[i] = (k-1)*(a[i-1]+a[i-2]);
}
cout << a[n] << endl;
//cout << foo(n, k) << endl;
return 0;
}
<file_sep>/timus/1180.py
import sys
c = int(sys.stdin.readline())
s = c % 3
print 1 if s else 2
if s:
print s
<file_sep>/timus/1642.py
n, x = map(int, raw_input().split())
obs = map(int, raw_input().split())
x1 = -1000
x2 = 1000
for i in obs:
if i < 0:
x1 = max(x1, i)
if i > 0:
x2 = min(x2, i)
if x1 < x < x2:
if x > 0:
print x, x-2*x1
else:
print 2*x2-x, -x
else:
print 'Impossible'
<file_sep>/timus/1036.py
from itertools import *
print list(combinations_with_replacement(range(50), 50))
<file_sep>/timus/1017.py
N = int(raw_input())
q = [0]*(N+1)
q[0] = 1
for i in range(1, N+1):
for j in range(N, i-1, -1):
q[j] += q[j-i]
print q[N]-1
<file_sep>/timus/1777.py
def difference(l):
ans = float('inf')
for i, x in enumerate(l):
for j, y in enumerate(l):
if i == j:
break
diff = abs(x-y)
if diff < ans:
ans = diff
return ans
l = map(int, raw_input().split())
ans = 0
while True:
diff = difference(l)
l.append(diff)
ans += 1
if diff == 0:
break
print ans
<file_sep>/timus/P581.cpp
#include <iostream>
using namespace std;
int a[1001];
int main(){
int n;
cin >> n;
for(int i = 0;i<n;i++){
cin >> a[i];
}
int count = 1;
for(int i = 0;i<n;i++){
if(a[i]==a[i+1])
count++;
if(a[i]!=a[i+1]){
cout << count << " " << (a[i]) << " ";
count = 1;
}
}
cout << endl;
return 0;
}
<file_sep>/timus/P255.py
n= 5
for i in range(n):
u = 0
v = 1
for i in range(1, n):
t = u+v
u = v
v = t
print v*2
<file_sep>/timus/1671.py
import sys
import gc
gc.disable()
class Node:
def __init__(self):
self.parent = None
self.rank = 0
class Edge:
def __init__(self, fr, to):
self.fr = fr
self.to = to
self.isInQ = False
class UnionFind:
def __init__(self, size):
self.connectedComponentsCount = size
self.roots = {}
def find_root(self, node):
while node != node.parent:
node = node.parent
return node.parent
def union(self, node1, node2):
self.connectedComponentsCount -= 1
if node1.rank > node2.rank:
node2.parent = node1
else:
node1.parent = node2
if node1.rank == node2.rank:
node2.rank += 1
def process(self, edge):
fromRoot = self.find_root(edge.fr)
toRoot = self.find_root(edge.to)
if fromRoot != toRoot:
self.union(fromRoot, toRoot)
N, M = map(int, sys.stdin.readline().split())
nodes = []
for i in range(N):
nodes.append(Node())
nodes[-1].parent = nodes[-1]
edges = []
for i in range(M):
fr, to = map(int, sys.stdin.readline().split())
edges.append(Edge(nodes[fr-1], nodes[to-1]))
Q = int(sys.stdin.readline())
removes = map(int, sys.stdin.readline().split())
qedges = []
qedges = [edges[remove-1] for remove in removes]
for qedge in qedges:
qedge.isInQ = True
uf = UnionFind(N)
for edge in edges:
if not edge.isInQ:
uf.process(edge)
result = []
for qedge in reversed(qedges):
result.append(uf.connectedComponentsCount)
uf.process(qedge)
for r in reversed(result):
sys.stdout.write(str(r) + " ")
sys.stdout.write('\n')
<file_sep>/timus/1457.py
N = float(raw_input())
print '%.6f' % (sum(map(float, raw_input().split()))/N)
<file_sep>/timus/1902.py
n, t, s = map(int, raw_input().split())
y = map(int, raw_input().split())
for x in y:
if x >= s:
print '%.6f' % (x + (t-(x-s))/2.0)
else:
print '%.6f' % (s + (t-(s-x))/2.0)
<file_sep>/timus/P048.cpp
#include <vector>
#include <cstdio>
using namespace std;
vector<char> v1;
vector<char> v2;
int main(){
int N;
scanf("%d", &N);
for(int i=0;i<N;i++){
char c;
scanf("\n%c ",&c);
v1.push_back(c);
scanf("%c",&c);
v2.push_back(c);
}
int carry=0;
int sum;
for(int i=N-1;i>=0;i--){
sum = (v1[i]-'0')+(v2[i]-'0');
v1[i]=(sum+carry)%10;
carry = (sum+carry)/10;
}
if(carry!=0){
printf("%d",carry);
}
for(int i=0;i<N;i++){
printf("%c",v1[i]+'0');
}
puts("");
return 0;
}
<file_sep>/timus/1837.py
import sys
import gc
import heapq
gc.disable()
n = int(raw_input())
teams = []
names = set()
for i in xrange(n):
name = sys.stdin.readline().split()
teams.append(set(name))
for s in name:
names.add(s)
hq = [(0, 'Isenbaev')]
mp = {}
while hq:
d, name = heapq.heappop(hq)
if name in mp:
continue
mp[name] = d
for i in xrange(n):
if name in teams[i]:
for s in teams[i]:
if s != name:
heapq.heappush(hq, (d+1, s))
for name in sorted(names):
print name,
if name in mp:
print mp[name]
else:
print 'undefined'
<file_sep>/timus/1290.py
l = []
N = int(raw_input())
for i in xrange(N):
l.append(int(raw_input()))
l = sorted(l, reverse=True)
print '\n'.join(map(str,l)),
<file_sep>/timus/P319.cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main(){
int N;
cin >> N;
vector<queue<int> > v(N*2-1, queue<int>());
//for(int i=0;i<N*2-1;i++){
// for(int j=0;j<N;j++){
// v[i][j] = 0;
// }
//}
int t=1;
for(int i=0;i<N;i++){
for(int j=0;j<=i;j++){
v[i].push(t);
t++;
}
}
for(int i=N;i<N*2-1;i++){
for(int j=0;j<N*2-i-1;j++){
v[i].push(t);
t++;
}
}
int row=N-1;
for(int i=0;i<N;i++){
for(;row>=i;row--){
cout << v[row].front();
v[row].pop();
if(row!=i)cout<<" ";
}
row+=N+1;
cout << endl;
}
return 0;
}
<file_sep>/timus/1414.py
class Node:
def __init__(self):
self.childs = {}
self.word_marker = False
def add_item(self, string):
if not len(string):
self.word_marker = True
return
key = string[0]
string = string[1:]
if key in self.childs:
self.childs[key].add_item(string)
else:
node = Node()
self.childs[key] = node
node.add_item(string)
def dfs(self, sofar=None):
if not self.childs:
print ' ' + sofar
return
if self.word_marker:
print ' ' + sofar
for key in sorted(self.childs.keys()):
self.childs[key].dfs(sofar+key)
def search(self, string, sofar=""):
if len(string):
key = string[0]
string = string[1:]
if key in self.childs:
self.childs[key].search(string, sofar + key)
else:
if self.word_marker == True:
print ' ' + sofar
for key in sorted(self.childs.keys()):
self.childs[key].dfs(sofar+key)
root = Node()
while True:
try:
command = raw_input().strip()
except:
break
key = command[0]
string = command[1:]
if key == '?':
print string
root.search(string)
else:
root.add_item(string)
<file_sep>/timus/1139.py
import fractions
N, M = map(int, raw_input().split())
N -= 1
M -= 1
a = fractions.gcd(N,M)
if a == 1:
print N+M-1
else:
print N+M-a
<file_sep>/timus/P349.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int n;
cin >> n;
for(int a=1;a<=100;a++){
for(int b=1;b<=100;b++){
for(int c=1;c<=100;c++){
if( (int)pow((double)a,n)+(int)pow((double)b,n)==(int)pow((double)c,n)){
if(a!=b && b!=c && a!=c){
cout << a << " " << b << " " << c << endl;
return 0;}
}
}
}
}
cout << -1 << endl;
return 0;
}
<file_sep>/timus/1876.py
a, b = map(int, raw_input().split())
print max(120 + 2*(b-40), 119 + 2*(a-40))
<file_sep>/timus/P356.cpp
#include <iostream>
using namespace std;
int arr[100000], cnt = 0;
bool nprime[1000001];
bool isPrime(int n){
if(n<=1) return false;
for(long long i = 2; i * i <= n; i ++)
if(n % i == 0)
return false;
return true;
}
void getFactors(int n, int& b, int &c){
b = c= 0;
for(int i = 0; i < cnt; i ++){
int x = arr[i];
if(isPrime(n - x)){
b = x;
c = n - x;
return;
}
}
}
/*
int foo(int y){
int i =0;
while( arr[i++] < y);
return i-1;
}
void getFactors2(int x, int n, int i, int&b, int &c){
int y = x - arr[n-i];
if(y==0){
c = arr[n-i];
return;
}
if(y<2){
getFactors2(x,n,i+1,b,c);
}else{
b = arr[n-i];
getFactors2(y, foo(y), 0, b, c);
}
}
*/
int main(){
for (long long i = 2; i <= 100000; ++i) {
if(!nprime[i]){
arr[cnt++] = i;
for(long long j = i*i;j<10000;j+=i)
nprime[j] = true;
}
}
int t, a, b, c;
for(cin>>t;t--;){
// goldbach's conjecture
cin >> a;
if(isPrime(a))
cout << a << endl;
else if(a%2!=0){
if(isPrime(a-2))
cout << 2 << " " << a-2 << endl;
else{
getFactors(a-3,b,c);
// getFactors2(a,foo(a),0,b,c);
cout << 3 << " " << b << " " << c << endl;
}
}else{
getFactors(a,b,c);
cout << b << " " << c << endl;
}
}
return 0;
}
<file_sep>/timus/1796.py
import operator
x = map(int, raw_input().split())
money = int(raw_input())
y = [10, 50, 100, 500, 1000, 5000]
maxx = sum(map(operator.mul, x, y))/money
x[x.index(next(xx for xx in x if xx > 0))] -= 1
minn = sum(map(operator.mul, x, y))/money + 1
print maxx-minn+1
print ' '.join(map(str, range(minn,maxx+1)))
<file_sep>/timus/P005.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int N, tmp, min;
int sumA=0, sumB=0;
vector<int> A;
vector<int> B;
cin >> N;
for(int i=0;i<N;i++){
cin >> tmp;
A.push_back(tmp);
sumA+=tmp;
}
sort(A.begin(),A.end());
}
<file_sep>/timus/1638.py
thickness, cover, left, right = map(int, raw_input().split())
print abs((right-left)*(cover*2+thickness) - thickness)
<file_sep>/timus/P613.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class city{
public:
long long c;
int i;
bool operator<(const city& x) const{
return c < x.c;
}
};
bool bin_search(int l, int r);
city x[70010];
int ans[70010];
city cc;
int a,b;
long c;
int n2;
int main(){
int n;
cin >> n;
for(int i=1;i<=n;i++){
cin >> x[i].c;
x[i].i = i;
}
stable_sort(x+1,x+n+1);
pair<city*,city*> bounds;
cin >> n2;
for(int i=0;i<n2;i++){
cin >> a >> b >> c;
cc.c = c;
bounds = equal_range(x+1, x+n+1, cc);
if(bounds.first==bounds.second){
ans[i]=0;
continue;
}
ans[i] = bin_search((int)(bounds.first-x), (int)(bounds.second-bounds.first)+(int)(bounds.first-x)-1);
}
for(int i=0;i<n2;i++){
cout << ans[i];
}
cout << endl;
return 0;
}
bool bin_search(int l, int r){
int start = l, end = r;
while(start<=end){
int mid = (start+end)/2;
if(x[mid].i<a){
start = mid + 1;
}else if(x[mid].i > b){
end = mid - 1;
}else{
return 1;
}
}
return 0;
}
<file_sep>/timus/1792.py
line = map(int, raw_input().split())
for i in range(8):
if (line[1]+line[2]+line[3]) % 2 == line[4] and (line[0]+line[2]+line[3]) % 2 == line[5] and (line[0]+line[1]+line[3]) % 2 == line[6]:
break
else:
line[i] = 1 - line[i]
if i != 0:
line[i-1] = 1 - line[i-1]
print ' '.join(str(i) for i in line)
<file_sep>/timus/P881.cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
int h,w,n;
string word;
cin >> h >> w >> n;
int curLen = 0;
int curLine = 0;
int numPage = 1;
for(int i=0;i<n;i++){
cin >> word;
int len = word.length();
// perfect fit
if(curLen+len==w){
curLine++;
curLen=0;
}else if(curLen+len>w){
curLine++;
curLen=len+1;
}else{
curLen+=len+1;
}
if(curLine==h){
numPage++;
curLine=0;
}
}
if(curLen==0 && curLine==0){
numPage-=1;
}
cout << numPage << endl;
return 0;
}
<file_sep>/timus/1161.py
import sys
import math
n = int(sys.stdin.readline())
l = sorted(map(int, sys.stdin.readlines()), reverse=True)
ans = l[0]
for i in xrange(1, n):
ans = 2 * math.sqrt(ans*l[i])
print '%.2f' % ans
<file_sep>/codewars-rust/src/lib.rs
pub struct Codewars {}
impl Codewars {
// Roman Numerals Encoder
pub fn num_as_roman(num: i32) -> String {
let codes = [
("M", 1000),
("CM", 900),
("D", 500),
("CD", 400),
("C", 100),
("XC", 90),
("L", 50),
("XL", 40),
("X", 10),
("IX", 9),
("V", 5),
("IV", 4),
("I", 1),
];
let mut number = num;
let mut s = String::new();
for (roman, n) in codes.iter() {
while *n <= number {
s += roman;
number -= n;
}
}
s
}
// Difference of Volumes of Cuboids
pub fn find_difference(a: &[i32; 3], b: &[i32; 3]) -> i32 {
(a.iter().product::<i32>() - b.iter().product::<i32>()).abs()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn num_as_roman() {
assert_eq!(Codewars::num_as_roman(182), "CLXXXII");
assert_eq!(Codewars::num_as_roman(1990), "MCMXC");
assert_eq!(Codewars::num_as_roman(1875), "MDCCCLXXV");
}
#[test]
fn find_different() {
assert_eq!(Codewars::find_difference(&[3, 2, 5], &[1, 4, 4]), 14);
assert_eq!(Codewars::find_difference(&[9, 7, 2], &[5, 2, 2]), 106);
assert_eq!(Codewars::find_difference(&[11, 2, 5], &[1, 10, 8]), 30);
assert_eq!(Codewars::find_difference(&[4, 4, 7], &[3, 9, 3]), 31);
assert_eq!(Codewars::find_difference(&[15, 20, 25], &[10, 30, 25]), 0);
}
}
<file_sep>/timus/P356.py
def primes(n):
if n==2: return [2]
elif n<2: return []
s=range(3,n+1,2)
mroot = n ** 0.5
half=(n+1)/2-1
i=0
m=3
while m <= mroot:
if s[i]:
j=(m*m-3)/2
s[j]=0
while j<half:
s[j]=0
j+=m
i=i+1
m=2*i+3
return [2]+[x for x in s if x]
ps = []
ans = []
def foo(x, n, i):
y = x-ps[n-i]
print x - ps[n-i]
if y==0:
ans.append(ps[n-i])
return
if y < 2:
foo( x, n, i+1)
else:
ans.append(ps[n-i])
foo(y, bar(y), 0)
def bar(x):
for (i,j) in enumerate(ps):
if j > x:
return i-1
n = 14983
ps = primes(n)
foo(n, len(ps), 1)
print ps
print ans
<file_sep>/timus/1220.cpp
#include <cstdio>
#include <string>
#define MAX_OPS 100000
#define MAX_STACKS 1000
int N;
int STACK[MAX_OPS];
int COUNT[MAX_STACKS + 1];
int STACK_POINTER[MAX_STACKS + 1];
int main(){
int stack, value;
char op[8];
for (int i = 0; i <= MAX_STACKS; i++)
COUNT[i] = 0;
scanf("%d", &N);
for (int i = 0; i < N; i++){
scanf("%s %d", op, &stack);
if (op[1] == 'U'){
scanf("%d", &value);
COUNT[stack]++;
}
}
STACK_POINTER[0] = 0;
for (int i = 0; i < MAX_STACKS; i++)
STACK_POINTER[i+1] = STACK_POINTER[i] + COUNT[i];
fseek(stdin, 0, SEEK_SET);
scanf("%d", &N);
for (int i = 0; i < N; i++){
scanf("%s %d", op, &stack);
if (op[1] == 'U'){
scanf("%d", &value);
STACK[STACK_POINTER[stack]++] = value;
}else{
printf("%d\n", STACK[--STACK_POINTER[stack]]);
}
}
return 0;
}
<file_sep>/README.md
My programming practices
------------------------
* [euler](http://projecteuler.net/)
* [codingdojo](http://codingdojo.org/cgi-bin/wiki.pl?KataCatalogue)
* [timus](http://acm.timus.ru/)
* [codewars](http://www.codewars.com/)
It seems scala is not a good language for programming competitions:
1. Compile time is too slow - code writing time need to be maximised during competitions,
thus we can not wait for that extra compilation time.
2. Execution time and memory usage is non-deterministic if functional style is used.
For example, the [Reverse Root](http://acm.timus.ru/problem.aspx?space=1&num=1001) from timus,
the execution time ranges from 0.781 to 1.921 and the memory usage are all above 11308KB.
In the meanwhile all C solutions are below 0.203/2192KB, all python solutions are below 1.031/11286KB.
<file_sep>/timus/1925.py
n, k = map(int, raw_input().split())
sumb = k
sumg = 0
for i in range(n):
b, g = map(int, raw_input().split())
sumb += b
sumg += g
if sumb >= sumg+2*(n+1):
print sumb - sumg - 2*(n+1)
else:
print 'Big Bang!'
<file_sep>/timus/1644.py
n = int(raw_input())
hungry = []
satisfied = []
for i in xrange(n):
a, b = raw_input().split()
if b[0] == 'h':
hungry.append(int(a))
else:
satisfied.append(int(a))
if hungry:
maxx = max(hungry)
else:
maxx = 2
if satisfied:
minn = min(satisfied)
else:
minn = 10
if maxx >= minn:
print 'Inconsistent'
else:
print minn
<file_sep>/timus/P68.cpp
#include <iostream>
using namespace std;
int main(){
int a,ans;
cin >> a;
if(a==0)
ans = 1;
else if(a<0)
ans = (-1)*(int) (a-1)*(a/2.0 )+ 1;
else
ans = (int) (a+1)*(a/2.0);
cout << ans << endl;
return 0;
}
<file_sep>/timus/P110.cpp
#include <iostream>
using namespace std;
int main(){
int N, M, Y;
cin >> N >> M >> Y;
if(Y>=M){
cout<<-1<<endl;
return 0;
}
int tmp = 0;
int ans;
for(int i=0;i<M;i++){
ans = i%M;
for(int j=0;j<N-1;j++){
ans*=i;
ans%=M;
}
if(ans==Y){
cout << i << " ";
tmp = 1;
}
}
if(tmp==0)
cout << -1 << endl;
return 0;
}
<file_sep>/timus/1601.py
import sys
start_of_sentence = True
while 1:
s = sys.stdin.read(1)
if not s:
break
if start_of_sentence:
if s.islower():
s = s.upper()
if s.isupper():
start_of_sentence = False
else:
if s.isupper():
s = s.lower()
if s in ['.', '?', '!']:
start_of_sentence = True
sys.stdout.write(s)
<file_sep>/timus/P877.cpp
#include <iostream>
using namespace std;
int main(){
int a,b;
cin >> a >> b;
cout << (a%2!=0 && b%2==0 ? "no" : "yes") << endl;
return 0;
}
<file_sep>/timus/1120.py
import sys
import gc
import math
gc.disable()
N = int(sys.stdin.readline())
N *= 2
div = [1]
for i in xrange(2, int(math.sqrt(N))+1):
if N % i == 0:
div.append(N/i)
div.append(i)
div.sort(reverse=True)
for num in div:
r = N / num
r = r - num + 1
if r > 0 and r % 2 == 0:
print r/2, num
break
<file_sep>/timus/1018.py
N, Q = map(int, raw_input().split())
tmp = {}
Nodes = {}
costs = {}
while True:
try:
fr, to, cost = map(int, raw_input().split())
except:
break
if fr not in tmp:
tmp[fr] = { }
if to not in tmp:
tmp[to] = { }
tmp[fr][to] = cost
tmp[to][fr] = cost
def build(root):
if root not in tmp:
return
if not tmp[root]:
tmp.pop(root, None)
return
if len(tmp[root])==2:
left, right = tmp[root]
tmp[right].pop(root, None)
tmp[left].pop(root, None)
Nodes[root] = (left, right)
costs[right] = tmp[root][right]
costs[left] = tmp[root][left]
build(left)
build(right)
build(1)
costs[1] = 0
cache = {}
def V(x, y):
if (x,y) in cache:
return cache[(x,y)]
if y == 0: return 0
if y == 1: return costs[x]
if x not in Nodes: return 0
a, b = Nodes[x]
maxx = max(costs[x] + V(a, i) + V(b, y-1-i) for i in xrange(y))
cache[(x,y)] = maxx
return maxx
print V(1, Q+1)
<file_sep>/timus/1404.py
import sys
import gc
gc.disable()
string = sys.stdin.readline()
step = [ord(string[0]) - ord('a')]
if step[0]-5 < 0:
ans = [ ord('z')+step[0]-4-ord('a') ]
else:
ans = [step[0]-5]
for s in string[1:]:
for letter in xrange(26):
if (step[-1] + letter) % 26 == ord(s) - ord('a'):
ans.append(letter)
step.append(step[-1]+letter)
break
print ''.join(map(lambda s: chr(s+ord('a')), ans))
<file_sep>/timus/1131.py
N, K = map(int, raw_input().split())
done = N
i = 1
time = 0
while i <= K and i < N:
i = i + i
time += 1
if i >= N:
print time
else:
print time + (N-i+K-1) / K
<file_sep>/timus/1510.py
import gc
import sys
num = 0
gc.disable()
for i in xrange(input()):
n = int(sys.stdin.readline())
if num == 0:
ans = n
num = 0
num += 1 if ans==n else -1
print ans
<file_sep>/timus/P020.cpp
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
double dist(double x1,double x2,double y1,double y2){
double d1=abs(x1-x2);
double d2=abs(y1-y2);
if(d1==0)
return (d2);
else if(d2==0)
return (d1);
else
return sqrt(d1*d1 + d2*d2);
}
int main(){
int N;
double R;
cin >> N;
cin >> R;
vector<vector<double> > v(N,vector<double>(2));
double len=0;
for(int i=0;i<N;i++){
cin >> v[i][0];
cin >> v[i][1];
}
for(int i=1;i<N;i++){
len += dist(v[i][0],v[i-1][0],v[i][1],v[i-1][1]);
}
len += dist(v[0][0],v[N-1][0],v[0][1],v[N-1][1]);
cout.setf(ios::fixed);
cout.precision(2);
cout << (N==1?0:len)+2*3.14159*R << endl;
return 0;
}
<file_sep>/timus/P585.cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
cin >> n;
int e,m,l;
e=m=l=0;
string s, s2;
for(int i=0;i<n;i++){
cin >> s >> s2;
if(s[0]=='E'){e++; continue;}
if(s[0]=='M'){m++; continue;}
if(s[0]=='L') l++;
}
if( e>m && e>l ) cout << "Emperor Penguin" << endl;
if( m>l && m>e ) cout << "Macaroni Penguin" << endl;
if( l>m && l>e ) cout << "Little Penguin" << endl;
return 0;
}
<file_sep>/timus/1402.py
import math
N = int(raw_input())
count = 0
for i in range(2, N+1):
count += math.factorial(N)/(math.factorial(N-i))
print count
|
fd50788d5f5b8d9aaffa5ac80a3c2d6d92e009d7
|
[
"Markdown",
"Makefile",
"Rust",
"Python",
"C++"
] | 77
|
C++
|
Boshen/kata
|
cb7c7057326dce04711a5aa898b677ed664d25ae
|
335be944d9ff155f76c3b410b5857a3589a04a31
|
refs/heads/master
|
<repo_name>R0R0N0A-Z0R0/demoMVVM<file_sep>/demoMVVM/demoMVVM/userViewModel.swift
//
// userViewModel.swift
// demoMVVM
//
// Created by <NAME> on 8/8/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
class UserViewModel:NSObject {
var searchInput = BehaviorRelay<String?>(value: "")
var searchResult = BehaviorRelay<[UserModel]>(value: [])
//var searchResult = [UserModel]()
let disposeBag = DisposeBag()
override init() {
super.init()
bindingData()
}
func bindingData(){
print("aaaaaaaa")
self.searchInput.asObservable().subscribe(onNext: { (text) in
if text!.isEmpty {
self.searchResult.accept([])
} else
{
self.requestJSON(url: "https://api.github.com/search/users?q=\(text!)")
}
}, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: disposeBag)
}
func requestJSON(url:String){
print("xxxxxxxxx.........")
let url = URL(string: url)
let session = URLSession.shared
session.dataTask(with: url!) { (data, res, err) in
if err == nil {
print("Resume.........")
do {
if let result:Dictionary<String,Any> = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? Dictionary<String,Any>{
var userArray:Array<UserModel> = []
if let items:Array<Any> = result["items"] as? Array<Any> {
for i in items{
let user = UserModel(object: i)
userArray.append(user)
}
self.searchResult.accept(userArray)
}
}
} catch{}
}
}.resume()
}
}
<file_sep>/demoMVVM/demoMVVM/userModel.swift
//
// userModel.swift
// demoMVVM
//
// Created by <NAME> on 8/8/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct UserModel {
var userName:String!
var id:Int!
init() {
self.userName = ""
self.id = 0
}
init(object:Any) {
if let dic:Dictionary<String,Any> = object as? Dictionary<String,Any>{
if let userName = dic["login"] as? String {
self.userName = userName
} else {
self.userName = ""
}
if let id = dic["id"] as? Int {
self.id = id
} else {
self.id = 0
}
}else{
self.userName = ""
self.id = 0
}
}
}
<file_sep>/demoMVVM/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'demoMVVM' do
pod 'RxSwift', '~> 4.2'
pod 'RxCocoa', '~> 4.2'
end
<file_sep>/demoMVVM/demoMVVM/ViewController.swift
//
// ViewController.swift
// demoMVVM
//
// Created by <NAME> on 8/8/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class ViewController: UIViewController {
@IBOutlet weak var searchInputTextField: UITextField!
@IBOutlet weak var userTableView: UITableView!
let disposeBag = DisposeBag()
var userViewModel = UserViewModel()
override func viewDidLoad() {
super.viewDidLoad()
bindUI()
doTable()
doTable2()
// Do any additional setup after loading the view, typically from a nib.
userTableView.estimatedRowHeight = 150
userTableView.rowHeight = 150
}
func bindUI(){
print("bbbbbbbb")
self.searchInputTextField.rx.text.asObservable().bind(to: self.userViewModel.searchInput).disposed(by: disposeBag)
print("ffffff")
self.userViewModel.searchResult.asObservable().bind(to: self.userTableView.rx.items(cellIdentifier: "Cell", cellType: TableViewCell.self)){
(index,user,cell) in
cell.userNameLabel.text = user.userName
cell.idLabel.text = String(user.id)
}.disposed(by: disposeBag)
}
func doTable(){
userTableView.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in
let cell = self?.userTableView.cellForRow(at: indexPath) as? TableViewCell
cell?.backgroundColor = UIColor.blue
print("cccccccccccc")
}).disposed(by: disposeBag)
}
func doTable2(){
userTableView.rx.itemDeleted.subscribe(onNext: { [weak self] indexPath in
let cell = self?.userTableView.cellForRow(at: indexPath) as? TableViewCell
if cell?.editingStyle == .delete{
print("da xoa")
self?.userViewModel.remove
}
}).disposed(by: disposeBag)
}
}
|
1317eff64eb75c6d1214fb46641d82f68d01ddd6
|
[
"Swift",
"Ruby"
] | 4
|
Swift
|
R0R0N0A-Z0R0/demoMVVM
|
89be57521347fe2227ae75409bd4f1736d9ad848
|
cc58ea5ca5cff0d93f438b609137a334f686a0e7
|
refs/heads/main
|
<repo_name>collectForked/dataStructure<file_sep>/linkedList/singly/test.ts
import { SinglyLinkedList } from "./singlyLinkedList.ts";
// import { SinglyLinkedList } from "https://deno.land/x/datastructure/mod.ts"
const singlyLinkedList = SinglyLinkedList.createSL()
singlyLinkedList.prepend({key: 'a', value: 'apple'})
singlyLinkedList.prepend({key: 'b', value: [1, 2, 3]})
singlyLinkedList.prepend({key: 11, value: 'add to head'})
// singlyLinkedList.append({key: 'c', value: 'add to last'})
// singlyLinkedList.add({key: 'x', value: 'X'}, 1)
// singlyLinkedList.add({key: 'x', value: 'X'}, 1)
// console.log(singlyLinkedList.getFromHead());
// console.log(singlyLinkedList.getFromTail());
// console.log(singlyLinkedList.remove('c'));
// console.log(singlyLinkedList.update('b', 'after head'));
// console.log(singlyLinkedList.search('a'));
// const it = singlyLinkedList.iterator()
// let itNext = it.next()
// console.log(it.next(), it.next(), it.next());
// while (itNext.done === false) {
// console.log(itNext.value);
// itNext = it.next()
// }
// console.log(singlyLinkedList);
singlyLinkedList.log()
<file_sep>/mod.js
/**
* Data Structure
*
* Different Data Structures implementation API provided by this module.
* API available in TypeScript & JavaScript.
*
* @package dataStructure
* @author <NAME> [<NAME>]
* @email <<EMAIL>>
* @authorUrl https://abmsourav.com
* @sourceCode https://github.com/AbmSourav/dataStructure
* @version 1.2.1
*
* Copyright (c) 2021 <NAME>
*/
export { BlockChain } from "./blockChain/blockChain.bundle.js";
export { HashTable } from "./hashTable/hashTable.bundle.js";
export { SinglyLinkedList } from "./linkedList/singly/singlyLinkedList.bundle.js";
export { DoublyLinkedList } from "./linkedList/doubly/doublyLinkedList.bundle.js";
export { Stack } from "./stack/stack.bundle.js"
export { Queue } from "./queue/queue.bundle.js"
<file_sep>/queue/queue.ts
import { QueueType, DataType, QueueApi } from "./helper.d.ts"
import { QueueNode } from "./queueNode.ts"
import {
searchGenerator,
updateGenerator,
iteratorGenerator
} from "./generators.ts"
export class Queue implements QueueApi {
#frontNode: QueueType
#backNode: QueueType
public size: number
constructor() {
this.#frontNode = null
this.#backNode = null
this.size = 0
}
static createQueue() {
return new this();
}
getFront() {
if (this.#frontNode === null) return null
return this.#frontNode!.data
}
getBack() {
if (this.#frontNode === null) return null
return this.#backNode!.data
}
enqueue(data: DataType<any>) {
const newNode = new QueueNode(data)
if (this.#frontNode === null) {
// adding same pointer for frontNode & backNode
this.#frontNode = newNode
this.#backNode = newNode
return true;
}
// pointer and it's greatness
this.#backNode!.next = newNode
this.#backNode = newNode
this.size++
return true;
}
dequeue() {
if (this.#frontNode === null) {
return false;
} else if (this.#frontNode!.next === null) {
this.#backNode = null
}
const node = this.#frontNode
this.#frontNode = node!.next
this.size--
if (this.#frontNode === null) this.size = 0
return node!.data;
}
search(key: string|number) {
if (this.#frontNode === null) {
return false
}
if (key === this.#frontNode!.data.key) {
return this.#frontNode!.data
}
if (key === this.#backNode!.data.key) {
return this.#backNode!.data
}
// generator function that returns an iterator
const iterator = searchGenerator(key, this.#frontNode)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return iteratorNext.value
}
return false
}
update(key: string|number, newValue: any) {
if (this.#frontNode === null) {
return false
}
if (key === this.#frontNode!.data.key) {
this.#frontNode!.data.value = newValue
return this.#frontNode!.data
}
if (key === this.#backNode!.data.key) {
this.#backNode!.data.value = newValue
return this.#backNode!.data
}
// generator function that returns an iterator
const iterator = updateGenerator(key, this.#frontNode, newValue)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return iteratorNext.value
}
return false
}
log() {
const iterator = this.iterator()
let iteratorNext = iterator.next()
while (iteratorNext.done === false) {
console.log(iteratorNext.value);
iteratorNext = iterator.next()
}
}
iterator() {
// generator function that returns an iterator
const iterator = iteratorGenerator(this.#frontNode)
return iterator
}
}
<file_sep>/hashTable/test.ts
import { HashTable } from "./hashTable.ts"
import { assert, assertEquals } from "https://deno.land/std/testing/asserts.ts";
const hashTable = HashTable.createHT()
hashTable.add({key: "abm", value: "Sourav"})
hashTable.add({key: "bma", value: {company: "Apple LLC"}})
hashTable.add({key: "appl", value: {product: "iPhone"}})
hashTable.add({key: "microsoft", value: "MicroSoft"})
// hashTable.add({key: "Linux", value: "Ubuntu"})
// hashTable.add({key: "ChromeOS", value: "Google"})
// console.log(hashTable.remove("microsoft"));
// const it = hashTable.iterator()
// console.log(it.next(), it.next(), it.next(), it.next());
// console.log(hashTable.update('bma', {name: 'Apple'}));
// console.log(hashTable)
hashTable.log()
// Deno.test("Add", function() {
// assertEquals(hashTable.add({key: "abm", value: "Sourav"}), true)
// })
// Deno.test("remove", function() {
// assertEquals(hashTable.remove("microsoft"), false);
// })
<file_sep>/hashTable/hashTable.ts
import { HashTableApi, DataType } from "./helper.d.ts";
import { hashFunction } from "./hashFunction.ts";
import { HashNode } from "./hashNode.ts";
import {
addGenerator,
removeGenerator,
updateGenerator,
getGenerator,
iteratorGenerator
} from "./generators.ts";
export class HashTable implements HashTableApi {
#table: Array<any>
public length: number
constructor() {
this.#table = new Array()
this.length = 0
}
static createHT() {
return new this();
}
add(data: DataType<any>) {
const index = hashFunction(data.key)
const node = new HashNode(data)
if (this.#table[index] === undefined) {
this.#table[index] = node
this.length++
return true
}
if (this.#table[index].next === null) {
this.#table[index].next = node
return true
}
let currentNode = this.#table[index].next
// generator function that returns an iterator
const iterator = addGenerator(currentNode, node)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return true
}
return false;
}
remove(key: string) {
let index = hashFunction(key)
if (this.#table[index] === undefined) return false
if (this.#table[index].data.key === key) {
delete this.#table[index]
this.length--
return true;
}
if (this.#table[index].next !== null) {
let currentNode = this.#table[index]
// generator function that returns an iterator
const iterator = removeGenerator(key, currentNode)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return true
}
}
return false
}
update(key: string, newValue: any) {
let index = hashFunction(key)
if (this.#table[index] === undefined) return false
if (this.#table[index].data.key === key) {
this.#table[index].data.value = newValue
return this.#table[index].data.value;
}
if (this.#table[index].next !== null) {
let currentNode = this.#table[index]
// generator function that returns an iterator
const iterator = updateGenerator(key, newValue, currentNode)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return true
}
}
return false
}
get(key: string) {
let index = hashFunction(key)
if (this.#table[index] === undefined) return false
if (this.#table[index].data.key === key) {
return this.#table[index].data;
}
if (this.#table[index].next !== null) {
let currentNode = this.#table[index]
// generator function that returns an iterator
const iterator = getGenerator(key, currentNode)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return iteratorNext.value
}
}
return false
}
log(key?: string) {
if (this.length <= 0) return false
if (key) {
let index = hashFunction(key)
if (this.#table[index].data.key === key) {
return console.log(this.#table[index])
}
if (this.#table[index] && this.#table[index].next) {
let currentNode = this.#table[index].next
while (currentNode) {
if (currentNode.data.key === key) {
return console.log(currentNode)
}
currentNode = currentNode.next
}
}
}
for (let cell in this.#table) {
console.log(this.#table[cell])
}
}
iterator() {
// generator function that returns an iterator
const iterator = iteratorGenerator(this.#table)
return iterator
}
}
<file_sep>/queue/helper.d.ts
// data type
export type DataType<T> = {
key: string|number
value: T
}
export type QueueType = {
data: DataType<any>
next: null|QueueType
}|null
// Stack interface
export interface QueueApi {
size: number;
getFront(): null|DataType<any>
getBack(): null|DataType<any>
enqueue(data: DataType<any>): boolean
dequeue(): boolean|DataType<any>
search(key: string|number): boolean|DataType<any>
update(key: string|number, newValue: any): boolean|DataType<any>
log(): void
}
<file_sep>/blockChain/test.ts
import { BlockChain } from "./blockChain.ts";
// import { BlockChain } from "https://deno.land/x/datastructure/mod.ts";
const blockChain = BlockChain.createBlockChain()
blockChain.createBlock({key: 'sourav', value: "Sourav"})
blockChain.createBlock({key: 'abm', value: "AbmSourav"})
blockChain.createBlock({key: 'apple', value: "Apple Inc."})
// const iterator = blockChain.iterator()
// let iteratorNext = iterator.next()
// console.log(iterator.next(), iterator.next());
// while (iteratorNext.done === false) {
// console.log(iteratorNext.value);
// iteratorNext = iterator.next()
// }
// console.log(blockChain.latestBlock());
// blockChain.latestBlock().data.key = '1'
// console.log(blockChain.checkValidation());
blockChain.log(null, 3)
// console.log(blockChain.search('sourav'))
// console.log(blockChain.length)
<file_sep>/linkedList/doubly/generators.ts
import { NodeType, DataType } from "./helper.d.ts";
import { DoublyNode } from "./doublyNode.ts";
export function *addGenerator(currentNode: NodeType, data: DataType<any>, position: number) {
let count = 0
let prevNode: NodeType = null;
while (currentNode !== null) {
if (count === position) {
prevNode!.next = new DoublyNode(data)
prevNode!.next.next = currentNode
yield true
}
prevNode = currentNode
currentNode = currentNode.next
count++
}
return false
}
export function *updateGenerator(key: string|number, currentNode: NodeType, newValue: any) {
while (currentNode !== null) {
if (currentNode.data.key === key) {
currentNode.data.value = newValue
yield currentNode.data;
}
currentNode = currentNode.next
}
return false
}
export function *searchGenerator(key: string|number, currentNode: NodeType) {
while (currentNode !== null) {
if (currentNode.data.key === key) {
yield currentNode.data;
}
currentNode = currentNode.next
}
return false
}
export function *iteratorGenerator(currentNode: NodeType) {
while (currentNode !== null) {
yield currentNode.data;
currentNode = currentNode.next
}
return false
}
<file_sep>/hashTable/hashTable.bundle.js
function hashFunction(str) {
let hash = 17;
for(let i = 0; i < str.length; i++){
let newStr = str.charCodeAt(i) / 31;
hash = 13.11 * hash * newStr / str.length;
}
return hash;
}
class HashNode {
data;
next;
constructor(data1){
this.data = data1;
this.next = null;
}
}
function* addGenerator(currentNode, newNode) {
while(currentNode !== null){
if (currentNode.next === null) {
currentNode.next = newNode;
yield true;
}
currentNode = currentNode.next;
}
return false;
}
function* removeGenerator(key, currentNode) {
let prevNode = null;
while(currentNode !== null){
if (currentNode.data.key === key) {
prevNode.next = currentNode.next;
yield true;
}
prevNode = currentNode;
currentNode = currentNode.next;
}
return false;
}
function* iteratorGenerator(table) {
for(let key in table){
yield table[key];
}
return false;
}
function* updateGenerator(key, newValue, currentNode) {
while(currentNode !== null){
if (currentNode.data.key === key) {
currentNode.data.value = newValue;
yield true;
}
currentNode = currentNode.next;
}
return false;
}
function* getGenerator(key, currentNode) {
while(currentNode !== null){
if (currentNode.data.key === key) {
yield currentNode.data;
}
currentNode = currentNode.next;
}
return false;
}
class HashTable1 {
#table;
length;
constructor(){
this.#table = new Array();
this.length = 0;
}
static createHT() {
return new this();
}
add(data) {
const index = hashFunction(data.key);
const node = new HashNode(data);
if (this.#table[index] === undefined) {
this.#table[index] = node;
this.length++;
return true;
}
if (this.#table[index].next === null) {
this.#table[index].next = node;
return true;
}
let currentNode = this.#table[index].next;
const iterator = addGenerator(currentNode, node);
const iteratorNext = iterator.next();
if (iteratorNext.value) {
return true;
}
return false;
}
remove(key) {
let index = hashFunction(key);
if (this.#table[index] === undefined) return false;
if (this.#table[index].data.key === key) {
delete this.#table[index];
this.length--;
return true;
}
if (this.#table[index].next !== null) {
let currentNode = this.#table[index];
const iterator = removeGenerator(key, currentNode);
const iteratorNext = iterator.next();
if (iteratorNext.value) {
return true;
}
}
return false;
}
update(key, newValue) {
let index = hashFunction(key);
if (this.#table[index] === undefined) return false;
if (this.#table[index].data.key === key) {
this.#table[index].data.value = newValue;
return this.#table[index].data.value;
}
if (this.#table[index].next !== null) {
let currentNode = this.#table[index];
const iterator = updateGenerator(key, newValue, currentNode);
const iteratorNext = iterator.next();
if (iteratorNext.value) {
return true;
}
}
return false;
}
get(key) {
let index = hashFunction(key);
if (this.#table[index] === undefined) return false;
if (this.#table[index].data.key === key) {
return this.#table[index].data;
}
if (this.#table[index].next !== null) {
let currentNode = this.#table[index];
const iterator = getGenerator(key, currentNode);
const iteratorNext = iterator.next();
if (iteratorNext.value) {
return iteratorNext.value;
}
}
return false;
}
log(key) {
if (this.length <= 0) return false;
if (key) {
let index = hashFunction(key);
if (this.#table[index].data.key === key) {
return console.log(this.#table[index]);
}
if (this.#table[index] && this.#table[index].next) {
let currentNode = this.#table[index].next;
while(currentNode){
if (currentNode.data.key === key) {
return console.log(currentNode);
}
currentNode = currentNode.next;
}
}
}
for(let cell in this.#table){
console.log(this.#table[cell]);
}
}
iterator() {
const iterator = iteratorGenerator(this.#table);
return iterator;
}
}
export { HashTable1 as HashTable };
<file_sep>/linkedList/doubly/readme.md
## Doubly Linked List Api
```ts
DataType<T> = {
key: string|number
value: T
}
// static method that creates a instance of `DoublyLinkedList` class.
DoublyLinkedList.createDL()
// Time Complexity: O(1)
size: number;
// *generator function, it returens an iterator.
iterator(): Generator
// Time Complexity: O(1)
prepend(data: DataType<any>): boolean;
append(data: DataType<any>): boolean;
// Time Complexity: O(n)
add(data: DataType<any>, position: number): boolean;
// Time Complexity: O(1)
getFromHead(): object|false;
// Time Complexity: O(1)
getFromTail(): object|false;
// Time Complexity: O(n)
log(): void;
// Time Complexity:
// head node: O(1), other nodes: O(n)
remove(key: string|number): object|boolean;
// Time Complexity:
// head node & tail: O(1), other nodes: O(n)
update(key: string|number, newValue: any): object|boolean;
// Time Complexity:
// head node & tail node: O(1), other nodes: O(n)
search(key: string|number): object|null
```
<br>
<br>
## Examples
```ts
import { DoublyLinkedList } from "https://deno.land/x/datastructure/mod.ts";
const doublyLinkedList = DoublyLinkedList.createDL()
// iterator method returns a *generator function
const iterator = doublyLinkedList.iterator()
let iteratorNext = iterator.next()
// console.log(iteratorNext.next(), iteratorNext.next());
while (iteratorNext.done === false) {
console.log(iteratorNext.value);
iteratorNext = iterator.next()
}
// get the size of the linked list
doublyLinkedList.size
// insert in the head
doublyLinkedList.prepend({key: 'a', value: 'apple'})
doublyLinkedList.prepend({key: 'b', value: [1, 2, 3]})
doublyLinkedList.prepend({key: 11, value: {name: 'Sourav'}})
// insert in the tail
doublyLinkedList.append({key: 'c', value: 'add to last'})
// insert anywhere except head & tail
doublyLinkedList.add({key: 'x', value: 'X'}, 1)
// get data from head or tail of linked list
doublyLinkedList.getFromHead()
doublyLinkedList.getFromTail()
// console all values
doublyLinkedList.log()
// remove or delete data from linked list
doublyLinkedList.remove('a')
// update data in linked list
doublyLinkedList.update('a', [1, 4, 8])
// search data in the linked list
doublyLinkedList.search('Sourav')
```
<file_sep>/stack/stack.ts
import { StackType, DataType, StackApi } from "./helper.d.ts"
import { StackNode } from "./stackNode.ts"
import {
searchGenerator,
updateGenerator,
iteratorGenerator
} from "./generators.ts"
export class Stack implements StackApi {
#topNode: StackType
#bottomNode: StackType
public size: number
constructor() {
this.#topNode = null
this.#bottomNode = null
this.size = 0
}
static createStack() {
return new this();
}
getTop() {
if (this.#topNode === null) return null;
return this.#topNode!.data
}
getBottom() {
if (this.#topNode === null) return null;
return this.#bottomNode!.data
}
push(data: DataType<any>) {
const newNode = new StackNode(data)
if (this.#topNode === null) {
this.#topNode = newNode
this.#bottomNode = newNode
return true;
}
newNode.next = this.#topNode
if (newNode.next === null) {
this.#bottomNode = newNode.next
}
this.#topNode = newNode
this.size++
return true;
}
pop() {
if (this.#topNode === null) {
return false;
} else if (this.#topNode!.next === null) {
this.#bottomNode = null
}
const node = this.#topNode
this.#topNode = node!.next
this.size--
if (this.#topNode === null) this.size = 0
return node!.data;
}
search(key: string|number) {
if (this.#topNode === null) {
return false
}
if (key === this.#topNode!.data.key) {
return this.#topNode!.data
}
if (key === this.#bottomNode!.data.key) {
return this.#bottomNode!.data
}
// generator function that returns an iterator
const iterator = searchGenerator(key, this.#topNode)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return iteratorNext.value
}
return false
}
update(key: string|number, newValue: any) {
if (this.#topNode === null) {
return false
}
if (key === this.#topNode!.data.key) {
this.#topNode!.data.value = newValue
return this.#topNode!.data
}
if (key === this.#bottomNode!.data.key) {
this.#bottomNode!.data.value = newValue
return this.#bottomNode!.data
}
// generator function that returns an iterator
const iterator = updateGenerator(key, this.#topNode, newValue)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
return iteratorNext.value
}
return false
}
log() {
let currentNode = this.#topNode
while (currentNode !== null) {
console.log(currentNode.data);
currentNode = currentNode.next
}
}
iterator() {
// generator function that returns an iterator
const iterator = iteratorGenerator(this.#topNode)
return iterator
}
}
<file_sep>/linkedList/doubly/helper.d.ts
// data type
export type DataType<T> = {
key: string|number
value: T
}
// singly linked list node class
export type NodeType = {
data: DataType<any>
next: null|NodeType
prev: null|NodeType
}|null
// singly linked list interface
export interface LinkedListApi {
size: number;
prepend(data: DataType<any>): boolean;
append(data: DataType<any>): boolean;
add(data: DataType<any>, position: number): boolean;
getFromHead(): object|false;
getFromTail(): object|false;
log(): void;
remove(key: string|number): object|boolean;
update(key: string|number, newValue: any): object|boolean;
search(key: string|number): object|boolean
iterator(): Generator
}
<file_sep>/blockChain/generators.ts
export function *searchGenerator(key: string, chain: Array<any>) {
for (let block in chain) {
if (chain[block].data.key === key) {
yield chain[block]
}
}
return false
}
export function *iteratorGenerator(chain: Array<any>) {
for (let block in chain) {
yield chain[block]
}
return false
}
<file_sep>/stack/test.ts
// import { Stack } from "https://deno.land/x/datastructure/mod.ts";
import { Stack } from "./stack.ts";
const stack = Stack.createStack()
stack.push({key: 'a', value: 'apple'})
stack.push({key: 'b', value: [1, 2, 4]})
stack.push({key: 'c', value: [8, 9, 2]})
stack.push({key: 'd', value: 'dd'})
// stack.pop();
// console.log(stack.update('d', {name: 'Sourav'}));
// console.log(stack.getTop(), stack.getBottom());
// console.log(stack.search('d'));
const iterator = stack.iterator()
// let iteratorNext = iterator.next()
console.log(iterator.next(), iterator.next(), iterator.next());
// while (iteratorNext.done === false) {
// console.log(iteratorNext.value);
// iteratorNext = iterator.next()
// }
// console.log(stack)
// stack.log()
<file_sep>/hashTable/helper.d.ts
// data type
export type DataType<T> = {
key: string
value: T
}
export type NodeType = {
data: DataType<any>
next: null|NodeType
}|null
export interface HashTableApi {
length: number
add(data: DataType<any>): boolean
remove(key: string): boolean|any[]
update(key: string, newValue: DataType<any>): boolean|DataType<any>
get(key: string): boolean|DataType<any>
log(key?: string): void,
iterator(): Generator
}
<file_sep>/README.md
# Data Structure
Different Data Structures implementation API provided by this module.
API available in TypeScript & JavaScript[ES6].
<br>
This library is also available as **[Deno Third party Module](https://deno.land/x/datastructure)**
<p>
If you're already using this module in your Deno project,
then run <code>deno run -r projectName/fileName.ts</code> for latest version.
</p>
<br>
## List of Data Structures:
* Block Chain -- **[Documentation](https://deno.land/x/datastructure/blockChain#blockChain-api)**
* Hash Table -- **[Documentation](https://deno.land/x/datastructure/hashTable#hash-table-api)**
* Singly Linked List -- **[Documentation](https://deno.land/x/datastructure/linkedList/singly#singly-linked-list-api)**
* Doubly Linked List -- **[Documentation](https://deno.land/x/datastructure/linkedList/doubly#doubly-linked-list-api)**
* Stack -- **[Documentation](https://deno.land/x/datastructure/stack#stack-api)**
* Queue -- **[Documentation](https://deno.land/x/datastructure/queue#queue-api)**
<br>
<br>
. <file_sep>/linkedList/doubly/test.ts
import { DoublyLinkedList } from "./doublyLinkedList.ts";
// import { DoublyLinkedList } from "https://deno.land/x/datastructure/mod.ts"
const doublyLinkedList = DoublyLinkedList.createDL()
doublyLinkedList.prepend({key: 'a', value: 'apple'})
doublyLinkedList.prepend({key: 'b', value: [1, 2, 3]})
// doublyLinkedList.prepend({key: 11, value: {val: 'add to head'}})
// doublyLinkedList.append({key: 'c', value: 'add before last'})
doublyLinkedList.append({key: 'd', value: 'add to last'})
// doublyLinkedList.add({key: 'x', value: 'X'}, 1)
// console.log(doublyLinkedList.getFromHead());
// console.log(doublyLinkedList.getFromTail());
// console.log(doublyLinkedList.remove('c'));
// console.log(doublyLinkedList.update('b', 'bbbb'));
console.log(doublyLinkedList.search('b'));
console.log('');
// console.log(doublyLinkedList)
doublyLinkedList.log()
// const it = doublyLinkedList.iterator()
// let itNext = it.next()
// console.log(it.next(), it.next(), it.next());
// while (itNext.done === false) {
// console.log(itNext.value);
// itNext = it.next()
// }
<file_sep>/queue/queueNode.ts
import { DataType, QueueType } from "./helper.d.ts"
export class QueueNode {
public data: DataType<any>
public next: QueueType|null = null
constructor(data: DataType<any>) {
this.data = data;
this.next = null;
}
}
<file_sep>/stack/helper.d.ts
// data type
export type DataType<T> = {
key: string|number
value: T
}
export type StackType = {
data: DataType<any>
next: null|StackType
}|null
// Stack interface
export interface StackApi {
size: number;
getTop(): null|DataType<any>
getBottom(): null|DataType<any>
push(data: DataType<any>): boolean
pop(): boolean|DataType<any>
search(key: string|number): boolean|DataType<any>
update(key: string|number, newValue: any): boolean|DataType<any>
log(): void
iterator(): Generator
}
<file_sep>/queue/test.ts
// import { Queue } from "https://deno.land/x/datastructure/mod.ts";
import { Queue } from "./queue.ts";
const queue = Queue.createQueue()
queue.enqueue({key: 'a', value: 'aa'});
queue.enqueue({key: 'b', value: [1, 2, 5]})
queue.enqueue({key: 'sourav', value: {name: "Sourav"}})
// console.log(queue.getFront(), queue.getBack());
// queue.dequeue()
// console.log(queue.update('sourav', 'Abm'));
// console.log(queue.search('b'));
// const iterator = queue.iterator()
// let iteratorNext = iterator.next()
// console.log(iterator.next(), iterator.next(), iterator.next());
// while (iteratorNext.done === false) {
// console.log(iteratorNext.value);
// iteratorNext = iterator.next()
// }
// console.log(queue);
queue.log()
<file_sep>/stack/generators.ts
import { StackType } from "./helper.d.ts";
export function *searchGenerator(key: string|number, currentNode: StackType) {
while (currentNode !== null) {
if (key === currentNode.data.key) {
return currentNode.data
}
currentNode = currentNode.next
}
return false
}
export function *updateGenerator(key: string|number, currentNode: StackType, newValue: any) {
while (currentNode !== null) {
if (key === currentNode.data.key) {
currentNode.data.value = newValue
return currentNode.data
}
currentNode = currentNode.next
}
return false
}
export function *iteratorGenerator(currentNode: StackType) {
while (currentNode !== null) {
yield currentNode.data;
currentNode = currentNode.next
}
return false
}
<file_sep>/blockChain/blockNode.ts
import { DataType, BlockType } from "./helper.d.ts";
import { createHash } from "https://deno.land/std/hash/mod.ts";
function blockHash(index: number, data: DataType<any>, time: Date) {
let hash = createHash("sha256")
hash = hash.update(JSON.stringify(data) + index + time)
return hash.toString();
}
export class Block {
index: number
data: DataType<any>
hash: string
prevHash: string|null
time: Date
constructor(data: DataType<any>, index: number) {
this.index = index
this.data = data
this.time = new Date()
this.hash = blockHash(index, data, this.time)
this.prevHash = null;
}
regenerateHash() {
const data: DataType<any>|any = this.data
const hash = blockHash(this.index, data, this.time)
return hash.toString();
}
}
<file_sep>/hashTable/generators.ts
import { NodeType } from "./helper.d.ts";
export function *addGenerator(currentNode: NodeType, newNode: NodeType) {
while (currentNode !== null) {
if (currentNode.next === null) {
currentNode.next = newNode
yield true
}
currentNode = currentNode.next
}
return false
}
export function *removeGenerator(key: string, currentNode: NodeType) {
let prevNode: NodeType = null
while (currentNode !== null) {
if (currentNode.data.key === key) {
prevNode!.next = currentNode.next
yield true
}
prevNode = currentNode
currentNode = currentNode.next
}
return false
}
export function *iteratorGenerator(table: Array<any>) {
for (let key in table) {
yield table[key]
}
return false
}
export function *updateGenerator(key: string, newValue: any, currentNode: NodeType) {
while (currentNode !== null) {
if (currentNode.data.key === key) {
currentNode.data.value = newValue
yield true
}
currentNode = currentNode.next
}
return false
}
export function *getGenerator(key: string, currentNode: NodeType) {
while (currentNode !== null) {
if (currentNode.data.key === key) {
yield currentNode.data
}
currentNode = currentNode.next
}
return false
}
<file_sep>/deploy.sh
#!/bin/bash
echo "Press 'Y' to start deployment"
read confirmation
if [ $confirmation != 'Y' ]; then
echo "Exiting..."
exit;
fi
echo "Deleting hidden settings..."
vscode=".vscode"
if [ -d $vscode ]; then
rm -R $vscode;
git add -A
git commit -m "workspace settings removed"
fi
echo "Release Version: "
read version
echo "Release comments: "
read comments
echo ""
echo "Creating git tag..."
git tag $version -m "$comments"
echo "Press Y to push new release"
read pushNow
if [ $pushNow == 'Y' ]; then
git push origin $version
exit;
fi
<file_sep>/mod.ts
/**
* Data Structure
*
* Different Data Structures implementation API provided by this module.
* API available in TypeScript & JavaScript.
*
* @package dataStructure
* @author <NAME> [<NAME>]
* @email <<EMAIL>>
* @authorUrl https://abmsourav.com
* @sourceCode https://github.com/AbmSourav/dataStructure
* @version 1.2.1
*
* Copyright (c) 2021 <NAME>
*/
export { BlockChain } from "./blockChain/blockChain.ts";
export { HashTable } from "./hashTable/hashTable.ts";
export { SinglyLinkedList } from "./linkedList/singly/singlyLinkedList.ts";
export { DoublyLinkedList } from "./linkedList/doubly/doublyLinkedList.ts";
export { Stack } from "./stack/stack.ts"
export { Queue } from "./queue/queue.ts"
<file_sep>/blockChain/readme.md
## BlockChain Api
<p><code>sha256</code> has been used for creating Hashes.</p>
```ts
// Each block type
type BlockType = {
index: number
data: DataType<any>
time: Date
hash: string
prevHash: null|string
}
// data type
DataType<T> = {
key: string
value: T
}
// static method that creates a instance of `BlockChain` class.
BlockChain.createBlockChain()
// Time Complexity: O(1)
length: number;
// *generator function, it returens an iterator.
// loop through all blocks in the chain
iterator(): Generator
// Time Complexity: O(n)
// check for "the blockChain is corrupted/manipulated or valid".
checkValidation(): boolean
// Time Complexity: O(1)
createBlock(data: DataType<any>): boolean
// Time Complexity: O(1)
latestBlock(): boolean|BlockType
// Time Complexity:
// log all: O(n)
// log by key: O(n)
// log by index: O(1)
log(key: null|string = null, index: null|number = null): void;
// Time Complexity:
// search by key: O(n)
// search by index: O(1)
search(key: null|string, index: null|number = null): boolean|BlockType
```
<br>
<br>
## Examples
```ts
import { BlockChain } from "https://deno.land/x/datastructure/mod.ts";
const blockChain = BlockChain.createBlockChain()
// iterator method returns a *generator function
const iterator = blockChain.iterator()
let iteratorNext = iterator.next()
// console.log(iteratorNext.next(), iteratorNext.next());
while (iteratorNext.done === false) {
console.log(iteratorNext.value);
iteratorNext = iterator.next()
}
// length or count of total blocks.
blockChain.length
// create a new block in the blockChain.
blockChain.createBlock({key: 'sourav', value: {name: "Sourav"}})
blockChain.createBlock({key: 'abm', value: "AbmSourav"})
blockChain.createBlock({key: 'JS', value: ['JS', 'TS']})
// get latest created block
blockChain.latestBlock()
// console all values
blockChain.log()
// console the block that has key: 'abm'
blockChain.log('abm')
// console then block which is index: 3
blockChain.log(null, 3)
// searching block by key
blockChain.search('JS')
// searching block by index
blockChain.search(null, 2)
```
<file_sep>/linkedList/singly/singlyLinkedList.bundle.js
class SinglyNode {
data;
next;
constructor(data1){
this.data = data1;
this.next = null;
}
}
function* addGenerator(currentNode, data1, position) {
let count = 0;
let prevNode = null;
while(currentNode !== null){
if (count === position) {
prevNode.next = new SinglyNode(data1);
prevNode.next.next = currentNode;
yield true;
}
prevNode = currentNode;
currentNode = currentNode.next;
count++;
}
return false;
}
function* updateGenerator(key, currentNode, newValue) {
while(currentNode !== null){
if (currentNode.data.key === key) {
currentNode.data.value = newValue;
yield currentNode.data;
}
currentNode = currentNode.next;
}
return false;
}
function* searchGenerator(key, currentNode) {
while(currentNode !== null){
if (currentNode.data.key === key) {
yield currentNode.data;
}
currentNode = currentNode.next;
}
return false;
}
function* iteratorGenerator(currentNode) {
while(currentNode !== null){
yield currentNode.data;
currentNode = currentNode.next;
}
return false;
}
class SinglyLinkedList1 {
#head;
#tail;
size;
constructor(){
this.#head = null;
this.#tail = null;
this.size = 0;
}
static createSL() {
return new this();
}
prepend(data) {
if (this.#head === null) {
const newNode = new SinglyNode(data);
this.#head = newNode;
this.#tail = newNode;
return true;
}
const currentNode = this.#head;
this.#head = new SinglyNode(data);
this.#head.next = currentNode;
if (currentNode.next === null) {
this.#tail = currentNode;
}
this.size++;
return true;
}
append(data) {
const newNode = new SinglyNode(data);
if (this.#head === null) {
this.#head = newNode;
this.#tail = newNode;
return true;
}
this.#tail.next = newNode;
this.#tail = newNode;
this.size++;
return false;
}
add(data, position) {
if (position === 0) {
console.error("Use `prepend()` method to insert data at Head.");
return false;
} else if (position === this.size) {
console.error("Use `append()` method to insert data at Tail.");
return false;
} else if (position > this.size && position != this.size + 1) {
console.error(`Out of range. Size of the linkedList is ${this.size}`);
return false;
}
let currentNode = this.#head;
const iterator = addGenerator(currentNode, data, position);
const iteratorNext = iterator.next();
if (iteratorNext.value) {
this.size++;
return true;
}
return false;
}
getFromHead() {
if (this.#head === null) {
return false;
}
return this.#head.data;
}
getFromTail() {
if (this.#tail === null) {
return false;
}
return this.#tail.data;
}
log() {
let currentNode = this.#head;
while(currentNode !== null){
console.log(currentNode.data);
currentNode = currentNode.next;
}
}
remove(key) {
if (this.#head === null) {
return false;
} else if (this.#head.next === null) {
this.#tail = null;
}
if (this.#head.data.key === key) {
const prevHeadData = this.#head.data;
this.#head = this.#head.next;
if (this.#head.next === null) this.#tail = this.#head;
this.size--;
if (this.#head === null) this.size = 0;
return true;
}
let previousNode = null;
let currentNode = this.#head;
while(currentNode !== null){
if (key === currentNode.data.key) {
const temp = currentNode.data;
previousNode.next = currentNode.next;
if (currentNode.next === null) this.#tail = previousNode;
this.size--;
return true;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
return false;
}
update(key, newValue) {
if (this.#head === null) {
return false;
}
if (this.#head.data.key === key) {
this.#head.data.value = newValue;
return this.#head.data;
}
if (this.#tail.data.key === key) {
this.#tail.data.value = newValue;
return this.#tail.data;
}
let currentNode = this.#head.next;
const iterator = updateGenerator(key, currentNode, newValue);
const iteratorNext = iterator.next();
if (iteratorNext.value) {
return iteratorNext.value;
}
return false;
}
search(key) {
if (this.#head === null) {
return false;
}
if (this.#head.data.key === key) {
return this.#head.data;
}
if (this.#tail.data.key === key) {
return this.#tail.data;
}
let currentNode = this.#head.next;
const iterator = searchGenerator(key, currentNode);
const iteratorNext = iterator.next();
if (iteratorNext.value) {
return iteratorNext.value;
}
return false;
}
iterator() {
const currentNode = this.#head;
const iterator = iteratorGenerator(currentNode);
return iterator;
}
}
export { SinglyLinkedList1 as SinglyLinkedList };
<file_sep>/blockChain/helper.d.ts
export type DataType<T> = {
key: string
value: T
}
// BlockChain type of each block
export type BlockType = {
index: number
data: DataType<any>
time: Date
hash: string
prevHash: null|string
}
// Block chain interface
export interface BlockChainApi {
length: number
createBlock(data: DataType<any>): boolean
search(key: null|string, index: null|number): boolean|BlockType
latestBlock(): boolean|BlockType
log(key: null|string, index: null|number): void;
iterator(): Generator
checkValidation(): boolean
}
<file_sep>/blockChain/blockChain.ts
import { BlockChainApi, BlockType, DataType } from "./helper.d.ts";
import { searchGenerator, iteratorGenerator } from "./generators.ts"
import { Block } from "./blockNode.ts";
export class BlockChain implements BlockChainApi {
#chain: Array<any>
length: number
constructor() {
this.#chain = new Array()
this.length = this.#chain.length
}
static createBlockChain() {
return new this();
}
createBlock(data: DataType<any>) {
const newBlock = new Block(data, this.#chain.length + 1)
if (this.#chain.length === 0) {
this.#chain.push(newBlock)
this.length++
return true
}
if (this.#chain.length > 0) {
const prevBlock = this.latestBlock()
newBlock.prevHash = prevBlock!.hash
this.#chain.push(newBlock)
this.length++
return true
}
return false
}
search(key: null|string, index: null|number = null) {
if (this.#chain.length === 0) {
return false
}
if (key) {
const iterator = searchGenerator(key, this.#chain)
let iteratorNext = iterator.next()
if (iteratorNext.value) {
return iteratorNext.value
}
}
if (index) {
return this.#chain[index - 1]
}
return false;
}
latestBlock() {
if (this.#chain.length <= 0) return false
return this.#chain[this.#chain.length - 1]
}
iterator() {
return iteratorGenerator(this.#chain)
}
checkValidation() {
const iterator = this.iterator()
let iteratNext = iterator.next()
let prevHash: null|string = null
let prevBlock: null|BlockType = null
while (iteratNext.value) {
const block = iteratNext.value
const regeneratedHash = block.regenerateHash()
if (block.hash !== regeneratedHash) {
console.error(`index: ${block.index}, block is corrupted`)
return false
}
if (prevBlock != null && block.prevHash !== prevHash) {
console.error(`index: ${prevBlock!.index}, block is corrupted`)
return false
}
prevHash = block.regenerateHash()
prevBlock = block
iteratNext = iterator.next()
}
console.log('The Chain is valid.')
return true
}
log(key: null|string = null, index: null|number = null) {
if (key) {
return console.log(this.search(key))
}
if (index) {
return console.log(this.#chain[index - 1])
}
console.log(this.#chain)
}
}
<file_sep>/linkedList/doubly/doublyNode.ts
import { DataType, NodeType } from "./helper.d.ts";
export class DoublyNode {
public data: DataType<any>
public next: NodeType|null
public prev: NodeType|null
constructor(data: DataType<any>) {
this.data = data;
this.next = null;
this.prev = null;
}
}
<file_sep>/linkedList/doubly/doublyLinkedList.ts
import { LinkedListApi, NodeType, DataType } from "./helper.d.ts";
import { DoublyNode } from "./doublyNode.ts";
import {
addGenerator,
updateGenerator,
searchGenerator,
iteratorGenerator
} from "./generators.ts"
export class DoublyLinkedList implements LinkedListApi {
#head: null|NodeType
#tail: null|NodeType
public size: number
constructor() {
this.#head = null
this.#tail = null
this.size = 0
}
static createDL() {
return new this();
}
// insert in the head
prepend(data: DataType<any>) {
const newNode = new DoublyNode(data);
if (this.#head === null) {
this.#head = newNode
this.#tail = newNode
return true;
}
const currentNode = this.#head
this.#head = newNode
this.#head.next = currentNode
currentNode.prev = newNode
this.size++
return true;
}
// inset in the tail
append(data: DataType<any>) {
const newNode = new DoublyNode(data);
if (this.#head === null) {
this.#head = newNode
this.#tail = newNode
return true;
}
const currentNode = this.#tail
this.#tail!.next = newNode
this.#tail = newNode
this.#tail.prev = currentNode
this.size++
return false;
}
// // add anywhere of the linked list except head & tail
add(data: DataType<any>, position: number) {
if (position === 0) {
console.error("Use `prepend()` method to insert data at Head.");
return false;
} else if (position === this.size) {
console.error("Use `append()` method to insert data at Tail.");
return false;
} else if (position > this.size && position != this.size + 1) {
console.error(`Out of range. Size of the linkedList is ${this.size}`);
return false;
}
// generator function that returns an iterator
const iterator = addGenerator(this.#head, data, position)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
this.size++
return true
}
return false;
}
getFromHead() {
if (this.#head === null) {
return false
}
return this.#head.data;
}
getFromTail() {
if (this.#tail === null) {
return false
}
return this.#tail.data
}
log() {
let currentNode = this.#head
while (currentNode !== null) {
console.log(currentNode.data);
currentNode = currentNode.next
}
}
remove(key: string|number) {
if (this.#head === null) {
return false;
}
if (this.#head.data.key === key) {
const prevHeadData = this.#head.data
this.#head = this.#head.next
if (this.#head === null) this.#tail = this.#head
this.size--
if (this.#head === null) this.size = 0
return prevHeadData;
}
if (this.#tail!.data.key === key) {
const prevTailData = this.#tail!.data
this.#tail = this.#tail!.prev
this.#tail!.next = null
return prevTailData;
}
// two pointer approach
let previousNode: NodeType = null;
let currentNode: NodeType = this.#head
while (currentNode !== null) {
if (key === currentNode.data.key) {
const temp = currentNode.data
previousNode!.next = currentNode.next
currentNode.next!.prev = previousNode
if (currentNode!.next === null) this.#tail = previousNode
this.size--
return temp;
}
previousNode = currentNode
currentNode = currentNode.next
}
return false;
}
update(key: string|number, newValue: any) {
if (this.#head === null) {
return false;
}
if (this.#head.data.key === key) {
this.#head.data.value = newValue
return this.#head.data;
}
if (this.#tail!.data.key === key) {
this.#tail!.data.value = newValue
return this.#tail!.data;
}
// generator function that returns an iterator
const iterator = updateGenerator(key, this.#head, newValue)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
this.size++
return iteratorNext.value
}
return false;
}
search(key: string|number) {
if (this.#head === null) {
return false;
}
if (this.#head.data.key === key) {
return this.#head.data;
}
if (this.#tail!.data.key === key) {
return this.#tail!.data
}
// generator function that returns an iterator
const iterator = searchGenerator(key, this.#head)
const iteratorNext = iterator.next()
if (iteratorNext.value) {
this.size++
return iteratorNext.value
}
return false;
}
iterator() {
// generator function that returns an iterator
const iterator = iteratorGenerator(this.#head)
return iterator
}
}
<file_sep>/queue/readme.md
## Queue Api
```ts
DataType<T> = {
key: string|number
value: T
}
// static method that creates a instance of Queue class.
Queue.createQueue()
// Time Complexity: O(1)
size: number;
// *generator function, it returens an iterator.
iterator(): Generator
// Time Complexity: O(1)
getFront(): number|DataType<any>
// Time Complexity: O(1)
getBack(): number|DataType<any>
// Time Complexity: O(1)
enqueue(data: DataType<any>): boolean
// Time Complexity: O(1)
dequeue(): boolean|DataType<any>
// Time Complexity:
// Front Node & Back Node: O(1), other Nodes: O(n)
search(key: string|number): null|DataType<any>
// Time Complexity:
// Front Node & Back Node: O(1), other Nodes: O(n)
update(key: string|number, newValue: any): boolean|DataType<any>
// Time Complexity: O(n)
log(): void;
```
<br>
<br>
## Example
```ts
import { Queue } from "https://deno.land/x/datastructure/mod.ts";
const queue = Queue.createQueue()
// add data in the Queue in a FIFO way
queue.enqueue({key: 'a', value: [1, 2, 5]})
queue.enqueue({key: 'sourav', value: {name: "Sourav"}})
// get and remove first added data from the Queue
queue.dequeue()
// get the item which added at first
queue.getFront()
// get the item which added at last
queue.getBack()
// search item data in the Queue
queue.search('sourav')
// update item data
queue.update('sourav', '<NAME>')
// iterator method returns a *generator function
const iterator = queue.iterator()
let iteratorNext = iterator.next()
// console.log(iteratorNext.next(), iteratorNext.next());
while (iteratorNext.done === false) {
console.log(iteratorNext.value);
iteratorNext = iterator.next()
}
// console all values
queue.log()
```
<file_sep>/linkedList/singly/readme.md
## Singly Linked List Api
```ts
DataType<T> = {
key: string|number
value: T
}
// static method that creates a instance of `SinglyLinkedList` class.
SinglyLinkedList.createSL()
// Time Complexity: O(1)
size: number;
// *generator function, it returens an iterator.
iterator(): Generator
// Time Complexity: O(1)
prepend(data: DataType<any>): boolean;
append(data: DataType<any>): boolean;
// Time Complexity: O(n)
add(data: DataType<any>, position: number): boolean;
// Time Complexity: O(1)
getFromHead(): object|false;
// Time Complexity: O(1)
getFromTail(): object|false;
// Time Complexity: O(n)
log(): void;
// Time Complexity:
// head node: O(1), other nodes: O(n)
remove(key: string|number): object|boolean;
// Time Complexity:
// head & tail node: O(1), other nodes: O(n)
update(key: string|number, newValue: any): object|boolean;
// Time Complexity:
// head node & tail node: O(1), other nodes: O(n)
search(key: string|number): object|boolean
```
<br>
<br>
## Examples
```ts
import { SinglyLinkedList } from "https://deno.land/x/datastructure/mod.ts";
const singlyLinkedList = SinglyLinkedList.createSL()
// iterator method returns a *generator function
const iterator = singlyLinkedList.iterator()
let iteratorNext = iterator.next()
// console.log(iteratorNext.next(), iteratorNext.next());
while (iteratorNext.done === false) {
console.log(iteratorNext.value);
iteratorNext = iterator.next()
}
// linked list size
singlyLinkedList.size
// adding data at the head of linked list
singlyLinkedList.prepend({key: 'a', value: 'apple'})
singlyLinkedList.prepend({key: 'b', value: [1, 2, 3]})
singlyLinkedList.prepend({key: 11, value: 'add to head'})
// adding data at the tail of linked list
singlyLinkedList.append({key: 'c', value: 'add to last'})
// insert anywhere except head & tail
singlyLinkedList.add({key: 'x', value: 'X'}, 1)
// get data from head or tail
singlyLinkedList.getFromHead()
singlyLinkedList.getFromTail()
// console all values
singlyLinkedList.log()
// remove or delete data from linked list
singlyLinkedList.remove('a')
// update data in linked list
singlyLinkedList.update('a', [1, 4, 8])
// searching data in linked list
singlyLinkedList.search('Sourav')
```
<file_sep>/hashTable/readme.md
## Hash Table Api
```ts
// data type
DataType<T> = {
key: string
value: T
}
// static method that creates a instance of `HashTable` class.
HashTable.createHT()
// Time Complexity: O(1)
length: number
// *generator function, it returens an iterator.
iterator(): Generator
// Time Complexity:
// average cases: O(1)
// worst case: O(n)
add(data: DataType<any>): boolean
// Time Complexity:
// average cases: O(1)
// worst case: O(n)
remove(key: string): boolean|any[]
// Time Complexity:
// average cases: O(1)
// worst case: O(n)
update(key: string, newValue: DataType<any>): boolean|DataType<any>
// Time Complexity:
// average cases: O(1)
// worst case: O(n)
get(key: string): boolean|DataType<any>
// Time Complexity:
// log all items: O(n)
// log by key: avg. O(1), worst: O(n)
log(key?: string): void,
```
<br>
<br>
## Example
```ts
import { HashTable } from "https://deno.land/x/datastructure/mod.ts";
const hashTable = HashTable.createHT()
// add element in the hash table
// if hash keys are same, then it will create chaining with LinkedList
hashTable.add({key: "abm", value: "Sourav"})
hashTable.add({key: "apple", value: {company: "Apple Inc"}})
hashTable.add({key: "arr", value: [1, 2, 3]})
// remove element from hastabel
hashTable.remove("arr");
const iterator = hashTable.iterator()
let iteratorNext = iterator.next()
// console.log(iteratorNext.next(), iteratorNext.next());
while (iteratorNext.done === false) {
console.log(iteratorNext.value);
iteratorNext = iterator.next()
}
// get element from hash table
hashTable.get('abm')
// update element's data using the key
hashTable.update('abm', {name: 'AbmSourav'})
// console all elements
hashTable.log()
// console element by key
hashTable.log('abm')
```
<file_sep>/stack/stackNode.ts
import { DataType, StackType } from "./helper.d.ts"
export class StackNode {
public data: DataType<any>
public next: StackType|null = null
constructor(data: DataType<any>) {
this.data = data;
this.next = null;
}
}
<file_sep>/stack/readme.md
## Stack Api
```ts
DataType<T> = {
key: string|number
value: T
}
// static method that creates a instance of `Stack` class.
Stack.createStack()
// Time Complexity: O(1)
size: number;
// *generator function, it returens an iterator.
iterator(): Generator
// Time Complexity: O(1)
getTop(): null|DataType<any>
// Time Complexity: O(1)
getBottom(): null|DataType<any>
// Time Complexity: O(1)
push(data: DataType<any>): boolean
// Time Complexity: O(1)
pop(): boolean|DataType<any>
// Time Complexity:
// Top Node & Bottom Node: O(1), other Nodes: O(n)
search(key: string|number): null|DataType<any>
// Time Complexity:
// Top Node & Bottom Node: O(1), other Nodes: O(n)
update(key: string|number, newValue: any): boolean|DataType<any>
// Time Complexity: O(n)
log(): void;
```
<br>
<br>
## Example
```ts
import { Stack } from "https://deno.land/x/datastructure/mod.ts";
const stack = Stack.createStack()
// stack length/size
stack.size
// iterator method returns a *generator function
const iterator = stack.iterator()
let iteratorNext = iterator.next()
// console.log(iteratorNext.next(), iteratorNext.next());
while (iteratorNext.done === false) {
console.log(iteratorNext.value);
iteratorNext = iterator.next()
}
// add data in the stack in a LIFO way
stack.push({key: 'a', value: 'apple'})
stack.push({key: 'b', value: [1, 2, 4]})
stack.push({key: 'b', value: {name: 'AbmSourav'}})
// get data from stack (LIFO)
stack.pop()
// searching data in the stack
stack.search('a');
// get the last added item of the stack
stack.getTop()
// get the item that added at fast
stack.getBottom()
// update stack item data
stack.update('a', {name: '<NAME>'})
// console all values
stack.log()
```
<file_sep>/hashTable/hashFunction.ts
export function hashFunction(str: string) {
let hash = 17
for (let i = 0; i < str.length; i++) {
let newStr = str.charCodeAt(i) / 31
hash = (13.11 * hash * newStr) / str.length
}
// weak hash function for testing
// for (let i = 0; i < str.length; i++) {
// // let newStr = str.charCodeAt(i) / 31
// hash = (2 * hash) % str.length
// }
// console.log(hash);
return hash;
}
|
f730ee4ad7f315ac9301a75322ecd6ca372d2f53
|
[
"JavaScript",
"TypeScript",
"Markdown",
"Shell"
] | 37
|
TypeScript
|
collectForked/dataStructure
|
690cb71b6717ba6e34083f12e49ecaf59b65566a
|
c04991dc4e1dd95308046aa4bd2e51fc72ae9c46
|
refs/heads/master
|
<repo_name>Modius22/folium-map-kjg<file_sep>/README.md
# folium-map-kjg
Visualization of member residences
<file_sep>/create_map.py
import folium
import pandas as pd
from folium.plugins import MarkerCluster
from geopy.geocoders import Nominatim
data = pd.read_csv("kjg-mitglieder.csv", sep=";")
geolocator = Nominatim(timeout=None)
location_list = []
for i in range(data.__len__()):
location = geolocator.geocode(data['plz'][i])
location_list.append((location.latitude, location.longitude))
folium_map = folium.Map(location=[50.144, 8.902],
zoom_start=9.5,
tiles="CartoDB positron")
marker_cluster = MarkerCluster().add_to(folium_map)
for point in range(0, data.__len__()):
folium.Marker(location_list[point]).add_to(marker_cluster)
marker_cluster.save("kjg_dv_fulda_locations.html")
|
8ce3953052b52597e17cc5431eab0e6d7e9ff053
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
Modius22/folium-map-kjg
|
f58865f6b43a3b32fe74ed795f094438426083f1
|
073d86b908829e21361a5dc0f90e0835e3f80059
|
refs/heads/master
|
<file_sep><?php
class Section {
public static $host;//"http://aztlan.org.ar/";
public static $menuArticles;
public static $selectedArticle;
public static $section;
public static $contents;
public static $site;
public static $extention = '.html';
public function __construct(){
//setSection devuelve un array con el path segun el menu [{seccion},{seccion},furl de articulo:String]
//getContents
//1 Se fija si hay que cargar el menu de articulos
//2 carga el contenido de seccion si no es un articulo
//3 carga el contenido de articulo si es articulo
//4 pone al articulo en un array para que lo tome bien "articulo.php";
//5 carga el path para los meta del articulo o seccion
}
public static function getContents(){
// var_dump(self::$section);die;
$cont = count(self::$section);
$obj = new stdClass();
if($cont>1 && self::$section[1]->showContent==1 || $cont>1){
self::$menuArticles = GET_site::getMenuArticles(self::$section[1]->id,self::$section[1]->path);
}
if($cont<3){
$obj->contents = GET_site::getContentsBySection(self::$section[$cont-1]->id,self::$section[$cont-1]->path);
$obj->path = self::$section[$cont-1]->path;
}else
{
foreach (self::$menuArticles as $articulo)
{
if(Section::$section[2] == $articulo->furl) self::$selectedArticle = $articulo;
}
$obj->contents = array();
$obj->contents[0] =GET_site::getContent(self::$selectedArticle->id,self::$section[1]->id,Section::$section[1]->path);
$obj->path = $obj->contents[0]->path;
}
//var_dump($obj);die;
self::$contents = $obj;
}
public static function getSite(){
return self::$site;
}
public static function getTitle(){
if(is_null(self::$contents))echo "404 Error";
else echo utf8_decode(self::$contents->contents[0]->details->titulo);
}
public static function getHost(){
echo self::$host;
}
public static function host(){
return self::$host;
}
public static function getFbMeta(){
//var_dump(Section::$contents->contents[0]->details);die;
echo '<meta property="og:type" content="article" />';
echo "\n";
echo '<meta property="og:url" content="'. self::$host . self::$contents->path.Section::$extention. '" />';
echo "\n";
echo '<meta property="og:title" content="'.Section::$contents->contents[0]->details->titulo.'"/>';
echo "\n";
echo '<meta property="og:image" content="'. self::$host .'images/images/'. Section::$contents->contents[0]->img .'"/>';
echo "\n";
echo'<meta property="og:site_name" content="'.'Aztlan - Escuela de Psicología Y Filosofía'.'"/>';
echo "\n";
echo'<meta property="og:description" content="'. substr(strip_tags(base64_decode(Section::$contents->contents[0]->details->descripcion)),0,500) .'" />';
echo "\n";
}
public static function resolveImgAlign($n){
switch($n){
case 0:return "img-left";
case 1:return "img-middle";
case 2:return "img-right";
case 3:return "img-bottom";
case 4:return "img-super-left";
case 5:return "img-super-right";
}
}
public static function shortArticle($text){
$cant=1000;
$hasToShort = ($cant < strlen($text)) ? true : false;
$dots = ($hasToShort) ? "[...]" : "";
$cant = min($cant,strlen($text));
$text = substr($text,0,$cant);
return $text.$dots;
/*$text = $text.split('</p>');
$text.pop();
$text = $text.join('</p>');*/
$result = new stdClass();
$result->short = $hasToShort;
$result->text = $text.$dots;
return $result;
}
public static function getSocial($mini,$cont,$content){
if($cont>1 && $mini==0 || $cont==1 && $mini==1)return '';
$size = "24";
$str = '<ul class="list-inline list-unstyled social-big">';
if($cont>1){
$size="16";
$str = '<ul class="list-inline list-unstyled social-mini">';
}
$str.='<li> <a class="td-social-sharing-buttons td-social-twitter" href="https://twitter.com/intent/tweet?text='.urlencode($content->details->titulo).'&via=escuelaztlan&url='.urlencode(Section::host().$content->path.Section::$extention).'" onclick="window.open(this.href,' ."'". 'mywin'. "','". 'left=50,top=50,width=600,height=350,toolbar=0'."'".'); return false;"> <div class="td-sp td-sp-share-twitter"></div> <div class="td-social-but-text">Twitter</div></a> </li>';
$str.='<li> <a class="td-social-sharing-buttons td-social-facebook" href="https://www.facebook.com/sharer/sharer.php?u='.urlencode(Section::host().$content->path.Section::$extention).'" onclick="window.open(this.href,' ."'". 'mywin'. "','". 'left=50,top=50,width=600,height=350,toolbar=0'."'".'); return false;"> <div class="td-sp td-sp-share-facebook"></div> <div class="td-social-but-text">Facebook</div></a> </li>';
$str.='<li> <a class="td-social-sharing-buttons td-social-google" href="https://plus.google.com/share?url='.urlencode(Section::host().$content->path.Section::$extention).'" onclick="window.open(this.href,' ."'". 'mywin'. "','". 'left=50,top=50,width=600,height=350,toolbar=0'."'".'); return false;"> <div class="td-sp td-sp-share-google"></div> <div class="td-social-but-text">Google +</div></a> </li>';
$str.='</ul>';
return $str;
}
}
?><file_sep><?php
/**
* Date: 14/08/2013 14:28:41
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2013, <NAME>
* @filename DA.class.php
* @package
**/
/**
*/
class DA_Abs {
public static $idIdioma = null;
public static $onlyActives = false;
protected static function lastId($db){
$rs = $db->getRecordset();
$rs->execute("select last_insert_id() as id");
$id = intval($rs->field("id"));
$rs->close();
return $id;
}
}
?><file_sep>app.view.Login = app.Section.extend({
el:'div#login',
initialize: function() {
}
});
<file_sep>app.Address = {
subscriptores:[],
register : function(subscriptor){
this.subscriptores.push(subscriptor);
},
hashChange : function(section,route,params){
for(subs in this.subscriptores)
{
app.logger.log("subscriptor(modelo): ",this.subscriptores[subs].name);
this.subscriptores[subs].hashChange(section,route,params);
}
},
unregister : function(subscriptor){
for(var index in this.subscriptores){
if(this.subscriptores[index]==subscriptor){
this.subscriptores.splice(index,1);
}
}
}
};<file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
$idioma = GET_section::getIdiomaByStr($this->data->idioma);
$_SESSION['idioma'] = $idioma->idIdioma;
parent::addToSend(GET_section::getIdioma(), "idioma");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep>app.data.models.EventosModel = app.models.Model.extend({
name: 'EventosModel',
eventos:null,
owners:null,
sources:null,
user:null,
buscar: function($txt){
//console.log($txt);
var $self = this;
this.url.eventos.buscar($txt,function(data){
$self.set('eventos',data.eventos);
});
},
login : function(obj){
var $self = this;
this.url.user.login(function(data){
$self.set('user',data.user);
});
},
load : function(obj){
var $self = this;
this.url.eventos.getEventos(function(data){
$self.set('eventos',data.eventos);
});
},
loadLatetst : function(obj){
var $self = this;
this.url.eventos.getLatestsEventos(function(data){
$self.set('eventos',data.eventos);
});
},
getOwners : function(){
var $self = this;
this.url.eventos.getOwners(function(data){
$self.set('owners',data.owners);
});
},
getSources : function(){
var $self = this;
this.url.eventos.getSources(function(data){
$self.set('sources',data.sources);
});
},
getNameSource : function(id){
var sources = this.get('sources');
$.each(sources,function(){
if(this.idFuente == id) {
sources = this.nombre;
return;
}
});
return sources;
}
});
<file_sep><?php
class Mail {
private $_vPara = array ();
private $_from;
private $_fromName;
private $_asunto;
private $_body;
private $_isHtml = true;
public function __construct() {
}
public function clearRecipients() {
$this->_vPara = array ();
}
public function addRecipient($mail, $nombre = "") {
if ($nombre == "") {
$this->_vPara[] = "$mail";
} else {
$this->_vPara[] = "$nombre <$mail>";
}
}
public function from($mail, $nombre = "") {
$this->_from = "<" . $mail . ">";
$this->_fromName = $nombre;
}
public function subject($asunto) {
$this->_asunto = $asunto;
}
public function body($body) {
$this->_body = $body;
}
public function isHtml($hmtl) {
$this->_isHtml = $hmtl;
}
public function send() {
$from = $this->_fromName . " " . $this->_from;
foreach ($this->_vPara as $para) {
$cabeceras = "MIME-Version: 1.0 \r\n";
if (!$this->_isHtml) {
$cabeceras .= "Content-type: text/plain; charset=iso-8859-1 \r\n";
} else {
$cabeceras .= "Content-type: text/html; charset=iso-8859-1 \r\n";
}
$cabeceras .= "From: $from \r\n";
mail($para, $this->_asunto, $this->_body, $cabeceras, "-f ".$this->_from);
}
}
}
?><file_sep><?php
abstract class AAppObject extends FWObject{
protected $imgLoad=false;
protected $imgP="";
protected $imgS=array();
public final function getImage(){
if(!$this->imgLoad) $this->loadImages();
return $this->imgP;
}
public final function getImages($cant=null){
if(!$this->imgLoad) $this->loadImages();
if(is_null($cant)) return $this->imgS;
return array_slice($this->imgS, 0,$cant);
}
private function loadImages(){
$urlGet=Application::appKey("url").Application::appConfig("urlGallery")."get/?folder=".$this->getId();
$a=json_decode(@file_get_contents($urlGet));
if(!is_null($a)){
if(count($a->gallery)>0){
$this->imgP=$a->gallery[0];
}
for($x=1;$x<count($a->gallery);$x++){
$this->imgS[]=$a->gallery[$x];
}
}
$this->imgLoad=true;
}
}
?><file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
if($_GET['idEvento']){
$idEvento = $_GET['idEvento'];
$evt = GET_eventos::getEvento($idEvento);
$fp = fopen( 'php://temp/maxmemory:'. (12*1024*1024) , 'r+' );
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT idOwner,nombre FROM owners WHERE activo = 1 ";
//echo $sql;die;
$owners = $rs->getObjects($sql);
$thelink = "http://www.aztlan.org.ar/pages/";
if($evt->tipoEvento_idTipo == '1')$thelink.="cineclub";
else $thelink.="psi";
$thelink.="/?c=".$idEvento.'/';
//+owner+'/'+fuente;
fputcsv( $fp, array('Nombre','FBMuro','FBImpulsar','EventoFB','Email','Adwords','Inbox'));
foreach ($owners as $owner){
//var_dump($evt);die;
$owner->muro = $thelink.$owner->idOwner."/".'1';
$owner->impulsar = $thelink.$owner->idOwner."/".'2';
$owner->evento = $thelink.$owner->idOwner."/".'5';
$owner->email = $thelink.$owner->idOwner."/".'6';
$owner->adwords = $thelink.$owner->idOwner."/".'8';
$owner->inbox = $thelink.$owner->idOwner."/".'9';
fputcsv( $fp, array($owner->nombre,$owner->muro,$owner->impulsar,$owner->evento,$owner->email,$owner->adwords,$owner->inbox));
}
ob_clean();
//die;
rewind( $fp );
$output = stream_get_contents( $fp );
$output = str_replace(",",";",$output);
fclose( $fp );
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=linksreservas_'. $idEvento .'.csv' );
header('Content-Length: '. strlen($output) );
echo $output;
exit;
}
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
class FWException extends Exception{
/**
*
* @param FWExceptionCode $code
* @param string $msg
*/
public function __construct($code, $msg=""){
parent::__construct("FWException: ".$msg, $code);
Logger::logError($this);
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idSection
parent::addToSend(GET_section::getOrders($this->data->id),'orders');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql
* @filesource
**/
/**
*
**/
class SQLExceptionCode{
const DB_ERR_UNKNOWN = 0;
const DB_ERR_DUP_ENTRY = 1062;
const DB_ERR_WRONG_VALUE_COUNT_ON_ROW =1136;
const DB_ERR_NO_SUCH_TABLE =1146;
}
?><file_sep><?php
function smarty_modifier_iconv($string, $from="UTF-8", $to="ISO-8859-1"){
return iconv($from, $to, $string);
}
?><file_sep><?php
class SET_section extends DA_Abs{
public static function createSection($data){
//var_dump($data);die;
$active = $data->details->active;
$toMain = $data->details->toMainMenu;
$name = escape($data->details->name);
$tomainname = escape($data->details->toMainName);
$level = $data->level;
$parent = $data->parent;
$order = $data->order;
$type = $data->type;
$showContent = $data->showContent;
$rname = escape($data->rname);
$fecha = new Fecha();
$sqlAbs = "INSERT INTO sections (fecha,
contentTypes_idType,
level,
sectionOrder,
referenceName,
showContent)
VALUES (
'$fecha',$type,$level,$order,'$rname',$showContent)";
try
{
$db = Conexion::getConexion();
//echo $sqlAbs;die;
$db->execute($sqlAbs);
$nid = self::lastId($db);
$sqlDetails = "INSERT INTO `section_details`
(`idiomas_idIdioma`,
`sections_idSection`,
`name`,
`toMainMenu`,
`toMainName`,
`active`)
VALUES (".
self::$idIdioma . ",
$nid,
'$name',
$toMain,
'$tomainname',
$active )";
//echo $sqlDetails;die;
$db->execute($sqlDetails);
if($level !=0){
$sqlRelations = "INSERT INTO section_relations (subSection,parent) VALUES (
$nid,$parent )";
//echo $sqlRelations;die;
$db->execute($sqlRelations);
}
return GET_section::getSection($nid);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error inesperado ($c):" . $e->getMessage(), 200);
}
}
public static function updateSection($data){
$idSection = $data->id;
$active = $data->details->active;
$toMain = $data->details->toMainMenu;
$type = $data->type;
$name = escape($data->details->name);
$tomainname = escape($data->details->toMainName);
$rname = escape($data->rname);
$showContent = $data->showContent;
$fecha = new Fecha();
//var_dump($data);die;
$sqlAbs = "UPDATE sections SET referenceName='$rname',fecha='$fecha',contentTypes_idType=$type,showContent=$showContent WHERE idSection=$idSection";
$details = GET_section::getDetails($idSection);
if(is_null($details)){
$sqlDetails = "INSERT INTO `section_details`
(`idiomas_idIdioma`,
`sections_idSection`,
`name`,
`toMainMenu`,
`toMainName`,
`active`)
VALUES (".
self::$idIdioma . ",
$idSection,
'$name',
$toMain,
'$tomainname',
$active )";
}
else{
$sqlDetails = "UPDATE section_details SET
name='$name',
active=$active,
toMainMenu=$toMain,
toMainName='$tomainname'
WHERE sections_idSection=$idSection
AND idiomas_idIdioma=" . self::$idIdioma;
}
try
{
$db = Conexion::getConexion();
if(self::$idIdioma == 1) $db->execute($sqlAbs);//solo modificamos si es castewllano
$db->execute($sqlDetails);
return true;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error updateSection() ($c):" . $e->getMessage(), 200);
}
}
public static function delete($id){
$section = GET_section::getSection($id);
foreach($section->sections as $sub)
{
self::delete($sub->id);
}
//contenidos to seccion
//sectionrelations
//sectionDetails
//section
$sql_1 = "DELETE FROM content_tosection WHERE sections_idSection=$id";
$sql_2 = "DELETE FROM section_relations WHERE parent=$id";
$sql_3 = "DELETE FROM section_relations WHERE subSection=$id";
$sql_4 = "DELETE FROM section_details WHERE sections_idSection=$id";
$sql_5 = "DELETE FROM sections WHERE idSection=$id";
try
{
$db = Conexion::getConexion();
//echo $sqlDetails;die;
if(self::$idIdioma == 1)//solo borramos si es castewllano
{
$db->execute($sql_1);
$db->execute($sql_2);
$db->execute($sql_3);
$db->execute($sql_4);
$db->execute($sql_5);
return true;
}
return false;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error delete() ($c):" . $e->getMessage(), 200);
}
}
public static function changeOrder($secciones){
//var_dump($secciones);die;
$sql ="UPDATE sections SET sectionOrder= ";
foreach($secciones as $sec){
$csql = $sql.$sec->order . " WHERE idSection=" . $sec->idSection;
//echo $csql;die;
try
{
$db = Conexion::getConexion();
$db->execute($csql);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error inesperado ($c):" . $e->getMessage(), 200);
}
}
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
parent::addToSend(GET_eventos::getReservas($this->data->idEvento),'reservas');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
include "../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
parent::addToSend(GET_site::getIdioma(), "idioma");
parent::addToSend(GET_site::getSite(), "site");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
/**
* Date: 26/10/2011 14:19:55
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2011, <NAME>
*
*/
set_exception_handler("SerializableController::sendError");
abstract class PageSerializableController extends PageController implements IserializableController{
var $data=null;
public function __construct(){
$this->pageType=PageType::service;
parent::__construct();
$this->data=SerializableController::getData();
}
function addToSend($obj, $name=null){
SerializableController::addToSend($obj, $name);
}
function send($msg=""){
SerializableController::send();
}
}
?><file_sep><?php
// 23/10/2008 20:01:48
abstract class Controller{
private function __construct(){
}
public static function load($className){
if(@class_exists($className)){
$classTmp=new $className;
$classTmp->init();
$classTmp->onLoad();
$classTmp->onPreRender();
$classTmp->onRender();
$classTmp->onUnLoad();
$classTmp->close();
$classTmp->dispose();
return;
}
throw new Exception("Controller::load() / Controlador no encontrado: ".$className);
}
}
?><file_sep><?php
abstract class AApplicationDb extends AFWDataBase {
}
?><file_sep><?php
class GET_section extends DA_Abs{
public static function getSite(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
if(self::$onlyActives)
{
$sql="SELECT sections.idSection as id,sections.sectionOrder
FROM sections,section_details
WHERE sections.level=0
AND sections.idSection = section_details.sections_idSection
AND section_details.active = 1
AND section_details.idiomas_idIdioma = " . self::$idIdioma ."
order by sections.sectionOrder";
}
else
{
$sql="SELECT idSection as id,sectionOrder
FROM sections
WHERE level=0
order by sectionOrder";
}
//echo $sql;die;
$site=$rs->getObjects($sql);
$rsite = array();
foreach ($site as $valor)$rsite[] = self::getSection($valor->id);
return $rsite;
}
public static function getOrders($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT sections.idSection as id,
sections.sectionOrder,
section_details.name
FROM section_details,sections";
$section = self::getSection($id);
if($section->level == 0)
{
$sql.=" WHERE section_details.sections_idSection = sections.idSection
AND sections.level = 0 ";
}
else
{
$parent = self::getParent($id)->id;
$sql.=" WHERE sections_idSection IN (SELECT subSection FROM section_relations WHERE parent = $parent)
AND section_details.sections_idSection = sections.idSection ";
}
$sql.="AND idiomas_idIdioma=". self::$idIdioma .
" order by sections.sectionOrder";
//echo $sql;die;
$sections=$rs->getObjects($sql);
return $sections;
}
public static function getSubSections($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$furl = self::getFurl($id);
$sql="SELECT sections.idSection as id,
sections.sectionOrder,
sections.referenceName,
section_details.name,
section_details.toMainMenu,
section_details.active,
sections.contentTypes_idType as type
FROM section_details,sections
WHERE sections_idSection IN (SELECT subSection FROM section_relations WHERE parent = $id)
AND section_details.sections_idSection = sections.idSection
AND idiomas_idIdioma=". self::$idIdioma ;
if(self::$onlyActives)$sql.=" AND section_details.active=1";
$sql.=" order by sections.sectionOrder";
$sections=$rs->getObjects($sql);
addFurl($sections,$furl);
return $sections;
}
public static function getParent($idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql = "SELECT parent FROM section_relations WHERE subSection = '$idSection'";
$parent = $rs->getObject($sql);
//var_dump($parent);die;
if($parent)
{
return self::getSection($parent->parent);
}
return null;
}
public static function getFurl($idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT section_details.name
FROM section_details,sections
WHERE section_details.sections_idSection = sections.idSection
AND section_details.idiomas_idIdioma=". self::$idIdioma . "
AND sections.idSection = $idSection ";
$section = $rs->getObject($sql);
addFurl($section); ;
return $section->furl;
}
public static function getSection($idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT sections.idSection as id,
sections.sectionOrder,
sections.level,
sections.referenceName,
section_details.name,
section_details.toMainName,
section_details.toMainMenu,
section_details.active,
sections.contentTypes_idType as type
FROM section_details,sections
WHERE section_details.sections_idSection = sections.idSection
AND section_details.idiomas_idIdioma=". self::$idIdioma . "
AND sections.idSection = $idSection ";
$section = $rs->getObject($sql);
if($section->level != 0)
{
$parent = self::getParent($section->id);
//$sql = "SELECT parent FROM section_relations WHERE subSection = '$section->id'";
//$parentFurl = toFurl(self::getSection($rs->getObject($sql)->parent)->name);
addFurl($section,$parent->furl);
}
else {
addFurl($section);
$section->sections=self::getSubSections($section->id);
}
return $section;
}
public static function getIdiomaByStr($str){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas WHERE idioma='$str'";
return $rs->getObject($sql);
}
public static function getIdioma(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas WHERE idIdioma= " . self::$idIdioma ;
return $rs->getObject($sql);
}
}
?><file_sep><?php
class AztlanPageController extends PageController {
var $idioma = 1;
public function __construct(){
HX_Fmwk::registerApplication(Application::appKey("application"));
parent::__construct();
}
public function onPreRender(){
parent::onPreRender();
if(!is_null($_SESSION['idioma']))$this->idioma = $_SESSION['idioma'];
DA_Abs::$idIdioma = $this->idioma;
Section::$host = "http://".$_SERVER['HTTP_HOST']."/";
// echo gethostname();;die;
//var_dump($_SERVER);die;
#remove the directory path we don't want
//$request = str_replace("/", "", $_SERVER['REQUEST_URI']);
$request = $_SERVER['REQUEST_URI'];
//var_dump($request );
//echo $request;
#split the path by '/'
//para el .html
if(strrpos($request, ".")){
$filebroken = explode( '.', $request);
$extension = array_pop($filebroken);
$request = implode('.', $filebroken);
}
$params = explode("/", $request);
array_shift($params);
if($params[0]=='')$params[0]='home';
//echo "PARAMS 5";
//var_dump($params);die;
$safe_pages = array("home", "contactenos","contact-us","sitemap");
ob_clean();
$site = $this->getSite();
Section::$site = $site;
//var_dump($site);die;
$section = $this->getSection($site,$params);
//var_dump($section);die;
//var_dump($site->site);die;
if(count($section) > 0){
Section::$section = $section;
Section::getContents();
}
if(in_array($params[0], $safe_pages)) {
include($params[0].".php");
} else {
// articulos o videos o 404
//buscar en menu variables
// redireccionar a las tres opciones anteriores posibles
if(!count($section) > 0)include ('404.php');
else {
//Section::getContents();
include("articulo.php");
}
}
}
public function getTitle(){
return utf8_decode(Section::$contents->contents[0]->details->titulo);
}
private function getSite(){
if(DA_Abs::$idIdioma == 2) return json_decode(utf8Encode(base64_decode(file_get_contents("menu64-en.txt"))));
return json_decode(utf8Encode(base64_decode(file_get_contents("menu64.txt"))));
}
private function getSection($site,$route){
//articulo es en realidad seccion...me confundo las secciones con el contenido articulo
$seccionStr = $route[0];
$seccion = null;
$articulo=null;
$result = array();
if(count($route)>1)$articulo=$route[1];
//var_dump($site);
foreach ($site as $key => $value)
{
//var_dump($value);die;
if($value->furl == $seccionStr)
{
$seccion = $value;
$result[] = $value;
//var_dump($articulo);die;
if(!is_null($articulo))
{
foreach ($seccion->sections as $subkey => $subvalue)
{
//var_dump($subvalue);die;
if($subvalue->furl == $articulo)
{
$result[] = $subvalue;
if(count($route)>2)$result[]=$route[2];//agregamos en nombre del articulo
/*if($subvalue->showContent == 1){
var_dump($subvalue);die;
}*/
//$articulo = $subvalue;
break;
}
}
}
break;
}
}
//if(!is_null($articulo)) $seccion = $articulo;
//var_dump($seccion);die;
//var obj = {seccion:seccion.id,path:seccion.path};
return $result;
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
parent::addToSend(DA_popup::getAll(), "popups");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep>app.data.models.ListaModel = app.models.SectionModel.extend({
name: 'ListaModel',
evento:null,
reservas:null,
resolveQuery : function(query) {
this.getReservas(query.route[0]);
this.getEvento(query.route[0]);
}
,
getEvento : function(idEvento){
var $self = this;
this.url.eventos.getEvento(idEvento,function(data){
$self.set('evento',data.evento);
});
},
getReservas : function(idEvento){
var $self = this;
this.url.eventos.getReservas(idEvento,function(data){
$self.set('reservas',data.reservas);
});
},
presentismo : function(obj,idEvento){
var $self = this;
this.url.eventos.presentismo(obj,function(data){
Url.setHash('#/ver-asistencia/'+idEvento);
});
},
clean : function(){
this.unset('query', {silent:true});
}
});<file_sep><?php
/**
* Date: 08/11/2011 12:12:44
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2011, <NAME>
* @package default
* @filesource
*/
interface IserializableController{
function addToSend($obj);
function send($msg="");
}
?><file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql
* @filesource
**/
/**
*
**/
interface IConnection{
/**
* @return IRecordset
*/
public function getRecordset();
/**
* @param string $strCon
* @return void
*/
public function open($strCon);
/**
* @param string $sql
* @return array
*/
public function execute($sql);
/**
* @return void
*/
public function close();
/**
* @return bool
*/
public function isClosed();
}
?><file_sep><?php
/**
* Date: 22/08/2012 16:37:29
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package
**/
/**
*
**/
class RecordsetMySqli implements IRecordset{
/**
*
* @var mysqli
*/
private $db;
/**
*
* @var mysqli_result
*/
private $result;
/**
*
* @var stdClass
*/
private $rs;
/**
*
* @var boolean
*/
public $eof=true;
/**
* @param IConnection $db
* @return void
*/
public function __construct($db){
$this->db=$db;
}
/**
* @param string $sql
* @throws MySqliException
*/
public function execute($sql) {
$this->result=$this->db->query($sql);
if(!$this->result){
throw new MySqliException(new Exception($this->db->error,$this->db->errno));
}
$this->rs=$this->result->fetch_object();
$this->eof=(is_null($this->rs))?true:false;
}
/**
*
* @param string $sql
* @return string
*/
public function getJSON($sql){
$ret=array();
$this->result=$this->db->query($sql);
if(!$this->result){
throw new MySqliException(new Exception($this->db->error,$this->db->errno));
}
while ($row = $this->result->fetch_object()) {
$ret[]=$row;
}
return @json_encode($ret);
}
/**
*
* @param string $sql
* @return array <stdClass>
*/
public function getObjects($sql){
$ret=array();
$this->result=$this->db->query($sql);
if(!$this->result){
throw new MySqliException(new Exception($this->db->error,$this->db->errno));
}
while ($row = $this->result->fetch_object()) {
$o=new stdClass();
foreach ($row as $k=>$v){
$o->$k=utf8Encode($v);
}
$ret[]=$o;
}
return $ret;
}
/**
*
* @param string $sql
* @return null|stdClass
*/
public function getObject($sql){
$ret=null;
$this->result=$this->db->query($sql);
if(!$this->result){
throw new MySqliException(new Exception($this->db->error,$this->db->errno));
}
$r=$this->result->fetch_object();
if(is_null($r)) return $ret;
$ret=new stdClass();
foreach ($r as $k=>$v){
$ret->$k=utf8Encode($v);
}
return $ret;
}
/**
* @return void
*/
public function moveNext() {
if ($this->rs = $this->result->fetch_object()) {
$this->eof = false;
} else {
$this->eof = true;
}
}
/**
* @param string $value
* @return string
*/
public function field($value) {
return utf8Encode($this->rs->$value);
}
/**
* @param string $value
* @return int
*/
public function getInt($value){
return intval($this->field($value));
}
/**
* @param string $value
* @return double
*/
public function getDouble($value){
return doubleval($this->field($value));
}
/**
* @param string $value
* @return Fecha
*/
public function getDate($value){
return new Fecha($this->field($value));
}
/**
* @return int
*/
public function rows() {
return $this->result->num_rows;
}
/**
* @return void
*/
public function close() {
$this->result->free();
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
error_reporting(0);
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//params
//camp
ob_clean();
if($this->data->params->eventSelect)
{
$evento = GET_eventos::getEvento($this->data->params->eventSelect);
}else
{
$evento = GET_eventos::getEvento($this->data->evento);
}
$owner = GET_camp::getOwner($this->data->owner);
$source = GET_camp::getSource($this->data->source);
$isReserva = ($evento->tipo == 1) ? true:false;
$usuario = SET_camp::setUsuario($evento,$owner,$source,$this->data->params);
if($isReserva) {
SET_camp::setReserva($evento,$owner,$source,$this->data->params,$usuario->idUsuario);
parent::addToSend(GET_camp::getReserva($this->data->evento,$usuario->idUsuario),'reserva');
}
else SET_camp::setConsulta($this->data->params,$usuario->idUsuario);
parent::addToSend($usuario,'usuario');
/*
if($isReserva){
parent::send();
return;
}
*/
$fecha = new Fecha();
// PREPARE THE BODY OF THE MESSAGE
$message .= '';
//$message .= '<html>';
$message .= '<body style="font-family:Tahoma, Geneva, sans-serif;">';
$message .= '<div style="background: #1b1b1b;width:800px;margin:0 auto;">';
$message .= '<div style="color:black;background: #F9FAF7;width:800px;text-align:center">';
$message .= '<h3 style="margin:0px;padding-top:20px;">CONSULTAS DESDE LA WEB</h3>';
$message .= '<h2 style="margin:0px;padding-top:20px;"> '. $evento->titulo .'</h2>';
$message .= '<h2 style="margin:0px;padding-top:20px;"> '. $evento->subtitulo .'</h2>';
$message .= '<h2 style="margin:0px;padding-top:20px;"> '. $evento->fechaStr .'</h2>';
$message .= '<h3 style="margin:0px;padding:20px 0px">FORMULARIO '.$fecha.'</h3>';
$message .= '</div>';
$message .= '<table rules="all" style="background: white;border-color: #666;" cellpadding="10" width="800">';
foreach ($this->data->params as $key => $valor)
{
if(ucfirst(strtolower($key)) != "G-recaptcha-response")
{
$message .= '<tr><td><strong>'.ucfirst(strtolower($key)).'</strong> </td><td>' . strip_tags($valor) . '</td></tr>';
}
}
$message .= '<tr><td><strong>'.$owner->nombre .'</strong> </td><td>' . $source->nombre . '</td></tr>';
$message .= '</table>';
$message .= '</div>';
$message .= "</body>";
//$message .= '</html>';
//echo $message;return;
$mail = new PHPMailer;
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$emailserver = '<EMAIL>';
//DESCOMENTAR ESTOS PARA CORREO PRIVADO
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = $emailserver;
$mail->Password = '<PASSWORD>';
$mail->From = $emailserver;
$mail->FromName = 'Form Web Psico';
$mail->addAddress($owner->email);
$mail->addReplyTo($emailserver, 'Respuesta de formulario web');
//$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
/*$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');*/
$mail->isHTML(true); // Set email format to HTML
if($isReserva) $mail->Subject = 'Reserva - ' .$usuario->idUsuario ;
else $mail->Subject = 'Consulta - ' .$usuario->idUsuario ;
$mail->Body = $message;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$serviceMsg = '';
if(!$mail->send()) {
$serviceMsg.= 'Message could not be sent.';
$serviceMsg.= '\n' . 'Mailer Error: ' . $mail->ErrorInfo;
//TWROW EXEPTION;
}else $serviceMsg.= 'Message has been sent';
parent::addToSend($serviceMsg,"email");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
//ALTER TABLE `owners` ADD `email` VARCHAR( 300 ) NOT NULL AFTER `nombre` ;
?>
<file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
if($_GET['idEvento']){
$idEvento = $_GET['idEvento'];
//$fecha = $_GET['fecha'];
$fp = fopen( 'php://temp/maxmemory:'. (12*1024*1024) , 'r+' );
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * FROM reservas WHERE eventos_idEvento = $idEvento "; //no borrado AND confirmado !=2
//echo $sql;die;
$reservas = $rs->getObjects($sql);
//var_dump($reservas);die;
foreach ($reservas as $reserva){
$id = $reserva->usuarios_idUsuario;
$c = $reserva->camp_idCamp;
$tipoUsuario = $reserva->tipoUsuario;
if($tipoUsuario==1)$sql = "SELECT * FROM usuarios WHERE idUsuario = $id";
else $sql = "SELECT * FROM falsos_usuarios WHERE idUsuario = $id";
$reserva->usuario = $rs->getObject($sql);
$sql="SELECT owners.nombre FROM campaings,owners
WHERE idCamp = $c
AND campaings.owners_idOwner = owners.idOwner
";
$reserva->owner = $rs->getObject($sql)->nombre;
if(is_null($reserva->owner)){
$c = $reserva->owners_idOwner;
$sql="SELECT nombre FROM owners
WHERE idOwner = $c";
$reserva->owner = $rs->getObject($sql)->nombre;
}
$nombre = $reserva->usuario->nombre;
$apellido = $reserva->usuario->apellido;
$email = $reserva->usuario->email;
$telefono = $reserva->usuario->telefono;
$source = $reserva->owner;
$idReserva = $reserva->idReserva;
fputcsv( $fp, array($apellido,$nombre,'','',$email,$telefono,$source,$idReserva));
}
ob_clean();
//die;
rewind( $fp );
$output = stream_get_contents( $fp );
$output = str_replace(",",";",$output);
fclose( $fp );
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=reservas_'. $idEvento .'.csv' );
header('Content-Length: '. strlen($output) );
echo $output;
exit;
}
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {translate} function plugin
*
* Type: function<br>
* Name: translate<br>
* Purpose: traducir una palabra en tiempo de ejecucion<br>
* @link http://smarty.php.net/manual/en/language.function.eval.php {eval}
* (Smarty online manual)
* @author <NAME> <hugo at hexium dot com dot ar>
* @param array
* @param Smarty
*/
function smarty_function_translate($params, & $smarty) {
if (!isset ($params['var'])) {
$smarty->trigger_error("eval: missing 'var' parameter");
return;
}
if (isset ($params['type'])) {
return CultureInfo::translate($params['var'], $params['type']);
}
return CultureInfo::translate($params['var']);
}
/* vim: set expandtab: */
?>
<file_sep><?php
include "../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//nombre
//email
//consulta
//telefono
//newsletter
$nombre = escape($this->data->nombre);
$tel = escape($this->data->telefono);
$email = escape($this->data->email);
$dni = escape($this->data->dni);
$consulta = escape($this->data->consulta);
$facebook = escape($this->data->facebook);
$newsletter = $this->data->newsletter;
$fecha = new Fecha();
$cid = SET_consulta::setConsulta($this->data);
parent::addToSend($cid,'consulta');
// PREPARE THE BODY OF THE MESSAGE
$message .= '';
//$message .= '<html>';
$message .= '<body style="font-family:Tahoma, Geneva, sans-serif;">';
$message .= '<div style="background: #1b1b1b;width:800px;margin:0 auto;">';
$message .= '<div style="color:black;background: #F9FAF7;width:800px;text-align:center">';
if($newsletter==1)$message .= '<h2 style="margin:0px;padding-top:20px;">SUSCRIPCION AL NEWSLETTER DE PSICOLOGÍA</h2>';
else $message .= '<h2 style="margin:0px;padding-top:20px;">CONSULTAS DESDE LA WEB DE PSICOLOGÍA</h2>';
//$message .= '<img style="margin-bottom:0px;" src="http://www.kyk-impo.com.ar/email/images/separacion_rayas.jpg" alt="www.kyk-impo.com.ar" />';
$message .= '<h3 style="margin:0px;padding:20px 0px">FORMULARIO</h3>';
$message .= '</div>';
//$message .= '<br/><br/>';
$message .= '<table rules="all" style="background: white;border-color: #666;" cellpadding="10" width="800">';
$message .= '<tr><td><strong>Nombre:</strong> </td><td>' . strip_tags($nombre) . '</td></tr>';
$message .= '<tr><td><strong>Teléfono:</strong></td><td>' . strip_tags($tel) . '</td></tr>';
$message .= '<tr><td><strong>Email:</strong></td><td>' . strip_tags($email) . '</td></tr>';
$message .= '<tr><td><strong>DNI:</strong></td><td>' . strip_tags($dni) . '</td></tr>';
$message .= '<tr><td><strong>Facebook:</strong></td><td>' . strip_tags($facebook) . '</td></tr>';
$message .= '<tr><td><strong>Consulta:</strong> </td><td>' . strip_tags($consulta) . '</td></tr>';
$message .= '<tr><td><strong>Fecha:</strong> </td><td>' . strip_tags($fecha) . '</td></tr>';
$message .= '</table>';
$message .= '</div>';
$message .= "</body>";
//$message .= '</html>';
//echo $message;return;
$mail = new PHPMailer;
//$mail->isSMTP(); // Set mailer to use SMTP
//$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
//$mail->SMTPAuth = true; // Enable SMTP authentication
//$mail->Username = 'jswan'; // SMTP username
//$mail->Password = '<PASSWORD>'; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->CharSet = 'UTF-8';
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$emailserver = '<EMAIL>';
$emailserver = '<EMAIL>';
//DESCOMENTAR ESTOS PARA CORREO PRIVADO
//$mail->Host = "localhost";
//$mail->Port = 25;
$mail->Host = 'smtp.gmail.com';
//$mail->Port = 587;//465
$mail->Port = 465;
$mail->Username = $emailserver;
$mail->Password = '<PASSWORD>';
$mail->Password = '<PASSWORD>';
$mail->From = $emailserver;
$mail->FromName = 'Form Web Psico';
//$mail->addAddress($this->data->email,$this->data->nombre); // Name is optional
$mail->addAddress('<EMAIL>');
$mail->addReplyTo($emailserver, 'Respuesta de formulario web');
//$mail->addCC('<EMAIL>');
//$mail->addBCC('<EMAIL>');
//$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
$mail->addBCC('<EMAIL>');
//$mail->addAttachment('../../email/firmas/firma-sergio-itic.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Formulario Web Psicología - n° ' . $cid ;
$mail->Body = $message;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$serviceMsg = '';
if(!$mail->send()) {
$serviceMsg.= 'Message could not be sent.';
$serviceMsg.= '\n' . 'Mailer Error: ' . $mail->ErrorInfo;
//TWROW EXEPTION;
}else $serviceMsg.= 'Message has been sent';
parent::addToSend($serviceMsg,"email");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
set_exception_handler("SerializableController::sendError");
abstract class PageSerializableController extends PageController implements IserializableController{
var $data=null;
public function __construct(){
parent::__construct();
$this->data=SerializableController::getData();
}
function addToSend($obj, $name=null){
SerializableController::addToSend($obj, $name);
}
function send($msg=""){
SerializableController::send($msg);
}
}
?><file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql/MySql
* @filesource
**/
/**
*
**/
class MySqlException extends Exception {
/**
* @param Exception $e
* @return void
*/
public function __construct($e){
switch ($e->getCode()) {
case 1062:
parent::__construct("DB_ERR_DUP_ENTRY", $e->getCode());
break;
case 1136:
parent::__construct("DB_ERR_WRONG_VALUE_COUNT_ON_ROW", $e->getCode());
break;
case 1146:
parent::__construct("DB_ERR_NO_SUCH_TABLE", $e->getCode());
break;
default:
parent::__construct($e->getMessage(), 0);
break;
}
//Logger::logError($e);
}
}
?><file_sep>(function(app) {
function Logger() {
}
Logger.prototype.log = function() {
if (!app.application.log)
return;
var e = 'console.log(\'Logger->\',';
for ( var x = 0; x < arguments.length; x++) {
e += 'arguments[' + x + '],';
}
eval(e.replace(/,$/, ')'));
};
app.logger = new Logger();
})(window.app);
<file_sep><?php
function smarty_function_post($params, &$smarty){
// be sure equation parameter is present
if (empty($params['var'])) {
$smarty->trigger_error("math: missing var parameter");
return;
}
return $_POST[$params['var']];
}
?><file_sep>
app.Router = Backbone.Router.extend({
routes : {
":query(/*params)" : "hashChange", // #search/kiwis/p7
"" : "hashChange"
},
hashChange : function(section, url) {
var route = [];
var params;// = {};
var hash;
if (url)hash= url.split('?');
if(hash && hash.length>1){
eval('params={'
+ hash[1].replace(/=/g, ':\'').replace(/&/g, '\',')
+ '\'}');
}
if (hash)route = hash[0].split('/');
if(section==undefined)section='dashboard';
app.logger.log('ROUTER --> ',"S: ", section,"-R: ", route,"-P: ",params);
app.Address.hashChange(section,route,params);
}
});
var eventos = new app.data.models.EventosModel();
$(function() {
if(isMobile.any())$('body').addClass('mobile');
app.router = new app.Router();
//Componentes solos
new app.view.Menu({model:eventos});
var sectionManagerModel = new app.models.SectionManagerModel();
app.Address.register(sectionManagerModel);
//secciones
sectionManagerModel.registerSections(new app.view.Dashboard({model:eventos}), 'dashboard');
sectionManagerModel.registerSections(new app.view.Lista(), 'lista');
sectionManagerModel.registerSections(new app.view.ListaVerAsistencia(), 'ver-asistencia');
sectionManagerModel.registerSections(new app.view.EditarAsistencia(), 'editar-asistencia');
sectionManagerModel.registerSections(new app.view.Form(), 'form');
sectionManagerModel.registerSections(new app.view.Login({model:eventos}), 'login');
sectionManagerModel.registerSections(new app.view.Usuario(), 'usuario');
eventos.bind('change',startSite);
eventos.loadLatetst();
$('.buscar').click(function(){
eventos.buscar($('.buscador').val());
Url.setHash('');
});
$( "form#target" ).submit(function( event ) {
eventos.buscar($('.buscador').val());
event.preventDefault();
Url.setHash('');
});
/*
$('.btn-ver-todos').click(function(){
eventos.loadLatetst();
});
$('.btn-ver-ultimos').click(function(){
eventos.load();
});*/
});
function startSite(){
eventos.unbind('change',startSite);
eventos.getOwners();
eventos.getSources();
Backbone.history.start();
log('start');
}
<file_sep><?php
/**
* Date: 19/12/2012 17:21:29
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package
**/
/**
*
**/
class PageType{
const service="service" ;
const page="page";
const template="template";
}
?><file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql
* @filesource
**/
/**
*
**/
interface IRecordset{
/**
* @param string $sql
* @return void
*/
public function execute($sql);
/**
* @return void
*/
public function moveNext();
/**
* @param string $value
* @return string
*/
public function field($value);
/**
* @return array
*/
public function rows();
/**
* @return void
*/
public function close();
/**
* @param string $value
* @return int
*/
public function getInt($value);
/**
* @param string $value
* @return double
*/
public function getDouble($value);
/**
* @param string $value
* @return Fecha
*/
public function getDate($value);
/**
*
* @param string $sql
* @return string
*/
public function getJSON($sql);
/**
*
* @param string $sql
* @return array <stdClass>
*/
public function getObjects($sql);
/**
*
* @param string $sql
* @return stdClass
*/
public function getObject($sql);
}
?><file_sep><?php
class FWExceptionCode {
const UNKNOWN_EXCEPTION = -200;
const IO_EXCEPTION = -201;
const FILE_NOT_FOUND = -202;
const COMMUNICATION_EXCEPTION = -203;
}
?><file_sep><?php
//echo base_convert('1000', 10, 36);die;
session_start();
$_SESSION['now'] = time();
// var_dump($_SESSION);
if (!isset($_SESSION['log'])) {
header('Location: '.'login.php');
}
else {
$now = time(); // Checking the time now when home page starts.
if ($now > $_SESSION['expire']) {
session_destroy();
header('Location: '.'login.php');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Eventos</title>
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Gentium+Book+Basic:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="site/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="site/bootstrap/css/bootstrap-switch.min.css" rel="stylesheet">
<!--
<link rel="stylesheet/less" type="text/css" href="site/less/estilos.less" />
<script src="site/less/less-1.4.1.min.js"></script>
-->
<link href="site/css/estilos.css?v=0.2" rel="stylesheet">
<!-- PLUGINS -->
<link href="../site/css/plugins/toastr.css" rel="stylesheet">
<script src="site/js/script.js?random=<?php echo uniqid(); ?>"></script>
<?php
$limit = (((($_SESSION['expire'] - $_SESSION['now'])/60)*60)*1000) + 300000;
echo '<script>var endtime='.$limit.';</script>';
?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if IE ]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<link href="site/css/ie.css" rel="stylesheet">
<![endif]-->
</head>
<body>
<nav class="header-nav">
<div class="header container">
<div class="row">
<div class="logo col-xs-2 col-sm-2 col-md-4 hidden-xs ">
<img src="images/logo.png" class="pull-left">
<div class="pull-left hidden-sm">
<h1 class="h1Header">Aztlan</h1>
<h4 class="h4Header">Director <NAME></h4>
</div>
</div>
<div class="slogan col-xs-8 col-sm-8 col-md-6">
<h1 class="h1Header">Escuela de Filosof�a y Psicolog�a</h1>
<h4 class="h4Header"><strong>Ense�anza Privada Nivel Terciario - No oficial</strong></h4>
<p class="pHeader hidden-xs">Personer�a Jur�dica N� I.G.J. 748</p>
<p class="pHeader hidden-xs">Centro Nacional de Organizaciones de la Comunidad C.E.N.O.C. N� 16528</p>
</div>
<div class="slogan col-xs-2 col-sm-2 col-md-2">
<div class="btn-home"><a href="http://aztlan.com.ar/eventos" ><button class="btn btn-default"><span style="font-size:15px;" class="glyphicon glyphicon-home"></span><strong> Home</strong></a></button></div>
<div class="btn-salir"><a href="logout.php"><button class="btn btn-default"><span style="font-size:15px;" class="glyphicon glyphicon-remove"></span> <strong> Salir</strong></a></button></div>
</div>
</div>
</div>
</nav>
<nav class="nav-section">
<div class="container">
<div class="row">
<h2 class="pull-left"><span>�ltimos</span> Eventos</h2>
<div class="botonera pull-right">
<form id="target">
<input type="text" name="buscador" value="" class="buscador">
<span class="buscar glyphicon glyphicon-search" style="font-size:20px;"></span>
</form>
<a type="button" class="btn btn-default btn-lg" href="crear/evento.php"><span class="glyphicon glyphicon-ok-sign" style="font-size:20px;"></span> Crear Nuevo Evento</a>
</div>
</div>
</div>
</nav>
<div id="form" class="container">
<form class="form-horizontal" role="form">
<div class="form-group" >
<label for="inputName" class="col-sm-2 control-label">Nombre</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="nombre" validate chars="2" msg="Debes ingresar tu nombre" value="Sergio"
placeholder="Nombre">
</div>
</div>
<div class="form-group" >
<label for="inputLastname" class="col-sm-2 control-label">Apellido</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="apellido" validate chars="2" msg="Debes ingresar tu apellido" value="Makaruk"
placeholder="Apellido">
</div>
</div>
<div class="form-group" >
<label for="dni" class="col-sm-2 control-label">Dni</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="dni" validate chars="8" msg="Debes ingresar tu dni" value="32392290"
placeholder="33322211">
</div>
</div>
<div class="form-group">
<label for="inputTel" class="col-sm-2 control-label">Tel�fono</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="telefono" validate msg="Debes ingresar tu tel�fono" value="15.6378.5701"
placeholder="Tel�fono">
</div>
</div>
<input type="hidden" name="lugares" value="1">
<!-- <div class="form-group">
<label for="inputCantidad" class="col-sm-2 control-label">Lugares</label>
<div class="col-sm-10">
<select class="form-control" name="lugares">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
</div> -->
<div class="form-group">
<label class="col-sm-2 control-label">Owner</label>
<div class="col-sm-10">
<select class="form-control" name="owner" id="owner">
<option></option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Fuente</label>
<div class="col-sm-10">
<select class="form-control" name="fuente" id="fuente">
<option></option>
</select>
</div>
</div>
<input type="text" class="form-control" name="tipo" id="tipo" style="display:none">
<input type="text" class="form-control" name="idEvento" id="idEvento" style="display:none">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input class="form-control" type="checkbox" name="addBase" value="0">
Agregar a base de emails
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input class="form-control" type="checkbox" name="guardarEmail" value="0">
Guardar Email
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control locked" name="email" validate="email" msg="Debes ingresar tu email" value="<EMAIL>"
placeholder="Email" disabled>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btnSend btn btn-warning">Enviar</button>
<div class="loading-form">
<h4>Enviando...</h4>
<div class="slider">
<div class="line"></div>
<div class="break dot1"></div>
<div class="break dot2"></div>
<div class="break dot3"></div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="usuario-template usuario-tm row" style="display:none;">
<h1>HISTORIAL DE USUARIO</h1>
<h2 class="nombre"></h2>
<div class="row">
<div class="col-md-6">
<h3>DNI: <span class="dni"></span></h3>
<h3 class="">EMAIL: <span class="email"></span></h3>
<h3 class="">TEL: <span class="telefono"></span></h3>
<h3 class="">SITUACIÓN: <span class="situacion"></span></h3>
</div>
<div class="col-md-6">
<div class="col-xs-12">
<form class="">
<label for=""><input type="checkbox" name="radio-admitido" value="1">
Admitido
</label>
<div class="motivo" style="display:none">
<label for="">Motivo</label>
<textarea class="admitido_txt" rows="8" cols="80"></textarea>
</div>
</div>
<div class="col-xs-12">
<button class="btn btn-default user-actualizar" type="button" name="button">Actualizar estado de usuario</button>
</div>
</form>
</div>
</div>
<table>
<tr>
<th>Fecha</th>
<th>Evento</th>
<th>Asistencia</th>
</tr>
<tbody class="eventos-user-container">
</tbody>
</table>
</div>
<div id="usuario-container" class="container">
</div>
<div class="evento-template row" style="display:none;">
<div class="col-md-6 col-xs-12">
<h3 class="titulo">Nombre de Evento</h3>
<h3 class="subtitulo">Subtitulo</h3>
<h4 class="fecha">Fecha</h4>
<h5 class="lugar">Lugar</h5>
</div>
<div class="col-md-6 col-xs-12">
<ul class="list-unstyled list-inline reservas">
<li>
<ul class="list-unstyled">
<li>Reservas</li>
<li class="cantidad n-reservas">120</li>
</ul>
</li>
<li>
<ul class="list-unstyled" >
<li>Confirmados</li>
<li class="cantidad confirmados">120</li>
</ul>
</li>
<li>
<ul class="list-unstyled" >
<li>Asistencia</li>
<li class="cantidad asistencia">0</li>
</ul>
</li>
<li>
<ul class="list-unstyled" >
<li>Anotados</li>
<li class="cantidad anotados">0</li>
</ul>
</li>
<li>
<ul class="list-unstyled">
<li>Disponibilidad</li>
<li class="cantidad disponibilidad">120</li>
</ul>
</li>
</ul>
<ul class="list-unstyled list-inline links">
<li><button type="button" class="btn btn-warning btn-xs btn-volver">Volver</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-form">Ver Formulario</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-lista">Ver Listado</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-links">Ver Links</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-ver">Ver Asistencia</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-editar">Editar Asistencia</button></li>
</ul>
</div>
</div>
<div id="lista" class="container">
<div class="row">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Nombre y Apellido</th>
<!-- <th>Dni</th> -->
<th>Email</th>
<!-- <th>Tel�fono</th> -->
<th>Estado</th>
<th>Lugares</th>
<th>Link</th>
<th>Fuente</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="btn-group template-btn" style="display:none;">
<button type="button" class="btn btn-default btn-estado btn-sm" data-estado="0"> <span class="glyphicon glyphicon-remove"></span></button>
<button type="button" class="btn btn-default btn-estado btn-sm" data-estado="9"> <span class="glyphicon glyphicon-phone-alt"></span></button>
<button type="button" class="btn btn-default btn-estado btn-sm" data-estado="8"> <span class="glyphicon glyphicon-envelope"></span></button>
<button type="button" class="btn btn-default btn-estado btn-sm" data-estado="1"> <span class="glyphicon glyphicon-ok"></span> </button>
<button type="button" class="btn btn-default btn-estado btn-sm btn-borrar" data-estado="2"> <span class="glyphicon glyphicon-trash"></span></button>
<button type="button" class="btn btn-default btn-usuario btn-sm"> <span class="glyphicon glyphicon-user"></span></button>
</div>
</div>
</div>
<div id="lista-editar-asistencia" class="container">
<div class="row">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Nombre y Apellido</th>
<th>Email</th>
<th>Presente</th>
<th>Lugares</th>
<th>Pago</th>
<th>Anotado</th>
</tr>
</thead>
<tbody>
<tr class="last-line">
<td>TOTAL:</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="total-pagos"></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="footer-editar"><button type="button" class="btn btn-default btn-lg btn-guardar"> GUARDAR</button> </div>
</div>
<div id="lista-ver-asistencia" class="container">
<div class="row">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Nombre y Apellido</th>
<th>Dni</th>
<th>Email</th>
<th>Tel�fono</th>
<th>Presente</th>
<th>Lugares</th>
<th>Pago</th>
<th>Anotado</th>
<th>Link</th>
<th>Fuente</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div id="login" class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Login</h3>
</div>
<div class="panel-body">
<form role="form">
<div class="form-group">
<label >Email address</label>
<input type="email" class="form-control" placeholder="Enter email">
</div>
<div class="form-group">
<label >Password</label>
<input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>">
</div>
<button type="submit" class="btn btn-default">Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="dashboard" class="container">
<div class="evt-container"></div>
<div class="evento row">
<div class="col-md-6 col-xs-12">
<h3 class="titulo">Nombre de Evento</h3>
<h3 class="subtitulo">Subtitulo</h3>
<h4 class="fecha">Fecha</h4>
<h5 class="lugar">Lugar</h5>
</div>
<div class="col-md-6 col-xs-12">
<ul class="list-unstyled list-inline reservas">
<li>
<ul class="list-unstyled">
<li>Reservas</li>
<li class="cantidad n-reservas">120</li>
</ul>
</li>
<li>
<ul class="list-unstyled" >
<li>Confirmados</li>
<li class="cantidad confirmados">120</li>
</ul>
</li>
<li>
<ul class="list-unstyled" >
<li>Asistencia</li>
<li class="cantidad asistencia">0</li>
</ul>
</li>
<li>
<ul class="list-unstyled" >
<li>Anotados</li>
<li class="cantidad anotados">0</li>
</ul>
</li>
<li>
<ul class="list-unstyled">
<li>Disponibilidad</li>
<li class="cantidad disponibilidad">120</li>
</ul>
</li>
</ul>
<ul class="list-unstyled list-inline links">
<li><button type="button" class="btn btn-warning btn-xs btn-form">Ver Formulario</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-lista">Ver Listado</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-edit-evento">Editar Evento</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-links">Ver Links</button></li>
</ul>
<ul class="list-unstyled list-inline links">
<li><button type="button" class="btn btn-warning btn-xs btn-ver">Ver Asistencia</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-editar">Editar Asistencia</button></li>
<li><button type="button" class="btn btn-warning btn-xs btn-descargar">Descargar CSV</button></li>
</ul>
</div>
</div>
</div>
<nav class="footer " role="navigation">
<div class="container">
<div class="row">
<span>© 2014 ESCUELA AZTLAN - Almagro, Ciudad Aut�noma de Buenos Aires, Argentina - <a href="mailto:<EMAIL>"><EMAIL></a> - 4981-0592/2442</span>
</div>
</div>
</nav>
<div class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Ver links</h4>
</div>
<div class="modal-body">
<select id="owner"></select>
<select id="fuente"></select>
<ul class="link-resultado list-unstyled">
<li class="view-link"><input class="form-control col-xs-6"></input><li>
<!-- <li class="view-link-copy"><button class="btn btn-warning">Copiar Link</button></li> -->
<li class="view-link-csv"><button class="btn btn-warning">Descargar Todos</button></li>
</ul>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="site/bootstrap/js/bootstrap.min.js"></script>
<script src="site/bootstrap/js/bootstrap-switch.min.js"></script>
<script>
setTimeout(function(){ window.location.reload(); }, endtime);
</script>
</body>
</html>
<file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql
* @filesource
**/
/**
*
**/
class Conexion{
private static $conexiones=array();
private function __construct(){
}
/**
* @param string|null $value
* @return IConnection
*/
public static function getConexion($value=null){
$value=(is_null($value))?"default":$value;
if(array_key_exists($value, self::$conexiones)){
if(!self::$conexiones[$value]->isClosed())
return self::$conexiones[$value];
}
$cadena=Configuration::connectionString($value);
$pos=strpos($cadena,";");
$drv=substr($cadena,0,$pos);
$cp=new ConnProperty(substr($cadena,$pos+1));
switch (strtolower($drv)){
case "drv=mysql":
self::$conexiones[$value]=new ConnectionMySql();
self::$conexiones[$value]->open($cp);
break;
case "drv=mysqli":
self::$conexiones[$value]=new ConnectionMySqli();
self::$conexiones[$value]->open($cp);
break;
}
return self::$conexiones[$value];
}
/**
* @param string|null $value
* @return void
*
*/
public static function close($value=""){
$value=($value=="")?"default":$value;
if(array_key_exists($value, self::$conexiones)){
self::$conexiones[$value]->close();
unset(self::$conexiones[$value]);
}
}
/**
* @return void
*/
public static function closeAll(){
foreach(array_keys(self::$conexiones) as $value){
self::close($value);
}
}
}
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql/MySql
* @filesource
**/
/**
*
**/
class ConnProperty{
var $server="";
var $database="";
var $uid="";
var $pwd="";
var $port="";
/**
* @param string $strConn
* @return void
*/
public function __construct($strConn){
$vConn=explode(";",$strConn);
foreach ($vConn as $valor){
$v=explode("=",$valor);
switch (strtolower($v[0])){
case "server":
$this->server=$v[1];
break;
case "database":
$this->database=$v[1];
break;
case "uid":
$this->uid=$v[1];
break;
case "pwd":
$this->pwd=$v[1];
break;
case "port":
$this->port=$v[1];
break;
}
}
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//secciones {id:n,order:n}
parent::addToSend(SET_section::changeOrder($this->data->secciones),'orderChanged');
parent::addToSend(GET_section::getSite(),'site');
GET_site::saveMenu();
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idContent
//idSection ( para el path )
$section = GET_site::getSection($this->data->idSection);
parent::addToSend($section,'section');
parent::addToSend(GET_site::getParent($this->data->idSection),'parent');
parent::addToSend(GET_site::getContent($this->data->idContent,$this->data->idSection,$section->path),'content');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
class GET_contactos extends DA_Abs{
public static function formastro(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * from formulario_contacto_astro";
//$sql="SELECT * from usuarios";
return $rs->getObjects($sql);
}
public static function formPsico(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * from formulario_contacto";
//$sql="SELECT * from usuarios";
return $rs->getObjects($sql);
}
public static function getUsuarios(){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * from usuarios LIMIT 20";
$sql="SELECT * from usuarios";
return $rs->getObjects($sql);
}
public static function getAlumnoEmail($mail){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * from alumnos WHERE mail LIKE '$mail'";
return $rs->getObject($sql);
}
}
?><file_sep><?php
// 25/11/2008 15:12:28
// <EMAIL>
//define(pathTemplates,rootPath.Configuration::appConfig("pathTemplates"));
//define(pathTemplates_c,rootPath.Configuration::appConfig("pathTemplates_c"));
include(libsPath."smarty/Smarty.class.php");
class Template extends Smarty {
protected $masterTemplate=null;
protected $application="";
public function __construct($app=null){
if(is_null($app)){
$app=HX_Fmwk::getApplication();
}
$this->application=$app;
$this->template_dir=(is_null($this->template_dir))?rootPath.Configuration::appConfig("pathTemplates"):$this->template_dir;
$this->compile_dir=(is_null($this->compile_dir))?rootPath.Configuration::appConfig("pathTemplates_c"):$this->compile_dir;
$this->compile_id=(is_null($this->compile_id))?"":$this->compile_id;
}
public function render($template) {
ob_start();
if(substr($template, 0,2)=="./"){
$this->template_dir=dirname($_SERVER["SCRIPT_FILENAME"]).DIRECTORY_SEPARATOR;
//$this->template_dir=dirname(Server::DOCUMENT_ROOT().Server::SCRIPT_NAME()).DIRECTORY_SEPARATOR;
}
if(is_null($this->masterTemplate)){
parent :: display($template);
}else{
$this->assign("__TEMPLATE__",$template);
parent :: display($this->masterTemplate);
}
$miHtml = ob_get_contents();
ob_end_clean();
$js=JScript::render();
if($js!=""){
$c=0;
$miHtml=str_replace("<head>",$js."<head>", $miHtml,$c);
if($c==0){
$miHtml=$js.$miHtml;
}
}
echo $miHtml;
}
public function renderXML($template){
//header_remove();
header ("content-type: text/xml", true);
parent :: display($template);
}
public function getContent($template) {
ob_start();
Template::render($template);
$miHtml = ob_get_contents();
ob_end_clean();
return $miHtml;
}
public function saveAs($template, $path) {
@ unlink($path);
if (!$gestor = fopen($path, "a")) {
return false;
}
if (!fwrite($gestor, Template::getContent($template))) {
return false;
}
return true;
}
public function setTemplateDir($tplDir){
$this->template_dir=$tplDir;
}
public function setCompileDir($cpDir){
$this->compile_dir=$cpDir;
}
public function setCompileId($cpId){
$this->compile_id=$cpId;
}
public function setMasterTemplate($template){
$this->masterTemplate=$template;
}
}
?><file_sep><?php
interface ISerializable{
function serialize($mode);
function getObject();
}
?><file_sep><?php
/**
* Date: 14/08/2013 13:39:30
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2013, <NAME>
* @filename AppException.class.php
* @package
**/
/**
*/
class AppException extends Exception {
/**
*
* @param string $msg
* @param string $code
*/
public function __construct($msg, $code) {
parent::__construct(utf8_encode($msg), $code);
//Logger::logError($this);
}
}
?><file_sep><?php
/**
* Date: 14/08/2013 14:28:41
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2013, <NAME>
* @filename DA.class.php
* @package
**/
/**
*/
class DA_Article extends DA_Abs {
}
?>
<file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idContent
//idSection ( para el path )
parent::addToSend(GET_content::getContent($this->data->idContent,$this->data->idSection),'content');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
class Application extends Configuration{
private static $usuario=null;
public static function getPathImagenesColores(){
return Server::APP_ROOT_PATH().Application::appConfig("pathImagenesColores");
}
public static function getUrlImagenesColores(){
return Application::appKey("url").Application::appConfig("urlImagenesColores");
}
public static function getPathImagenesProductos(){
return Server::APP_ROOT_PATH(). Application::appConfig("pathImagenesProducto");
}
public static function getTmpDir(){
return Server::APP_ROOT_PATH(). Application::appConfig("tmpDir");
}
public static function getUrlImagenesProductos(){
return Application::appKey("url").Application::appConfig("urlImagenesProducto");
}
private static $pais=null;
public static function getPais(){
if(is_null(Application::$pais)){
Application::$pais=RepoPais::obtenerPorId(Application::appKey("idPais"));
}
Return Application::$pais;
}
public static function getDefaultTimeZone(){
return "America/Buenos_Aires";
}
public static function getTimeZone(){
if(HX_Fmwk::getApplication()=="backoffice")
return Backoffice::getUserTimeZone();
return self::getDefaultTimeZone();
}
public static function getTimeZones(){
$ret=array();
foreach (DateTimeZone::listAbbreviations() as $k=>$v){
if($v[0]["timezone_id"]!="")
$ret[$v[0]["timezone_id"]]=$v[0]["timezone_id"];
}
return $ret;
}
}
?><file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql/MySql
* @filesource
**/
/**
*
**/
class RecordsetMySql implements IRecordset {
private $db;
private $result;
private $rs;
public $eof=true;
/**
* @param IConnection $db
* @return void
*/
public function __construct($db){
$this->db=$db;
}
/**
* @param string $sql
* @return void
*/
public function execute($sql) {
$this->result = mysql_query($sql, $this->db);
if (!$this->result) {
throw new Exception(mysql_error(),mysql_errno());
} else {
if ($this->rs = mysql_fetch_object($this->result)) {
$this->eof = false;
} else {
$this->eof = true;
}
}
}
/**
*
* @param string $sql
* @return string
*/
public function getJSON($sql){
$ret=array();
$this->result = mysql_query($sql, $this->db);
if (!$this->result) {
throw new Exception(mysql_error(),mysql_errno());
}
while ($row = mysql_fetch_object($this->result)) {
$ret[]=$row;
}
return @json_encode($ret);
}
/**
*
* @param string $sql
* @return array <stdClass>
*/
public function getObjects($sql){
$ret=array();
$this->result = mysql_query($sql, $this->db);
if (!$this->result) {
throw new Exception(mysql_error(),mysql_errno());
}
while ($row = mysql_fetch_object($this->result)) {
$o=null;
foreach ($row as $k=>$v){
$o->$k=utf8Encode($v);
}
$ret[]=$o;
}
return $ret;
}
/**
*
* @param string $sql
* @return stdClass
*/
public function getObject($sql){
$ret=null;
$this->result = mysql_query($sql, $this->db);
if (!$this->result) {
throw new Exception(mysql_error(),mysql_errno());
}
$r=mysql_fetch_object($this->result);
if(!$r) return null;
foreach ($r as $k=>$v){
$ret->$k=utf8Encode($v);
}
return $ret;
}
/**
* @return void
*/
public function moveNext() {
if ($this->rs = mysql_fetch_object($this->result)) {
$this->eof = false;
} else {
$this->eof = true;
}
}
/**
* @param string $value
* @return string
*/
public function field($value) {
return utf8Encode($this->rs->$value);
}
/**
* @param string $value
* @return int
*/
public function getInt($value){
return intval($this->field($value));
}
/**
* @param string $value
* @return double
*/
public function getDouble($value){
return doubleval($this->field($value));
}
/**
* @return array
*/
public function rows() {
return mysql_num_rows($this->result);
}
/**
* @return void
*/
public function close() {
mysql_free_result($this->result);
}
/**
* @param string $value
* @return Fecha
*/
public function getDate($value){
$var=$this->field($value);
$d=new Fecha(substr($var,8,2),substr($var,5,2),substr($var,0,4),substr($var,11,2),substr($var,14,2),substr($var,17,2));
return $d;
}
}
?>
<file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
if(isset($this->data->search)){
ob_clean();
echo 'hola';
parent::addToSend(GET_eventos::getLatestEventos($this->data->search),'eventos');
}else if($this->data->latest == true){
parent::addToSend(GET_eventos::getLatestEventos(),'eventos');
}
else parent::addToSend(GET_eventos::getEventos(),'eventos');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?>
<file_sep><?php
/**
* Date: 14/08/2013 14:28:41
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2013, <NAME>
* @filename DA.class.php
* @package
**/
/**
*/
class DA_img extends DA_Abs {
public static function setFoto($data){
if(!self::guardarImg(escape($data->img),escape($data->nombre),escape($data->path))){
throw new AppException("Error setFoto:" . 'NO SE GUARDO LA FOTO: nombre- ' .escape($data->nombre).' - '.escape($data->path), 200);
}
return true;
}
private static function guardarImg($foto,$nombre,$path) {
echo '../../'.$path.$nombre;
try
{
if ($fp = fopen('../../'.$path.$nombre,"wb")) {
fwrite($fp,base64_decode($foto));
fclose($fp);
return true;
}
}
catch (Exception $e) {
new AppException("guardarImg(): Error inesperado ($c):" . $e->getMessage(), 200);
}
return false;
}
}
?>
<file_sep>app.models.SectionManagerModel = app.models.HashModel.extend({
name: 'sectionManagerModel',
sections:[],
sname:'',//currentSectionName
section:null,//currentSection
registerSections : function(section, name) {
this.sections[name]=section;
section.onRegister();
},
hashChange:function(sname,route,params)
{
if(sname == this.sname)
{
if(this.section.model){
this.section.model.set('query',{route:route,params:params});
}
return;
}
if(this.sections[sname]==undefined)
{
app.router.navigate('error');
sname = 'error';
//return;
}
if(this.section)this.section.hide();
this.section = this.sections[sname];
//console.log(this.views,sname,this.views[sname]);
this.sname = sname;
this.section.render();
if(route && this.section.model){
this.section.model.set('query',{route:route,params:params});
}
this.section.show();
}
});<file_sep><?php
if(count($_POST) > 0){
echo "RECORD";
//var_dump($_POST);die;
$newEvento = GET_eventos::setEvento($_POST);
//var_dump($evento);die;
if(isset($_POST['idEvento'])){
header('Location: eventoCreado.php?success=1&changed=1&idEvento='.$newEvento);
}
else {
GET_Eventos::setCamp($newEvento);
header('Location: eventoCreado.php?success=1&idEvento='.$newEvento);
}
exit;
}
?>
<!DOCTYPE html>
<html lang="es"><head>
<meta charset="utf-8">
<title>Eventos</title>
<link rel="icon" type="../../image/png" href="favicon.png">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Gentium+Book+Basic:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<link href="../site/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="../site/bootstrap/css/bootstrap-switch.min.css" rel="stylesheet">
<link href="../site/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<link rel="stylesheet/less" type="text/css" href="../site/less/estilos.less" />
<script src="../site/less/less-1.4.1.min.js"></script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/moment.js"></script>
<script src="js/bootstrap-datetimepicker.min.js"></script>
<script src="../site/bootstrap/js/bootstrap-switch.min.js"></script>
<script src="ckeditor/ckeditor.js"></script>
<script src="ckeditor/adapters/jquery.js" type="text/javascript" ></script>
<script src="js/script.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if IE ]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<link href="http://aztlan.com.ar/site/css/ie.css" rel="stylesheet">
<![endif]-->
</head>
<body>
<nav class="header-nav">
<div class="header container">
<div class="row">
<div class="logo col-xs-2 col-sm-3 col-md-4 hidden-xs ">
<img src="../images/logo.png" class="pull-left">
<div class="pull-left hidden-sm">
<h1 class="h1Header">Aztlan</h1>
<h4 class="h4Header">Director <NAME></h4>
</div>
</div>
<div class="slogan col-xs-8 col-sm-8 col-md-6">
<h1 class="h1Header">Escuela de Filosofía y Psicología</h1>
<h4 class="h4Header"><strong>Enseñanza Privada Nivel Terciario - No oficial</strong></h4>
<p class="pHeader hidden-xs">Personería Jurídica Nº I.G.J. 748</p>
<p class="pHeader hidden-xs">Centro Nacional de Organizaciones de la Comunidad C.E.N.O.C. Nº 16528</p>
</div>
<div class="slogan col-xs-2 col-sm-2 col-md-2">
<a href="http://aztlan.com.ar/eventos" ><span style="font-size:50px;" class="glyphicon glyphicon-home"></span></a>
</div>
</div>
</div>
</nav>
<div id="form" class="container" style="padding-top:50px;">
<form class="form-horizontal" role="form" action="evento.php" method="POST">
<?php
if(isset($evento) && !is_null($evento)){
echo '<div class="form-group" style="display:none;">';
echo '<label for="idEvento" class="col-sm-3 control-label">IdEvento</label>';
echo '<div class="col-sm-8">';
echo '<input type="number" class="form-control" id="idEvento" name="idEvento" value="'.$evento->idEvento.'">';
echo '</div>';
echo '</div>';
}
?>
<div class="form-group">
<label for="activo" class="col-sm-3 control-label">Activo</label>
<div class="col-sm-8">
<div class="switch-wrapper">
<?php
echo '<input id="switch-state" type="checkbox" name="activo"';
if(!isset($evento) || $evento->activo == 1) echo 'checked';
echo ' >';
?>
</div>
</div>
</div>
<div class="form-group">
<label for="mostrarHome" class="col-sm-3 control-label">Mostrar en Home</label>
<div class="col-sm-8">
<div class="switch-wrapper">
<?php
echo '<input id="switch-state-2" type="checkbox" name="mostrarHome"';
if(!isset($evento) || $evento->mostrarHome == 1) echo 'checked';
echo ' >';
?>
</div>
</div>
</div>
<div class="form-group">
<label for="mostrarAstro" class="col-sm-3 control-label">Mostrar en Web Astrología</label>
<div class="col-sm-8">
<div class="switch-wrapper">
<?php
echo '<input id="switch-state-3" type="checkbox" name="mostrarAstro"';
if(!isset($evento) || $evento->mostrarAstro == 1) echo 'checked';
echo ' >';
?>
</div>
</div>
</div>
<div class="form-group">
<label for="mostrarPsico" class="col-sm-3 control-label">Mostrar en Web Psicología</label>
<div class="col-sm-8">
<div class="switch-wrapper">
<?php
echo '<input id="switch-state-4" type="checkbox" name="mostrarPsico"';
if(!isset($evento) || $evento->mostrarPsico == 1) echo 'checked';
echo ' >';
?>
</div>
</div>
</div>
<div class="form-group">
<label for="tipoEvento" class="col-sm-3 control-label">Tipo Evento</label>
<div class="col-sm-8">
<select class="form-control" name="tipoEvento" >
<option>----------SIN CLASIFICAR ------------------------------------------------------------</option>
<option value="3" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 3 || !isset($evento))echo 'selected';?> >3 // Landing sin horario >> Terapia Transpersonal</option>
<option value="4" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 4)echo 'selected';?> >4 // Landing sin horario >> Curso de Mindfulness</option>
<option value="25" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 25)echo 'selected';?> >25 // Landing sin horario >> Curso de Astrología Holística</option>
<option value="30" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 30)echo 'selected';?> >30 // Landing sin horario >> Tarot como Oráculo</option>
<option>----------PSICOLOGÍA ------------------------------------------------------------</option>
<option value="100" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 100)echo 'selected';?> >100 // LUN 14/08 - 11:30 hs >> Terapia Transpersonal</option>
<option value="103" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 103)echo 'selected';?> >103 // DOM 20/08 - 19:30 hs >> Psicología Transpersonal</option>
<option>----------ASTROLOGÍA ------------------------------------------------------------</option>
<option value="112" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 112)echo 'selected';?> >112 // LUN 14/08 - 10:30 hs >> Astrología Holística</option>
<option value="111" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 111)echo 'selected';?> >111 // JUE 17/08 - 11:30 hs >> Astrología Holística</option>
<option value="114" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 114)echo 'selected';?> >114 // JUE 17/08 - 18:30 hs >> Astrología Holística</option>
<option>----------TAROT ------------------------------------------------------------</option>
<option>----------TALLERES Y OTROS CURSOS ------------------------------------------------------------</option>
<option value="31" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 31)echo 'selected';?> >31 // SÁBADOS 10 hs >> Curso de Yoga</option>
<option value="117" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 117)echo 'selected';?> >117 // SÁBADOS 10 hs >> Profesorado y Clases de Yoga</option>
<option>----------EVENTOS Y OTROS ------------------------------------------------------------</option>
<option value="27" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 27)echo 'selected';?> >27 // VIE 18/08 - 19 hs >> <NAME></option>
<option>----------FUERA DE USO ------------------------------------------------------------</option>
<option value="110" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 110)echo 'selected';?> >110 // Wagner</option>
<option value="28" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 28)echo 'selected';?> >28 // Bhagavad-Gita</option>
<option value="19" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 19)echo 'selected';?> >19 // <NAME>bo</option>
<option value="33" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 33)echo 'selected';?> >33 // El Poder de los Números</option>
<option value="116" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 116)echo 'selected';?> >116 // Taller Mindfulness</option>
<option value="20" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 20)echo 'selected';?> >20 // Curso de Mindfulness</option>
<option value="24" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 24)echo 'selected';?> >24 // Alimentación Consciente</option>
<option value="32" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 32)echo 'selected';?> >32 // Alimentación Consciente</option>
<option value="105" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 105)echo 'selected';?> >105 // TAROT</option>
<option value="106" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 106)echo 'selected';?> >106 // TAROT</option>
<option value="107" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 107)echo 'selected';?> >107 // TAROT</option>
<option value="108" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 108)echo 'selected';?> >108 // TAROT</option>
<option value="109" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 109)echo 'selected';?> >109 // TAROT</option>
<option value="26" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 26)echo 'selected';?> >26 // TAROT</option>
<option value="18" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 18)echo 'selected';?> >18 // Astrología Kármica</option>
<option value="34" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 34)echo 'selected';?> >34 // Astrología Kármica</option>
<option value="115" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 115)echo 'selected';?> >115 // Astrología Kármica</option>
<option value="113" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 113)echo 'selected';?> >113 // Astrología y Autoconocimiento</option>
<option value="29" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 29)echo 'selected';?> >29 // Terapia Transpersonal</option>
<option value="101" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 101)echo 'selected';?> >101 // Práctica de Autoconocimiento</option>
<option value="102" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 102)echo 'selected';?> >102 // Práctica de Autoconocimiento</option>
<option value="7" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 7)echo 'selected';?> >7 // Práctica de Autoconocimiento</option>
<option value="104" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 104)echo 'selected';?> >104 // Psicología Transpersonal</option>
<option value="118" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 118)echo 'selected';?> >118 // fuera de uso</option>
<option value="119" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 119)echo 'selected';?> >119 // fuera de uso</option>
<option value="120" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 120)echo 'selected';?> >120 // fuera de uso</option>
<option value="9" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 9)echo 'selected';?> >9 // I-CHING</option>
<!-- <option value="1" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 1)echo 'selected';?> >1 // Cineclub</option>
<option value="2" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 2)echo 'selected';?> >2 // Taller</option> -->
<!-- <option value="8" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 8)echo 'selected';?> >8 // Consultoría Astrológica</option> -->
<!-- OPTION value 18 > ex: Charla Psicología y Astrología, actual: Taller I Ching -->
<!-- <option value="10" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 10)echo 'selected';?> >10 // Consulta Psicología</option>
<option value="11" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 11)echo 'selected';?> >11 // Consulta Astrología</option>
<option value="12" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 12)echo 'selected';?> >12 // Consulta Tarot</option>
<option value="13" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 13)echo 'selected';?> >13 // Entrevista Psicología</option>
<option value="14" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 14)echo 'selected';?> >14 // Entrevista Astrología</option>
<option value="17" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 17)echo 'selected';?> >17 // Entrevista Tarot</option>
<option value="15" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 15)echo 'selected';?> >15 // Beca Psicología</option>
<option value="16" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 16)echo 'selected';?> >16 // Beca Astrología</option>-->
<!-- OPTION value 18 > ex: Psicología con Videos, actual: <NAME> -->
<!-- OPTION value 18 > ex: Astrología con Videos, actual: Taller de Mindfulness -->
<!-- OPTION value 18 > ex: Tarot con Videos, actual: Curso de Mindfulness -->
<!-- OPTION value 28 > ex: Consultas Cursos y Talleres 2017, actual: <NAME> -->
<!-- <option value="21" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 21)echo 'selected';?> >21 // Psicologia Charla 2016</option>
<option value="22" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 22)echo 'selected';?> >22 // Astrologia Charla 2016</option>
<option value="23" <?php if(isset($evento) && $evento->tipoEvento_idTipo == 23)echo 'selected';?> >23 // Tarot Charla 2016</option> -->
<!-- OPTION value 30 > ex: Consultas Astrología 2017, actual: Charla Astrología opción 2 -->
<!-- OPTION value 31 > ex: Consultas Tarot 2017, actual: Curso de Yoga -->
<!-- OPTION value 32 > ex: Descuento Psicología 2017, actual: Curso de Cocina -->
<!-- OPTION value 33 > ex: Descuento Astrología 2017, actual: Charla Psicología opción 2 -->
<!-- OPTION value 34 > ex: Descuento Tarot 2017, actual: Taller Anti-Estrés Nivel 1 y 2 -->
</select>
</div>
</div>
<div class="form-group">
<label for="disponibilidad" class="col-sm-3 control-label">Disponibilidad</label>
<div class="col-sm-8">
<input type="number" class="form-control" id="disponibilidad" name="disponibilidad" placeholder="Disponibilidad" value="120">
</div>
</div>
<div class="form-group">
<label for="lugar" class="col-sm-3 control-label">Lugar</label>
<div class="col-sm-8">
<select class="form-control" name="lugar" >
<option value="1" <?php if(isset($evento) && $evento->lugar_idLugar == 1)echo 'selected';?> >Apart Hotel Congreso - Sala Grande</option>
<option value="2" <?php if(isset($evento) && $evento->lugar_idLugar == 2)echo 'selected';?> >Apart Hotel Congreso - Sala Chica</option>
<option value="3" <?php if(isset($evento) && $evento->lugar_idLugar == 3 || !isset($evento))echo 'selected';?>>Escuela Aztlan - Sede Central</option>
<option value="4" <?php if(isset($evento) && $evento->lugar_idLugar == 4)echo 'selected';?> >Escuela Aztlan - Sede Almagro II</option>
<option value="5" <?php if(isset($evento) && $evento->lugar_idLugar == 5)echo 'selected';?> ><NAME></option>
<option value="6" <?php if(isset($evento) && $evento->lugar_idLugar == 6)echo 'selected';?> >Sr. Duncan - Centro Cultural</option>
<option value="7" <?php if(isset($evento) && $evento->lugar_idLugar == 7)echo 'selected';?> >Salon</option>
</select>
</div>
</div>
<div class="form-group">
<label for="fecha" class="col-sm-3 control-label">Fecha Sistema</label>
<div class="col-sm-8">
<div class='input-group date' id='datetimepicker5'>
<input type='text' class="form-control" data-date-format="YYYY/MM/DD" name="fecha" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<?php if(isset($evento)){
echo '<script type="text/javascript">
$(function (){
/* $("#setDate").click(function () {*/
$("#datetimepicker5").data("DateTimePicker").setDate("'.$evento->date.'");
/* });
$("#datetimepicker5").data("DateTimePicker").show(); */
});
</script>';
}
?>
</div>
<div class="form-group">
<label for="titulo" class="col-sm-3 control-label">Título</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="titulo" placeholder="Título" name="titulo" <?php if(isset($evento)) echo 'value="'.utf8_decode($evento->titulo).'"'?> >
</div>
</div>
<div class="form-group">
<label for="subtitulo" class="col-sm-3 control-label">Subtítulo</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="subtitulo" placeholder="Subtítulo" name="subtitulo" <?php if(isset($evento)) echo 'value="'.utf8_decode($evento->subtitulo).'"'?>>
</div>
</div>
<div class="form-group">
<label for="fechaVisible" class="col-sm-3 control-label">Fecha Visible</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="fechaVisible" placeholder="Fecha Visible" name="fechaStr" <?php if(isset($evento)) echo 'value="'.utf8_decode($evento->fechaStr).'"'?>>
</div>
</div>
<div class="form-group">
<label for=""horario"" class="col-sm-3 control-label">Horario</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="horario" name="horario" <?php if(isset($evento)) echo 'value="'.utf8_decode($evento->horario).'"'; else echo 'value=17:00'; ?>>
</div>
</div>
<div class="form-group">
<label for="maxHorario" class="col-sm-3 control-label">Max Horario</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="maxHorario" name="maxHorario" <?php if(isset($evento)) echo 'value="'.utf8_decode($evento->maxHorario).'"'; else echo 'value=17:15'; ?>>
</div>
</div>
<div class="form-group <?php echo (isset($evento) && $evento->tipoEvento_idTipo == 1) ? 'visible' : 'hidden'?> ">
<label for="idYoutube" class="col-sm-3 control-label">Video de YouTube (solo ID)</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="idYoutube" placeholder="Solo si es CINECLUB, insertar ID de Video de YOUTUBE" name="idYoutube" <?php if(isset($evento) && $evento->idYoutube != '') echo 'value="'.$evento->idYoutube.'"'?>>
</div>
</div>
<div class="form-group <?php echo (isset($evento) && $evento->tipoEvento_idTipo == 1) ? 'visible' : 'hidden'?> ">
<label for="link" class="col-sm-3 control-label">Link</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="link" placeholder="Link" name="link" <?php if(isset($evento) && $evento->link != '') echo 'value="'.$evento->link.'"'?>>
</div>
</div>
<div class="form-group">
<label for="fechaVisible" class="col-sm-3 control-label">Texto</label>
<div class="col-sm-8">
<textarea name="texto" id="editorEditar" rows="10" class="ckeditor required form-control" ><?php if(isset($evento)) echo utf8_decode(htmlspecialchars_decode($evento->texto)) ?></textarea>
</div>
</div>
<?php if(isset($evento) && !is_null($evento)){
echo '<button type="submit" class="btn btn-warning btn-lg col-sm-offset-3">Editar Evento</button>';
}else echo '<button type="submit" class="btn btn-warning btn-lg col-sm-offset-3">Crear Evento</button>';
?>
</form>
<?php if(isset($evento) && !is_null($evento)){
echo '<a class="btn btn-warning btn-lg col-sm-offset-3" href="eventoCreado.php?idEvento='.$evento->idEvento.'">Modificar fotos</a>';
}
?>
</div>
</body>
</html><file_sep><?php
/**
* Date: 22/08/2012 16:36:59
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package
**/
/**
*
**/
class ConnectionMySqli implements IConnection {
private $db;
/**
* @return IRecordset
*/
function getRecordset() {
return new RecordsetMySqli($this->db);
}
/**
* @param string $strCon
* @throws MySqliException
*/
function open($cp) {
$this->db=new mysqli($cp->server, $cp->uid, $cp->pwd, $cp->database, $cp->port);
if ($this->db->connect_errno) {
throw new MySqliException(new Exception($this->db->connect_error,$this->db->connect_errno));
}
}
/**
* @param string $sql
* @throws MySqliException
* @return int
*/
function execute($sql){
if(!$this->db->query($sql)){
throw new MySqliException(new Exception($this->db->error,$this->db->errno));
}
return $this->db->affected_rows;
}
/**
* @return void
*/
function close(){
if(is_null($this->db)) return;
mysqli_close($this->db);
$this->db=null;
}
public function isClosed(){
return is_null($this->db);
}
}
?><file_sep><?php
// 23/10/2008 22:30:16
// <EMAIL>
class Server {
private function __construct(){
}
static function APP_ROOT_PATH(){
return rootPath;
}
static function HTTP_ACCEPT_LANGUAGE(){
return $_SERVER["HTTP_ACCEPT_LANGUAGE"];
}
static function SERVER_SOFTWARE(){
return $_SERVER["SERVER_SOFTWARE"];
}
static function SERVER_NAME(){
return $_SERVER["SERVER_NAME"];
}
static function SERVER_ADDR(){
return $_SERVER["SERVER_ADDR"];
}
static function SERVER_PORT(){
return $_SERVER["SERVER_PORT"];
}
static function REMOTE_ADDR(){
return $_SERVER["REMOTE_ADDR"];
}
static function DOCUMENT_ROOT(){
return $_SERVER["DOCUMENT_ROOT"];
}
static function SCRIPT_FILENAME(){
return $_SERVER["SCRIPT_FILENAME"];
}
static function SCRIPT_NAME(){
return $_SERVER["SCRIPT_NAME"];
}
static function PHP_SELF(){
return $_SERVER["PHP_SELF"];
}
}
?><file_sep>app.view.Dashboard = app.Section.extend({
el:'div#dashboard',
template:null,
thelink:null,
currentEvt:null,
initialize: function() {
var self = this;
var ui = $(this.el);
this.listenTo(this.model, "change:eventos", this.renderEventos);
this.listenTo(this.model, "change:user", this.renderEventos);
this.template = ui.find('div.evento').clone();
ui.find('div.evento').remove();
$('.modal select#fuente').change(function(){
self.showLink(self)});
$('.modal select#owner').change(function(){
self.showLink(self)});
$('.view-link-csv').click(function(){
Url.go('http://www.aztlan.com.ar/services/eventos/getCSVLinksInstructores/?idEvento='+self.currentEvt.idEvento);
});
},
showLink:function(self){
//console.log(self);
var fuente = $('.modal select#fuente').val();
var owner = $('.modal select#owner').val();
if(fuente != null && owner != null){
self.thelink = "http://www.aztlan.org.ar/pages/";
if(self.currentEvt.tipoEvento_idTipo == 1)self.thelink+="cineclub"
else self.thelink+="psi";
self.thelink+="/?c="+self.currentEvt.idEvento+'/'+owner+'/'+fuente;
$('.modal .view-link>input').val(self.thelink);
$('.modal .link-resultado').show();
}
},
renderOwners : function(){
var owners = eventos.get('owners');
var selec = $('.modal').find('select#owner');
selec.empty();
selec.append('<option>Instructor</option>');
var option;
$(owners).each(function(){
option = $('<option>'+this.nombre+'</option>');
option.attr('value',this.idOwner);
selec.append(option);
});
},
renderSources: function(){
var sources = eventos.get('sources');
var selec = $('.modal').find('select#fuente');
selec.empty();
var option;
$(sources).each(function(){
option = $('<option>'+this.nombre+'</option>');
option.attr('value',this.idFuente);
selec.append(option);
});
},
renderEventos : function(){
var eventos = this.model.get('eventos');
var ui = $(this.el);
var cont = ui.find('.evt-container');
cont.empty();
var self = this;
$(eventos).each(function(){
//console.log(this);
var evento = self.template.clone();
var evt = this;
cont.append(evento);
//evento.attr('eid',evento.idEvento);
evento.find('.titulo').html(this.titulo);
evento.find('.subtitulo').html(this.subtitulo);
evento.find('.fecha').html(this.fechaStr);
evento.find('.lugar').html(this.lugar + " / " + this.direccion);
evento.find('.disponibilidad').html(this.lugares);
evento.find('.n-reservas').html(this.reservas);
evento.find('.confirmados').html(this.confirmados);
evento.find('.anotados').html(evt.anotados);
evento.find('.asistencia').html(evt.asistencia);
evento.find('.btn-links').click(function(){
//console.log(evt);
self.currentEvt = evt;
//console.log(self.currentEvt);
self.createModal();
$('.modal').modal('show');
});
evento.find('.btn-ver').click(function(){
Url.setHash('#/ver-asistencia/'+evt.idEvento);
});
evento.find('.btn-editar').click(function(){
Url.setHash('#/editar-asistencia/'+evt.idEvento);
});
evento.find('.btn-lista').click(function(){
Url.setHash('#/lista/'+evt.idEvento);
});
evento.find('.btn-form').click(function(){
Url.setHash('#/form/'+evt.idEvento);
});
evento.find('.btn-edit-evento').click(function(){
Url.go('crear/evento.php?idEvento='+evt.idEvento);
});
evento.find('.btn-descargar').click(function(){
Url.go('http://www.aztlan.com.ar/services/eventos/getCSV/?idEvento='+evt.idEvento);
});
});
/*
lugar_idLugar
"2"
lugares
"150"
tipoEvento_idTipo
"1"
*/
},
createModal:function(){
$('.modal .link-resultado').hide();
$('.modal .view-link input').html('');
this.renderOwners();
this.renderSources();
}
});
<file_sep><?php
class Paginado {
private static $filasVisibles=10;
private static $pagina=1;
private static $totalFilas=0;
private static $init=false;
public static function init() {
if(Paginado::$init){
return;
}
if(isset($_REQUEST["pag"])){
Paginado::setPagina($_REQUEST["pag"]);
}elseif(!is_null(Session::get("_pag_".md5(Server::SCRIPT_NAME())))){
Paginado::setPagina(Session::get("_pag_".md5(Server::SCRIPT_NAME())));
}
if(isset($_REQUEST["vis"])){
Paginado::setFilasVisibles($_REQUEST["vis"]);
}elseif(!is_null(Session::get("_vis_".md5(Server::SCRIPT_NAME())))){
Paginado::setFilasVisibles(Session::get("_vis_".md5(Server::SCRIPT_NAME())));
}
Session::set("_pag_".md5(Server::SCRIPT_NAME()),Paginado::$pagina);
Session::set("_vis_".md5(Server::SCRIPT_NAME()),Paginado::$filasVisibles);
Paginado::$init=true;
}
public static function setFilasVisibles($vis){
Paginado::$filasVisibles=intval($vis);
Session::set("_vis_".md5(Server::SCRIPT_NAME()),Paginado::$filasVisibles);
}
public static function getFilasVisibles(){
Paginado::init();
if(Paginado::$filasVisibles>0){
return Paginado::$filasVisibles;
}
return 10;
}
public static function setPagina($pag){
Paginado::$pagina=intval($pag);
Session::set("_pag_".md5(Server::SCRIPT_NAME()),Paginado::$pagina);
}
public static function getPagina(){
Paginado::init();
if(Paginado::$pagina>0){
return Paginado::$pagina;
}
return 1;
}
public static function setTotalFilas($totalFilas){
Paginado::init();
Paginado::$totalFilas=intval($totalFilas);
}
public static function getTotalFilas() {
Paginado::init();
return Paginado::$totalFilas;
}
public static function getTotalPaginas() {
Paginado::init();
return intval((Paginado::getTotalFilas() / Paginado::getFilasVisibles()) + (((Paginado::getTotalFilas() % Paginado::getFilasVisibles()) == 0) ? 0 : 1));
}
public static function tieneSiguiente() {
Paginado::init();
return (Paginado::getTotalPaginas() > Paginado::getPagina());
}
public static function tieneAnterior() {
Paginado::init();
return (Paginado::getPagina() > 1);
}
public static function filaInicio(){
Paginado::init();
$f=intval((Paginado::getPagina()- 1) * Paginado::getFilasVisibles());
if($f>Paginado::getTotalFilas()){
return 0;
}
return $f;
}
private static $paginasVisibles=10;
public static function getPaginasVisibles() {
return self::$paginasVisibles;
}
public static function setPaginasVisibles($paginasVisibles) {
self::$paginasVisibles=$paginasVisibles;
}
public static function paginasVisibles($t=null){
if(is_null($t)) $t=self::$paginasVisibles;
Paginado::init();
$r=array();
if(Paginado::getTotalPaginas()<=$t){
for($x=1;$x<=Paginado::getTotalPaginas();$x++){
$r[]=$x;
}
return $r;
}
$ini=1;
$fin=10;
$pre=intval($t/2);
if(Paginado::getPagina() > $pre){
$ini=Paginado::getPagina()-$pre+1;
$fin=$ini+$t-1;
}
if($fin>Paginado::getTotalPaginas()){
$fin=Paginado::getTotalPaginas();
$ini=$fin-$t+1;
}
for($x=$ini;$x<=$fin;$x++){
$r[]=$x;
}
return $r;
}
}
?><file_sep><?php
function smarty_modifier_translate($string){
return CultureInfo::translate($string);
}
?><file_sep><?php
class GET_content extends DA_Abs{
/*
public static function getOrders($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT sections.idSection as id,
sections.sectionOrder,
section_details.name
FROM section_details,sections";
$section = self::getSection($id);
if($section->level == 0)
{
$sql.=" WHERE section_details.sections_idSection = sections.idSection
AND sections.level = 0 ";
}
else
{
$parent = self::getParent($id)->id;
$sql.=" WHERE sections_idSection IN (SELECT subSection FROM section_relations WHERE parent = $parent)
AND section_details.sections_idSection = sections.idSection ";
}
$sql.="AND idiomas_idIdioma=". self::$idIdioma .
" order by sections.sectionOrder";
//echo $sql;die;
$sections=$rs->getObjects($sql);
return $sections;
}
*/
public static function getCustomPopup(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM customPopup WHERE id = 1";
//echo $sql;die;
$content = $rs->getObject($sql);
return $content;
}
public static function getCustomHome(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM customHome WHERE id = 1";
//echo $sql;die;
$content = $rs->getObject($sql);
return $content;
}
public static function getContentsBySection($idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql = "SELECT
contents.idContent as id,
contents.contentTypes_idType as type,
contents.referenceName,
contents.img,
contents.imgAlign,
content_tosection.content_order as orden ";
if(self::$onlyActives){
$sql.="FROM content_details,contents,content_tosection
WHERE content_details.contents_idContent = contents.idContent
AND content_tosection.contents_idContent = contents.idContent
AND content_tosection.sections_idSection = $idSection";
$sql.=" AND content_details.idiomas_idIdioma=". self::$idIdioma ;
$sql.=" AND content_details.activo=1";
}
else{
$sql.="FROM contents,content_tosection
WHERE content_tosection.contents_idContent = contents.idContent
AND content_tosection.sections_idSection = $idSection";
}
$sql.=" ORDER BY content_tosection.content_order ASC, contents.idContent ASC";
$contents = $rs->getObjects($sql);
foreach ($contents as $valor){
$sql="SELECT
titulo,
descripcion,
SEO_desc,
activo
FROM content_details
WHERE contents_idContent = $valor->id
AND content_details.idiomas_idIdioma=". self::$idIdioma ;
//echo $sql;die;
$valor->details = $rs->getObject($sql);
}
$sectionHash = GET_section::getHashSection($idSection);
addContentFurl($contents,$sectionHash->path);
return $contents;
}
public static function getContent($id,$idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT
contents.idContent as id,
contents.contentTypes_idType as type,
contents.referenceName,
contents.img,
contents.imgAlign,
content_tosection.content_order as orden
FROM contents,content_tosection
WHERE contents.idContent = $id
AND content_tosection.contents_idContent = $id
AND content_tosection.sections_idSection = $idSection";
//echo $sql;die;
$content = $rs->getObject($sql);
$sql="SELECT
titulo,
descripcion,
SEO_desc,
activo
FROM content_details
WHERE contents_idContent = $content->id
AND content_details.idiomas_idIdioma=". self::$idIdioma ;
$content->details = $rs->getObject($sql);
$section = GET_section::getSection($idSection);
addContentFurl($content,$section->path);
return $content;
}
public static function getDetails($idContent){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT
titulo,
descripcion,
SEO_desc,
activo
FROM content_details
WHERE contents_idContent = $idContent
AND idiomas_idIdioma=". self::$idIdioma ;
return $rs->getObject($sql);
}
}
?><file_sep><?php
include "../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idCamp
//source
parent::addToSend(SET_consulta::getConsultasAstro(),'consultas');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
/**
* Date: 25/10/2011 16:04:27
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2011, <NAME>
* @package default
* @filesource
*/
class SerializableMode{
const json="json";
const xml="xml";
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
parent::addToSend(GET_section::getIdiomas(), "idiomas");
parent::addToSend(GET_section::getIdioma(), "idioma");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
include "../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
$section = GET_site::getSection($this->data->idSection);
parent::addToSend($section, "section");
parent::addToSend(GET_site::getMenuArticles($this->data->idSection,$section->path), "contents");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
class GET_site extends DA_Abs{
public static function saveMenu(){
$currentIdioma = self::$idIdioma;
self::$idIdioma = 1;
$myfile = fopen("../../../menu64.txt", "w") or die("Unable to open file!");
$json = base64_encode(@json_encode(self::getSite()));
fwrite($myfile, $json);
fclose($myfile);
self::$idIdioma = 2;
$myfile = fopen("../../../menu64-en.txt", "w") or die("Unable to open file!");
$json = base64_encode(@json_encode(self::getSite()));
fwrite($myfile, $json);
fclose($myfile);
self::$idIdioma = $currentIdioma;
}
public static function getSite(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT sections.idSection as id,
sections.sectionOrder,
sections.level,
sections.referenceName,
sections.contentTypes_idType as type,
sections.showContent,
section_details.name,
section_details.toMainName,
section_details.toMainMenu
FROM section_details,sections
WHERE section_details.sections_idSection = sections.idSection
AND idiomas_idIdioma=". self::$idIdioma ."
AND section_details.active=1";
$sql.=" order by sections.level ASC ,sections.sectionOrder ASC, sections.idSection DESC";
$site=$rs->getObjects($sql);
$rsite = array();
foreach ($site as $valor){
if($valor->level == 0){
$nsec = self::formatObj($valor);
$nsec->sections = array();
addFurl($nsec);
$subs = self::subs($nsec->id);
foreach ($subs as $idSub){
foreach ($site as $subsect){
if($subsect->id == $idSub->subSection){
$nsubsect = self::formatObj($subsect);
addFurl($nsubsect,$nsec->path);
$nsec->sections[] = $nsubsect;
}
}
}
$rsite[] = $nsec;
}
}
//die;
return $rsite;
}
private static function subs($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT subSection FROM section_relations WHERE parent = $id";
return $rs->getObjects($sql);
}
private static function formatObj($obj){
$nobj = new stdClass();
$details = new stdClass();
foreach ($obj as $key => $valor){
if($key != 'name' && $key != 'toMainName' && $key != 'toMainMenu' && $key != 'titulo' && $key != 'descripcion'){
$nobj->$key=$valor;
}
else{
$details->$key=$valor;
}
}
$nobj->details = $details;
return $nobj;
}
public static function getSection($idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT
sections.idSection,
sections.level,
sections.showContent,
section_details.name
FROM section_details,sections
WHERE section_details.sections_idSection = $idSection
AND section_details.sections_idSection = sections.idSection
AND section_details.idiomas_idIdioma=". self::$idIdioma ;
$result = $rs->getObject($sql);
if($result->level != 0){
$parent = self::getParent($result->idSection);
}
//echo $sql;die;
$section = new stdClass();
$section->details = $result;
if($parent)addFurl($section,$parent->path);
else addFurl($section);
return $section;
}
public static function getParent($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT
section_details.name
FROM section_details,section_relations
WHERE section_relations.subSection =". $id;
$sql.=" AND section_details.sections_idSection = section_relations.parent";
$result = $rs->getObject($sql);
if(is_null($result))return null;
$parent = new stdClass();
$parent->details = $result;
addFurl($parent);
return $parent;
}
public static function getMenuArticles($idSection,$path){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql = "SELECT
contents.idContent as id,
contents.contentTypes_idType as type,
content_details.titulo,
content_tosection.content_order as orden
FROM contents,content_details,content_tosection
WHERE content_details.contents_idContent = contents.idContent
AND content_tosection.contents_idContent = contents.idContent
AND content_tosection.sections_idSection = $idSection";
$sql.=" AND content_details.idiomas_idIdioma=". self::$idIdioma ;
$sql.=" AND content_details.activo=1";
$sql.=" ORDER BY content_tosection.content_order ASC, contents.idContent ASC";
$contents = $rs->getObjects($sql);
$ncontents = array();
foreach ($contents as $cont){
$ncont = self::formatObj($cont);
addContentFurl($ncont,$path);
$ncontents[] = $ncont;
}
return $ncontents;
}
public static function getContentsBySection($idSection,$path){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql = "SELECT
contents.idContent as id,
contents.contentTypes_idType as type,
contents.referenceName,
contents.img,
contents.imgAlign,
content_tosection.content_order as orden ";
$sql.="FROM content_details,contents,content_tosection
WHERE content_details.contents_idContent = contents.idContent
AND content_tosection.contents_idContent = contents.idContent
AND content_tosection.sections_idSection = $idSection";
$sql.=" AND content_details.idiomas_idIdioma=". self::$idIdioma ;
$sql.=" AND content_details.activo=1";
$sql.=" ORDER BY content_tosection.content_order ASC, contents.idContent ASC";
///echo $sql;die;
$contents = $rs->getObjects($sql);
foreach ($contents as $valor){
$sql="SELECT
titulo,
descripcion,
SEO_desc,
activo
FROM content_details
WHERE contents_idContent = $valor->id
AND content_details.idiomas_idIdioma=". self::$idIdioma ;
//echo $sql;die;
$valor->details = $rs->getObject($sql);
}
addContentFurl($contents,$path);
return $contents;
}
public static function getContent($id,$idSection,$path){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT
contents.idContent as id,
contents.contentTypes_idType as type,
contents.referenceName,
contents.img,
contents.imgAlign,
content_tosection.content_order as orden
FROM contents,content_tosection
WHERE contents.idContent = $id
AND content_tosection.contents_idContent = $id
AND content_tosection.sections_idSection = $idSection";
//echo $sql;die;
$content = $rs->getObject($sql);
$sql="SELECT
titulo,
descripcion,
SEO_desc,
activo
FROM content_details
WHERE contents_idContent = $content->id
AND content_details.idiomas_idIdioma=". self::$idIdioma ;
$content->details = $rs->getObject($sql);
addContentFurl($content,$path);
return $content;
}
public static function getIdiomaByStr($str){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas WHERE idioma='$str'";
return $rs->getObject($sql);
}
public static function getIdioma(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas WHERE idIdioma= " . self::$idIdioma ;
return $rs->getObject($sql);
}
public static function getIdiomas(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas";
return $rs->getObjects($sql);
}
}
?><file_sep><?php
class HX_Fmwk {
private static $instance=null;
private static $application=null;
private static $production=null;
public static function value($name){
return HX_Fmwk::$instance->value($name);
}
public static function load($config){
HX_Fmwk::$instance=new BasicConfiguration($config);
}
public static function registerApplication($app){
HX_Fmwk::$application=$app;
}
public static function getApplication(){
return HX_Fmwk::$application;
}
public static function production(){
if(!is_null(HX_Fmwk::$production)){
return HX_Fmwk::$production;
}
if(!is_null(HX_Fmwk::value("development"))){
if(HX_Fmwk::value("development")=="true"){
HX_Fmwk::$production=false;
return HX_Fmwk::$production;
}
}
HX_Fmwk::$production=true;
return HX_Fmwk::$production;
}
}
?><file_sep><?php
// 23/10/2008 22:20:32
// <EMAIL>
abstract class Configuration{
private function __construct(){
}
protected static $pathClass=array();
protected static $connectionStrings=array();
protected static $appKeys=array();
protected static $appConfig=array();
protected static $systemDebug=false;
protected static $archivo="";
public static function load($archivo){
self::$archivo=$archivo;
self::parsearConfigXML();
}
public static function systemDebug(){
return self::$systemDebug;
}
public static function pathClass(){
return self::$pathClass;
}
public static function connectionString($name){
return self::$connectionStrings[$name];
}
public static function appKey($name){
return self::$appKeys[$name];
}
public static function appConfig($name){
return self::$appConfig[$name];
}
private static function parsearConfigXML(){
$xml=new XMLParser();
$xml->load(self::$archivo);
if($xml->isLoaded()){
foreach ($xml->getNodes() as $nodo1){
switch (strtolower($nodo1->nodeName())){
case "appsettings":
foreach ($nodo1->getNodes() as $nodo2){
switch (strtolower($nodo2->nodeName())){
case "includepathclass":
foreach ($nodo2->getNodes() as $nodo3){
self::$pathClass[]=$nodo3->getAttribute("name");
}
break;
case "connectionstrings":
foreach ($nodo2->getNodes() as $nodo3){
self::$connectionStrings[$nodo3->getAttribute("name")]=$nodo3->getAttribute("value");
}
break;
case "appkeys":
foreach ($nodo2->getNodes() as $nodo3){
self::$appKeys[$nodo3->getAttribute("name")]=$nodo3->getAttribute("value");
}
break;
case "appconfig":
foreach ($nodo2->getNodes() as $nodo3){
self::$appConfig[$nodo3->getAttribute("name")]=$nodo3->getAttribute("value");
}
break;
}
}
break;
case "system":
foreach ($nodo1->getNodes() as $nodo2){
switch (strtolower($nodo2->nodeName())){
case "debug":
self::$systemDebug=(strtolower($nodo2->getAttribute("value"))=="true");
break;
}
}
break;
}
}
}
}
}
?><file_sep><?php
class AppMessage {
const Information ="Information";
const Warning = "Warning";
const Error = "Error";
const Success = "Success";
}
?><file_sep><?php
function smarty_function_paginado($params, & $smarty) {
switch ($params['value']) {
case "anterior":
return intval(Paginado::tieneAnterior());
break;
case "siguiente":
return intval(Paginado::tieneSiguiente());
break;
case "paginas":
$r="";
foreach (Paginado::paginasVisibles() as $x) {
$r.="<span>$x</span>";
}
return $r;
break;
case "json":
$ret=array();
$ret["anterior"]=Paginado::tieneAnterior();
$ret["siguiente"]=Paginado::tieneSiguiente();
$ret["paginas"]=Paginado::paginasVisibles();
$ret["pagina"]=Paginado::getPagina();
return json_encode($ret);
break;
case "filas":
return Paginado::getTotalFilas();
default:
$smarty->trigger_error("eval: missing 'value' parameter");
break;
}
}
?>
<file_sep>app.data.models.UsuarioModel = app.models.SectionModel.extend({
name: 'UsuarioModel',
usuario:null,
resolveQuery : function(query) {
this.getUsuario(query.route[0]);
}
,
getUsuario : function(id){
var $self = this;
//log("ID",id);
this.url.eventos.getUsuario(id,function(data){
//log(data);
$self.set('usuario',data.usuario);
});
},
update: function(id,estado,txt,callback){
var $self = this;
//log("ID",id);
this.url.eventos.setUsuario(id,estado,txt,callback);
},
clean : function(){
this.unset('query', {silent:true});
}
});
<file_sep>app.view.ListaVerAsistencia = app.Section.extend({
el:'div#lista-ver-asistencia',
template:null,
initialize: function() {
var ui = $(this.el);
this.model = new app.data.models.ListaModel();
this.model.onRegister();
this.listenTo(this.model, "change:evento", this.renderEvento);
this.listenTo(this.model, "change:reservas", this.renderReservas);
this.template = $('body').find('div.evento-template').clone();
this.template.show();
this.template.removeClass('evento-template');
this.template.find('.btn-lista').parent().remove();
this.template.find('.btn-ver').parent().remove();
this.template.find('.btn-form').parent().remove();
this.template.find('.btn-links').parent().remove();
this.template.addClass('evento');
},
renderReservas : function(){
var reservas = this.model.get('reservas');
reservas = _.sortBy(reservas, function(i) {return i.usuario.apellido.substring(0,1).toLowerCase()})
var ui = $(this.el);
var body = ui.find('tbody');
body.empty();
var tr,td,n;
n=0;
var self = this;
$(reservas).each(function(){
//log(this);
if(this.confirmado != 2 ){
n++;
tr = $('<tr>');
if(this.usuario.admitido == 0)tr.addClass('no-admitido');
body.append(tr);
td = $('<td>');
tr.append(td);
td.text(n);
td = $('<td>');
tr.append(td);
if(this.tipoUsuario == 1){
a = $('<a href="#/usuario/'+this.usuario.idUsuario+'">');
td.append(a);
a.text(this.usuario.apellido + " " + this.usuario.nombre);
}else{
//log(this.usuario);
td.text(this.usuario.apellido + " " + this.usuario.nombre);
}
td = $('<td>');
tr.append(td);
td.text(this.usuario.dni);
td = $('<td>');
tr.append(td);
td.text(this.usuario.email);
td = $('<td>');
tr.append(td);
td.text(this.usuario.telefono);
td = $('<td class="presentismo">');
tr.append(td);
if(this.asistencia && this.asistencia == 0)td.addClass('ausente');
if(this.asistencia && this.asistencia == 1)td.addClass('presente');
//td.text("si");
td = $('<td class=" text-center">');
tr.append(td);
td.text(this.cantLugares);
td = $('<td class=" text-center">');
tr.append(td);
if(this.pago)td.text('$'+this.pago);
td = $('<td class="altas-en-charlas text-center">');
tr.append(td);
if(this.anotado && this.anotado == 0)td.addClass('no-anotado');
if(this.anotado && this.anotado == 1)td.addClass('anotado');
td = $('<td>');
tr.append(td);
td.text(this.owner);
td = $('<td>');
tr.append(td);
if(this.source != 0) td.text(eventos.getNameSource(this.source));
else td.text(this.usuario.source);
};
});
},
renderEvento : function(){
var evt = this.model.get('evento');
//log(evt);
var ui = $(this.el);
ui.find('div.evento').remove();
var self = this;
var evento = self.template.clone();
ui.prepend(evento);
evento.find('.titulo').html(evt.titulo);
evento.find('.subtitulo').html(evt.subtitulo);
evento.find('.fecha').html(evt.fechaStr);
evento.find('.lugar').html(evt.lugar);
evento.find('.disponibilidad').html(evt.lugares);
evento.find('.n-reservas').html(evt.reservas);
evento.find('.confirmados').html(evt.confirmados);
evento.find('.anotados').html(evt.anotados);
evento.find('.asistencia').html(evt.asistencia);
if(!self.user){
//evento.find('.btn-form').hide();
evento.find('.btn-links').hide();
}
evento.find('.btn-volver').click(function(){
window.history.back();
});
evento.find('.btn-lista').click(function(){
Url.setHash('#/lista/'+evt.idEvento);
});
evento.find('.btn-form').click(function(){
Url.setHash('#/form/'+evt.idEvento);
});
evento.find('.btn-ver').click(function(){
Url.setHash('#/ver-asistencia/'+evt.idEvento);
});
evento.find('.btn-editar').click(function(){
Url.setHash('#/editar-asistencia/'+evt.idEvento);
});
},
hide : function(){
$(this.el).hide();
this.model.clean();
}
});
<file_sep><?php
class SET_content extends DA_Abs{
public static function setCustomHome($data){
$titulo = $data['titulo'];
$subtitulo = $data['subtitulo'];
$descuento = $data['descuento'];
$tieneDescuento = 0;
if(isset($data['tieneDescuento']))$tieneDescuento = ( $data['tieneDescuento'] == 'on') ? 1:0;
$texto = escape(htmlspecialchars($data['texto']));
$sql = "UPDATE customHome SET
titulo='$titulo',
subtitulo='$subtitulo',
descuento='$descuento',
tieneDescuento='$tieneDescuento',
texto='$texto'
WHERE id = 1";
try
{
$db = Conexion::getConexion();
$db->execute($sql);
return true;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error setCustomHome ($c):" . $e->getMessage(), 200);
}
}
public static function setCustomPopup($data){
//var_dump($data);
$activo = 0;
if(isset($data['activo']))$activo = ( $data['activo'] == 'on') ? 1:0;
$bordercolor = $data['bordercolor'];
$delay = $data['delay'];
$titulo = $data['titulo'];
$fontsize = $data['fontsize'];
$texto = escape(htmlspecialchars($data['texto']));
$textoboton = $data['textoboton'];
$link = $data['link'];
$isblank = 0;
if(isset($data['isblank']))$isblank = ( $data['isblank'] == 'on') ? 1:0;
$mostrarfooter = 0;
if(isset($data['mostrarfooter']))$mostrarfooter = ( $data['mostrarfooter'] == 'on') ? 1:0;
$sql = "UPDATE customPopup SET
activo='$activo',
bordercolor='$bordercolor',
delay='$delay',
titulo='$titulo',
fontsize='$fontsize',
texto='$texto',
textoboton='$textoboton',
link='$link',
isblank='$isblank',
mostrarfooter='$mostrarfooter'
WHERE id = 1";
try
{
$db = Conexion::getConexion();
$db->execute($sql);
return true;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error setCustomPopup ($c):" . $e->getMessage(), 200);
}
}
public static function createContent($data){
$active = $data->details->active;
$title = $data->details->title;
$desc = $data->details->description;
$SEO_desc = $data->details->SEO_desc;
$order = $data->order;
$idSection = $data->idSection;
$align = $data->align;
$pathImg = $data->pathImg;
$rname = $data->rname;
$fecha = new Fecha();
$sqlAbs = "INSERT INTO contents (fecha,
contentTypes_idType,
img,
imgAlign,
referenceName)
VALUES (
'$fecha',2,'$pathImg',$align,'$rname')";
try
{
$db = Conexion::getConexion();
$db->execute($sqlAbs);
//echo $sqlAbs;die;
$nid = self::lastId($db);
//creando...si tiene imagen...formateo el nombre sumando el id y lo guardo. El pathImg queda para guardar la imagen luego de la consulta...cuando ya tengo el id
if(!is_null($data->img)){
$data->pathImg = $rname ."_". $nid . ".jpg";
$pathImg = $data->pathImg;
$sqlAbs = "UPDATE contents SET img = '$pathImg' WHERE idContent=$nid";
//echo $sqlAbs;die;
$db->execute($sqlAbs);
}
$sqlDetails = "INSERT INTO `content_details`
(`idiomas_idIdioma`,
`contents_idContent`,
`titulo`,
`descripcion`,
`SEO_desc`,
`activo`)
VALUES (".
self::$idIdioma . ",
$nid,
'$title',
'$desc',
'$SEO_desc',
$active )";
//echo $sqlDetails;die;
$db->execute($sqlDetails);
$sqlRelations = "INSERT INTO content_tosection (contents_idContent,sections_idSection,content_order) VALUES (
$nid,$idSection,$order )";
//echo $sqlRelations;die;
$db->execute($sqlRelations);
$parent = GET_section::getParent($idSection);
if($parent){
$sqlRelations = "INSERT INTO content_tosection (contents_idContent,sections_idSection,content_order) VALUES (
$nid,$parent->id,$order)";
$db->execute($sqlRelations);
}
return GET_content::getContent($nid,$idSection);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error inesperado ($c):" . $e->getMessage(), 200);
}
}
public static function updateContent($data){
$cid = $data->id;
$active = $data->details->active;
$title = $data->details->title;
$desc = $data->details->description;
$SEO_desc = $data->details->SEO_desc;
$order = $data->order;
$idSection = $data->idSection;
$align = $data->align;
$pathImg = $data->pathImg;
//$fecha = new Fecha();
$sqlAbs = "UPDATE contents SET
imgAlign = $align,img = '$pathImg' WHERE idContent = $cid";
if(!is_null($pathImg)){
$sqlAbs = "UPDATE contents SET
imgAlign = $align,img = '$pathImg' WHERE idContent = $cid";
}else
{
$sqlAbs = "UPDATE contents SET
imgAlign = $align WHERE idContent = $cid";
}
//if getDetails update else create
$details = GET_content::getDetails($cid);
//echo $sqlAbs;die;
if(is_null($details)){
$sqlDetails = "INSERT INTO `content_details`
(`idiomas_idIdioma`,
`contents_idContent`,
`titulo`,
`descripcion`,
`SEO_desc`,
`activo`)
VALUES (".
self::$idIdioma . ",
$cid,
'$title',
'$desc',
'$SEO_desc',
$active )";
}
else{
$sqlDetails = "UPDATE `content_details`
SET `activo` = $active,
`titulo` = '$title',
`descripcion` = '$desc',
`SEO_desc` = '$SEO_desc'
WHERE `idiomas_idIdioma`=" . self::$idIdioma . "
AND `contents_idContent` = $cid";
}
//solo se modifica si es castellano
$sqlRelations = "UPDATE content_tosection
SET content_order = $order
WHERE contents_idContent = $cid AND sections_idSection = $idSection";
try
{
$db = Conexion::getConexion();
/*echo $sqlAbs;
echo ';<br>';
echo $sqlDetails;
echo ';<br>';
die;*/
$db->execute($sqlAbs);
$db->execute($sqlDetails);
//solo se modifica si es castellano
if(self::$idIdioma == 1)$db->execute($sqlRelations);
return GET_content::getContent($cid,$idSection);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error inesperado ($c):" . $e->getMessage(), 200);
}
}
public static function delete($cid){
//contenidos to seccion
//contentDetails
//content
$sql_1 = "DELETE FROM content_tosection WHERE contents_idContent=$cid";
$sql_2 = "DELETE FROM content_details WHERE contents_idContent=$cid";
$sql_3 = "DELETE FROM contents WHERE idContent=$cid";
try
{
$db = Conexion::getConexion();
//echo $sqlDetails;die;
if(self::$idIdioma == 1)//solo borramos si es castewllano
{
$db->execute($sql_1);
$db->execute($sql_2);
$db->execute($sql_3);
return true;
}
return false;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error inesperado ($c):" . $e->getMessage(), 200);
}
}
// public static function changeOrder($secciones){
// //var_dump($secciones);die;
// $sql ="UPDATE sections SET sectionOrder= ";
// foreach($secciones as $sec){
// $csql = $sql.$sec->order . " WHERE idSection=" . $sec->idSection;
// //echo $csql;die;
// try
// {
// $db = Conexion::getConexion();
// $db->execute($csql);
// }
// catch (Exception $e) {
// $c = $e->getCode();
// throw new AppException("Error inesperado ($c):" . $e->getMessage(), 200);
// }
// }
// }
}
?><file_sep>Utils = {
urlParams : function(url){
if(url==null)url = window.location.href;
var params;
var hash= url.split('?');
if(hash && hash.length>1){
eval('params={'
+ hash[1].replace(/=/g, ':\'').replace(/&/g, '\',')
+ '\'}');
}
return params;
},
timestp : function(){
return new Date().getTime();
},
resolveImgAlign : function(n){
switch(Number(n)){
case 0:return "img-left";
case 1:return "img-middle";
case 2:return "img-right";
case 3:return "img-bottom";
case 4:return "img-super-left";
case 5:return "img-super-right";
}
},
resolveRef : function(sectionType,ref)
{
var url="";
switch(Number(sectionType))
{
case 1:url='home';break;
case 2:url='article';break;
case 3:url='pictures';break;
case 4:url='videos';break;
case 5:url='contact';break;
}
if(sectionType==2 || sectionType==4 || sectionType==5)
{
url+='/'+ref;
}
return '#/' + url;
},
db64ToText : function ($text)
{
return $.base64.decode($text);
},
db64ToPreviewText : function ($text,$cant)
{
return Utils.shortStr($.base64.decode($text),$cant);
},
shortStr : function($text,$cant){
if(!$cant)$cant=1000;
var dots = ($cant < $text.length) ? "..." : "";
$cant = Math.min($cant,$text.length);
return $text.substr(0,$cant)+dots;
},
shortArticle : function($text,$cant){
if(!$cant)$cant=1000;
var hasToShort = ($cant < $text.length) ? true : false;
var dots = (hasToShort) ? "[...]" : "";
$cant = Math.min($cant,$text.length);
$text = $text.substr(0,$cant);
/*$text = $text.split('</p>');
$text.pop();
$text = $text.join('</p>');*/
return {short:hasToShort,text:$text+dots};
},
serialize : function(obj){
return $.base64.encode(JSON.stringify(obj));
},
unserialize : function(data){
return JSON.parse($.base64.decode(data));
}
}
// static class Encode
function Encode() {
}
Encode.encode = function(t) {
return t.replace(/[^a-z0-9_\/]+/gi, '_');
};
Encode.friendlyUrl = function(url) {
url = '#!' + this.encode(url) + '.html';
return url;
};
// end static class Encode
function Url(){}
Url.setHash = function($hash){
window.location.hash = $hash;
};
Url.reload = function(){
window.location = 'index.php';
};
Url.go = function(url){
//log(window.location);return;
window.location = url;
};
<file_sep><?php
class GET_camp extends DA_Abs{
public static function getOwner($id){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * FROM owners WHERE idOwner = $id";
//echo $sql;die;
$camp = $rs->getObject($sql);
return $camp;
}
public static function getSource($id){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * FROM fuentes WHERE idFuente = $id";
//echo $sql;die;
$camp = $rs->getObject($sql);
return $camp;
}
public static function getConsultas($data){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * FROM consultas,usuarios WHERE usuarios.idUsuario=consultas.usuarios_idUsuario ORDER BY consultas.idConsulta DESC LIMIT 30";
//echo $sql;die;
$camp = $rs->getObjects($sql);
return $camp;
}
public static function getCamp($data){
$id = $data->cid;
$so = $data->so;
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * FROM campaings WHERE idCamp = $id";
//echo $sql;die;
$camp = $rs->getObject($sql);
if(is_null($camp))return null;
$camp->source = $rs->getObject("SELECT * FROM fuentes WHERE idFuente=$so");
$o = $camp->owners_idOwner;
$camp->owner = $rs->getObject("SELECT * FROM owners WHERE idOwner=$o");
$t = $camp->evento_idEvento;
$camp->evento = $rs->getObject("SELECT * FROM eventos WHERE idEvento=$t");
$t = $camp->evento->tipoEvento_idTipo;
$camp->evento->tipo = $rs->getObject("SELECT * FROM tipos_evento WHERE idTipo=$t");
return $camp;
}
public static function getUsuario($email){
try
{
$db = Conexion::getConexion('usuarios');
$sql = "SELECT * FROM usuarios WHERE email='$email'";
$rs=$db->getRecordset();
return $rs->getObject($sql);
}
catch (Exception $e) {
new AppException("getUsuario(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
public static function getFakeUsuario($id){
try
{
$db = Conexion::getConexion('usuarios');
$sql = "SELECT * FROM usuarios WHERE idUsuario='$id'";
$rs=$db->getRecordset();
return $rs->getObject($sql);
}
catch (Exception $e) {
new AppException("getFakeUsuario(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
public static function getReserva($idevt,$idUsuario){
$evento = $idevt;
$sql = "SELECT * FROM reservas WHERE usuarios_idUsuario=$idUsuario AND eventos_idEvento=$evento ORDER BY idReserva DESC LIMIT 1";
try
{
$db = Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
//echo $sql;die;
return $rs->getObject($sql);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("getReserva(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
}
?><file_sep>
<!DOCTYPE html>
<html lang="es"><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Eventos</title>
<link rel="icon" type="../../image/png" href="favicon.png">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Gentium+Book+Basic:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<link href="../site/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="../site/bootstrap/css/bootstrap-switch.min.css" rel="stylesheet">
<!-- The main CSS file -->
<link href="mini-upload-form/assets/css/style.css" rel="stylesheet" />
<link rel="stylesheet/less" type="text/css" href="../site/less/estilos.less" />
<script src="../site/less/less-1.4.1.min.js"></script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="mini-upload-form/assets/js/jquery.knob.js"></script>
<?php echo '<script>var idEvento='.$evento->idEvento.';</script>'?>
<!-- jQuery File Upload Dependencies -->
<script src="mini-upload-form/assets/js/jquery.ui.widget.js"></script>
<script src="mini-upload-form/assets/js/jquery.iframe-transport.js"></script>
<script src="mini-upload-form/assets/js/jquery.fileupload.js"></script>
<!-- Our main JS file -->
<script src="mini-upload-form/assets/js/script.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if IE ]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<link href="http://aztlan.com.ar/site/css/ie.css" rel="stylesheet">
<![endif]-->
<style type="text/css">
.btn,.btn:visited{margin-top:20px;color:white;};
</style>
</head>
<body>
<nav class="header-nav" style="margin-bottom:30px;">
<div class="header container">
<div class="row">
<div class="logo col-xs-2 col-sm-3 col-md-4 hidden-xs ">
<img src="../images/logo.png" class="pull-left">
<div class="pull-left hidden-sm">
<h1 class="h1Header">Aztlan</h1>
<h4 class="h4Header">Director <NAME></h4>
</div>
</div>
<div class="slogan col-xs-8 col-sm-8 col-md-6">
<h1 class="h1Header">Escuela de Filosofía y Psicología</h1>
<h4 class="h4Header"><strong>Enseñanza Privada Nivel Terciario - No oficial</strong></h4>
<p class="pHeader hidden-xs">Personería Jurídica Nº I.G.J. 748</p>
<p class="pHeader hidden-xs">Centro Nacional de Organizaciones de la Comunidad C.E.N.O.C. Nº 16528</p>
</div>
<div class="slogan col-xs-2 col-sm-2 col-md-2">
<a href="http://aztlan.com.ar/eventos" ><span style="font-size:50px;" class="glyphicon glyphicon-home"></span></a>
</div>
</div>
</div>
</nav>
<div class="container">
<?php if(isset($_GET['success']) && $_GET['success']==1){
if(isset($_GET['changed'])) $palabra = "MODIFICADO";
else $palabra = "CREADO";
echo '<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<span class="glyphicon glyphicon-ok" style="font-size: 50px;"></span> <span style="font-size: 30px;padding-left:30px;">El evento fue '. $palabra .' correctamente.</span>
</div>';
}
?>
<div class="row">
<div class="col-sm-4 col-sm-offset-1">
<?php
$path = '../../images/eventos/home/';
$modificar = isset($_GET['modificar']);
if(!$modificar && file_exists($path.$_GET['idEvento'].'.jpg')){
echo '<p><strong>FOTO HOME</strong></p>';
echo '<img src="'. $path.$_GET['idEvento'].'.jpg?k='.time().'" width="330" height="258">';
echo '<div class="btn-toolbar" role="toolbar" >';
echo '<a class="btn btn-warning" href="eventoCreado.php?idEvento='.$_GET['idEvento'].'&modificar=1" >Modificar</a>';
echo '<a class="btn btn-warning" href="http://www.aztlan.com.ar" >Ver Home</a>';
echo '</div>';
}else{
echo
'<form class="upload" id="upload-1" method="post" action="mini-upload-form/upload-1.php?idEvento='. $_GET['idEvento'].'" enctype="multipart/form-data">
<div id="drop">
Foto HOME
<a>Cargar foto</a>
<input type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>';
}
?>
</div>
<div class="col-sm-4 col-sm-offset-1">
<?php
$path = '../../images/eventos/landing/';
if(!$modificar && file_exists($path.$_GET['idEvento'].'.jpg')){
echo '<p><strong>FOTO LANDING</strong></p>';
echo '<img src="'. $path.$_GET['idEvento'].'.jpg?k='.time().'" height="30%">';
echo '<div class="btn-toolbar" role="toolbar" >';
echo '<a class="btn btn-warning" href="eventoCreado.php?idEvento='.$_GET['idEvento'].'&modificar=1" >Modificar</a>';
echo '<a class="btn btn-warning" href="http://www.aztlan.com.ar/pages/psi/?c='.$evento->idEvento.'/3/7" >Ver Landing</a>';
echo '</div>';
}else{
echo
'<form class="upload" id="upload-2" method="post" action="mini-upload-form/upload-2.php?idEvento='. $_GET['idEvento'].'" enctype="multipart/form-data">
<div id="drop">
Foto LANDING
<a>Cargar foto</a>
<input type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>';
}
?>
</div>
</div>
</div>
</body>
</html><file_sep><?php
/**
* Date: 26/07/2012 13:48:20
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package
**/
/**
*
**/
class SerializableController {
private static $toSend=array();
private static $data=null;
private function __construct(){
}
public static function getData(){
if(is_null(self::$data)){
if(!is_null($_REQUEST["data"])){
self::$data=@json_decode(utf8Encode(base64_decode($_REQUEST["data"])));
}
else if(!is_null($_POST["data"])){
self::$data=@json_decode(utf8Encode(base64_decode($_POST["data"])));
}
else if(!is_null($_GET["data"])){
self::$data=@json_decode(utf8Encode(base64_decode($_GET["data"])));
}
if(is_null(self::$data)) self::$data=new stdClass();
}
foreach ($_REQUEST as $clave => $valor){
self::$data->$clave = $valor;
}
return self::$data;
}
public static function addToSend($obj,$name=null){
if(is_null($name)){
self::$toSend[]=$obj;
}else{
self::$toSend[$name]=$obj;
}
}
/**
*
* @param Exception $e
*/
public static function sendError($e){
$code=$e->getCode();
$msg=$e->getMessage();
if($code>0){
$code=-1;
$msg="error interno de servidor";
}
if(Application::appConfig("debug")=="true"){
self::sendData(array("error"=>1,
"debugCode"=>$e->getCode(),
"debugMsg"=>$e->getMessage(),
"errorCode"=>$code,
"errorMsg"=>$msg
));
}else{
//Logger::logError($e);
self::sendData(array("error"=>1,
"errorCode"=>$code,
"errorMsg"=>$msg
));
}
}
public static function send(){
self::sendData(array("error"=>0,"errorCode"=>0,"errorMsg"=>"","data"=>self::$toSend));
}
/**
*
* @param array $data
*/
private static function sendData($data){
self::sendHeaders();
echo self::getDataToSend($data);
}
/**
*
* @param array $data
* @return string
*/
private static function getDataToSend($data){
$data["last_updated"]=date("Y-m-d H:i:s");
if(count($data["data"])==0){
$data["data"]=new stdClass();
}
if(isset($_REQUEST["xml"])){
$d=new stdClass();
foreach ($data as $k=>$v){
$d->$k=$v;
}
$sData=Encode::toXml($d);
}else{
$sData=@json_encode($data);
}
$o=new stdClass();
if(Application::appConfig("debug")=="true"){
$o->responseDebug=$data;
$o->requestDebug=self::getData();
$o->data=base64_encode($sData);
//$o->encdata=Encriptador::encriptar($sData);
}else{
if(Application::appConfig("encrypt")=="true"){
$o->data=Encriptador::encriptar($sData);
}else{
$o->data=base64_encode($sData);
}
}
if(isset($_REQUEST["xml"]))
return Encode::toXml($o);
return json_encode($o);
}
/**
* Envia encabezados al cliente
*/
private static function sendHeaders(){
ob_clean();
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
if(isset($_REQUEST["xml"]))
header ("content-type: text/xml");
else
header('Content-type: application/json', true);
}
}
?><file_sep><?php
class Session {
private function Session() {
}
public static function set($key,$value){
$_SESSION[$key]=serialize($value);
}
public static function get($key) {
if (isset ($_SESSION[$key])) {
return unserialize($_SESSION[$key]);
} else {
return null;
}
}
public static function unRegister($key) {
$_SESSION[$key]=null;
unset($_SESSION[$key]);
}
public static function id(){
return session_id();
}
public static function un_Set(){
session_unset();
}
public static function destroy(){
session_destroy();
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idSection
if($this->data->active)GET_content::$onlyActives = true;
parent::addToSend(GET_content::getContentsBySection($this->data->idSection),'contents');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep>$('body').ready(function(){
$('#datetimepicker5').datetimepicker({
pickTime: false
});
$('input#switch-state').bootstrapSwitch();
$('input#switch-state-2').bootstrapSwitch();
$('input#switch-state-3').bootstrapSwitch();
$('input#switch-state-4').bootstrapSwitch();
$('select[name="tipoEvento"]').change(function(){
console.log($(this).val());
if($(this).val() == 1){
$('#idYoutube').closest('.form-group').removeClass('hidden');
$('#link').closest('.form-group').removeClass('hidden');
}else{
$('#idYoutube').closest('.form-group').addClass('hidden');
$('#link').closest('.form-group').addClass('hidden');
}
});
//console.log($('#datetimepicker5'));
});<file_sep><?php
//error_reporting(0);
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idCamp
//source
$camp = GET_camp::getCamp($this->data);
parent::addToSend($camp,'camp');
parent::addToSend(SET_camp::setEstadistica($camp),'estadistica');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.1
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/System
* @filesource
**/
/**
* version 1.1 se agrego la funcionalidad show soporte de intl
**/
class Fecha extends DateTime {
const DEFAULT_FORMAT="Y-m-d H:i:s";
/**
* Retorna un nuevo objeto Fecha
* Para utilizar Unix timestamp, anteponer @ en el string de $time.
* @param string $time[optional]
* @param DateTimeZone $timezone[optional]
*/
function __construct($time = null, DateTimeZone $timezone = null) {
if(is_null($timezone))
parent::__construct($time);
else
parent::__construct($time,$timezone);
}
/**
* Retorna la fecha formateada en AAAA-MM-DD HH:MM:SS
* @return string
*/
public function __toString(){
return $this->format();
}
/**
* Retorna la fecha formateada de acuerdo al string pasado
* @param string $format
* @return string
*/
public function format($format=self::DEFAULT_FORMAT){
return parent::format($format);
}
/**
* Retorna la fecha formateada dependiendo del locale del cliente
* si el modulo intl esta activo, por defecto $dateFormatter=IntlDateFormatter::SHORT,
* $timeFormatter=IntlDateFormatter::MEDIUM
* @param IntlDateFormatter $dateFormatter
* @param IntlDateFormatter $timeFormatter
* @return string
*/
public function show($dateFormatter=3,$timeFormatter=2){
if(extension_loaded("intl")){
$locale=locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
$fmt = new IntlDateFormatter( $locale ,$dateFormatter,$timeFormatter,Application::getTimeZone());
return $fmt->format($this);
}else{
return $this->format();
}
}
/**
* Agrega la cantidad de dias segun el parametro
* @param int $d
*/
public function addDays($d){
$this->add(new DateInterval("P".$d."D"));
}
/**
* Agrega la cantidad de horas segun el parametro
* @param int $d
*/
public function addHours($h){
$this->add(new DateInterval("PT".$h."H"));
}
/**
* Agrega la cantidad de minutos segun el parametro
* @param int $d
*/
public function addMinutes($m){
$this->add(new DateInterval("PT".$m."M"));
}
/**
* Compara el valor de esta instancia con un valor de Fecha especificado y
* devuelve un entero que indica si esta instancia es anterior, igual o posterior
* al valor de Fecha especificado
* @param Fecha $fecha
* @return number
*/
public function compareTo(Fecha $value){
if($this->getTimestamp()>$value->getTimestamp()){
return 1;
}elseif($this->getTimestamp()==$value->getTimestamp()){
return 0;
}
return -1;
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
parent::addToSend(GET_eventos::setUsuario($this->data->id,$this->data->estado,$this->data->txt),'usuario');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?>
<file_sep><?php
// 27/10/2008 15:31:08
// <EMAIL>
class XMLParser{
private $doc;
private $root;
public function __construct(){
$this->doc=new DOMDocument();
}
public function load($value){
@$this->doc->load($value);
$this->root=$this->doc->documentElement;
if(is_null($this->root)){
throw new Exception("XMLParser::load el archivo \"$value\" XML no se cargo");
}
}
public function isLoaded(){
return (is_null($this->root))?false:true;
}
public function getNodes (){
$ret=array();
foreach($this->root->childNodes as $node){
if($node->nodeType==XML_ELEMENT_NODE){
$ret[]=new XMLNode($node);
}
}
return $ret;
}
}
class XMLNode{
var $node;
public function __construct(DOMElement $value){
$this->node=$value;
}
public function getNodes (){
$ret=array();
foreach($this->node->childNodes as $node){
if($node->nodeType==XML_ELEMENT_NODE){
$ret[]=new XMLNode($node);
}
}
return $ret;
}
public function nodeName(){
return $this->node->nodeName;
}
public function nodeValue(){
return $this->node->nodeValue;
}
public function getAttribute($value){
return $this->node->getAttributeNode($value)->value;
}
public function hasAttribute($value){
return $this->node->hasAttribute($value);
}
}
?><file_sep>(function(app) {
app.data.PersistentData = {
parse : function(data) {
app.logger.log('PersistentData.parse', data);
for ( var propertyName in data) {
eval('app.data.PersistentData.' + propertyName + '=data.' + propertyName);
}
return data;
}
};
})(window.app);<file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
parent::addToSend(DA_popup::showPopup(), "popup");
parent::addToSend(GET_section::getIdioma(), "idioma");
$_SESSION['popup']=true;
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idSection
parent::addToSend(GET_section::getParent($this->data->id),'parent');
parent::addToSend(SET_section::delete($this->data->id),'deleted');
parent::addToSend(GET_section::getSite(),'site');
GET_site::saveMenu();
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
/**
* Date: 25/11/2008 09:41:54
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package HX_Fmwk/Sql
* @filesource
**/
/**
*
**/
class Autonum {
private function __construct(){
}
/**
* @return int
*/
public static function getNewId() {
$id = 0;
$db = Conexion :: getConexion();
$sql = "insert into autonum () values ()";
$db->execute($sql);
$rs = $db->getRecordset();
$rs->execute("select last_insert_id() as id");
$id = intval($rs->field("id"));
$rs->close();
return $id;
}
}
/*
DROP TABLE IF EXISTS autonum;
CREATE TABLE autonum (
`id` int(10) NOT NULL auto_increment,
`fecha` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1000 DEFAULT CHARSET=latin1;
*/
?><file_sep><?php
class BasicConfiguration {
private $values=array();
public function value($name){
return $this->values[$name];
}
public function __construct($config){
$this->load($config);
}
private function load($config){
$doc = new DOMDocument();
$doc->load($config);
$root = $doc->documentElement;
$node = $root->firstChild;
while ($node) {
if (($node->nodeType == XML_ELEMENT_NODE) && ($node->nodeName == 'add')) {
$name=$node->attributes->getNamedItem("name")->textContent;
$value=$node->attributes->getNamedItem("value")->textContent;
if(!is_null($name)){
$this->values[$name]=$value;
}
}
$node = $node->nextSibling;
}
}
}
?><file_sep><?php
/**
* Date: 23/08/2012 16:05:38
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package
**/
/**
*
**/
class MysqlOutFile{
private function __construct(){
}
/**
* Retorna el full path del archivo generado en formato csv
* @param array $head
* @param string $sqlData
* @throws BackofficeException
* @return string
*/
public static function generarCSV($head,$sqlData){
$file=addslashes(tempnam(sys_get_temp_dir(), "_csv_"));
@unlink($file);
$db = Conexion :: getConexion();
$sqlHead="select cast('".implode("' as char(255)),cast('",$head)."' as char(255))";
try {
$db->execute("drop temporary table if exists temp");
$db->execute("CREATE TEMPORARY TABLE temp ".$sqlHead);
$db->execute("insert into temp ".$sqlData);
$db->execute("select * from temp
INTO OUTFILE '$file'
FIELDS TERMINATED BY ';'
ESCAPED BY '\"'
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\r\n'");
$db->execute("drop temporary table if exists temp");
return $file;
} catch (Exception $e) {
throw new BackofficeException($e->getMessage());
}
}
/**
* Retorna el full path del archivo generado en formato XLS
* @param array $head
* @param string $sqlData
* @throws BackofficeException
* @return string
*/
public static function generarXLS($head,$sqlData){
$file=addslashes(tempnam(sys_get_temp_dir(), "_csv_"));
@unlink($file);
$db = Conexion :: getConexion();
$sqlHead="select cast('".implode("' as char(255)),cast('",$head)."' as char(255))";
try {
$db->execute("drop temporary table if exists temp");
$db->execute("CREATE TEMPORARY TABLE temp ".$sqlHead);
$db->execute("insert into temp ".$sqlData);
$db->execute("select * from temp
INTO OUTFILE '$file'
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'");
$db->execute("drop temporary table if exists temp");
return $file;
} catch (Exception $e) {
throw new BackofficeException($e->getMessage());
}
}
}
?><file_sep><?php
class SET_camp extends DA_Abs{
public static function setEstadistica($camp){
$owner = $camp->owners_idOwner;
$fuente = $camp->source->idFuente;
$camp = $camp->idCamp;
$ip = self::getRealIP();
$ips = array('192.168.3.11','172.16.17.32');
if (in_array($ip, $ips)) return 1;
$url = null;
$fecha = new Fecha();
$toView = $fecha->format('Y-m-d');
$sql = "INSERT INTO estadisticas (ip,url,navegador,camp,owner,fuente,fecha,fecha_simple)
VALUES (
'$ip','$url','$navegador',$camp,$owner,$fuente,'$fecha','$toView')";
try
{
$db = Conexion::getConexion('usuarios');
//echo $sql;die;
$db->execute($sql);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setEstadistica(): Error inesperado ($c):" . $e->getMessage(), 200);
}
return 1;
}
public static function getRealIP()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
return $_SERVER['HTTP_CLIENT_IP'];
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
return $_SERVER['HTTP_X_FORWARDED_FOR'];
return $_SERVER['REMOTE_ADDR'];
}
public static function setUsuario($evt,$owner,$source,$params){
$nombre = escape($params->nombre);
$apellido = escape($params->apellido);
$dni = (property_exists($params, 'dni')) ? escape($params->dni) : '';
$email = escape($params->email);
$tel = escape($params->telefono);
$tipo = escape($evt->tipo->nombre);
$source = escape($source->nombre);
$owner = escape($owner->nombre);
//$idCamp = escape($camp->idCamp);
$fecha = new Fecha();
$sql = "INSERT INTO usuarios (nombre,apellido,dni,email,telefono,tipo,source,owner,campaing,creado)
VALUES (
'$nombre','$apellido','$dni','$email','$tel','$tipo','$source','$owner','','$fecha')";
try
{
$db = Conexion::getConexion('usuarios');
//echo $sql;die;
$db->execute($sql);
//$nid = self::lastId($db);
//return $nid;
}
catch (Exception $e) {
$c = $e->getCode();
if($c != 1062)throw new AppException("setUsuario(): Error inesperado ($c):" . $e->getMessage(), 200);
else{
$sql = "UPDATE usuarios SET
nombre='$nombre',
apellido='$apellido',
dni='$dni',
telefono='$tel'
WHERE email='$email'";
//echo $sql;die;
try{
$db->execute($sql);
}catch (Exception $e) {
throw new AppException("setUsuarioUPDATE(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
}
return GET_camp::getUsuario($email);
}
public static function setReserva($evt,$owner,$source,$params,$idUsuario){
$evento = $evt->idEvento;
$lugares = $params->lugares;
$sou = $source->idFuente;
$own = $owner->idOwner;
//$camp = $camp->idCamp;
$sql = "INSERT INTO reservas (eventos_idEvento,usuarios_idUsuario,cantLugares,fecha,camp_idCamp,source,owners_idOwner,confirmado,tipoUsuario)
VALUES (
$evento,$idUsuario,$lugares,now(),0,$sou,$own,0,1)";
//echo $sql;die;
try
{
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
return true;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setReserva(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
public static function setConsulta($params,$idUsuario){
$consulta = $params->consulta;
$sql = "INSERT INTO consultas (usuarios_idUsuario,consulta)
VALUES (
$idUsuario,'$consulta')";
try
{
$db = Conexion::getConexion('usuarios');
//echo $sql;die;
$db->execute($sql);
return true;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setConsulta(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
}
?><file_sep><?php
class JScript {
private static $vars = array();
private static $scripts = array();
private static $scriptsDR = array();
private static $scriptsWO = array();
private function __construct() {}
public static function registerScript($script) {
JScript::$scripts[] = $script;
}
public static function windowOnload($script) {
JScript::$scriptsWO[] = $script;
}
public static function documentReady($script) {
JScript::$scriptsDR[] = $script;
}
public static function registerVar($key, $value) {
JScript::$vars[$key] = json_encode($value);
}
public static function render() {
if (count(JScript::$scriptsDR) == 0 && count(JScript::$scriptsWO) == 0 && count(JScript::$scripts) == 0 && count(JScript::$vars) == 0)
return "";
$ret = "\n";
$ret .= "<script type=\"text/javascript\">\n";
if (count(JScript::$scriptsWO) > 0) {
$ret .= "window.onload = function () {\n";
foreach (JScript::$scriptsDR as $s) {
$ret .= "$s\n";
}
$ret .= "};\n";
}
if (count(JScript::$scriptsDR) > 0) {
$ret .= "\$(document).ready(function() {\n";
foreach (JScript::$scriptsDR as $s) {
$ret .= "$s\n";
}
$ret .= "});\n";
}
foreach (JScript::$scripts as $s) {
$ret .= "$s\n";
}
foreach (JScript::$vars as $k => $v) {
$ret .= "var $k=" . $v . ";";
}
$ret .= "\n</script>\n";
return $ret;
}
public static function closeWindow() {
ob_end_clean();
echo ("<script>self.close();</script>");
exit();
}
public static function redirect($url) {
ob_end_clean();
echo ("<script> top.location.href='$url'</script>");
exit();
}
public static function downloadTmpFile($file, $nombre = "archivo", $utf8Decode = false) {
$a["file"] = $file;
$a["nombre"] = $nombre;
$a["utf8Decode"] = $utf8Decode;
$data = base64_encode(json_encode($a));
JScript::registerScript("\$b.downloadTmpFile('$data');");
}
public static function downloadFile($url, $data = "", $method = "post") {
$k = Random::nextAlphaNumeric(30);
Session::set("ss_key", $k);
$data .= "&ss_id=" . session_id() . "&ss_key=" . $k;
JScript::registerScript("\$b.download('$url','$data', '$method');");
}
}
?><file_sep><?php
abstract class FWObject extends Object implements IFWObject {
protected $id=0;
protected $habilitado=false;
protected $eliminado=false;
protected $fechaCreado=null;
protected $fechaModificado=null;
public function setId($id){
$this->id=intval($id);
}
public function getId(){
return $this->id;
}
public function setHabilitado($habilitado){
$this->habilitado=(boolean) $habilitado;
}
public function getHabilitado(){
return ($this->habilitado)?1:0;
}
public function setEliminado($eliminado){
$this->eliminado=(boolean) $eliminado;
}
public function getEliminado(){
return ($this->eliminado)?1:0;
}
public function setFechaCreado($fecha){
$this->fechaCreado=$fecha;
}
public function getFechaCreado($format=null){
if(is_null($format)){
return $this->fechaCreado;
}
return $this->fechaCreado->format($format);
}
public function setFechaModificado($fecha){
$this->fechaModificado=$fecha;
}
public function getFechaModificado($format=null){
if(is_null($format)){
return $this->fechaModificado;
}
return $this->fechaModificado->format($format);
}
}
?><file_sep><?php
class AppPageController extends PageController {
public function __construct(){
HX_Fmwk::registerApplication(Application::appKey("application"));
parent::__construct();
}
}
?><file_sep>app.view.Usuario = app.Section.extend({
el:'div#usuario-container',
template:null,
initialize: function() {
var ui = $(this.el);
this.model = new app.data.models.UsuarioModel();
this.model.onRegister();
this.listenTo(this.model, "change:usuario", this.renderUsuario);
this.template = $('body').find('div.usuario-template').clone();
this.template.show();
this.template.removeClass('usuario-template');
/*
this.template.find('.btn-lista').parent().remove();
this.template.find('.btn-ver').parent().remove();
this.template.find('.btn-form').parent().remove();
this.template.find('.btn-links').parent().remove();
this.template.addClass('evento');
*/
},
renderUsuario : function(){
//log('hola');
var usuario = this.model.get('usuario');
var ui = $(this.el);
//var body = ui.find('tbody');
ui.empty();
var tr,td,n;
n=0;
var self = this;
var view = self.template.clone();
ui.append(view);
view.find('.nombre').text(usuario.nombre + " " + usuario.apellido);
view.find('.email').text(usuario.email);
view.find('.dni').text(usuario.dni);
view.find('.telefono').text(usuario.telefono);
view.find('.situacion').text(usuario.situacion);
if(usuario.admitido_txt != null)view.find('.admitido_txt').text(usuario.admitido_txt);
var radio = $("[name='radio-admitido']")
if(usuario.admitido == 1){
radio.prop('checked','true');
radio.prop('value','1');
}else{
$('.motivo').show();
}
$("[name='radio-admitido']").bootstrapSwitch();
$("[name='radio-admitido']").on('switchChange.bootstrapSwitch', function(event, state) {
$(this).val((state) ? "1" : "0");
usuario.admitido = (state) ? 1:0;
if(state == false) $('.motivo').show();
else $('.motivo').hide();
});
view.find('.user-actualizar').click(function(){
var txt = view.find(".admitido_txt").val();
//console.log(usuario.admitido);return;
self.model.update(usuario.idUsuario,usuario.admitido,txt,function(){
window.history.back();
});
});
var cont = view.find('.eventos-user-container');
var r,t,c;
for (var variable in usuario.reservas) {
r = usuario.reservas[variable];
t = $('<tr>');
c = $('<td class="date">');
c.text(r.date);
t.append(c);
c = $('<td>');
a = $('<a href="#ver-asistencia/'+r.idEvento+'">"');
a.text(r.titulo);
c.append(a);
t.append(c);
//c = $('<td>');
c = $('<td class="presentismo">');
//tr.append(c);
if(r.asistencia && r.asistencia == 0)c.addClass('ausente');
if(r.asistencia && r.asistencia == 1)c.addClass('presente');
/*if(r.asistencia)c.text('Presente');
else c.text('Ausente');*/
t.append(c);
cont.append(t);
}
$(this.el).show();
},
hide : function(){
//
$(this.el).hide();
this.model.clean();
}
});
<file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//title
//active
//description
//img
//thumb
//align
//order
//idSection
//var_dump(phpinfo());
//echo ini_get("max_input_vars");
//var_dump($POST);
//echo $this->data->details->active;
//echo $this-data->img;
//echo '</br>';
//var_dump($this->data);die;
$newContent = is_null($this->data->id);
$this->data->pathImg = null;
if(!$newContent && $this->data->img){
//update
//$content = GET_content::getContent($this->data->id,$this->data->idSection);
//para q no subreescriba el nombre segun la imagen
$title = $this->data->details->title;
$this->data->details->title = $this->data->referenceName;
$this->formatReferenceNameContent();
$this->data->pathImg = $this->data->rname ."_". $this->data->id . ".jpg";
$this->data->details->title = $title;
}
else
{
$this->formatReferenceNameContent();
}
if(!$newContent){
parent::addToSend(SET_content::updateContent($this->data),'content');
}
else{
$content = SET_content::createContent($this->data);
parent::addToSend($content,'content');
}
if($this->data->img)
{
//$this->data->pathImg = $this->data->rname ."_". $content->id . ".jpg";// si es nuevo..la variable se formatea en la consulta,sino se formatea arriva
//parent::trace($img);
$img = $this->data->pathImg;
if (@file_put_contents("../../../images/images/$img", @base64_decode($this->data->img))) {
parent::addToSend($img,'img');
} else {
throw new AppException("Error en subir la imagen", 105);
}
if (@file_put_contents("../../../images/thumbs/$img", @base64_decode($this->data->thumb))) {
//parent::addToSend($img,'img');
} else {
throw new AppException("Error en subir el thumb", 105);
}
}
//parent::addToSend(GET_section::getSection($this->data->idSection),'section');
parent::addToSend(GET_section::getSite(),'site');
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
class ConnectionMySql implements IConnection {
private $db;
/**
* @return IRecordset
*/
function getRecordset() {
return new RecordsetMySql($this->db);
}
/**
* @param string $strCon
* @return void
*/
function open($cp) {
die($cp);
$this->db=mysql_connect($cp->server.":".$cp->port, $cp->uid, $cp->pwd)
or die("Error al conectar con la base de datos: host/usuario/contraseña");
mysql_select_db($cp->database,$this->db)
or die("No existe la base de datos: ".$cp->database );
}
/**
* @param string $sql
* @return array
*/
function execute($sql){
$result = mysql_query($sql, $this->db);
if (!$result){
throw new Exception(mysql_error(), mysql_errno());
return;
}
return $result;
}
/**
* @return void
*/
function close(){
if($this->db)
mysql_close ($this->db);
}
public function isClosed(){
return ($this->db);
}
}
?>
<file_sep><?php
if($_POST){
//var_dump($_POST);die;
$dsn = 'mysql:dbname=azwuser_usuarios;host=localhost';
$user = 'root';
$password = '';
/*$dsn = 'mysql:dbname=azwuser_usuarios;host=localhost;port=3306';
$user = 'azwuser_admin';
$password = '<PASSWORD>';*/
try{
$dbh = new PDO($dsn,$user,$password);
$user = htmlspecialchars($_POST['user']);
$pass = htmlspecialchars($_POST['pass']);
$sql = "SELECT id FROM login WHERE
user = '$user' AND
pass = <PASSWORD>'
";
//echo $sql;
$result = $dbh->query($sql);
$id = $result->fetchObject();
if($id){
session_start();
$_SESSION['start'] = time(); // Taking now logged in time.
$_SESSION['log'] = 'in';
// Ending a session in 30 minutes from the starting time.
//$_SESSION['expire'] = $_SESSION['start'] + (60);
if($id->id == 1) $_SESSION['expire'] = $_SESSION['start'] + (60 * 30);
else $_SESSION['expire'] = $_SESSION['start'] + (5*60);
header('Location: '.'index.php');
}
else{
$_POST = null;
$_POST['error'] = true;
}
} catch (PDOException $e) {
echo 'Conexi�n fallida: '.$e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<!-- <meta charset="utf-8"> -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<title>Login</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Gentium+Book+Basic:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="site/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet/less" type="text/css" href="site/less/estilos.less" />
<script src="site/less/less-1.4.1.min.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="header-nav">
<div class="header container">
<div class="row">
<div class="logo col-xs-2 col-sm-2 col-md-4 hidden-xs ">
<img src="images/logo.png" class="pull-left">
<div class="pull-left hidden-sm">
<h1 class="h1Header">Aztlan</h1>
<h4 class="h4Header">Director <NAME></h4>
</div>
</div>
<div class="slogan col-xs-8 col-sm-8 col-md-6">
<h1 class="h1Header">Escuela de Filosof�a y Psicolog�a</h1>
<h4 class="h4Header"><strong>Ense�anza Privada Nivel Terciario - No oficial</strong></h4>
<p class="pHeader hidden-xs">Personer�a Jur�dica N� I.G.J. 748</p>
<p class="pHeader hidden-xs">Centro Nacional de Organizaciones de la Comunidad C.E.N.O.C. N� 16528</p>
</div>
<div class="slogan col-xs-2 col-sm-2 col-md-2">
<a href="http://aztlan.com.ar/eventos" ><span style="font-size:50px;" class="glyphicon glyphicon-home"></span></a>
</div>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4">
<?php if (isset($_POST['error'])){
echo '<div class="alert alert-danger" role="alert">';
echo '<strong>Usuario no registrado</strong></div>';
}?>
<!-- <form class="form-signin" method="post" action="login.php"> -->
<form class="form-horizontal login-form" role="form" action="login.php" method="POST">
<h2 class="form-signin-heading">Login</h2>
<label for="inputEmail" class="sr-only">Usuario</label>
<input type="email" id="inputEmail" name="user" class="form-control" placeholder="Usuario" required autofocus>
<label for="inputPassword" class="sr-only">Contrase�a</label>
<input type="<PASSWORD>" id="inputPassword" name="pass" class="form-control" placeholder="<PASSWORD>" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" >Entrar</button>
</form>
</div>
</div> <!-- /row -->
</div> <!-- /container -->
</body>
</html>
<file_sep><?php
class AppTemplatePageController extends TemplatePageController {
var $mensaje="";
public function __construct(){
HX_Fmwk::registerApplication(Application::appKey("application"));
parent::__construct();
$this->setTemplateDir(Server::APP_ROOT_PATH().Application::appConfig("templateDir"));
$this->setCompileDir(Server::APP_ROOT_PATH().Application::appConfig("templateCompileDir"));
$this->setCompileId(str_replace("/", ".",Server::PHP_SELF()));
//set_exception_handler(array($this, 'errorHandler'));
}
public function errorHandler($excepcion) {
header("location: ../error/");
}
public function onPreRender(){
parent::onPreRender();
#remove the directory path we don't want
$request = str_replace("/aztlanback/", "", $_SERVER['REQUEST_URI']);
//$request = $_SERVER['REQUEST_URI'];
echo $request;
#split the path by '/'
$params = explode("/", $request);
var_dump($params);
$safe_pages = array("home", "search", "thread");
if(in_array($params[0], $safe_pages)) {
include($params[0].".php");
} else {
include("404.php");
}
}
}
?><file_sep><?php
/**
* Date: 22/08/2012 16:37:16
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2012, <NAME>
* @package
**/
/**
*
**/
class MySqliException extends Exception {
/**
* @param Exception $e
* @return void
*/
const DB_ERR_DUP_ENTRY=1062;
const DB_ERR_WRONG_VALUE_COUNT_ON_ROW=1136;
const DB_ERR_NO_SUCH_TABLE=1146;
public function __construct($e){
switch ($e->getCode()) {
case self::DB_ERR_DUP_ENTRY:
parent::__construct("DB_ERR_DUP_ENTRY", $e->getCode());
break;
case DB_ERR_WRONG_VALUE_COUNT_ON_ROW:
parent::__construct("DB_ERR_WRONG_VALUE_COUNT_ON_ROW", $e->getCode());
break;
case DB_ERR_NO_SUCH_TABLE:
parent::__construct("DB_ERR_NO_SUCH_TABLE", $e->getCode());
break;
default:
parent::__construct($e->getMessage(), 0);
break;
}
//Logger::logError($e);
}
}
?><file_sep><?php
// 24/10/2008 00:23:56
// <EMAIL>
interface IPageController{
public function __construct();
public function onLoad();
public function onUnLoad();
public function init();
public function onPreRender();
public function onRender();
public function dispose();
}
?><file_sep><?php
function smarty_function_concat($params, & $smarty) {
if (!isset ($params['var'])) {
$smarty->trigger_error("eval: missing 'var' parameter");
return;
}
$s=":";
if (isset ($params['separator'])) {
$s=$params['separator'];
}
$ret="";
foreach ($params['var'] as $v){
$ret.=" $v$s";
}
return substr($ret, 0, -1);
}
?>
<file_sep><?php
function smarty_modifier_show($obj,$dateFormatter=3,$timeFormatter=2){
return $obj->show($dateFormatter,$timeFormatter);
}
?><file_sep><?php
// 23/10/2008 22:22:25
abstract class PageController implements IPageController {
/* order de inicio de la clase (Controller)
$classTmp->init();
$classTmp->onLoad();
$classTmp->onPreRender();
$classTmp->onRender();
$classTmp->onUnLoad();
$classTmp->dispose();
*
* */
public function __construct(){
}
public function clear(){
$this->attributes=array();
}
public function init(){
//IOTrafficController::init();
//var_dump("init");
}
public function onLoad(){
//var_dump("onLoad");
}
public function onUnLoad(){
//var_dump("onUnLoad");
}
public function onPreRender(){
//var_dump("preRender");
}
public function onRender(){
//var_dump("render");
}
public function close(){
//IOTrafficController::appLog($this->pageType);
}
public final function dispose(){
//var_dump("dispose");
Conexion::closeAll();
}
}
?><file_sep><?php
class GET_section extends DA_Abs{
public static function getSite(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
if(self::$onlyActives)//filtra por activos, y por secciones que tengan el detalle del idioma discriminado
{
$sql="SELECT sections.idSection as id,sections.sectionOrder
FROM sections,section_details
WHERE sections.level=0
AND sections.idSection = section_details.sections_idSection
AND section_details.active = 1
AND section_details.idiomas_idIdioma = " . self::$idIdioma ."
order by sections.sectionOrder";
}
else//todas las secciones de nivel 0
{
$sql="SELECT idSection as id,sectionOrder
FROM sections
WHERE level=0
order by sectionOrder";
}
//echo $sql;die;
$site=$rs->getObjects($sql);
$rsite = array();
foreach ($site as $valor)$rsite[] = self::getSection($valor->id);
//die;
return $rsite;
}
public static function getOrders($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT sections.idSection as id,
sections.sectionOrder,
section_details.name
FROM section_details,sections";
$section = self::getSection($id);
if($section->level == 0)
{
$sql.=" WHERE section_details.sections_idSection = sections.idSection
AND sections.level = 0 ";
}
else
{
$parent = self::getParent($id)->id;
$sql.=" WHERE sections_idSection IN (SELECT subSection FROM section_relations WHERE parent = $parent)
AND section_details.sections_idSection = sections.idSection ";
}
$sql.="AND idiomas_idIdioma=". self::$idIdioma .
" order by sections.sectionOrder ASC, sections.idSection ASC";
//echo $sql;die;
$sections=$rs->getObjects($sql);
return $sections;
}
public static function getSubSections($id,$furl){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
//$furl = self::getFurl($id);
if(self::$onlyActives)//filtra por activos, y por secciones que tengan el detalle del idioma discriminado
{
$sql="SELECT sections.idSection as id,
sections.sectionOrder,
sections.level,
sections.referenceName,
sections.contentTypes_idType as type,
sections.showContent
FROM section_details,sections
WHERE sections.idSection IN (SELECT subSection FROM section_relations WHERE parent = $id)
AND section_details.sections_idSection = sections.idSection
AND idiomas_idIdioma=". self::$idIdioma ."
AND section_details.active=1";
$sql.=" order by sections.sectionOrder ASC, sections.idSection DESC";
}
else
{
$sql="SELECT idSection as id,
sectionOrder,
level,
referenceName,
contentTypes_idType as type,
showContent
FROM sections
WHERE idSection IN (SELECT subSection FROM section_relations WHERE parent = $id)";
$sql.=" order by sectionOrder ASC, sections.idSection DESC";
}
try{
$sections=$rs->getObjects($sql);
//var_dump($sections);
foreach ($sections as $section)$section->details = self::getDetails($section->id);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error getSubSections() ($c):" . $e->getMessage(), 200);
}
addFurl($sections,$furl);
return $sections;
}
public static function getParent($idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql = "SELECT parent FROM section_relations WHERE subSection = '$idSection'";
try{
$parent = $rs->getObject($sql);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error getParent() ($c):" . $e->getMessage(), 200);
}
//var_dump($parent);die;
if($parent)
{
try{
$parent = $rs->getObject($sql);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error getParent() ($c):" . $e->getMessage(), 200);
}
return self::getSection($parent->parent);
}
return null;
}
public static function getHashSection($idSection){
//esta funcion es igual a getSection, pero sin buscar las subsecciones
//como las subsecciones no tienen servicio propio, dejo de usar esta funcion y le paso el parametro furl desde otra funcion
// pero ahora la uso para get content
//entonces la modifico y solo devuelve lo minimo para furl y path
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT idSection as id,
level,
referenceName
FROM sections
WHERE sections.idSection = $idSection";
try{
$section = $rs->getObject($sql);
$section->details = self::getDetails($section->id);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error getFurl() ($c):" . $e->getMessage(), 200);
}
//echo $sql;die;
if($section->level != 0)
{
$parent = self::getParent($section->id);
addFurl($section,$parent->furl);
}
else {
addFurl($section);
}
return $section;
}
public static function getSection($idSection){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT idSection as id,
sectionOrder,
level,
referenceName,
contentTypes_idType as type,
showContent
FROM sections
WHERE sections.idSection = $idSection";
try{
$section = $rs->getObject($sql);
$section->details = self::getDetails($idSection);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error getSection() ($c):" . $e->getMessage(), 200);
}
//echo $sql;die;
if($section->level != 0)
{
$parent = self::getParent($section->id);
addFurl($section,$parent->furl);
}
else {
addFurl($section);
$section->sections=self::getSubSections($section->id,$section->furl);
}
if($section->showContent == 1)$section->contents = GET_content::getContentsBySection($idSection);
return $section;
}
public static function getDetails($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sqlDetails="SELECT
name,
toMainName,
toMainMenu,
active
FROM section_details
WHERE sections_idSection = $id
AND idiomas_idIdioma=". self::$idIdioma ;
return $rs->getObject($sqlDetails);
}
public static function getIdiomaByStr($str){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas WHERE idioma='$str'";
return $rs->getObject($sql);
}
public static function getIdioma(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas WHERE idIdioma= " . self::$idIdioma ;
return $rs->getObject($sql);
}
public static function getIdiomas(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM idiomas";
return $rs->getObjects($sql);
}
}
?><file_sep>app.view.Form = app.Section.extend({
el:'div#form',
template:null,
initialize: function() {
//console.log('Iniciando..')
var ui = $(this.el);
this.model = new app.data.models.FormModel();
this.model.onRegister();
this.listenTo(this.model, "change:evento", this.renderEvento);
this.listenTo(eventos, "change:owners", this.renderOwners);
this.listenTo(eventos, "change:sources", this.renderSources);
this.template = $('body').find('div.evento-template').clone();
this.template.show();
this.template.removeClass('evento-template');
this.template.find('.btn-form').remove();
this.template.addClass('evento');
var self = this;
ui.find("form").validate(Validation.validate(ui.find("form"),function(form){
//log(form.addBase);return;
if(form.addBase == null || form.addBase == undefined) form.addBase = 0;
self.model.send(form);
return false;
}));
$("[name='addBase']").bootstrapSwitch();
$("[name='guardarEmail']").bootstrapSwitch();
$("[name='addBase']").on('switchChange.bootstrapSwitch', function(event, state) {
$(this).val((state) ? "1" : "0");
if(state == false)
{
ui.find("form").find('.locked').attr('disabled','disabled');
}
else
{
ui.find("form").find('.locked').prop('disabled','');
}
});
$("[name='guardarEmail']").on('switchChange.bootstrapSwitch', function(event, state) {
$(this).val((state) ? "1" : "0");
if(state == false)
{
ui.find("form").find('.locked').attr('disabled','disabled');
}
else
{
ui.find("form").find('.locked').prop('disabled','');
}
});
},
renderOwners : function(){
var owners = eventos.get('owners');
var selec = $(this.el).find('select#owner');
var option;
$(owners).each(function(){
option = $('<option>'+this.nombre+'</option>');
option.attr('value',this.idOwner);
selec.append(option);
});
},
renderSources: function(){
var sources = eventos.get('sources');
var selec = $(this.el).find('select#fuente');
var option;
$(sources).each(function(){
option = $('<option>'+this.nombre+'</option>');
option.attr('value',this.idFuente);
selec.append(option);
});
},
renderEvento : function(){
var evt = this.model.get('evento');
var ui = $(this.el);
ui.find('div.evento').remove();
var self = this;
var evento = self.template.clone();
ui.prepend(evento);
evento.find('.titulo').html(evt.titulo);
evento.find('.subtitulo').html(evt.subtitulo);
evento.find('.fecha').html(evt.fechaStr);
evento.find('.lugar').html(evt.lugar);
evento.find('.disponibilidad').html(evt.lugares);
evento.find('.n-reservas').html(evt.reservas);
evento.find('.confirmados').html(evt.confirmados);
evento.find('.anotados').html(evt.anotados);
evento.find('.asistencia').html(evt.asistencia);
if(!self.user){
//evento.find('.btn-form').hide();
evento.find('.btn-links').hide();
}
evento.find('.btn-volver').click(function(){
window.history.back();
});
evento.find('.btn-lista').click(function(){
Url.setHash('#/lista/'+evt.idEvento);
});
evento.find('.btn-form').click(function(){
Url.setHash('#/form/'+evt.idEvento);
});
evento.find('.btn-ver').click(function(){
Url.setHash('#/ver-asistencia/'+evt.idEvento);
});
evento.find('.btn-editar').click(function(){
Url.setHash('#/editar-asistencia/'+evt.idEvento);
});
ui.find('input#tipo').val(evt.nombretipo);
ui.find('input#idEvento').val(evt.idEvento);
}
});
<file_sep><?php
//error_reporting(E_ALL);
//ini_set("display_errors", 1);
//ini_set("display_startup_errors", 1);
include "../../php/HX_Fmwk/load.php";
class Index extends AppPageController {
public function onLoad() {
ob_clean();
$idEvento = $_GET['idEvento'];
if(!is_null($idEvento)){
$evento = GET_eventos::getEvento($idEvento);
$this->renderEvento($evento);
}
else{
$this->renderNewEvento();
}
}
private function renderEvento($evento){
//var_dump($evento);
//echo "EDIT Evento";
include('includes/form.php');
}
private function renderNewEvento(){
//echo "new Evento";
include('includes/form.php');
}
public function onUnLoad() {}
}
Controller::load("Index");
/*ALTER TABLE `eventos` ADD `fotoHome` VARCHAR( 1000 ) NOT NULL AFTER `foto`*/
/*ALTER TABLE `eventos` ADD `mostrarHome` INT( 1 ) NOT NULL AFTER `activo`*/
/*ALTER TABLE `eventos` ADD `idYoutube` VARCHAR( 250 ) NOT NULL AFTER `fotoHome`*/
/*ALTER TABLE `eventos` ADD `horario` VARCHAR( 250 ) NOT NULL AFTER `fechaStr`*/
/*ALTER TABLE `eventos` ADD `maxHorario` VARCHAR( 250 ) NOT NULL AFTER `horario`*/
/*ALTER TABLE `eventos` ADD `link` VARCHAR( 1000 ) NOT NULL AFTER `idYoutube`*/
/*GET_EVENTOS)*/
?><file_sep><?php
class Object {
protected $attributes = array();
public function __construct(){}
public function __get($key){
return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : null;
}
public function __set($key, $value){
$this->attributes[$key] = $value;
}
public function getClass(){
return get_class($this);
}
}
?><file_sep><?php
include "../../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
//PARAMS:------->
//idSection == 0
//active
//name
//toMainMenu
//toMainName
$this->formatReferenceNameSection();
parent::addToSend(SET_section::createSection($this->data),'section');
//parent::addToSend(GET_section::getSection($this->data->idSection),'section');
parent::addToSend(GET_section::getSite(),'site');
GET_site::saveMenu();
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
function smarty_modifier_toutf8($string)
{
return utf8_encode($string);
}
?><file_sep><?php
//error_reporting(E_ALL);
//ini_set("display_errors", 1);
//ini_set("display_startup_errors", 1);
include "../../php/HX_Fmwk/load.php";
class Index extends AppPageController {
public function onLoad() {
ob_clean();
$idEvento = $_GET['idEvento'];
if(!is_null($idEvento)){
$evento = GET_eventos::getEvento($idEvento);
//var_dump($evento);
echo "cargar Fotos";
include('includes/upload.php');
}
else{
$this->errorLoadEvento();
}
}
private function errorLoadEvento(){
echo "El Evento no fue creado correctamente";
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep>app.Section = app.View.extend({
onRegister: function(){
$(this.el).hide();
},
show : function() {
$(this.el).show();
},
hide : function() {
$(this.el).hide();
}
});<file_sep><?php
include "../../php/HX_Fmwk/load.php";
class Index extends AppSerializableController {
public function onLoad() {
if($this->data->active)GET_section::$onlyActives = true;
//$_SESSION['idioma']
parent::addToSend(GET_section::getIdioma(), "idioma");
parent::addToSend(GET_section::getSite(), "site");
parent::send();
}
public function onUnLoad() {}
}
Controller::load("Index");
?><file_sep><?php
$desarrollo=true;
$files = array();
$files[]="../sources/assets/funciones.js";
$files[]="../sources/assets/libs/underscore.js";
$files[]="../sources/assets/libs/jquery-1.10.2.min.js";
$files[]="../sources/assets/libs/backbone.js";
addFiles("../sources/assets/libs/plugins");
$files[]="../sources/assets/Application.js";
addFiles("../sources/assets/core");
addFiles("../sources/assets/data");
//addFiles("./mvc/model");
$files[]="../sources/mvc/model/appModel.js";
$files[]="../sources/mvc/model/hashModel.js";
$files[]="../sources/mvc/model/modalModel.js";
$files[]="../sources/mvc/model/SectionManagerModel.js";
$files[]="../sources/mvc/model/sectionModel.js";
//addFiles("./mvc/view");
$files[]="../sources/mvc/view/app.View.js";
$files[]="../sources/mvc/view/app.Section.js";
$files[]="../sources/mvc/view/app.viewController.js";
addFiles("../sources/app/view");
addFiles("../sources/app/model");
addFiles("../sources/app/utils");
addFiles("../sources/app");
//addFiles("./sources/HX");
function addFiles($d){
global $files;
foreach (glob("$d/*.js") as $f){
$files[]="$f";
}
}
if($desarrollo){
header ('Content-type: text/javascript; charset=UTF-8');
header("Cache-Control", "no-cache,no-store,must-revalidate");
header("Pragma", "no-cache");
header("Expires", 0);
ob_start('ob_gzhandler');
foreach($files as $file) {
if($desarrollo)
echo "\n// start -> $file **************************************************\n";
include($file);
if($desarrollo)
echo "\n// end -> $file **************************************************\n";
}
ob_end_flush();
die;
}
require_once 'jsmin.php';
$modified = 0;
foreach($files as $file) {
$age = filemtime($file);
if($age > $modified) {
$modified = $age;
}
}
$offset = 60 * 60 * 24 * 7; // Cache for 1 weeks
header ('Expires: ' . gmdate ("D, d M Y H:i:s", time() + $offset) . ' GMT');
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $modified) {
header("HTTP/1.0 304 Not Modified");
header ('Cache-Control:');
} else {
header ('Cache-Control: max-age=' . $offset);
header ('Content-type: text/javascript; charset=UTF-8');
header ('Pragma:');
header ("Last-Modified: ".gmdate("D, d M Y H:i:s", $modified )." GMT");
function compress($buffer) {
return JSMin::minify($buffer);
}
ob_start('ob_gzhandler');
foreach($files as $file) {
if(strpos(basename($file),'.min.')===false) { //compress files that aren't minified
ob_start("compress");
include($file);
ob_end_flush();
} else {
include($file);
}
}
ob_end_flush();
}
?>
<file_sep><?php
abstract class TemplatePageController extends PageController{
private $template;
private $templateHTML=null;
/*
* var int
* segundos en los que expira la pagina
*/
protected $expires=0;
public function __construct(){
$this->pageType=PageType::template;
$this->template=new Template(HX_Fmwk::getApplication());
parent::__construct();
}
public function assign($tpl_var,$value){
$this->template->assign($tpl_var,$value);
}
public function assignByRef($tpl_var,$value){
$this->template->assign_by_ref($tpl_var,$value);
}
public function render($templateHTML){
$this->templateHTML=$templateHTML;
}
public function onPreRender(){
parent::onPreRender();
if($this->expires>0){
header('Pragma: public');
header('Cache-Control: maxage='.$this->expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$this->expires) . ' GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
}else{
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
}
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
}
public function onRender() {
if(is_null($this->templateHTML)) return;
$this->assign("__IDIOMA__", CultureInfo::getIdioma()->getCodigo());
$this->template->render($this->templateHTML);
parent::onRender();
}
public function renderXML($templateXML){
$this->render=false;
$this->template->renderXML($templateXML);
//parent::onRender();
}
public function renderPDF($templatePDF, $outputName="file.pdf"){
$this->render=false;
$html=$this->getContent($templatePDF);
$pdf=new Pdf($this->template->compile_dir);
$pdf->setHtml($html);
$pdf->render();
ob_end_clean();
$pdf->stream($outputName);
}
public function getContent($template) {
return $this->template->getContent($template);
}
public function saveAs($template, $path) {
return $this->template->saveAs($template, $path);
}
public function setTemplateDir($tplDir){
$this->template->template_dir=$tplDir;
}
public function setCompileDir($cpDir){
$this->template->compile_dir=$cpDir;
}
public function setCompileId($cpId){
$this->template->compile_id=$cpId;
}
public function setMasterTemplate($template){
$this->template->setMasterTemplate($template);
}
public function translate($tpl_var,$value){
$this->assign($tpl_var, CultureInfo::translate($value));
}
}
?><file_sep><?php
/**
* Date: 23/10/2008 19:56:32
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2011, <NAME>
* @package hx_fmwk
*
*/
$__microtime__=microtime(true);
session_start();
ob_start();
define("rootPath",str_replace("\\", "/",dirname(dirname(__FILE__))."/"));
define("fmwkPath",rootPath."HX_Fmwk/");
define("appPath",rootPath."Application/");
define("libsPath",fmwkPath."libs/");
require_once fmwkPath."Functions/functions.php";
//manejador de excepciones
set_exception_handler('gestorExcepciones');
loadFrameworks();
?><file_sep><?php
abstract class ARepoApplication extends AFWRepositorio{
}
?><file_sep><?php
/**
* Date: 14/08/2013 15:28:01
* @version 1.0
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2013, <NAME>
* @filename AppRestrictedSerializableController.class.php
* @package
**/
/**
*/
abstract class AppRestrictedSerializableController extends AppSerializableController {
public function __construct() {
parent::__construct();
if (is_null($this->usuario)) {
throw new AppException("El usuario no esta registrado!", 102);
}
}
}
?><file_sep><?php
class SET_consulta extends DA_Abs{
public static function getConsultas(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * FROM formulario_contacto ORDER BY id DESC LIMIT 30";
//echo $sql;die;
$camp = $rs->getObjects($sql);
return $camp;
}
public static function getConsultasAstro(){
$db=Conexion::getConexion("centroastrologicoaztlan");
$rs=$db->getRecordset();
$sql="SELECT * FROM formulario_contacto ORDER BY id DESC LIMIT 30";
//echo $sql;die;
$camp = $rs->getObjects($sql);
return $camp;
}
public static function setConsulta($data){
$nombre = escape($data->nombre);
$tel = escape($data->telefono);
$email = escape($data->email);
$consulta = escape($data->consulta);
$dni = escape($data->dni);
$facebook = escape($data->facebook);
$newsletter = $data->newsletter;
$fecha = new Fecha();
$sqlAbs = "INSERT INTO formulario_contacto (nombre,dni,telefono,email,facebook,consulta,newsletter,fecha)
VALUES (
'$nombre','$dni','$tel','$email','$facebook','$consulta',$newsletter,'$fecha')";
try
{
$db = Conexion::getConexion();
//echo $sqlAbs;die;
$db->execute($sqlAbs);
$nid = self::lastId($db);
return $nid;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error inesperado ($c):" . $e->getMessage(), 200);
}
}
}
?><file_sep>(function(w) {
function Application() {
this.baseUrl = '';
this.log = true;
this.development = true;
this.encode64 = true;
}
w.app = {};
w.app.data = {};
w.app.data.models = {};
w.app.application= new Application();
w.app.view = {};
w.app.view.sections = {};
app.models = {};
})(window);<file_sep>app.view.Lista = app.Section.extend({
el:'div#lista',
template:null,
btns:null,
initialize: function() {
var ui = $(this.el);
this.model = new app.data.models.ListaModel();
this.model.onRegister();
this.listenTo(this.model, "change:evento", this.renderEvento);
this.listenTo(this.model, "change:reservas", this.renderReservas);
this.template = $('body').find('div.evento-template').clone();
this.template.show();
this.template.removeClass('evento-template');
this.template.find('.btn-lista').parent().remove();
this.template.find('.btn-links').parent().remove();
this.template.addClass('evento');
this.btns = $('body').find('div.template-btn').clone();
this.btns.show();
this.btns.removeClass('template-btn');
this.btns.remove();
},
renderReservas : function(){
var reservas = this.model.get('reservas');
reservas = _.sortBy(reservas, function(i) {return i.usuario.apellido.substring(0,1).toLowerCase()})
var ui = $(this.el);
var body = ui.find('tbody');
body.empty();
var tr,td,n,a;
n=0;
var self = this;
$(reservas).each(function(){
//log(this.confirmado);
if(this.confirmado != 2){ // si no esta borrado
n++;
//log(this);
tr = $('<tr data-estado='+this.confirmado+'>');
if(this.usuario.admitido == 0)tr.addClass('no-admitido');
body.append(tr);
td = $('<td>');
tr.append(td);
td.text(n);
td = $('<td>');
tr.append(td);
if(this.tipoUsuario == 1){
a = $('<a href="#/usuario/'+this.usuario.idUsuario+'">');
td.append(a);
a.text(this.usuario.apellido + " " + this.usuario.nombre);
}else{
td.text(this.usuario.apellido + " " + this.usuario.nombre);
}
// td = $('<td>');
// tr.append(td);
// td.text(this.usuario.dni);
td = $('<td>');
tr.append(td);
td.text(this.usuario.email);
// td = $('<td>');
// tr.append(td);
// td.text(this.usuario.telefono);
td = $('<td class="estado">');
tr.append(td);
//td.text(self.getEstado(this.confirmado));
td = $('<td>');
tr.append(td);
td.text(this.cantLugares);
td = $('<td>');
tr.append(td);
td.text(this.owner);
td = $('<td>');
tr.append(td);
if(this.source != 0) td.text(eventos.getNameSource(this.source));
else td.text(this.usuario.source);
td = $('<td class="acciones">');
tr.append(td);
td.html(self.btns.clone());
var buttons = new app.view.Acciones({el:tr,attributes:this});
//buttons.attr('data-id-reserva',this.idReserva);
}
});
},
renderEvento : function(){
var evt = this.model.get('evento');
var ui = $(this.el);
ui.find('div.evento').remove();
var self = this;
var evento = self.template.clone();
ui.prepend(evento);
evento.find('.titulo').html(evt.titulo);
evento.find('.subtitulo').html(evt.subtitulo);
evento.find('.fecha').html(evt.fechaStr);
evento.find('.lugar').html(evt.lugar);
evento.find('.disponibilidad').html(evt.lugares);
evento.find('.n-reservas').html(evt.reservas);
evento.find('.confirmados').html(evt.confirmados);
evento.find('.anotados').html(evt.anotados);
evento.find('.asistencia').html(evt.asistencia);
if(!self.user){
//evento.find('.btn-form').hide();
evento.find('.btn-links').hide();
}
evento.find('.btn-volver').click(function(){
window.history.back();
});
evento.find('.btn-lista').click(function(){
Url.setHash('#/lista/'+evt.idEvento);
});
evento.find('.btn-form').click(function(){
Url.setHash('#/form/'+evt.idEvento);
});
evento.find('.btn-ver').click(function(){
Url.setHash('#/ver-asistencia/'+evt.idEvento);
});
evento.find('.btn-editar').click(function(){
Url.setHash('#/editar-asistencia/'+evt.idEvento);
});
},
hide : function(){
$(this.el).hide();
this.model.clean();
}
});
<file_sep><?php
abstract class AppSerializableController extends PageSerializableController {
/**
*
* @var int
*/
var $idioma = 1;
public function __construct() {
parent::__construct();
/*
$this->uid = FbContext::getUid();
$this->usuario = DA::getUsuarioPorUid($this->uid);
*/
if(!is_null($_SESSION['idioma']))$this->idioma = $_SESSION['idioma'];
DA_Abs::$idIdioma = $this->idioma;
//if(is_null($_SESSION['idioma']))$idIdioma
}
protected function trace($obj,$muere,$clean)
{
if(!is_null($clean) && $clean== false) 'no clear';
else ob_clean();
var_dump($obj);
if(!is_null($muere) && $muere == false) 'no die';
else die;
}
protected function formatReferenceNameContent(){
if(!is_null($this->data->details->title))$this->data->rname = toFurl($this->data->details->title);
}
protected function formatReferenceNameSection(){
if(!is_null($this->data->details->name))$this->data->rname = toFurl($this->data->details->name);
}
}
?><file_sep><?php
class GET_eventos extends DA_Abs{
public static function getOwners(){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * from owners WHERE activo = 1 ORDER BY nombre";
return $rs->getObjects($sql);
}
public static function getSources(){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * from fuentes";
return $rs->getObjects($sql);
}
public static function setUsuario($id,$estado,$txt){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="UPDATE usuarios
SET admitido = '$estado', admitido_txt = '$txt' WHERE idUsuario = $id";
//echo $sql;die;
try
{
echo $sql;
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
//return $estado;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setEvento(): Error setUsuarioUPDATEsuario ($c):" . $e->getMessage(), 200);
}
return $estado;
}
public static function getUsuario($id){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * FROM usuarios
WHERE idUsuario = $id";
//echo $sql;die;
$usuario = $rs->getObject($sql);
$sql="SELECT * FROM reservas
JOIN eventos ON reservas.eventos_idEvento = eventos.idEvento
WHERE usuarios_idUsuario = $id AND tipoUsuario = 1 ";
//echo $sql;die;
$usuario->reservas = $rs->getObjects($sql);
return $usuario;
}
public static function getHomeEventosAstro(){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT eventos.*,tipos_evento.tipo FROM eventos,tipos_evento
WHERE eventos.mostrarHome = 1
AND eventos.mostrarAstro = 1
AND eventos.activo = 1
AND eventos.tipoEvento_idTipo = tipos_evento.idTipo
AND tipos_evento.tipo = 1
AND eventos.date >= CURDATE()
ORDER BY eventos.date ASC
";
//echo $sql;die;
$eventos = $rs->getObjects($sql);
foreach ($eventos as $evento){
$id = $evento->idEvento;
$sql="SELECT idCamp FROM campaings
WHERE evento_idEvento = $id";
$evento->idCamp = $rs->getObject($sql)->idCamp;
// $evento->idCamp = $evento->idCamp->idCamp;
}
return $eventos;
}
public static function getHomeEventosPsico(){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT eventos.*,tipos_evento.tipo FROM eventos,tipos_evento
WHERE eventos.mostrarHome = 1
AND eventos.mostrarPsico = 1
AND eventos.activo = 1
AND eventos.tipoEvento_idTipo = tipos_evento.idTipo
AND tipos_evento.tipo = 1
AND eventos.date >= CURDATE()
ORDER BY eventos.date ASC
";
//echo $sql;die;
$eventos = $rs->getObjects($sql);
foreach ($eventos as $evento){
$id = $evento->idEvento;
$sql="SELECT idCamp FROM campaings
WHERE evento_idEvento = $id";
$evento->idCamp = $rs->getObject($sql)->idCamp;
// $evento->idCamp = $evento->idCamp->idCamp;
}
return $eventos;
}
public static function getEventos(){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT eventos.*,tipos_evento.tipo,tipos_evento.nombre as nombretipo ,lugares.* FROM eventos,tipos_evento,lugares
WHERE eventos.tipoEvento_idTipo = tipos_evento.idTipo
AND eventos.activo = 1
AND tipos_evento.tipo = 1
AND lugares.idLugar = eventos.lugar_idLugar
ORDER BY eventos.date DESC
LIMIT 10
";
//echo $sql;die;
$eventos = $rs->getObjects($sql);
foreach ($eventos as $evento){
$id = $evento->idEvento;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado !=2";
$evento->reservas = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado =1";
$evento->confirmados = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(anotado),0) as anotados FROM reservas WHERE eventos_idEvento=$id AND anotado =1";
$evento->anotados = $rs->getObject($sql)->anotados;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as asistencia FROM reservas WHERE eventos_idEvento=$id AND asistencia =1";
$evento->asistencia = $rs->getObject($sql)->asistencia;
}
return $eventos;
}
public static function getEventosByFechaAndTipo($fecha, $tipo){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT eventos.* FROM eventos
WHERE eventos.tipoEvento_idTipo = $tipo
AND eventos.activo = 1
AND eventos.date = '$fecha'
LIMIT 10
";
//echo $sql;die;
$eventos = $rs->getObjects($sql);
foreach ($eventos as $evento){
$id = $evento->idEvento;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado !=2";
$evento->reservas = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado =1";
$evento->confirmados = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(anotado),0) as anotados FROM reservas WHERE eventos_idEvento=$id AND anotado =1";
$evento->anotados = $rs->getObject($sql)->anotados;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as asistencia FROM reservas WHERE eventos_idEvento=$id AND asistencia =1";
$evento->asistencia = $rs->getObject($sql)->asistencia;
}
return $eventos;
}
public static function getLatestEventos($search=false){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT eventos.*,tipos_evento.tipo,tipos_evento.nombre as nombretipo ,lugares.* FROM eventos,tipos_evento,lugares
WHERE eventos.tipoEvento_idTipo = tipos_evento.idTipo
AND lugares.idLugar = eventos.lugar_idLugar
AND tipos_evento.tipo = 1";
if($search != false){
$sql.=" AND titulo LIKE '%$search%'";
}
$sql.=" ORDER BY eventos.date DESC
LIMIT 100";
//echo $sql;die;
$eventos = $rs->getObjects($sql);
foreach ($eventos as $evento){
$id = $evento->idEvento;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado !=2";
$evento->reservas = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado =1";
$evento->confirmados = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(anotado),0) as anotados FROM reservas WHERE eventos_idEvento=$id AND anotado =1";
$evento->anotados = $rs->getObject($sql)->anotados;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as asistencia FROM reservas WHERE eventos_idEvento=$id AND asistencia =1";
$evento->asistencia = $rs->getObject($sql)->asistencia;
}
return $eventos;
}
public static function getEvento($id){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT eventos.*,tipos_evento.tipo,tipos_evento.nombre as nombretipo ,lugares.lugar FROM eventos,tipos_evento,lugares
WHERE eventos.idEvento = $id
AND eventos.tipoEvento_idTipo = tipos_evento.idTipo
AND tipos_evento.tipo = 1
AND lugares.idLugar = eventos.lugar_idLugar
";
//echo $sql;die;
$evento = $rs->getObject($sql);
//var_dump($evento);die;
$id = $evento->idEvento;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado !=2";
$evento->reservas = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as reservas FROM reservas WHERE eventos_idEvento=$id AND confirmado =1";
$evento->confirmados = $rs->getObject($sql)->reservas;
$sql = "SELECT IFNULL(SUM(anotado),0) as anotados FROM reservas WHERE eventos_idEvento=$id AND anotado =1";
$evento->anotados = $rs->getObject($sql)->anotados;
$sql = "SELECT IFNULL(SUM(cantLugares),0) as asistencia FROM reservas WHERE eventos_idEvento=$id AND asistencia =1";
$evento->asistencia = $rs->getObject($sql)->asistencia;
$sql = "SELECT * FROM campaings WHERE evento_idEvento=$id AND owners_idOwner =3";
$evento->campescuela = $rs->getObject($sql);
return $evento;
}
public static function getReservas($id){
$db=Conexion::getConexion('usuarios');
$rs=$db->getRecordset();
$sql="SELECT * FROM reservas WHERE eventos_idEvento = $id "; //no borrado AND confirmado !=2
//echo $sql;die;
$reservas = $rs->getObjects($sql);
foreach ($reservas as $reserva){
$id = $reserva->usuarios_idUsuario;
$c = $reserva->camp_idCamp;
$tipoUsuario = $reserva->tipoUsuario;
if($tipoUsuario==1)$sql = "SELECT * FROM usuarios WHERE idUsuario = $id";
else $sql = "SELECT * FROM falsos_usuarios WHERE idUsuario = $id";
$reserva->usuario = $rs->getObject($sql);
$sql="SELECT owners.nombre FROM campaings,owners
WHERE idCamp = $c
AND campaings.owners_idOwner = owners.idOwner
";
$reserva->owner = $rs->getObject($sql)->nombre;
if(is_null($reserva->owner)){
$c = $reserva->owners_idOwner;
$sql="SELECT nombre FROM owners
WHERE idOwner = $c";
$reserva->owner = $rs->getObject($sql)->nombre;
}
}
return $reservas;
}
public static function setEvento($params){
$tipo = $params['tipoEvento'];
$date = $params['fecha'];
$titulo = htmlentities($params['titulo']);
$subtitulo = htmlentities($params['subtitulo']);
$fechaStr = htmlentities($params['fechaStr']);
$horario = $params['horario'];
$maxHorario = $params['maxHorario'];
$idYoutube = $params['idYoutube'];
$link = $params['link'];
$texto = htmlspecialchars ($params['texto']); //strip_tags(htmlspecialchars_decode
$activo = ( $params['activo'] == 'on' ? 1:0);
$mostrarHome = ( $params['mostrarHome'] == 'on' ? 1:0);
$mostrarAstro= ( $params['mostrarAstro'] == 'on' ? 1:0);
$mostrarPsico= ( $params['mostrarPsico'] == 'on' ? 1:0);
$lugar = $params['lugar'];
$disponibilidad = $params['disponibilidad'];
if(isset($params['idEvento'])){
$sql = "UPDATE eventos SET
tipoEvento_idTipo='$tipo',
fecha=now(),
date='$date',
titulo='$titulo',
subtitulo='$subtitulo',
fechaStr='$fechaStr',
horario='$horario',
maxHorario='$maxHorario',
idYoutube='$idYoutube',
link='$link',
texto='$texto',
lugares='$disponibilidad',
lugar_idLugar='$lugar',
activo='$activo',
mostrarHome='$mostrarHome',
mostrarAstro='$mostrarAstro',
mostrarPsico='$mostrarPsico'
WHERE idEvento = ".$params['idEvento'];
}
else{
$sql = "INSERT INTO eventos (tipoEvento_idTipo,fecha,date,titulo,subtitulo,fechaStr,horario,maxHorario,idYoutube,link,texto,lugares,lugar_idLugar,activo,mostrarHome,mostrarAstro,mostrarPsico)
VALUES ('$tipo',now(),'$date','$titulo','$subtitulo','$fechaStr','$horario','$maxHorario','$idYoutube','$link','$texto','$disponibilidad','$lugar','$activo','$mostrarHome','$mostrarAstro','$mostrarPsico');";
}
try
{
echo $sql;
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
//return $estado;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setEvento(): Error setEvento ($c):" . $e->getMessage(), 200);
}
if(isset($params['idEvento'])){
return $params['idEvento'];
}
return self::lastId($db);;
}
public static function setCamp($idEvento){
$sql = "INSERT INTO campaings (owners_idOwner,email,evento_idEvento) VALUES (3,'<EMAIL>',$idEvento)";
try
{
echo $sql;
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
//return $estado;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setUsuario(): Error setCamp ($c):" . $e->getMessage(), 200);
}
}
public static function setPresentismo($params){
foreach ($params as $reserva){
$presentismo = $reserva->presentismo;
$id = $reserva->idReserva;
$pago = $reserva->pago;
$lugares = $reserva->lugares;
$anotado = $reserva->anotado;
$sql = "UPDATE reservas SET asistencia=$presentismo, pago=$pago, cantLugares=$lugares, anotado=$anotado WHERE idReserva=$id";
try
{
//echo $sql;die;
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
//return $estado;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setUsuario(): Error setPresentismo ($c):" . $e->getMessage(), 200);
}
}
return true;
}
public static function setReservaEstado($params){
$estado = $params->estado;
$idReserva = $params->idReserva;
$sql = "UPDATE reservas SET confirmado=$estado WHERE idReserva=$idReserva";
try
{
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
return $estado;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setUsuario(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
public static function setReserva($params){
$nombre = escape($params->nombre);
$apellido = escape($params->apellido);
$dni = (property_exists($params, 'dni')) ? escape($params->dni) : '';
$email = escape($params->email);
$tel = escape($params->telefono);
$tipo = escape($params->tipo);
$owner = escape($params->owner);
$source = escape($params->fuente);
$addBase = escape($params->addBase);
//var_dump($addBase);die;
if(is_null($addBase))$addBase = 1;//para todos los formularios viejos, que reservan directo a la base de mailing
$fecha = new Fecha();
if($addBase == 1){
$sql = "INSERT INTO usuarios (nombre,apellido,dni,email,telefono,tipo,source,owner,creado)
VALUES (
'$nombre','$apellido','$dni','$email','$tel','$tipo','formulario interno','$owner','$fecha')";
try
{
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
}
catch (Exception $e) {
$c = $e->getCode();
if($c != 1062)throw new AppException("setUsuario(): Error inesperado ($c):" . $e->getMessage(), 200);
else{
$sql = "UPDATE usuarios SET
nombre='$nombre',
apellido='$apellido',
dni='$dni',
telefono='$tel'
WHERE email='$email'";
//echo $sql;die;
try{
$db->execute($sql);
}catch (Exception $e) {
throw new AppException("setUsuarioUPDATE(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
}
$usuario = GET_camp::getUsuario($email);
$idUsuario = $usuario->idUsuario;
}
else{ //addBAse = 0
$sql = "INSERT INTO falsos_usuarios (nombre,apellido,dni,email,telefono)
VALUES (
'$nombre','$apellido','$dni','$email','$tel')";
try
{
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setUsuario-noAddBase(): Error inesperado ($c):" . $e->getMessage(), 200);
}
$idUsuario = self::lastId($db);
}
$evento = escape($params->idEvento);
$lugares = escape($params->lugares);
$sql = "INSERT INTO reservas (eventos_idEvento,usuarios_idUsuario,cantLugares,fecha,camp_idCamp,source,owners_idOwner,confirmado,tipoUsuario)
VALUES (
$evento,$idUsuario,$lugares,now(),0,$source,$owner,0,$addBase)";
try
{
$db = Conexion::getConexion('usuarios');
$db->execute($sql);
return true;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("setReserva(): Error inesperado ($c):" . $e->getMessage(), 200);
}
}
}
?>
<file_sep>app.models.SectionModel = app.models.Model.extend({
defaults: {
route:'',
params:'',
query:''
},
onRegister: function(){
/*this.on('change:route',function(){this.resolveHash(this.get('route'))});
this.on('change:params',function(){
var params = this.get('params');
this.resolveParams(params);
});*/
this.on('change:query',function(){this.resolveQuery(this.get('query'))});
},
resolveHash : function(route) {
app.logger.log('app.models.SectionModel:resolveHash() ', route);
},
resolveParams : function(params) {
app.logger.log('app.models.SectionModel:resolveParams() ', params);
},
resolveQuery : function(query) {
app.logger.log('app.models.SectionModel:resolveQuery() ', query);
}
});<file_sep><?php
class GET_CustomContent extends DA_Abs{
public static function getCustomContentById($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT * from customcontent WHERE id = $id";
return $rs->getObject($sql);
}
public static function getJsonContentById($id){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT content from customcontent WHERE id = $id";
return json_decode($rs->getObject($sql)->content);
}
public static function setCustomContent($id,$json){
//var_dump($data);
$json = escape($json);
$sql = "UPDATE customcontent SET
content='$json'
WHERE id = $id";
try
{
$db = Conexion::getConexion();
$db->execute($sql);
return true;
}
catch (Exception $e) {
$c = $e->getCode();
throw new AppException("Error setCustomContent ($c):" . $e->getMessage(), 200);
}
}
}
?><file_sep><?php
class DA_popup extends DA_Abs{
public static function getAll(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT *
FROM popups
WHERE nombre != 'ULTIMA'";
// echo $sql;die;
$popups = $rs->getObjects($sql);
return $popups;
}
public static function showPopup(){
$db=Conexion::getConexion();
$rs=$db->getRecordset();
$sql="SELECT *
FROM popups
WHERE active = 1";
$popups = $rs->getObjects($sql);
if(count($popups) > 1){
//si hay varios activos, traigo el ultimo y seteo como visto
//ultimo visto
$sql="SELECT *
FROM popups
WHERE popupType IN (SELECT popupType FROM popups WHERE nombre = 'ULTIMA')";
$popup = $rs->getObject($sql);
$id = $popup->idPopup;
$sql="SELECT *
FROM popups
WHERE idPopup !=$id AND nombre != 'ULTIMA' AND active=1" ;
$popups = $rs->getObjects($sql);
//var_dump($popups);die;
foreach ($popups as $pop){
if($pop->idPopup == ($id+1))$popup=$pop;
else $popup = $popups[0];
}
//grabo como ultimo
$id = $popup->idPopup;
$sql="UPDATE popups SET popupType=$id WHERE nombre = 'ULTIMA'";
$db->execute($sql);
return $popup;
}
else return $popups[0];
}
public static function setPopups($data){
$db=Conexion::getConexion();
//$rs=$db->getRecordset();
foreach ($data as $popup){
$sql="UPDATE popups SET active=".$popup->active." ,delay=".$popup->delay." ,traker='".$popup->traker."' WHERE idPopup=".$popup->idPopup;
//echo $sql;die;
$db->execute($sql);
}
return true;
}
}
?><file_sep>(function(app) {
app.data.Request = {
unserialize : function(data) {
//return data;
//return JSON.parse(data);
return JSON.parse($.base64.decode(data));
},
serialize : function(params) {
params = params || [];
var r = [], p = {};
if (typeof params.length != 'undefined') {
for ( var x = 0; x < params.length; x++) {
eval('p.' + params[x].name + '=params[x].value');
}
} else {
p = params;
}
r.push({
name : 'data',
value : $.base64.encode(JSON.stringify(p))
});
/*r.push({
name : 'token',
value : FbContext.getToken()
});*/
return r;
},
post : function(params) {
$.ajax({
url : params.url,
type : 'POST',
dataType : 'json',
data : app.data.Request.serialize(params.data),
error : function() {
hx.throwError(AppError.dataTransfer);
},
success : function(data) {
if(app.application.encode64)d = app.data.Request.unserialize(data.data);
else d = data;
if (d.error == 0) {
params.success(d.data);
} else {
// el servicio devuelve un error
var e = {};
e.errorCode = d.errorCode;
e.errorMsg = d.errorMsg;
app.logger.log(e);
// hx.throwError(e);
}
}
});
},
upload : function(params) {
var formData = new FormData();
$(params.form.find(':file')).each(function() {
formData.append($(this).attr('name'), this.files[0]);
});
var p = [];
for ( var x = 0; x < params.form.serializeArray().length; x++) {
p.push(params.form.serializeArray()[x]);
}
var data = app.data.Request.serialize(p);
for ( var x = 0; x < data.length; x++) {
formData.append(data[x].name, data[x].value);
}
$.ajax({
url : params.url,
type : 'POST',
dataType : 'json',
cache : params.cache || false,
contentType : params.contentType || false,
processData : params.processData || false,
data : formData,
error : function() {
hx.throwError(AppError.dataTransfer);
},
progress : params.progress || function() {
},
xhr : function() {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', params.progress, false);
}
return myXhr;
},
success : function(data) {
d = app.data.Request.unserialize(data.data);
if (d.error == 0) {
params.success(d.data);
} else {
// el servicio devuelve un error
var e = {};
e.errorCode = d.errorCode;
e.errorMsg = d.errorMsg;
hx.throwError(e);
}
}
});
}
};
})(window.app);
|
86c73e35bbc277a6d4ceb80b0ffba6f6b4acbc89
|
[
"JavaScript",
"PHP"
] | 126
|
PHP
|
sergiomakaruk/aztlaneventos
|
1db671e3e9590f16dce0445a000f660654e70473
|
1a8a65da9e18a70a46deb36f491363c88ccc2966
|
refs/heads/master
|
<file_sep>Prework Calculator
<file_sep>using System;
namespace Prework_Calculator
{
class Program
{
static void Main(string[] args)
{
Add(3, 4);
Subtract(7, 4);
Multiply(2, 3);
Divide(15, 5);
}
// The below code takes in two parameters and returns their sum.
static int Add(int x, int y)
{
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}");
return sum;
}
// The below code takes in two parameters and subtracts the second from the first.
static int Subtract(int x, int y)
{
int sub = x - y;
Console.WriteLine($"{x} minus {y} equals {sub}");
return sub;
}
// The below code takes in two parameters and multiplies them.
static int Multiply(int x, int y)
{
int multi = x * y;
Console.WriteLine($"{x} times {y} equals {multi}");
return multi;
}
// The below code takes in two parameters and divides the first by the second.
static int Divide(int x, int y)
{
int div = x / y;
Console.WriteLine($"{x} divided by {y} equals {div}");
return div;
}
}
}
|
355d8275dbff56ff15f30bf9793b064d538f14fe
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
SEAsouthern/Prework-Calculator
|
cfa9d17463ee17d75ef0479b0ec5e9e383da115f
|
5e57ccd3f464b6457e740cd56de6932a2afad15b
|
refs/heads/master
|
<repo_name>HUANGCL-1/IIIProject_CampingWebSite<file_sep>/EEIT124Project/src/login/sumit/registration/MemberDAOImpl.java
package login.sumit.registration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MemberDAOImpl implements MemberDAO {
static Connection con;
static PreparedStatement pstmt;
@Override
public int insertMember(Member m) {
int status=1;
try {
con=MyCp.getCon();
pstmt=con.prepareStatement("insert into member values(?,?,?,?,?,?,?,?)");
pstmt.setString(1, m.getMobile());
pstmt.setString(2,m.getPassword());
pstmt.setString(3, m.getName());
pstmt.setString(4, m.getNickname());
pstmt.setString(5, m.getGender());
pstmt.setInt(6, m.getBirthday());
pstmt.setString(7, m.getEmail());
pstmt.setString(8, m.getAddress());
status=pstmt.executeUpdate();
con.close();
} catch (Exception e) {
// TODO: handle exception
}
return status;
}
@Override
public Member getMember(String mobile,String password) {
Member m=new Member();
try {
con=MyCp.getCon();
pstmt=con.prepareStatement("select* from member where mobile=? and password=?");
pstmt.setString(1, mobile);
pstmt.setString(2, password);
ResultSet rs=pstmt.executeQuery();
while(rs.next())
m.setMobile(rs.getString(1));
m.setPassword(rs.getString(2));
m.setName(rs.getString(3));
m.setNickname(rs.getString(4));
m.setGender(rs.getString(5));
m.setBirthday(rs.getInt(6));
m.setEmail(rs.getString(7));
m.setAddress(rs.getString(8));
} catch (Exception e) {
// TODO: handle exception
}
return m;
}
}
<file_sep>/EEIT124Project/src/login/sumit/registration/LoginRegister.java
package login.sumit.registration;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginRegister")
public class LoginRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginRegister() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); //setup response character encoding type
response.setContentType("text/html"); //setup response content type
response.setCharacterEncoding("UTF-8");
MemberDAO md=new MemberDAOImpl();
String mobile=request.getParameter("mobile");
String password=request.getParameter("password");
// String name=request.getParameter("name");
// String nickname=request.getParameter("nickname");
// String gender=request.getParameter("gender");
// int birthday=Integer.parseInt(request.getParameter("birthday"));
// String email=request.getParameter("email");
// String address=request.getParameter("address");
String submitType=request.getParameter("submit");
Member m=md.getMember(mobile, password);
if(submitType.equals("login") && m!=null && m.getMobile()!=null) {
request.setAttribute("message", m.getMobile());
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}else if(submitType.equals("register")) {
m.setMobile(request.getParameter("mobile"));
m.setPassword(request.getParameter("password"));
m.setName(request.getParameter("name"));
m.setNickname(request.getParameter("nickname"));
m.setGender(request.getParameter("gender"));
m.setBirthday(Integer.parseInt(request.getParameter("birthday")));
m.setEmail(request.getParameter("email"));
m.setAddress(request.getParameter("address"));
md.insertMember(m);
request.setAttribute("smessage","註冊成功,請登入" );
request.getRequestDispatcher("login.jsp").forward(request, response);
request.setAttribute("message","查無帳號123" );
request.getRequestDispatcher("login.jsp").forward(request, response);
}else {
request.setAttribute("message","帳號密碼有誤 請重新輸入" );
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
<file_sep>/EEIT124Project/src/login/sumit/registration/MemberDAO.java
package login.sumit.registration;
public interface MemberDAO {
public int insertMember(Member m);
public Member getMember(String mobile,String password);
// public Member getMember1(String mobile,String password,String name,String nickname,String gender,int birthday,String email,String address);
}<file_sep>/EEIT124Project/src/shoppingMall/testfile.java
package shoppingMall;
public class testfile {
}
<file_sep>/EEIT124Project/src/login/sumit/registration/Myp.java
package login.sumit.registration;
public interface Myp {
String username="system";
String password="<PASSWORD>";
String connUrl="jdbc:oracle:thin:@127.0.0.1:1521/xepdb1";
}
|
9e407a76269e5d2cf730b68032e9778580d64957
|
[
"Java"
] | 5
|
Java
|
HUANGCL-1/IIIProject_CampingWebSite
|
def591af1dc7c1f5a09016fb1647a13ebb1335f7
|
1b5a9ff027bceee5c244d7d2e6351c3c5c312d4c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.